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

109 lines
4.3 KiB
C#

using ChatServerSpace.Models;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.Google;
#pragma warning disable SKEXP0070 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
namespace ChatServerSpace.Services
{
public class GeminiChatService : IChatService
{
private readonly IChatHistoryService _historyService;
private readonly Kernel _kernel;
private readonly ILogger<GeminiChatService> _logger;
public GeminiChatService(IChatHistoryService historyService, IConfiguration config, ILogger<GeminiChatService> logger)
{
_historyService = historyService;
_logger = logger;
var apiKey = config["Google:GeminiApiKey"] ?? throw new ArgumentNullException("Google:GeminiApiKey configuration is missing");
var modelId = config["Google:ModelId"] ?? "gemini-1.5-pro";
_kernel = Kernel.CreateBuilder()
.AddGoogleAIGeminiChatCompletion(modelId, apiKey)
.Build();
}
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 chat history for Semantic Kernel
var chatHistory = new Microsoft.SemanticKernel.ChatCompletion.ChatHistory();
foreach (var message in history)
{
if (message.Role.Equals("user", StringComparison.OrdinalIgnoreCase))
{
chatHistory.AddUserMessage(message.Content);
}
else if (message.Role.Equals("assistant", StringComparison.OrdinalIgnoreCase))
{
chatHistory.AddAssistantMessage(message.Content);
}
}
try
{
// Get response from Gemini
var chatCompletionService = _kernel.GetRequiredService<IChatCompletionService>();
var exec = new PromptExecutionSettings
{
ExtensionData = new Dictionary<string, object>
{
{ "maxOutputTokens", 8192 },
{ "temperature", 0.7 },
{ "topP", 0.95 },
{ "stopSequences", new List<string>() }
}
};
var result = await chatCompletionService.GetChatMessageContentAsync(chatHistory, exec);
var responseText = result.ToString();
// Save assistant message to history
var assistantMessage = new ChatMessage
{
SessionId = request.SessionId,
Role = "assistant",
Content = responseText
};
await _historyService.SaveMessageAsync(assistantMessage);
await Task.Delay(2000);
return new ChatResponse
{
SessionId = request.SessionId,
Response = responseText
};
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting response from Gemini");
throw;
}
}
catch (Exception ex)
{
throw new Exception("Erro na parada!", ex);
}
}
}
}
#pragma warning restore SKEXP0070 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.