Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Created March 7, 2024 13:02
Show Gist options
  • Save davepcallan/8a2cd42f21befd72cfaeeef5acd1ca8e to your computer and use it in GitHub Desktop.
Save davepcallan/8a2cd42f21befd72cfaeeef5acd1ca8e to your computer and use it in GitHub Desktop.
Simple example of integrating with ChatGPT API from .NET
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Text;
using System.Text.Json;
namespace Samples;
public class ChatGPTAPIExample(ILogger<ChatGPTAPIExample> logger, IConfiguration configuration)
{
private string Prompt = "Please explain the following code :";
private string CouldNotLoadDescription = "ChatGPT description could not be loaded";
public async Task<string> ExplainCodeAsync(string codeSnippet)
{
// Get a key from : https://platform.openai.com/api-keys
var ApiKey = configuration["ChatGPT:APIKey"];
var ApiUrl = "https://api.openai.com/v1/chat/completions";
var Model = "gpt-4-turbo-preview";
var Temperature = 0.3;
var messages = new[]
{
new { role = "user", content = $"{Prompt}\n\n{codeSnippet}" }
};
var data = new
{
model = Model,
messages,
temperature = Temperature
};
var HttpClient = new HttpClient();
HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {ApiKey}");
var json = JsonSerializer.Serialize(data);
var requestContent = new StringContent(json, Encoding.UTF8, "application/json");
try
{
var response = await HttpClient.PostAsync(ApiUrl, requestContent);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(responseContent);
var choicesElement = doc.RootElement.GetProperty("choices");
var messageObject = choicesElement[0].GetProperty("message");
var content = messageObject.GetProperty("content").GetString();
if (content is not null)
{
return content;
}
else
{
logger.LogError("ChatGPT API response did not contain expected content");
return CouldNotLoadDescription;
}
}
else
{
logger.LogError("ChatGPT API request failed with status code: {StatusCode}", response.StatusCode);
return CouldNotLoadDescription;
}
}
catch (Exception ex)
{
logger.LogError(ex, "ChatGPT error occurred: {Message}", ex.Message);
return CouldNotLoadDescription;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment