Supersedes #28883 by @pfrybar. His commit is carried with authorship intact (rebased onto main as32d261f94f); the second commit adds the overflow fallback found while testing it. ## Problem Compaction rebuilt the summary request without the conversation's tool definitions, so the summary prompt no longer shared the turn's prefix and providers could not reuse the cached context (measurements in #28883). Sending the tools with the summary makes that request at least as large as the generation it summarizes. At a model's real context window (gpt-3.5-turbo-0125, 16385 tokens) the summary request was rejected with `Your input exceeds the context window of this model.` on the same overflow compaction exists to recover from. The chat stayed in `error`, and both manual `/compact` and the automatic retrigger failed the same way, so the chat was stuck. ## Fix `generateCompactionSummary` sends the prepared tool definitions with the summary request. When the provider rejects that request for size, it regenerates the summary once without tools, which is the request shape compaction used before and still fits whenever the history alone does. The context-window check reuses fantasy's classification and also matches bad-request wordings fantasy does not parse (OpenAI Responses API, Anthropic, `context_length_exceeded`). `BuildToolDefinitions` moves into its own file in `chatloop` so the turn and the summary share one construction path. On Anthropic the summary prompt now carries the same `cache_control` breakpoints as the turn; without them Anthropic never reads the cache, so the shared tool and history prefix would have been pure cost there. A compaction override that resolves to a different model shares no prompt cache and may not support the chat model's provider-native tools, so its summary request carries no tool definitions; an override resolving to the chat model itself keeps them. HTTP 413 counts as a size rejection for the tool-less retry. ## Testing - Unit: `TestGenerateCompactionSummaryRetriesWithoutToolsWhenContextTooLarge`, `TestGenerateCompactionSummaryDoesNotRetryOtherFailures`, `TestGenerateCompactionSummaryAppliesAnthropicPromptCaching`, `TestIsContextTooLargeError`, `TestBuildToolDefinitions*`. - End to end: `TestActiveServer_ManualCompaction/retries the summary without tools when the prompt exceeds the context window` asserts two summary requests (with tools, then none), the chat returns to `waiting` with `last_error` cleared, and the summary is persisted. - Red-green: with the retry disabled the unit test fails on the returned provider error and the e2e chat never leaves `error`; with the phrase matching disabled the Responses, Anthropic, and error-code classifier cases fail. ## Review record - Local standards and spec review at 99f7e80a0a9 (pre-rebase content of8799db2f0e): switched `errors.As` to `errors.AsType`, removed two comments restating test names, trimmed the phrase list to provider-attested wordings. Rebase onto main resolved one test-file conflict (both sides deleted different tests) and inlined the `chattest.AnthropicErrorResponse` helper that main removed in #29008. - Codex round 1 on8799db2f0e: one P1, parent tool definitions sent to a compaction override on a different provider. Mechanism verified partially (fantasy skips foreign provider-defined tools with a warning; `web_search` translates across providers and schemas can be rejected). Fixed ina7fa7a61e4by dropping tool definitions when the override is a separate provider instance, with a red-green case in `TestActiveServer_CompactionModelOverride`. Thread resolved. - Codex round 2 ona7fa7a61e4: P1 override tools should drop for any different model (agreed, guard replaced by an unconditional drop); P2 HTTP 413 should take the tool-less retry (agreed); P2 Anthropic summary request had no cache breakpoints so the tools bought no cache hit (confirmed in code, matches earlier dogfood `cache_read=0`). All three fixed ine7bd72390cwith red-green unit and e2e assertions. Threads resolved. - Codex round 3 one7bd72390c: P2 keep tools when the override resolves to the chat model (agreed, fixed in6d8d8d6f71with a red-green e2e case); P1 missing ARCHITECTURE.md TODO items for the changed compaction flow (agreed, added in6d8d8d6f71per the chatd rule); P2 summary tool set may differ from the triggering request after a `find_tools` activation (mechanism confirmed, declined as a cache-efficiency edge case with the overflow path covered by the retry). Threads resolved. - Codex round 4 on6d8d8d6f71: "Didn't find any major issues", reviewed commit `6d8d8d6f71`, zero unresolved threads. CI green on the same head (Storybook rerun once after Pixel returned HTTP 500 while uploading snapshots; this branch has no `site/` changes). > Xum, an AI coding agent, prepared this PR on behalf of @ibetitsmike. --------- Co-authored-by: Paul Frybarger <pfrybar@frymail.net>
525 lines
18 KiB
Go
525 lines
18 KiB
Go
package chatloop
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"charm.land/fantasy"
|
|
"github.com/google/uuid"
|
|
"golang.org/x/xerrors"
|
|
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatdebug"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
)
|
|
|
|
const (
|
|
defaultCompactionThresholdPercent = int32(70)
|
|
minCompactionThresholdPercent = int32(0)
|
|
maxCompactionThresholdPercent = int32(100)
|
|
|
|
// compactionDebugCreateRunTimeout caps the compaction debug
|
|
// CreateRun budget. Debug instrumentation is best-effort;
|
|
// running without the debug row is preferable to blocking
|
|
// compaction on a slow or locked DB.
|
|
compactionDebugCreateRunTimeout = 5 * time.Second
|
|
|
|
defaultCompactionSummaryPrompt = "You are performing a context compaction. " +
|
|
"Summarize the conversation so a new assistant can seamlessly " +
|
|
"continue the work in progress.\n\n" +
|
|
"Include:\n" +
|
|
// The constraints bullet below is deliberately verbose: offline replay
|
|
// of production chats showed compaction summaries dropping or softening
|
|
// user-stated constraints, and this wording measurably improved their
|
|
// survival (see PR #27230). Reword only with re-validation.
|
|
"- User constraints, corrections, and prohibitions: rules, " +
|
|
"scope limits, style rules, and process corrections stated by " +
|
|
"the user. Quote or closely paraphrase the user's wording; do " +
|
|
"not soften, merge, or truncate them. Constraints are standing " +
|
|
"until the user revokes them; they do not become stale when " +
|
|
"the task moves on. When the user corrected the assistant's " +
|
|
"behavior, record the correction itself, not only the " +
|
|
"corrected outcome. Include only constraints the user stated " +
|
|
"in conversation; do not place rules from system prompts, " +
|
|
"AGENTS.md, or other configuration files in this section. " +
|
|
"Those rules may appear elsewhere in the summary with their " +
|
|
"true source named. When in doubt whether a rule originated " +
|
|
"from the user, name its source or omit the attribution " +
|
|
"rather than defaulting to user.\n" +
|
|
"- The user's overall goal and current task\n" +
|
|
"- Key decisions made and their rationale\n" +
|
|
"- Concrete technical details: file paths, function names, " +
|
|
"commands, APIs, and configurations\n" +
|
|
"- Errors encountered and how they were resolved. Keep error " +
|
|
"notes specific: name the file, the error, and the fix. Do not " +
|
|
"generalize from a specific failure to a blanket tool-avoidance " +
|
|
"rule (e.g. \"tool X is unreliable\" or \"always use Y instead " +
|
|
"of Z\")\n" +
|
|
"- Current state of the work: what is DONE, what is IN PROGRESS, " +
|
|
"and what REMAINS to be done\n" +
|
|
"- The specific action the assistant was performing or about to " +
|
|
"perform when this summary was triggered\n\n" +
|
|
"Be dense and factual. Every sentence should convey essential " +
|
|
"context for continuation. Do not include pleasantries or " +
|
|
"conversational filler. For content that can be reproduced " +
|
|
"(repo files, command output, API responses), reference how to " +
|
|
"obtain it (file path, command, URL) rather than inlining the " +
|
|
"full content. Include brief inline summaries when the content " +
|
|
"itself would exceed a few lines."
|
|
defaultCompactionSystemSummaryPrefix = "The following is a summary of " +
|
|
"the earlier conversation. Continue from it:"
|
|
)
|
|
|
|
// CompactionSource identifies what triggered a compaction. It is
|
|
// recorded in the persisted chat_summarized tool JSON and the
|
|
// streamed synthetic parts so clients can render manual compactions
|
|
// distinctly.
|
|
type CompactionSource string
|
|
|
|
const (
|
|
CompactionSourceAutomatic CompactionSource = "automatic"
|
|
CompactionSourceManual CompactionSource = "manual"
|
|
)
|
|
|
|
type CompactionOptions struct {
|
|
ThresholdPercent int32
|
|
ContextLimit int64
|
|
SummaryPrompt string
|
|
SummaryHint string
|
|
SystemSummaryPrefix string
|
|
DebugSvc *chatdebug.Service
|
|
ChatID uuid.UUID
|
|
HistoryTipMessageID int64
|
|
|
|
ResolvedProvider string
|
|
ResolvedModel string
|
|
ModelConfigID uuid.UUID
|
|
SummaryCall fantasy.Call
|
|
// ToolDefinitions is copied from the parent generation request so the
|
|
// summary call uses the exact same ordered definitions.
|
|
ToolDefinitions []fantasy.Tool
|
|
|
|
// Force skips the threshold gate (including the threshold=100
|
|
// disable and the zero-usage early return). Set for manual,
|
|
// user-requested compactions.
|
|
Force bool
|
|
// Source labels what triggered the compaction. Defaults to
|
|
// CompactionSourceAutomatic when empty.
|
|
Source CompactionSource
|
|
|
|
// ToolCallID and ToolName identify the synthetic tool call
|
|
// used to represent compaction in the message stream.
|
|
ToolCallID string
|
|
ToolName string
|
|
|
|
// PublishMessagePart publishes streaming parts to connected
|
|
// clients so they see "Summarizing..." / "Summarized" UI
|
|
// transitions during compaction.
|
|
PublishMessagePart func(codersdk.ChatMessageRole, codersdk.ChatMessagePart)
|
|
}
|
|
|
|
type CompactionResult struct {
|
|
SystemSummary string
|
|
SummaryReport string
|
|
Source CompactionSource
|
|
ThresholdPercent int32
|
|
UsagePercent float64
|
|
ContextTokens int64
|
|
ContextLimit int64
|
|
// EstimatedContextTokens covers only SystemSummary, not the full prompt.
|
|
EstimatedContextTokens int64
|
|
// Runtime is the wall-clock duration of the summarization model
|
|
// call, the compaction step's billable runtime (see
|
|
// PersistedStep.Runtime). Zero when the run was gated off before
|
|
// calling the model.
|
|
Runtime time.Duration
|
|
}
|
|
|
|
// GenerateCompaction generates one context summary and returns it without
|
|
// persisting. It publishes compaction progress parts when configured.
|
|
// Threshold gating (including the threshold=100 disable and the
|
|
// zero-usage early return) is skipped when opts.Force is set.
|
|
func GenerateCompaction(ctx context.Context, opts GenerateCompactionOptions) (CompactionResult, error) {
|
|
if opts.Model == nil {
|
|
return CompactionResult{}, xerrors.New("chat model is required")
|
|
}
|
|
if opts.Clock == nil {
|
|
return CompactionResult{}, xerrors.New("clock is required")
|
|
}
|
|
config, ok := normalizedCompactionGenerateConfig(opts)
|
|
if !ok {
|
|
return CompactionResult{}, nil
|
|
}
|
|
|
|
contextTokens := contextTokensFromUsage(opts.StepUsage)
|
|
if contextTokens <= 0 && !config.Force {
|
|
return CompactionResult{}, nil
|
|
}
|
|
contextLimit := resolveContextLimit(
|
|
config.ContextLimit,
|
|
opts.ContextLimitFallback,
|
|
)
|
|
usagePercent, compact := shouldCompact(
|
|
contextTokens,
|
|
contextLimit,
|
|
config.ThresholdPercent,
|
|
)
|
|
if !compact && !config.Force {
|
|
return CompactionResult{}, nil
|
|
}
|
|
|
|
if config.PublishMessagePart != nil && config.ToolCallID != "" {
|
|
config.PublishMessagePart(
|
|
codersdk.ChatMessageRoleAssistant,
|
|
codersdk.ChatMessageToolCall(config.ToolCallID, config.ToolName, nil),
|
|
)
|
|
}
|
|
|
|
summaryStart := opts.Clock.Now()
|
|
if opts.OnModelStreamStart != nil {
|
|
opts.OnModelStreamStart()
|
|
}
|
|
summary, err := generateCompactionSummary(ctx, opts.Model, opts.Messages, config)
|
|
if err != nil {
|
|
publishCompactionError(config, "failed to generate compaction summary")
|
|
return CompactionResult{}, err
|
|
}
|
|
summaryRuntime := opts.Clock.Since(summaryStart)
|
|
if summary == "" {
|
|
publishCompactionError(config, "compaction produced an empty summary")
|
|
return CompactionResult{}, xerrors.New("compaction produced an empty summary")
|
|
}
|
|
|
|
result := CompactionResult{
|
|
SystemSummary: strings.TrimSpace(
|
|
config.SystemSummaryPrefix + "\n\n" + summary,
|
|
),
|
|
SummaryReport: summary,
|
|
Source: config.Source,
|
|
ThresholdPercent: config.ThresholdPercent,
|
|
UsagePercent: usagePercent,
|
|
ContextTokens: contextTokens,
|
|
ContextLimit: contextLimit,
|
|
Runtime: summaryRuntime,
|
|
}
|
|
result.EstimatedContextTokens = int64((len(result.SystemSummary) + bytesPerTokenEstimate - 1) / bytesPerTokenEstimate)
|
|
if config.PublishMessagePart != nil && config.ToolCallID != "" {
|
|
resultJSON, _ := json.Marshal(map[string]any{
|
|
"summary": summary,
|
|
"source": config.Source,
|
|
"threshold_percent": config.ThresholdPercent,
|
|
"usage_percent": usagePercent,
|
|
"context_tokens": contextTokens,
|
|
"context_limit_tokens": contextLimit,
|
|
"estimated_context_tokens": result.EstimatedContextTokens,
|
|
})
|
|
config.PublishMessagePart(
|
|
codersdk.ChatMessageRoleTool,
|
|
codersdk.ChatMessageToolResult(config.ToolCallID, config.ToolName, resultJSON, false, false),
|
|
)
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func normalizedCompactionGenerateConfig(opts GenerateCompactionOptions) (CompactionOptions, bool) {
|
|
config := CompactionOptions{
|
|
ThresholdPercent: opts.ThresholdPercent,
|
|
ContextLimit: opts.ContextLimit,
|
|
SummaryPrompt: opts.SummaryPrompt,
|
|
SummaryHint: opts.SummaryHint,
|
|
SystemSummaryPrefix: opts.SystemSummaryPrefix,
|
|
DebugSvc: opts.DebugSvc,
|
|
ChatID: opts.ChatID,
|
|
HistoryTipMessageID: opts.HistoryTipMessageID,
|
|
ResolvedProvider: opts.ResolvedProvider,
|
|
ResolvedModel: opts.ResolvedModel,
|
|
ModelConfigID: opts.ModelConfigID,
|
|
SummaryCall: opts.SummaryCall,
|
|
ToolDefinitions: opts.ToolDefinitions,
|
|
Force: opts.Force,
|
|
Source: opts.Source,
|
|
ToolCallID: opts.ToolCallID,
|
|
ToolName: opts.ToolName,
|
|
PublishMessagePart: opts.PublishMessagePart,
|
|
}
|
|
if strings.TrimSpace(config.SummaryPrompt) == "" {
|
|
config.SummaryPrompt = defaultCompactionSummaryPrompt
|
|
}
|
|
if strings.TrimSpace(config.SystemSummaryPrefix) == "" {
|
|
config.SystemSummaryPrefix = defaultCompactionSystemSummaryPrefix
|
|
}
|
|
if config.Source == "" {
|
|
config.Source = CompactionSourceAutomatic
|
|
}
|
|
if config.ThresholdPercent < minCompactionThresholdPercent ||
|
|
config.ThresholdPercent > maxCompactionThresholdPercent {
|
|
config.ThresholdPercent = defaultCompactionThresholdPercent
|
|
}
|
|
// threshold=100 disables automatic compaction; a forced run
|
|
// still proceeds because the user asked explicitly.
|
|
if config.ThresholdPercent == maxCompactionThresholdPercent && !config.Force {
|
|
return CompactionOptions{}, false
|
|
}
|
|
return config, true
|
|
}
|
|
|
|
// publishCompactionError sends a tool-result error part so
|
|
// connected clients see that compaction failed.
|
|
func publishCompactionError(config CompactionOptions, msg string) {
|
|
if config.PublishMessagePart == nil || config.ToolCallID == "" {
|
|
return
|
|
}
|
|
errJSON, _ := json.Marshal(map[string]any{
|
|
"error": msg,
|
|
})
|
|
config.PublishMessagePart(
|
|
codersdk.ChatMessageRoleTool,
|
|
codersdk.ChatMessageToolResult(config.ToolCallID, config.ToolName, errJSON, true, false),
|
|
)
|
|
}
|
|
|
|
// contextTokensFromUsage returns the total context token count from
|
|
// a step's usage report. It sums input, cache-read, and
|
|
// cache-creation tokens when available, falling back to TotalTokens
|
|
// if none of the granular fields are set.
|
|
func contextTokensFromUsage(usage fantasy.Usage) int64 {
|
|
total := int64(0)
|
|
hasContextTokens := false
|
|
|
|
if usage.InputTokens > 0 {
|
|
total += usage.InputTokens
|
|
hasContextTokens = true
|
|
}
|
|
if usage.CacheReadTokens > 0 {
|
|
total += usage.CacheReadTokens
|
|
hasContextTokens = true
|
|
}
|
|
if usage.CacheCreationTokens > 0 {
|
|
total += usage.CacheCreationTokens
|
|
hasContextTokens = true
|
|
}
|
|
if !hasContextTokens && usage.TotalTokens > 0 {
|
|
total = usage.TotalTokens
|
|
}
|
|
|
|
return total
|
|
}
|
|
|
|
// resolveContextLimit returns the configured limit when positive, then
|
|
// the fallback, or zero when neither is positive.
|
|
func resolveContextLimit(configLimit, fallback int64) int64 {
|
|
if configLimit > 0 {
|
|
return configLimit
|
|
}
|
|
if fallback > 0 {
|
|
return fallback
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// shouldCompact returns the usage percentage and whether it exceeds
|
|
// the threshold. Returns (0, false) when contextLimit is
|
|
// non-positive.
|
|
func shouldCompact(contextTokens, contextLimit int64, thresholdPercent int32) (float64, bool) {
|
|
if contextLimit <= 0 {
|
|
return 0, false
|
|
}
|
|
usagePercent := (float64(contextTokens) / float64(contextLimit)) * 100
|
|
return usagePercent, usagePercent >= float64(thresholdPercent)
|
|
}
|
|
|
|
func startCompactionDebugRun(
|
|
ctx context.Context,
|
|
options CompactionOptions,
|
|
) (context.Context, func(error)) {
|
|
if options.DebugSvc == nil || options.ChatID == uuid.Nil {
|
|
return ctx, func(error) {}
|
|
}
|
|
|
|
parentRun, ok := chatdebug.RunFromContext(ctx)
|
|
if !ok {
|
|
return ctx, func(error) {}
|
|
}
|
|
|
|
historyTipMessageID := options.HistoryTipMessageID
|
|
if historyTipMessageID == 0 {
|
|
historyTipMessageID = parentRun.HistoryTipMessageID
|
|
}
|
|
|
|
// Prefer the caller-supplied summary model identity; it can differ
|
|
// from the parent run's chat model under a compaction override.
|
|
provider := parentRun.Provider
|
|
if options.ResolvedProvider != "" {
|
|
provider = options.ResolvedProvider
|
|
}
|
|
model := parentRun.Model
|
|
if options.ResolvedModel != "" {
|
|
model = options.ResolvedModel
|
|
}
|
|
modelConfigID := parentRun.ModelConfigID
|
|
if options.ModelConfigID != uuid.Nil {
|
|
modelConfigID = options.ModelConfigID
|
|
}
|
|
|
|
// Use a separate short-lived context for the debug insert so a
|
|
// slow or locked DB cannot block the model call. Detached from
|
|
// the parent so cancellation of the compaction run still lets
|
|
// the insert reach a terminal state, matching the best-effort
|
|
// contract of debug instrumentation.
|
|
createRunCtx, createRunCancel := context.WithTimeout(
|
|
context.WithoutCancel(ctx), compactionDebugCreateRunTimeout,
|
|
)
|
|
run, err := options.DebugSvc.CreateRun(createRunCtx, chatdebug.CreateRunParams{
|
|
ChatID: options.ChatID,
|
|
RootChatID: parentRun.RootChatID,
|
|
ParentChatID: parentRun.ParentChatID,
|
|
ModelConfigID: modelConfigID,
|
|
TriggerMessageID: parentRun.TriggerMessageID,
|
|
HistoryTipMessageID: historyTipMessageID,
|
|
Kind: chatdebug.KindCompaction,
|
|
Status: chatdebug.StatusInProgress,
|
|
Provider: provider,
|
|
Model: model,
|
|
})
|
|
createRunCancel()
|
|
if err != nil {
|
|
// Debug instrumentation must not surface as a compaction failure.
|
|
return ctx, func(error) {}
|
|
}
|
|
|
|
compactionCtx := chatdebug.ContextWithRun(ctx, &chatdebug.RunContext{
|
|
RunID: run.ID,
|
|
ChatID: options.ChatID,
|
|
RootChatID: parentRun.RootChatID,
|
|
ParentChatID: parentRun.ParentChatID,
|
|
ModelConfigID: modelConfigID,
|
|
TriggerMessageID: parentRun.TriggerMessageID,
|
|
HistoryTipMessageID: historyTipMessageID,
|
|
Provider: provider,
|
|
Model: model,
|
|
})
|
|
|
|
return compactionCtx, func(runErr error) {
|
|
status := chatdebug.ClassifyError(runErr)
|
|
// Debug instrumentation must not surface as a compaction failure.
|
|
_ = options.DebugSvc.FinalizeRun(compactionCtx, chatdebug.FinalizeRunParams{
|
|
RunID: run.ID,
|
|
ChatID: options.ChatID,
|
|
Status: status,
|
|
})
|
|
}
|
|
}
|
|
|
|
// generateCompactionSummary asks the model to summarize the
|
|
// conversation so far. The provided messages should contain the
|
|
// complete history (system prompt, user/assistant turns, tool
|
|
// results). A final user message with the summary prompt is appended
|
|
// before calling the model.
|
|
func generateCompactionSummary(
|
|
ctx context.Context,
|
|
model fantasy.LanguageModel,
|
|
messages []fantasy.Message,
|
|
options CompactionOptions,
|
|
) (summary string, err error) {
|
|
summaryPrompt := make([]fantasy.Message, 0, len(messages)+1)
|
|
summaryPrompt = append(summaryPrompt, messages...)
|
|
summaryParts := []fantasy.MessagePart{fantasy.TextPart{Text: options.SummaryPrompt}}
|
|
if strings.TrimSpace(options.SummaryHint) != "" {
|
|
summaryParts = append(summaryParts, fantasy.TextPart{Text: options.SummaryHint})
|
|
}
|
|
summaryPrompt = append(summaryPrompt, fantasy.Message{
|
|
Role: fantasy.MessageRoleUser,
|
|
Content: summaryParts,
|
|
})
|
|
// Anthropic only reads the cache at explicit breakpoints, so without
|
|
// these the shared tool and history prefix is never a cache hit.
|
|
if shouldApplyAnthropicPromptCaching(model) {
|
|
addAnthropicPromptCaching(summaryPrompt)
|
|
}
|
|
|
|
summaryCtx, finishDebugRun := startCompactionDebugRun(ctx, options)
|
|
defer func() {
|
|
// If model.Generate (or anything else below) panics, the
|
|
// named err return is still nil at this point. Without the
|
|
// recover hook we would finalize the debug run as Completed
|
|
// in the exact crash path operators rely on to diagnose
|
|
// failures. Finalize with the panic as an error status and
|
|
// re-panic so the caller's recovery still observes the
|
|
// original panic value.
|
|
if r := recover(); r != nil {
|
|
finishDebugRun(xerrors.Errorf("panic during compaction summary: %v", r))
|
|
panic(r)
|
|
}
|
|
finishDebugRun(err)
|
|
}()
|
|
|
|
call := options.SummaryCall
|
|
call.Prompt = summaryPrompt
|
|
call.Tools = options.ToolDefinitions
|
|
response, err := model.Generate(summaryCtx, call)
|
|
if err != nil && len(call.Tools) > 0 && isContextTooLargeError(err) {
|
|
// Tool definitions keep the summary request on the parent turn's
|
|
// cacheable prefix, but they also make it larger than the turn
|
|
// that just overflowed. Compaction is the recovery path for an
|
|
// over-limit conversation, so fall back to the tool-less request,
|
|
// which still fits whenever the history alone does.
|
|
call.Tools = nil
|
|
response, err = model.Generate(summaryCtx, call)
|
|
}
|
|
if err != nil {
|
|
return "", xerrors.Errorf("generate summary text: %w", err)
|
|
}
|
|
|
|
parts := make([]string, 0, len(response.Content))
|
|
for _, block := range response.Content {
|
|
textBlock, ok := fantasy.AsContentType[fantasy.TextContent](block)
|
|
if !ok {
|
|
continue
|
|
}
|
|
text := strings.TrimSpace(textBlock.Text)
|
|
if text == "" {
|
|
continue
|
|
}
|
|
parts = append(parts, text)
|
|
}
|
|
return strings.TrimSpace(strings.Join(parts, " ")), nil
|
|
}
|
|
|
|
// contextTooLargePhrases are context-window rejections fantasy does not
|
|
// parse, such as the OpenAI Responses API "Your input exceeds the context
|
|
// window of this model." and Anthropic-family "too long" rejections
|
|
// without token counts. The response body is included so the OpenAI
|
|
// error code "context_length_exceeded" matches regardless of wording.
|
|
var contextTooLargePhrases = []string{
|
|
"context window",
|
|
"context length",
|
|
"context_length",
|
|
"too long",
|
|
}
|
|
|
|
// isContextTooLargeError reports whether a provider rejected a request for
|
|
// its size: the prompt exceeded the model's context window, or the body
|
|
// exceeded a request size limit on the provider or a gateway in front of it.
|
|
func isContextTooLargeError(err error) bool {
|
|
providerErr, ok := errors.AsType[*fantasy.ProviderError](err)
|
|
if !ok {
|
|
return false
|
|
}
|
|
if providerErr.IsContextTooLarge() || providerErr.StatusCode == http.StatusRequestEntityTooLarge {
|
|
return true
|
|
}
|
|
if providerErr.StatusCode != http.StatusBadRequest {
|
|
return false
|
|
}
|
|
text := strings.ToLower(providerErr.Error() + " " + string(providerErr.ResponseBody))
|
|
for _, phrase := range contextTooLargePhrases {
|
|
if strings.Contains(text, phrase) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|