I’ve written how to connect chatgpt with c# before and updated it with this article. Now it’s time to add Chat-GPT4 API to the list.

The code is below and this time there is a video too.

https://github.com/burakdownunder/ChatGPT4ConnectionExample

I hope it will be helpful.

Cheers,

private static async Task<string> GetChatGPTResponse(string prompt)
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

var requestBody = new
{
prompt = prompt,
max_tokens = 150
};

var jsonRequestBody = new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(apiUri, jsonRequestBody);

if (response.IsSuccessStatusCode)
{
string jsonResponse = await response.Content.ReadAsStringAsync();
var responseObject = JsonSerializer.Deserialize<JsonElement>(jsonResponse);
return responseObject.GetProperty("choices")[0].GetProperty("text").GetString();
}
else
{
return $"Error: {response.StatusCode}";
}
}

--

--