Integrating OpenAI’s ChatGPT API into your ASP.NET Core 8.0 application can enhance user interactions by providing AI-driven conversational capabilities. This guide will walk you through the process of setting up and using the ChatGPT API in your ASP.NET Core project, with examples and code snippets formatted for easy readability.

Prerequisites

Before you begin, ensure you have the following:

  • An OpenAI API key, which you can obtain from the OpenAI platform.
  • ASP.NET Core 8.0 installed on your development machine.
  • Basic knowledge of C# and ASP.NET Core.

Step 1: Setting Up Your ASP.NET Core Project

First, create a new ASP.NET Core Web API project:

dotnet new webapi -n ChatGPTIntegration
cd ChatGPTIntegration

Open the project in your preferred IDE.

Step 2: Install Required NuGet Packages

You’ll need to add packages for HTTP requests and JSON handling. Use the following commands to install them:

dotnet add package Microsoft.Extensions.Http
dotnet add package System.Text.Json

Step 3: Create a Service to Interact with ChatGPT

Create a new service class named ChatCompletionService to handle communication with the ChatGPT API.

using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class ChatCompletionService
{
    private readonly HttpClient _httpClient;
    private readonly string _apiKey;

    public ChatCompletionService(HttpClient httpClient, string apiKey)
    {
        _httpClient = httpClient;
        _apiKey = apiKey;
    }

    public async Task<string> GetChatCompletionAsync(string prompt)
    {
        var request = new HttpRequestMessage(HttpMethod.Post, "https://api.openai.com/v1/chat/completions")
        {
            Headers = { { "Authorization", $"Bearer {_apiKey}" } },
            Content = new StringContent(JsonSerializer.Serialize(new
            {
                model = "gpt-3.5-turbo",
                messages = new[] { new { role = "user", content = prompt } }
            }), Encoding.UTF8, "application/json")
        };

        var response = await _httpClient.SendAsync(request);
        response.EnsureSuccessStatusCode();

        var responseContent = await response.Content.ReadAsStringAsync();
        return responseContent;
    }
}

Step 4: Configure Dependency Injection

In Program.cs, register the ChatCompletionService with the dependency injection container:

builder.Services.AddHttpClient<ChatCompletionService>(client =>
{
    client.BaseAddress = new Uri("https://api.openai.com/");
});
builder.Services.AddSingleton(sp => new ChatCompletionService(sp.GetRequiredService<HttpClient>(), "YOUR_API_KEY"));

Replace "YOUR_API_KEY" with your actual OpenAI API key.

Step 5: Create a Controller to Handle Requests

Create a new controller named ChatController to expose an endpoint for interacting with ChatGPT.

using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

[ApiController]
[Route("[controller]")]
public class ChatController : ControllerBase
{
    private readonly ChatCompletionService _chatService;

    public ChatController(ChatCompletionService chatService)
    {
        _chatService = chatService;
    }

    [HttpGet("ask")]
    public async Task<IActionResult> Ask(string question)
    {
        var response = await _chatService.GetChatCompletionAsync(question);
        return Ok(response);
    }
}

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.