Where can I find documentation for integrating GPT into a C# project?

Hello there,I’m trying to connect ChatGPT to a C# program, but I couldn’t find any information available on GitHub or Youtube

These reference documents and teaching videos seem to like calling APIs in web pages, rather than integrating them into a program installed on the computer

Welcome to the forum!

The amazing thing about AI is that you can ask it how to integrate itself into your system.

If you don’t want to use a community maintained C# library, my goto would be to look at the documentation and ask GPT-4 how to take the curl command and adapt it to your framework.

USER

I want to use the following curl command in C#. What’s the best way to do that?


curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "Who won the world series in 2020?"
      },
      {
        "role": "assistant",
        "content": "The Los Angeles Dodgers won the World Series in 2020."
      },
      {
        "role": "user",
        "content": "Where was it played?"
      }
    ]
  }'

ASSISTANT

To replicate the functionality of the provided cURL command in C#, you can use the HttpClient class, which is part of the System.Net.Http namespace. Here’s an example of how to translate your cURL request into C# code:

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

class Program
{
    static readonly HttpClient client = new HttpClient();
    
    static async Task Main(string[] args)
    {
        // Remember to replace this with your actual OpenAI API key
        string openAiApiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");

        string apiUrl = "https://api.openai.com/v1/chat/completions";
        string requestBody = @"{
            ""model"": ""gpt-3.5-turbo"",
            ""messages"": [
                {
                    ""role"": ""system"",
                    ""content"": ""You are a helpful assistant.""
                },
                {
                    ""role"": ""user"",
                    ""content"": ""Who won the world series in 2020?""
                },
                {
                    ""role"": ""assistant"",
                    ""content"": ""The Los Angeles Dodgers won the World Series in 2020.""
                },
                {
                    ""role"": ""user"",
                    ""content"": ""Where was it played?""
                }
            ]
        }";

        // Ensure that your HttpClient instance is not disposed until the application is shutting down
        using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl)
        {
            Content = new StringContent(requestBody, Encoding.UTF8, "application/json")
        };

        request.Headers.Add("Authorization", $"Bearer {openAiApiKey}");

        try
        {
            // Send the request and get the response
            HttpResponseMessage response = await client.SendAsync(request);

            // Ensure we have a successful response
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine("Error: " + response.StatusCode);
            }
            else
            {
                // Read the response as a string
                string result = await response.Content.ReadAsStringAsync();
                Console.WriteLine(result);
            }
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);
        }
    }
}

Please make sure to replace "$OPENAI_API_KEY" with your actual OpenAI API key. Keep in mind that the use of environment variables or other secure storage methods is recommended for storing API keys instead of hardcoding them into your application.

In this example, we create a POST request with a JSON body. We set the necessary headers (Content-Type and Authorization), and send the request using the HttpClient. Finally, we read the response and print it. This code should be run in an async-capable environment (such as a console application with Main marked as async or in an async method in a different app type).

Hope this helps :slight_smile:

4 Likes

The Wiki page and playground project have a couple of samples, which may help you.
Wiki page: Home · betalgo/openai Wiki (github.com)
C# library: betalgo/openai: OpenAI .NET sdk

I recommend that you take a look at Microsoft’s Semantic-kernel library for C#. With this library, you can access models from Microsoft as well as models from OpenAI.