MikeHouston.net

Honorary member of the Shaolin

Simple c# example : calling chatGPT API

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

namespace ChatGPTExample
{
     class Program
     {
         static async Task Main(string[] args)
         {
             string endpoint = "https://api.openai.com/v1/engines/davinci-codex/completions";
             string apiKey = "YOUR_API_KEY_HERE";
            
             // Request body
             var requestBody = new
             {
                 prompt = "Hello, how are you?",
                 max_tokens = 50,
                 temperature = 0.7
             };
             var jsonRequestBody = JsonSerializer.Serialize(requestBody);
             var httpContent = new StringContent(jsonRequestBody, Encoding.UTF8, "application/json");
            
             // HTTP client
             var client = new HttpClient();
             client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
            
             // HTTP POST request
             var httpResponse = await client.PostAsync(endpoint, httpContent);
            
             // Response
             var responseString = await httpResponse.Content.ReadAsStringAsync();
             dynamic responseJson = JsonSerializer.Deserialize<dynamic>(responseString);
             string completion = responseJson.choices[0].text;
            
             Console.WriteLine("Completion: " + completion);
         }
     }
}

Comments are closed