Created
March 7, 2024 13:02
-
-
Save davepcallan/8a2cd42f21befd72cfaeeef5acd1ca8e to your computer and use it in GitHub Desktop.
Simple example of integrating with ChatGPT API from .NET
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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