OpenAI API – Get ChatGPT response in C#

In the world of evolving artificial intelligence, access to technologies like OpenAI's ChatGPT is becoming increasingly in demand. To facilitate the process of interacting with this tool, I wrote down the AmChat class, which provides a simple and convenient way to send requests to the ChatGPT API and receive responses. In this article, we'll look at the features of the AmChat class and how to use it to quickly and efficiently receive responses from ChatGPT in your C# code.

The AmChat class has only one public method – GetAnswer, which is static and asynchronous. This method takes a question as a parameter and returns the response from ChatGPT.

Due to the fact that the GetAnswer method is static and asynchronous, its use becomes very simple and convenient. The programmer can call this method and wait for a response using the await keyword, which greatly simplifies the code and makes it more readable.

AmChat provides reliable handling of possible errors that may occur when interacting with the ChatGPT API. This improves the stability and reliability of applications that use this class.

Let's look at an example of using the AmChat class:

if(txt == null) return;
string ansver = await AmChat.GetAnswer(txt);
await SendMessageToOne(chatId, ansver);

for example, you can send a response from the neural network to a telegram chat. Yes, you can get a question in the cart, through a bot, and give the answer to a person in his chat.

Below is the complete code of the AmChat class:

using CaSecrets;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace ChatGPT1;

public class AmChat
{
    static string questionTemplate = @"{
        ""model"": ""gpt-3.5-turbo"",
        ""messages"": [
            {
                ""role"": ""system"",
                ""content"": ""You are a helpful assistant.""
            },
            {
                ""role"": ""user"",
                ""content"": ""{0}""
            }
        ]
    }";

    public static async Task<string> GetAnswer(string question)
    {
        //question = CleanseString(question);
        string jsonContent = questionTemplate.Replace("{0}", question);

        var httpClient = new HttpClient();
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri("https://api.openai.com/v1/chat/completions"),
            Headers =
            {
                { HttpRequestHeader.ContentType.ToString(), "application/json" },
                { HttpRequestHeader.Authorization.ToString(), "Bearer " + Secrets.OPENAI_API_KEY},
            },
            Content = new StringContent(jsonContent, Encoding.UTF8, "application/json")
        };

        var response = await httpClient.SendAsync(request);
        string answer = await GetClearAnswerFromResponse(response);

        Db.SaveQA(question, answer);
        return answer;
    }

    static async Task<string> GetClearAnswerFromResponse(HttpResponseMessage response)
    {
        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            var parsedResponse = JObject.Parse(responseContent);

            var choices = parsedResponse["choices"];
            if (choices == null) return "*** 1";
            if (choices.Count() == 0) return "*** 2";
            if (choices[0] == null) return "*** 3";
            var message = choices![0]!["message"];
            if (message == null) return "*** 4";
            if (message["content"] == null) return "*** 5";
            var answer = message["content"]!.ToString();

            return answer;
        }

        var errorContent = await response.Content.ReadAsStringAsync();
        return $"Error: {response.StatusCode}, Content: {errorContent}";
    }
    static string CleanseString(string input)
    {
        return JsonConvert.ToString(input);
    }
}

Conclusion:

The AmChat class provides a convenient tool for interacting with ChatGPT through its API. Provides ease of use with its only public static and asynchronous GetAnswer method, which simplifies the process of getting answers from ChatGPT. I hope it helped someone.

PS:

ChatGPT contributed to the writing of this article.

Similar Posts

Leave a Reply

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