OpenChat/OpenChatApi/Program.cs
Ricardo Carneiro 5b6487b38f Initial commit
2025-01-26 19:30:38 -03:00

68 lines
2.2 KiB
C#

// Program.cs
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using OpenChatApi.Models;
using OpenChatApi.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// MongoDB Configuration
builder.Services.Configure<MongoDBSettings>(
builder.Configuration.GetSection("MongoDB"));
builder.Services.AddSingleton<IMongoDBService, MongoDBService>();
// Semantic Kernel Configuration
#pragma warning disable SKEXP0010 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
builder.Services.AddOpenAIChatCompletion("openchat-3.5-0106",
new Uri("https://gpt.serverspace.com.br/v1/chat/completions"),
"tIAXVf3AkCkkpSX+PjFvktfEeSPyA1ZYam50UO3ye/qmxVZX6PIXstmJsLZXkQ39C33onFD/81mdxvhbGHm7tQ==");
#pragma warning restore SKEXP0010 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.MapPost("/api/system-prompt", async (SystemPromptRequest request, IMongoDBService mongoService) =>
{
await mongoService.UpdateSystemPrompt(request.UserId, request.SystemPrompt);
return Results.Ok();
})
.WithName("SystemPrompt")
.WithOpenApi();
// Endpoint
app.MapPost("/api/chat", async (ChatRequest request, IMongoDBService mongoService, IChatCompletionService kernel) =>
{
var history = await mongoService.GetUserMessages(request.UserId);
// Create chat history
var chatHistory = new ChatHistory();
chatHistory.AddSystemMessage(history.SystemPrompt);
foreach (var msg in history.Messages)
{
if (msg.Type == "user")
chatHistory.AddUserMessage(msg.Content);
else
chatHistory.AddAssistantMessage(msg.Content);
}
// Add current message
chatHistory.AddUserMessage(request.Message);
// Get response
var response = await kernel.GetChatMessageContentAsync(chatHistory);
// Update MongoDB
await mongoService.UpdateMessages(request.UserId, request.Message, response.Content);
return Results.Ok(new { response = response });
})
.WithName("Chat")
.WithOpenApi();
app.Run();