How to Call OpenAI's ChatGPT API from a C# Application?

 

To call OpenAI's ChatGPT API from a C# application, you need to make HTTP requests using HttpClient. Here's an example of how to do this:

  1. Set Up the Project:

    • Create a new C# Console Application in Visual Studio.
    • Install System.Net.Http and Newtonsoft.Json via NuGet Package Manager.

    Sample code 

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

    namespace ChatGPTExample
    {
        class Program
        {
            private static readonly string apiKey = "YOUR_API_KEY_HERE";
            private static readonly string endpoint = "https://api.openai.com/v1/completions";

            static async Task Main(string[] args)
            {
                string prompt = "Explain the significance of machine learning in modern technology.";
                var response = await GetChatGPTResponse(prompt);
                Console.WriteLine(response);
            }

            public static async Task<string> GetChatGPTResponse(string prompt)
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

                    var requestBody = new
                    {
                        model = "text-davinci-003",
                        prompt = prompt,
                        max_tokens = 150
                    };

                    var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
                    var response = await httpClient.PostAsync(endpoint, content);
                    response.EnsureSuccessStatusCode();

                    var responseBody = await response.Content.ReadAsStringAsync();
                    dynamic result = JsonConvert.DeserializeObject(responseBody);
                    return result.choices[0].text;
                }
            }
        }
    }

Comments

Popular posts from this blog

How to Convert Word Document to PDF using C#

Sql query to get counts by quarterly and half yearly

How to Get First Day and Last Day of a Current Quarter in SQL Server