Update countTokens.ts
This commit is contained in:
parent
9c8ea71a9b
commit
6fd01351a5
1 changed files with 30 additions and 7 deletions
|
|
@ -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,
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue