ChatApi/Controllers/ChatController.cs~RF39ccb1.TMP
2024-11-28 22:49:03 -03:00

69 lines
3.1 KiB
Plaintext

using Microsoft.AspNetCore.Mvc;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Embeddings;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Connectors.InMemory;
#pragma warning disable SKEXP0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
namespace ChatApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class ChatController : ControllerBase
{
private readonly ILogger<ChatController> _logger;
private readonly ChatHistoryService _chatHistoryService;
private readonly IChatCompletionService _chatCompletionService;
private readonly Kernel _kernel;
public ChatController(ILogger<ChatController> logger, ChatHistoryService chatHistoryService, IChatCompletionService chatCompletionService, Kernel kernel)
{
_logger = logger;
_chatHistoryService = chatHistoryService;
_chatCompletionService = chatCompletionService;
_kernel = kernel;
}
[HttpGet(Name = "Response")]
public async Task<string> Get([FromQuery] ChatRequest chatRequest)
{
var stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
SessionIdStore sessionIdStore = new SessionIdStore(HttpContext);
var sessionId = sessionIdStore.GetSessionId();
var history = _chatHistoryService.Get(sessionId);
history.AddUserMessage(chatRequest.Message);
var embeddingGenerator = _kernel.GetRequiredService<ITextEmbeddingGenerationService>();
// Setup a memory store and create a memory out of it
#pragma warning disable SKEXP0020 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
var memoryStore = new InMemoryVectorStore();
#pragma warning restore SKEXP0020 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
var memory = new SemanticTextMemory(memoryStore, embeddingGenerator);
// Loading it for Save, Recall and other methods
_kernel.ImportPluginFromObject(new TextMemoryPlugin(memory));
string MemoryCollectionName = "MyCustomDataCollection";
var option = new PromptExecutionSettings
{
Memory = memory,
MemoryCollectionName = MemoryCollectionName
};
var response = await _chatCompletionService.GetChatMessageContentAsync(history);
history.AddMessage(response.Role, response.Content ?? "");
_chatHistoryService.UpdateHistory(sessionId, history);
stopWatch.Stop();
return $"{response.Content ?? ""}\n\nTempo: {stopWatch.ElapsedMilliseconds/1000}s";
}
}
}
#pragma warning restore SKEXP0001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.