添加项目文件。

This commit is contained in:
yangwx
2025-03-12 20:02:52 +08:00
parent 4d34907fa7
commit 3ccd6d9a39
32 changed files with 1833 additions and 0 deletions

54
Services/OpenAIService.cs Normal file
View File

@@ -0,0 +1,54 @@
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; }
}
}
}