Using ChatGPT in a C# Application

Introduction

Integrating ChatGPT into a C# application allows developers to enhance their applications with AI-powered text generation. In this guide, we will demonstrate how to connect a C# application to OpenAI's ChatGPT API.

Prerequisites

Ensure you have the following:

  • .NET 6 or later installed
  • An OpenAI API key
  • A C# development environment (such as Visual Studio or VS Code)

You can obtain an API key by signing up at OpenAI.

Setting Up the C# Project

Create a new C# console application using the .NET CLI:

mkdir ChatGPTApp
cd ChatGPTApp
dotnet new console

Install the required package for making HTTP requests:

dotnet add package System.Net.Http.Json

Implementing ChatGPT API Integration

1. Create a ChatGPT Service

Create a new file ChatGPTService.cs and add the following code:

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

public class ChatGPTService
{
    private readonly HttpClient _httpClient;
    private const string ApiUrl = "https://api.openai.com/v1/chat/completions";
    private readonly string _apiKey;

    public ChatGPTService(string apiKey)
    {
        _apiKey = apiKey;
        _httpClient = new HttpClient();
    }

    public async Task<string> GetResponseAsync(string prompt)
    {
        var requestBody = new
        {
            model = "gpt-4",
            messages = new[] { new { role = "user", content = prompt } },
            max_tokens = 100
        };

        var request = new HttpRequestMessage(HttpMethod.Post, ApiUrl);
        request.Headers.Add("Authorization", $"Bearer {_apiKey}");
        request.Content = JsonContent.Create(requestBody);

        var response = await _httpClient.SendAsync(request);
        response.EnsureSuccessStatusCode();
        
        var jsonResponse = await response.Content.ReadAsStringAsync();
        var responseData = JsonSerializer.Deserialize<JsonElement>(jsonResponse);
        return responseData.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
    }
}

2. Using the ChatGPT Service

Modify Program.cs to use the ChatGPT service:

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.Write("Enter your OpenAI API key: ");
        string apiKey = Console.ReadLine();
        var chatGPT = new ChatGPTService(apiKey);

        while (true)
        {
            Console.Write("You: ");
            string userInput = Console.ReadLine();
            if (string.IsNullOrWhiteSpace(userInput)) break;

            string response = await chatGPT.GetResponseAsync(userInput);
            Console.WriteLine($"ChatGPT: {response}\n");
        }
    }
}

Running the Application

Compile and run the application using:

dotnet run

Enter your OpenAI API key and start chatting with ChatGPT within your C# application.

Conclusion

This guide covered how to integrate ChatGPT into a C# application using OpenAI's API. You can further enhance the application by adding error handling, UI interfaces, or extending functionality for specific use cases.

Comments

Popular posts from this blog

Zustland : a minimal data store to consider for the Next React Project

How to run HugginFace models in Python