How to connect ChatGPT with C#

Burak Altın
1 min readDec 17, 2022

Since ChatGPT in our lives, I’ve been thinking to do something with it. But to be honest I don’t know how to use it so far. But maybe someone else can use it. So you can find the simple code example to connect ChatGPT (GPT-3) for C# Console app. Here is the github link.

https://github.com/altinburak/GPT3ConnectionExample

Please let me know if you find a way to implement it in your applications.

 static void Main(string[] args)
{
Console.WriteLine("Enter a prompt:");
string prompt = Console.ReadLine();

string apiKey = "Your API Key";
string model = "text-davinci-002";
int maxTokens = 1024;
float temperature = 0.5f;

// Build the API request
string requestUrl = $"https://api.openai.com/v1/completions";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

var requestJson = new
{
prompt = prompt,
max_tokens = maxTokens,
temperature = temperature,
model = model
};

StringContent content = new StringContent(JsonConvert.SerializeObject(requestJson), Encoding.UTF8, "application/json");

// Send the request and receive the response
HttpResponseMessage response = client.PostAsync(requestUrl, content).Result;
string responseJson = response.Content.ReadAsStringAsync().Result;

// Extract the completed text from the response
dynamic responseObject = JsonConvert.DeserializeObject(responseJson);
string completedText = responseObject.choices[0].text;

Console.WriteLine("Completed text: " + completedText);

}

There is an improved version of this now here.

--

--