46 lines
1.6 KiB
C#
46 lines
1.6 KiB
C#
using LLMApi.Data.Contracts.ChatGpt3_5;
|
|
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Serialization;
|
|
|
|
namespace LLMApi.Services;
|
|
|
|
public class ChatGpt3_5Service : ILlmApiService
|
|
{
|
|
private readonly HttpClient _client;
|
|
private static readonly JsonSerializerSettings jsonSerializerSettings = new()
|
|
{
|
|
ContractResolver = new DefaultContractResolver()
|
|
{
|
|
NamingStrategy = new SnakeCaseNamingStrategy()
|
|
}
|
|
};
|
|
private const string API_TOKEN = "";
|
|
private const string VERSION_IDENTIFIER = "gpt-3.5-turbo";
|
|
|
|
public ChatGpt3_5Service(HttpClient client)
|
|
{
|
|
_client = client;
|
|
_client.BaseAddress = new Uri("https://api.openai.com");
|
|
// _client.DefaultRequestHeaders.Add("Content-Type", "application/json");
|
|
_client.DefaultRequestHeaders.Add("Authorization", $"Bearer {API_TOKEN}");
|
|
}
|
|
|
|
public async Task<string> GetAnswerToPrompt(string prompt)
|
|
{
|
|
var requestContract = new ChatCompletionRequest(VERSION_IDENTIFIER,
|
|
new Message[]
|
|
{
|
|
new("system", "You are a helpful assistant."),
|
|
new("user", "Hello!"),
|
|
});
|
|
|
|
var response = await _client.PostAsJsonAsync("/v1/chat/completions", requestContract);
|
|
|
|
var content = await response.Content.ReadAsStringAsync();
|
|
|
|
var obj = JsonConvert.DeserializeObject<ChatCompletionResponse>(content, jsonSerializerSettings);
|
|
|
|
return obj!.ToString() + Environment.NewLine + string.Join(", ", obj!.Choices.Select(c => c.ToString()));
|
|
|
|
}
|
|
} |