Prompt-Caching, Tool-Ergebnis-Kappung und Kostenerfassung
T1 — Prompt-Caching. Bisher wurde bei jedem Schritt eines Runs der komplette Prompt neu berechnet, inklusive Tool-Definitionen und System-Prompt, die sich nie aendern. Bei zehn Schritten und einem 15k-Praefix sind das 150.000 statt 15.000 Eingabe-Tokens. ChatMessage bekommt dafuer einen eigenen JsonConverter: Der Inhalt geht weiterhin als String raus, bei gesetztem CacheBreakpoint jedoch als Blockarray mit cache_control. Beim Lesen werden beide Formate akzeptiert, damit bestehende ChatContext.json weiter geladen werden koennen. PromptCache setzt zwei Breakpoints: einen auf den System-Prompt (deckt Tool-Definitionen und System-Prompt ab) und einen rollierenden auf die letzte Nachricht mit Inhalt. Vorherige Markierungen werden vorher entfernt, damit sie sich nicht ansammeln. Aktivierung ueber promptCaching: auto (Default, aktiv fuer Modelle mit Unterstuetzung), on oder off. Der wichtigste Test dazu prueft die Praefix-Stabilitaet: Der System-Prompt muss ueber alle Schritte zeichengleich serialisiert werden. Ein einziger Zeitstempel darin wuerde den Cache still verwerfen — die Kosten blieben unveraendert, ohne dass es irgendwo auffiele. T9 — Usage liest prompt_tokens_details.cached_tokens; die Zahl wird bis in AgentRunResult durchgereicht. Ohne sie liesse sich die Wirkung nicht belegen. T2 — Tool-Ergebnisse werden jetzt zentral in ExecuteToolCallAsync gekappt (maxToolResultChars, Default 16.000). Bisher konnte ein einzelner WebFetch mit dem 512-KB-Standardlimit rund 130.000 Tokens in EINER Antwort erzeugen; die Compaction griff erst danach, bezahlt war der Request laengst. T3 — Die Zusammenfassung beim Kompaktieren laeuft ueber ein konfigurierbares summaryModel (Default gemini-2.5-flash) statt ueber das teure Agentenmodell. B4 — AgentRunResult fuehrt Prompt- und Completion-Tokens getrennt; die Kostenanzeige schaetzte bisher 50/50, real liegt das Verhaeltnis eher bei 95:5. Die veraltete Preistabelle bleibt offen. Neue Einstellungen sind im PropertyGrid sichtbar und werden vom AgentEditor bei neuen Agenten mitgeschrieben. Alle 91 Tests gruen. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
6bbe9f9a80
commit
69b5704add
@@ -1,24 +1,33 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ClawdDotNet.Core.Api.Models;
|
||||
|
||||
[JsonConverter(typeof(ChatMessageConverter))]
|
||||
public sealed class ChatMessage
|
||||
{
|
||||
[JsonPropertyName("role")]
|
||||
public string Role { get; set; } = "";
|
||||
|
||||
[JsonPropertyName("content")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? Content { get; set; }
|
||||
|
||||
[JsonPropertyName("tool_calls")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public List<ToolCall>? ToolCalls { get; set; }
|
||||
|
||||
[JsonPropertyName("tool_call_id")]
|
||||
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
public string? ToolCallId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Setzt einen Prompt-Caching-Breakpoint auf diese Nachricht.
|
||||
///
|
||||
/// Alles, was im Prompt VOR dem Breakpoint steht (Tool-Definitionen, System-Prompt,
|
||||
/// vorherige Nachrichten), wird beim nächsten Aufruf aus dem Cache gelesen und
|
||||
/// kostet nur einen Bruchteil. Der Inhalt wird dann als Block-Array statt als
|
||||
/// einfacher String serialisiert.
|
||||
///
|
||||
/// Wichtig: Der Prompt-Abschnitt vor dem Breakpoint muss zwischen zwei Aufrufen
|
||||
/// zeichengenau identisch sein, sonst greift der Cache nicht.
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public bool CacheBreakpoint { get; set; }
|
||||
|
||||
public static ChatMessage System(string content) => new() { Role = "system", Content = content };
|
||||
public static ChatMessage User(string content) => new() { Role = "user", Content = content };
|
||||
public static ChatMessage Assistant(string content) => new() { Role = "assistant", Content = content };
|
||||
@@ -36,3 +45,136 @@ public sealed class ChatMessage
|
||||
Content = content
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serialisiert <see cref="ChatMessage"/>. Der Inhalt geht normalerweise als einfacher
|
||||
/// String raus; ist ein <see cref="ChatMessage.CacheBreakpoint"/> gesetzt, stattdessen
|
||||
/// als Block-Array mit cache_control — das Format, das Anbieter für Prompt-Caching
|
||||
/// erwarten.
|
||||
///
|
||||
/// Beim Lesen werden beide Formate akzeptiert: Antworten liefern den Inhalt als String,
|
||||
/// gespeicherte Kontexte können ihn als Array enthalten.
|
||||
/// </summary>
|
||||
public sealed class ChatMessageConverter : JsonConverter<ChatMessage>
|
||||
{
|
||||
public override ChatMessage Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
if (reader.TokenType != JsonTokenType.StartObject)
|
||||
throw new JsonException("ChatMessage: Objekt erwartet.");
|
||||
|
||||
var message = new ChatMessage();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
if (reader.TokenType == JsonTokenType.EndObject)
|
||||
return message;
|
||||
|
||||
if (reader.TokenType != JsonTokenType.PropertyName)
|
||||
continue;
|
||||
|
||||
var propertyName = reader.GetString();
|
||||
reader.Read();
|
||||
|
||||
switch (propertyName)
|
||||
{
|
||||
case "role":
|
||||
message.Role = reader.GetString() ?? "";
|
||||
break;
|
||||
|
||||
case "content":
|
||||
message.Content = ReadContent(ref reader);
|
||||
break;
|
||||
|
||||
case "tool_calls":
|
||||
message.ToolCalls = reader.TokenType == JsonTokenType.Null
|
||||
? null
|
||||
: JsonSerializer.Deserialize<List<ToolCall>>(ref reader, options);
|
||||
break;
|
||||
|
||||
case "tool_call_id":
|
||||
message.ToolCallId = reader.GetString();
|
||||
break;
|
||||
|
||||
default:
|
||||
reader.Skip();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw new JsonException("ChatMessage: unerwartetes Ende.");
|
||||
}
|
||||
|
||||
/// <summary>Nimmt den Inhalt als String oder als Block-Array entgegen.</summary>
|
||||
private static string? ReadContent(ref Utf8JsonReader reader)
|
||||
{
|
||||
if (reader.TokenType == JsonTokenType.Null)
|
||||
return null;
|
||||
|
||||
if (reader.TokenType == JsonTokenType.String)
|
||||
return reader.GetString();
|
||||
|
||||
if (reader.TokenType != JsonTokenType.StartArray)
|
||||
{
|
||||
reader.Skip();
|
||||
return null;
|
||||
}
|
||||
|
||||
// Block-Array: die text-Anteile zusammenführen.
|
||||
var parts = new List<string>();
|
||||
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
|
||||
{
|
||||
if (reader.TokenType != JsonTokenType.StartObject)
|
||||
{
|
||||
reader.Skip();
|
||||
continue;
|
||||
}
|
||||
|
||||
using var block = JsonDocument.ParseValue(ref reader);
|
||||
if (block.RootElement.TryGetProperty("text", out var text) &&
|
||||
text.GetString() is { } value)
|
||||
{
|
||||
parts.Add(value);
|
||||
}
|
||||
}
|
||||
|
||||
return parts.Count > 0 ? string.Join("", parts) : null;
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, ChatMessage value, JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
writer.WriteString("role", value.Role);
|
||||
|
||||
if (value.Content is not null)
|
||||
{
|
||||
if (value.CacheBreakpoint)
|
||||
{
|
||||
// [{ "type": "text", "text": "…", "cache_control": { "type": "ephemeral" } }]
|
||||
writer.WriteStartArray("content");
|
||||
writer.WriteStartObject();
|
||||
writer.WriteString("type", "text");
|
||||
writer.WriteString("text", value.Content);
|
||||
writer.WriteStartObject("cache_control");
|
||||
writer.WriteString("type", "ephemeral");
|
||||
writer.WriteEndObject();
|
||||
writer.WriteEndObject();
|
||||
writer.WriteEndArray();
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteString("content", value.Content);
|
||||
}
|
||||
}
|
||||
|
||||
if (value.ToolCalls is { Count: > 0 })
|
||||
{
|
||||
writer.WritePropertyName("tool_calls");
|
||||
JsonSerializer.Serialize(writer, value.ToolCalls, options);
|
||||
}
|
||||
|
||||
if (value.ToolCallId is not null)
|
||||
writer.WriteString("tool_call_id", value.ToolCallId);
|
||||
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +42,23 @@ public sealed class Usage
|
||||
|
||||
[JsonPropertyName("total_tokens")]
|
||||
public int TotalTokens { get; set; }
|
||||
|
||||
[JsonPropertyName("prompt_tokens_details")]
|
||||
public PromptTokensDetails? PromptTokensDetails { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Anteil der Prompt-Tokens, der aus dem Cache gelesen wurde. Nur damit lässt sich
|
||||
/// belegen, ob das Prompt-Caching tatsächlich greift — ein still wirkungsloser
|
||||
/// Cache wäre sonst nicht zu bemerken.
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public int CachedTokens => PromptTokensDetails?.CachedTokens ?? 0;
|
||||
}
|
||||
|
||||
public sealed class PromptTokensDetails
|
||||
{
|
||||
[JsonPropertyName("cached_tokens")]
|
||||
public int CachedTokens { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ApiError
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
<RootNamespace>ClawdDotNet.Core</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="ClawdDotNet.Core.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.8" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.8" />
|
||||
|
||||
@@ -88,6 +88,24 @@ public sealed class AgentConfig
|
||||
|
||||
[JsonPropertyName("loopGuard")]
|
||||
public LoopGuardConfig LoopGuard { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Prompt-Caching: "auto" (Default), "on" oder "off".
|
||||
///
|
||||
/// Bei "auto" wird es für Modelle aktiviert, die cache_control unterstützen.
|
||||
/// Der Nutzen ist erheblich, weil jeder Schritt eines Runs den kompletten Prompt
|
||||
/// erneut sendet — System-Prompt und Tool-Definitionen also dutzendfach.
|
||||
/// </summary>
|
||||
[JsonPropertyName("promptCaching")]
|
||||
public string PromptCaching { get; set; } = "auto";
|
||||
|
||||
/// <summary>
|
||||
/// Maximale Länge eines einzelnen Tool-Ergebnisses in Zeichen, bevor es gekürzt in
|
||||
/// den Kontext wandert. Ohne Grenze kann ein einziger Abruf den gesamten Kontext
|
||||
/// sprengen (ein WebFetch mit 512 KB entspricht etwa 130.000 Tokens).
|
||||
/// </summary>
|
||||
[JsonPropertyName("maxToolResultChars")]
|
||||
public int MaxToolResultChars { get; set; } = 16_000;
|
||||
}
|
||||
|
||||
public sealed class SchedulerConfig
|
||||
@@ -137,6 +155,16 @@ public sealed class LoopGuardConfig
|
||||
[JsonPropertyName("compactionThreshold")]
|
||||
public double CompactionThreshold { get; set; } = 0.80;
|
||||
|
||||
/// <summary>
|
||||
/// Modell für die Zusammenfassung beim Kompaktieren. Leer = Modell des Agenten.
|
||||
///
|
||||
/// Zusammenfassen ist eine anspruchslose Aufgabe; sie mit einem teuren Modell zu
|
||||
/// erledigen kostet leicht mehr als der halbe Run, weil bis zu 30.000 Zeichen
|
||||
/// verarbeitet werden.
|
||||
/// </summary>
|
||||
[JsonPropertyName("summaryModel")]
|
||||
public string SummaryModel { get; set; } = "google/gemini-2.5-flash";
|
||||
|
||||
[JsonIgnore]
|
||||
public TimeSpan Timeout => TimeSpan.FromSeconds(TimeoutSeconds);
|
||||
}
|
||||
|
||||
@@ -109,13 +109,17 @@ public sealed class AgentEngine : IAgentMessageRouter
|
||||
messages.Add(ChatMessage.User(userMessage));
|
||||
|
||||
string? finalMessage = null;
|
||||
var totalTokens = 0;
|
||||
var tally = new TokenTally();
|
||||
var cachingEnabled = PromptCache.IsEnabledFor(agentConfig.PromptCaching, agentConfig.Model);
|
||||
|
||||
while (true)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
loopGuard.RecordStep();
|
||||
|
||||
if (cachingEnabled)
|
||||
PromptCache.ApplyBreakpoints(messages);
|
||||
|
||||
var request = new ChatRequest
|
||||
{
|
||||
Model = agentConfig.Model,
|
||||
@@ -128,7 +132,7 @@ public sealed class AgentEngine : IAgentMessageRouter
|
||||
var promptTokens = 0;
|
||||
if (response.Usage is not null)
|
||||
{
|
||||
totalTokens += response.Usage.TotalTokens;
|
||||
tally.Add(response.Usage);
|
||||
promptTokens = response.Usage.PromptTokens;
|
||||
loopGuard.RecordTokens(response.Usage.TotalTokens);
|
||||
}
|
||||
@@ -174,16 +178,21 @@ public sealed class AgentEngine : IAgentMessageRouter
|
||||
|
||||
sw.Stop();
|
||||
logger.LogInformation(
|
||||
"Agent run completed: {AgentId}, steps={Steps}, tokens={Tokens}, duration={Duration}ms",
|
||||
agentConfig.AgentId, loopGuard.Steps, totalTokens, sw.ElapsedMilliseconds);
|
||||
"Agent run completed: {AgentId}, steps={Steps}, tokens={Tokens} (davon {Cached} aus Cache), duration={Duration}ms",
|
||||
agentConfig.AgentId, loopGuard.Steps, tally.Total, tally.Cached, sw.ElapsedMilliseconds);
|
||||
|
||||
var result = new AgentRunResult(
|
||||
agentConfig.AgentId,
|
||||
AgentRunStatus.Completed,
|
||||
finalMessage,
|
||||
loopGuard.Steps,
|
||||
totalTokens,
|
||||
sw.Elapsed);
|
||||
tally.Total,
|
||||
sw.Elapsed)
|
||||
{
|
||||
PromptTokens = tally.Prompt,
|
||||
CompletionTokens = tally.Completion,
|
||||
CachedTokens = tally.Cached
|
||||
};
|
||||
OnRunCompleted?.Invoke(agentConfig.Model, result);
|
||||
return result;
|
||||
}
|
||||
@@ -318,13 +327,17 @@ public sealed class AgentEngine : IAgentMessageRouter
|
||||
AddChatEntry(agentConfig.AgentId, "user", userMessage, source);
|
||||
|
||||
string? finalMessage = null;
|
||||
var totalTokens = 0;
|
||||
var tally = new TokenTally();
|
||||
var cachingEnabled = PromptCache.IsEnabledFor(agentConfig.PromptCaching, agentConfig.Model);
|
||||
|
||||
while (true)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
loopGuard.RecordStep();
|
||||
|
||||
if (cachingEnabled)
|
||||
PromptCache.ApplyBreakpoints(messages);
|
||||
|
||||
var request = new ChatRequest
|
||||
{
|
||||
Model = agentConfig.Model,
|
||||
@@ -337,7 +350,7 @@ public sealed class AgentEngine : IAgentMessageRouter
|
||||
var promptTokens = 0;
|
||||
if (response.Usage is not null)
|
||||
{
|
||||
totalTokens += response.Usage.TotalTokens;
|
||||
tally.Add(response.Usage);
|
||||
promptTokens = response.Usage.PromptTokens;
|
||||
loopGuard.RecordTokens(response.Usage.TotalTokens);
|
||||
}
|
||||
@@ -386,7 +399,12 @@ public sealed class AgentEngine : IAgentMessageRouter
|
||||
sw.Stop();
|
||||
var result = new AgentRunResult(
|
||||
agentConfig.AgentId, AgentRunStatus.Completed, finalMessage,
|
||||
loopGuard.Steps, totalTokens, sw.Elapsed);
|
||||
loopGuard.Steps, tally.Total, sw.Elapsed)
|
||||
{
|
||||
PromptTokens = tally.Prompt,
|
||||
CompletionTokens = tally.Completion,
|
||||
CachedTokens = tally.Cached
|
||||
};
|
||||
OnRunCompleted?.Invoke(agentConfig.Model, result);
|
||||
return result;
|
||||
}
|
||||
@@ -786,9 +804,18 @@ public sealed class AgentEngine : IAgentMessageRouter
|
||||
|
||||
logger.LogDebug("Tool {Tool} completed: success={Success}", toolName, result.Success);
|
||||
|
||||
return result.Success
|
||||
? result.Content
|
||||
: JsonSerializer.Serialize(new { error = result.ErrorMessage });
|
||||
if (!result.Success)
|
||||
return JsonSerializer.Serialize(new { error = result.ErrorMessage });
|
||||
|
||||
var content = TruncateToolResult(result.Content, agentConfig.MaxToolResultChars);
|
||||
if (content.Length != result.Content.Length)
|
||||
{
|
||||
logger.LogInformation(
|
||||
"Tool-Ergebnis von {Tool} gekürzt: {Original} → {Limit} Zeichen",
|
||||
toolName, result.Content.Length, agentConfig.MaxToolResultChars);
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
catch (ToolAccessDeniedException ex)
|
||||
{
|
||||
@@ -808,6 +835,42 @@ public sealed class AgentEngine : IAgentMessageRouter
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sammelt die Token-Zahlen über alle Schritte eines Runs.</summary>
|
||||
private sealed class TokenTally
|
||||
{
|
||||
public int Total { get; private set; }
|
||||
public int Prompt { get; private set; }
|
||||
public int Completion { get; private set; }
|
||||
public int Cached { get; private set; }
|
||||
|
||||
public void Add(Usage usage)
|
||||
{
|
||||
Total += usage.TotalTokens;
|
||||
Prompt += usage.PromptTokens;
|
||||
Completion += usage.CompletionTokens;
|
||||
Cached += usage.CachedTokens;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kürzt ein Tool-Ergebnis, bevor es in den Kontext wandert.
|
||||
///
|
||||
/// Ohne diese Grenze kann ein einzelner Aufruf den Kontext sprengen — ein WebFetch
|
||||
/// mit dem Standardlimit von 512 KB entspricht rund 130.000 Tokens in EINER
|
||||
/// Tool-Antwort. Die Compaction greift erst danach, der teure Request ist zu dem
|
||||
/// Zeitpunkt längst bezahlt.
|
||||
/// </summary>
|
||||
internal static string TruncateToolResult(string result, int maxChars)
|
||||
{
|
||||
if (maxChars <= 0 || result.Length <= maxChars)
|
||||
return result;
|
||||
|
||||
var omitted = result.Length - maxChars;
|
||||
return result[..maxChars] +
|
||||
$"\n\n[… {omitted:N0} Zeichen gekürzt. Das Ergebnis war zu groß für den Kontext. " +
|
||||
"Grenze die Abfrage ein, wenn du den Rest brauchst.]";
|
||||
}
|
||||
|
||||
private static List<ToolDefinition> BuildToolDefinitions(IReadOnlyList<IAgentTool> tools)
|
||||
{
|
||||
return tools.Select(t => new ToolDefinition
|
||||
|
||||
@@ -8,7 +8,20 @@ public sealed record AgentRunResult(
|
||||
int TokensUsed,
|
||||
TimeSpan Duration,
|
||||
Exception? Error = null
|
||||
);
|
||||
)
|
||||
{
|
||||
/// <summary>Summe der Eingabe-Tokens über alle Schritte des Runs.</summary>
|
||||
public int PromptTokens { get; init; }
|
||||
|
||||
/// <summary>Summe der Ausgabe-Tokens über alle Schritte des Runs.</summary>
|
||||
public int CompletionTokens { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Anteil der Eingabe-Tokens, der aus dem Prompt-Cache kam. Diese Tokens sind bereits
|
||||
/// in <see cref="PromptTokens"/> enthalten, kosten aber nur einen Bruchteil.
|
||||
/// </summary>
|
||||
public int CachedTokens { get; init; }
|
||||
}
|
||||
|
||||
public enum AgentRunStatus
|
||||
{
|
||||
|
||||
@@ -69,8 +69,12 @@ public sealed class ContextCompactor
|
||||
return true;
|
||||
}
|
||||
|
||||
// Stufe 2: Auto-Compaction via LLM
|
||||
await CompactViaLlmAsync(messages, model, ct);
|
||||
// Stufe 2: Auto-Compaction via LLM — bewusst mit dem günstigen Modell.
|
||||
var summaryModel = string.IsNullOrWhiteSpace(guard.SummaryModel)
|
||||
? model
|
||||
: guard.SummaryModel;
|
||||
|
||||
await CompactViaLlmAsync(messages, summaryModel, ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
using ClawdDotNet.Core.Api.Models;
|
||||
|
||||
namespace ClawdDotNet.Core.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// Setzt Prompt-Caching-Breakpoints in die Nachrichtenliste.
|
||||
///
|
||||
/// Hintergrund: In einem Agenten-Run wird bei JEDEM Schritt der komplette Prompt erneut
|
||||
/// gesendet und voll berechnet — inklusive Tool-Definitionen und System-Prompt, die sich
|
||||
/// nie ändern. Bei zehn Schritten und einem 15k-Präfix sind das 150.000 Eingabe-Tokens
|
||||
/// statt 15.000.
|
||||
///
|
||||
/// Ein Breakpoint markiert das Ende eines stabilen Prompt-Abschnitts. Alles davor wird
|
||||
/// beim nächsten Aufruf aus dem Cache gelesen und kostet nur einen Bruchteil.
|
||||
///
|
||||
/// Zwei Breakpoints werden gesetzt:
|
||||
/// 1. auf den System-Prompt — deckt Tool-Definitionen und System-Prompt ab,
|
||||
/// 2. rollierend auf die letzte Nachricht — deckt den bereits gelaufenen Gesprächsverlauf ab.
|
||||
/// </summary>
|
||||
public static class PromptCache
|
||||
{
|
||||
/// <summary>
|
||||
/// Modelle, bei denen "auto" das Caching einschaltet. Andere Anbieter ignorieren
|
||||
/// cache_control entweder oder cachen ohnehin automatisch.
|
||||
/// </summary>
|
||||
private static readonly string[] AutoEnabledPrefixes = ["anthropic/"];
|
||||
|
||||
public static bool IsEnabledFor(string setting, string model) => setting?.ToLowerInvariant() switch
|
||||
{
|
||||
"on" => true,
|
||||
"off" => false,
|
||||
_ => AutoEnabledPrefixes.Any(p => model.StartsWith(p, StringComparison.OrdinalIgnoreCase))
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Setzt die Breakpoints neu. Vorherige werden entfernt, damit sich pro Schritt
|
||||
/// nie mehr als die beabsichtigten Markierungen ansammeln.
|
||||
/// </summary>
|
||||
public static void ApplyBreakpoints(List<ChatMessage> messages)
|
||||
{
|
||||
foreach (var msg in messages)
|
||||
msg.CacheBreakpoint = false;
|
||||
|
||||
if (messages.Count == 0)
|
||||
return;
|
||||
|
||||
// 1. System-Prompt — der stabilste Teil überhaupt.
|
||||
var system = messages[0].Role == "system" ? messages[0] : null;
|
||||
if (system?.Content is not null)
|
||||
system.CacheBreakpoint = true;
|
||||
|
||||
// 2. Letzte Nachricht mit Inhalt. Beim nächsten Schritt ist alles bis hierher
|
||||
// unverändert und wird aus dem Cache gelesen.
|
||||
// Eine assistant-Nachricht mit tool_calls hat keinen Textinhalt und kann
|
||||
// deshalb keinen Block tragen — in dem Fall bleibt es beim System-Breakpoint.
|
||||
for (var i = messages.Count - 1; i >= 1; i--)
|
||||
{
|
||||
if (messages[i].Content is null)
|
||||
continue;
|
||||
|
||||
if (!ReferenceEquals(messages[i], system))
|
||||
messages[i].CacheBreakpoint = true;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -326,13 +326,16 @@ public sealed class AgentEditorTool : IAgentTool
|
||||
tools = new Dictionary<string, object>(),
|
||||
scheduler = (object?)null,
|
||||
toolJobs = Array.Empty<object>(),
|
||||
promptCaching = "auto",
|
||||
maxToolResultChars = 16000,
|
||||
loopGuard = new
|
||||
{
|
||||
maxSteps = 20,
|
||||
maxCumulativeTokens = 500000,
|
||||
timeoutSeconds = 600,
|
||||
maxContextTokens = 100000,
|
||||
compactionThreshold = 0.8
|
||||
compactionThreshold = 0.8,
|
||||
summaryModel = "google/gemini-2.5-flash"
|
||||
}
|
||||
};
|
||||
await File.WriteAllTextAsync(
|
||||
|
||||
Reference in New Issue
Block a user