Files
gott/Endpoints/ChatEndpoint.cs
T

103 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Gott.Models;
using Gott.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Gott.Endpoints;
public static class ChatEndpoint
{
public static void MapChatEndpoint(this IEndpointRouteBuilder app)
{
app.MapPost("/api/chat", HandleChat);
}
private static async Task HandleChat(HttpRequest req, HttpResponse res, IHttpClientFactory httpFactory, IConfiguration config, ToolService toolService, DatabaseService db)
{
var body = await JsonSerializer.DeserializeAsync<ChatRequest>(req.Body);
if (body == null || body.Messages == null || body.Messages.Count == 0)
{
res.StatusCode = 400;
await res.WriteAsJsonAsync(new { error = "messages required" });
return;
}
var token = config["AnthropicToken"];
if (string.IsNullOrEmpty(token))
{
res.StatusCode = 500;
await res.WriteAsJsonAsync(new { error = "AnthropicToken not configured" });
return;
}
var modelId = body.Model switch
{
"opus" => "claude-opus-4-6",
"sonnet" => "claude-sonnet-4-6",
_ => "claude-sonnet-4-6"
};
res.Headers["Content-Type"] = "text/event-stream";
res.Headers["Cache-Control"] = "no-cache";
res.Headers["Connection"] = "keep-alive";
var sessionId = body.SessionId;
if (string.IsNullOrEmpty(sessionId))
{
res.StatusCode = 400;
await res.WriteAsJsonAsync(new { error = "sessionId required" });
return;
}
var chainId = Guid.NewGuid().ToString("N");
await db.CreateChain(new ChainRecord
{
ChainId = chainId,
SessionId = sessionId,
Model = modelId,
SystemPrompt = body.SystemPrompt
});
// Session-Timestamp aktualisieren
await db.UpdateSessionTimestamp(sessionId);
var messages = new List<object>();
foreach (var msg in body.Messages)
messages.Add(new { role = msg.Role, content = msg.Content });
// Nur die letzte User-Message speichern (= die neue)
var lastUserMsg = body.Messages.LastOrDefault(m => m.Role == "user");
if (lastUserMsg != null)
{
await db.SaveMessage(new MessageRecord
{
ChainId = chainId,
Iteration = 0,
Role = "user",
Type = "text",
Content = lastUserMsg.Content
});
}
var systemPrompt = new List<object>
{
new { type = "text", text = "You are Claude Code, Anthropic's official CLI for Claude." }
};
if (!string.IsNullOrWhiteSpace(body.SystemPrompt))
systemPrompt.Add(new { type = "text", text = body.SystemPrompt });
var anthropic = new AnthropicService(httpFactory, token, toolService, db);
await anthropic.StreamChat(res, modelId, systemPrompt, messages, chainId);
}
}