Thursday, 1 August 2024

Use ChatGPT API in a C# application

 To use the ChatGPT API in a C# application, you'll follow below steps:

1. Set Up Your OpenAI Account

  1. Sign Up: If you haven't already done so, create an account on the Open AI Website.

  1. Get API Key: After logging in, go to the API section and generate an API key.


Once you have the ChatGPT API Key, copy the method below into your application and run. You need to pass 2 parameters.

1) API Key
2) Prompt


I am using Model "gpt-3.5-turbo-instruct", you can choose your model based on your requirements.



  private static async Task<string> GetResutlsFromChatGPT()
  {
      var apiKey = "Your Key here";
      var prompt = "Your prompt here";

      var chatGPTRequest = new
      {
          model = "gpt-3.5-turbo-instruct",
          temperature = 0.5f,
          max_tokens = 1000,
          top_p = 0.5f,
          frequency_penalty = 1.0f,
          presence_penalty = 0.0f,
          prompt = prompt
      };

      ChatGPTResponseModel chatGPTResponse = null;
      using (HttpClient httpClient = new HttpClient())
      {
          using (var httpReq = new HttpRequestMessage(HttpMethod.Post, "https://api.openai.com/v1/completions"))
          {
              httpReq.Headers.Add("Authorization", $"Bearer {apiKey}");
              string requestString = JsonConvert.SerializeObject(chatGPTRequest);
              httpReq.Content = new StringContent(requestString, Encoding.UTF8, "application/json");

              using (HttpResponseMessage httpResponse = await httpClient.SendAsync(httpReq))
              {
                  if (httpResponse.IsSuccessStatusCode)
                  {
                      string responseString = await httpResponse.Content.ReadAsStringAsync();
                      chatGPTResponse = JsonConvert.DeserializeObject<ChatGPTResponseModel>(responseString);
                      if (chatGPTResponse != null)
                      {
                          string completionText = chatGPTResponse.Choices?[0]?.Text;
                          return await Task.Run<string>(() => { return completionText ?? string.Empty; });
                      }
                  }
              }
          }
      }

      return await Task.Run(() => { return string.Empty; });
  }


Below are the models for Deserialize the response


 public class ChatGPTResponseModel
 {
     [JsonPropertyName("id")]
     public string Id { get; set; }

     [JsonPropertyName("object")]
     [SuppressMessage("Naming", "CA1720:Identifier contains type name", Justification = "This is the name of the property returned by the API.")]
     public string @Object { get; set; }

     [JsonPropertyName("created")]
     public int Created { get; set; }

     [JsonPropertyName("model")]
     public string Model { get; set; }

     [JsonPropertyName("choices")]
     public List<ChatGPTChoice> Choices { get; set; }
 }


 [DebuggerDisplay("Text = {Text}")]
 public class ChatGPTChoice
 {
     [JsonPropertyName("text")]
     public string Text { get; set; }

 }


You can call your method like below in your main file.

 var output = await GetResutlsFromChatGPT();

This is all about this article. I hope you like it.



No comments:

Post a Comment

Enum with Flag Attribute in .NET

In .NET, you can use the Flags attribute with an enum. You can combine multiple values into one to represent a set of bit fields. It is use...