ChatGTP client in c#

By | June 14, 2023

It is continuation of previous post “Ask ChatGPT to answer a question using curl command” but request to ChatGPT server is sent by c# code. The authentication secret key in example below has been revoked, so if you want copy-paste the code you need to use your own OpenAI authentication secret key or request new one from there https://platform.openai.com/account/api-keys.
The example is c# console application, the question must be specified as an argument:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace ConsoleApp1
{
    class Program
    {
       static void Main(string[] args)
       {
            string secretKey = "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";
            string openAIUrl = "https://api.openai.com";
            string jsonBodyFmt = "\"model\": \"text-davinci-003\",\"prompt\": \"{0}\",\"temperature\": 1,\"max_tokens\": 256";
            string question = "";
            if (args.Length > 0)
                question = args[0];
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(openAIUrl);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + secretKey);
                string jsonBody = "{" + String.Format(jsonBodyFmt, question) + "}";
                HttpContent httpContent = new StringContent(jsonBody,
                                                            Encoding.UTF8,
                                                            "application/json");
                var response = client.PostAsync("v1/completions", httpContent).Result;
                var result = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(result);
            }
        }
    }
}

Execution:


D:\ChatGPTClient\bin\Debug\net45>ChatGPTClient.exe "Please write Hello world program in c"
{
  "id": "cmpl-7RNavCxtEz1XDwWX4tBqz4KVJJbXc",
  "object": "text_completion",
  "created": 1686759909,
  "model": "text-davinci-003",
  "choices": [
   {
    "text": "\n\n#include<stdio.h>\n\nint main()\n{\n printf(\"Hello World\");\n return 0;\n}",
    "index": 0,
    "logprobs": null,
    "finish_reason": "stop"
   }
  ],
  "usage": {
   "prompt_tokens": 7,
   "completion_tokens": 31,
   "total_tokens": 38
  }
}

Leave a Reply

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