From 6fd01351a5678f24add945537616b28453a46cc1 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 9 Jul 2025 15:56:02 -0700 Subject: [PATCH] Update countTokens.ts --- core/llm/countTokens.ts | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 78159c9cf..5030fe224 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -376,13 +376,36 @@ function pruneRawPromptFromTop( return pruneStringFromTop(modelName, maxTokens, prompt); } -/* - Goal: reconcile chat messages with available context length - Guidelines: - - Always keep last user message, system message, and tools - - Never allow tool output without the corresponding tool call - - Remove older messages first -*/ +/** + * Reconciles chat messages with available context length by intelligently pruning older messages + * while preserving critical conversation elements. + * + * Core Guidelines: + * - Always preserve the last user/tool message sequence (including any associated assistant message with tool calls) + * - Always preserve the system message and tools + * - Never allow orphaned tool responses without their corresponding tool calls + * - Remove older messages first when pruning is necessary + * - Maintain conversation coherence by flattening adjacent similar messages + * + * Process: + * 1. Handle image content conversion for models that don't support images + * 2. Extract and preserve system message + * 3. Filter out empty messages and trailing non-user/tool messages + * 4. Extract the complete tool sequence from the end (user message or assistant + tool responses) + * 5. Calculate token requirements for non-negotiable elements (system, tools, last sequence) + * 6. Prune older messages until within available token budget + * 7. Reassemble with proper ordering and flatten adjacent similar messages + * + * @param params - Configuration object containing: + * - modelName: LLM model name for token counting + * - msgs: Array of chat messages to process + * - contextLength: Maximum context length supported by the model + * - maxTokens: Maximum tokens to reserve for the response + * - supportsImages: Whether the model supports image content + * - tools: Optional array of available tools + * @returns Processed array of chat messages that fit within context constraints + * @throws Error if non-negotiable elements exceed available context + */ function compileChatMessages({ modelName, msgs,