ChatCheap/ChatGemini/Services/ServerSpaceChatService.cs
2025-05-20 21:51:05 -03:00

120 lines
4.4 KiB
C#

using ChatServerSpace.Models;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
namespace ChatServerSpace.Services
{
public class ServerSpaceChatService : IChatService
{
private readonly IChatHistoryService _historyService;
private readonly HttpClient _httpClient;
private readonly ILogger<ServerSpaceChatService> _logger;
private readonly string _apiKey;
private readonly JsonSerializerOptions _jsonOptions;
public ServerSpaceChatService(IChatHistoryService historyService, IConfiguration config, ILogger<ServerSpaceChatService> logger, HttpClient httpClient)
{
_historyService = historyService;
_logger = logger;
_httpClient = httpClient;
_apiKey = config["ServerSpace:ApiKey"] ?? throw new ArgumentNullException("ServerSpace:ApiKey configuration is missing");
_httpClient.BaseAddress = new Uri("https://gpt.serverspace.com.br/");
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
_jsonOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
}
public async Task<ChatResponse> ProcessMessageAsync(ChatRequest request)
{
try
{
// Save user message to history
var userMessage = new ChatMessage
{
SessionId = request.SessionId,
Role = "user",
Content = request.Message
};
await _historyService.SaveMessageAsync(userMessage);
// Get chat history
var history = await _historyService.GetSessionHistoryAsync(request.SessionId);
// Create messages array for API request
var messages = history.Select(m => new
{
role = m.Role,
content = m.Content
}).ToList();
// Create API request body
var requestBody = new
{
model = "anthropic/claude-3.5-haiku",
max_tokens = 1024,
top_p = 0.1,
temperature = 0.6,
messages
};
// Send request to ServerSpace API
var jsonContent = JsonSerializer.Serialize(requestBody, _jsonOptions);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("v1/chat/completions", content);
response.EnsureSuccessStatusCode();
var responseJson = await response.Content.ReadAsStringAsync();
var responseObj = JsonSerializer.Deserialize<ServerSpaceResponse>(responseJson, _jsonOptions);
if (responseObj == null || string.IsNullOrEmpty(responseObj.Choices?[0]?.Message?.Content))
{
throw new Exception("Invalid response from ServerSpace API");
}
var responseText = responseObj.Choices[0].Message.Content;
// Save assistant message to history
var assistantMessage = new ChatMessage
{
SessionId = request.SessionId,
Role = "assistant",
Content = responseText
};
await _historyService.SaveMessageAsync(assistantMessage);
return new ChatResponse
{
SessionId = request.SessionId,
Response = responseText
};
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing message with ServerSpace API");
throw;
}
}
private class ServerSpaceResponse
{
public List<ServerSpaceChoice>? Choices { get; set; }
}
private class ServerSpaceChoice
{
public ServerSpaceMessage? Message { get; set; }
}
private class ServerSpaceMessage
{
public string? Content { get; set; }
}
}
}