55 lines
1.5 KiB
C#
55 lines
1.5 KiB
C#
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Net.Http.Json;
|
|
|
|
namespace YwxApp.AiChat.Services
|
|
{
|
|
public class OpenAIService : IChatService
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
private string _modelName = "gpt-3.5-turbo";
|
|
|
|
public OpenAIService()
|
|
{
|
|
_httpClient = new HttpClient();
|
|
_httpClient.BaseAddress = new Uri("https://api.openai.com/v1/");
|
|
}
|
|
|
|
public void Configure(string apiKey, string modelName = "gpt-3.5-turbo")
|
|
{
|
|
_httpClient.DefaultRequestHeaders.Authorization =
|
|
new AuthenticationHeaderValue("Bearer", apiKey);
|
|
_modelName = modelName;
|
|
}
|
|
|
|
public async Task<string> GetResponseAsync(string prompt)
|
|
{
|
|
var requestBody = new
|
|
{
|
|
model = _modelName,
|
|
messages = new[] { new { role = "user", content = prompt } }
|
|
};
|
|
|
|
var response = await _httpClient.PostAsJsonAsync("chat/completions", requestBody);
|
|
var responseContent = await response.Content.ReadFromJsonAsync<OpenAIResponse>();
|
|
|
|
return responseContent?.Choices[0].Message.Content ?? "No response";
|
|
}
|
|
|
|
public class Message
|
|
{
|
|
public string Content { get; set; }
|
|
}
|
|
public class Choice
|
|
{
|
|
public Message Message { get; set; }
|
|
|
|
}
|
|
private class OpenAIResponse
|
|
{
|
|
public Choice[] Choices { get; set; }
|
|
|
|
}
|
|
}
|
|
}
|