Thursday 1 August 2024

Use ChatGPT API in a C# application to Read the Image

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

1. Set Up Your OpenAI Account

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

  1. Get API KeyAfter 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) Image Path

 I am using Model "gpt-4o" in the below code.

public static async Task<string> ReadImagefromChatGPTAsync()
  {
      var client = new HttpClient();
      string apiKey = "Your Key Here";
      string imgPath = "D:\\aaa.png"; // Image Path here
      string prompt = "Extract A1C Value and Date from Image";
      try
      {
          // Convert image to base64
          byte[] imageBytes = File.ReadAllBytes(imgPath);
          string base64Image = Convert.ToBase64String(imageBytes);
          string imageBase64Url = $"data:image/png;base64,{base64Image}";

          var requestContent = new
          {
              model = "gpt-4o",
              messages = new[]
              {
              new {
                  role = "user",
                  content = new object[]
                  {
                      new { type = "text", text = prompt },
                      new { type = "image_url", image_url = new { url = imageBase64Url } }
                  }
              }
          },
              max_tokens = 500
          };


          string jsonString = Newtonsoft.Json.Linq.JObject.FromObject(requestContent).ToString();
          var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
          client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
        
          var response = await client.PostAsync("https://api.openai.com/v1/chat/completions", content);
          var responseString = await response.Content.ReadAsStringAsync();
          ChatGPTResponseModel chatGPTResponse = null;
          chatGPTResponse = JsonConvert.DeserializeObject<ChatGPTResponseModel>(responseString);

          if (chatGPTResponse != null)
          {
              var message = chatGPTResponse.Choices?[0].Text;
              return await Task.Run<string>(() => { return string.Empty; });
          }
          return await Task.Run<string>(() => { return string.Empty; });
      }
      catch (Exception ex)
      {
          Console.WriteLine($"An error occurred: {ex.Message}");
          return await Task.Run<string>(() => { 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; }
    [JsonPropertyName("message")]
    public Message Message { get; set; }
 }

public class Message
{
    [JsonPropertyName("role")]
    public string Role { get; set; }

    [JsonPropertyName("conent")]
    public string Content { get; set; }
}

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

 var output = await ReadImagefromChatGPTAsync();


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

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.



Implement Authorization in Swagger with Static Value in Header .Net 8

If you want an anonymous user should not run the APIs. To run your API Endpoints From Swagger / Postman / Code the user should pass the head...