Improve system message token accounting in compaction and context validation

This commit is contained in:
Nate 2025-12-01 14:25:50 -08:00
parent 5ec8d74fc8
commit 0d25d2e70d
10 changed files with 639 additions and 123 deletions

View file

@ -54,7 +54,7 @@ describe("compaction infinite loop prevention", () => {
]);
// This should not hang - it should break out of the loop
const result = await compactChatHistory(history, mockModel, mockLlmApi, {});
const result = await compactChatHistory(history, mockModel, mockLlmApi);
// Should complete successfully even though token count is still too high
expect(result.compactedHistory).toBeDefined();
@ -88,7 +88,7 @@ describe("compaction infinite loop prevention", () => {
]);
// This should not hang
const result = await compactChatHistory(history, mockModel, mockLlmApi, {});
const result = await compactChatHistory(history, mockModel, mockLlmApi);
expect(result.compactedHistory).toBeDefined();
});
@ -129,7 +129,7 @@ describe("compaction infinite loop prevention", () => {
{ role: "user", content: "Another question" },
]);
const result = await compactChatHistory(history, mockModel, mockLlmApi, {});
const result = await compactChatHistory(history, mockModel, mockLlmApi);
expect(result.compactedHistory).toBeDefined();
// The function will call countTokens multiple times during the process

View file

@ -385,8 +385,10 @@ describe("compaction", () => {
]);
await compactChatHistory(history, mockModel, mockLlmApi, {
onStreamContent,
onStreamComplete,
callbacks: {
onStreamContent,
onStreamComplete,
},
});
expect(onStreamContent).toHaveBeenCalledWith("Summary ");
@ -406,7 +408,9 @@ describe("compaction", () => {
]);
await expect(
compactChatHistory(history, mockModel, mockLlmApi, { onError }),
compactChatHistory(history, mockModel, mockLlmApi, {
callbacks: { onError },
}),
).rejects.toThrow("Stream failed");
expect(onError).toHaveBeenCalledWith(mockError);

View file

@ -22,22 +22,27 @@ export interface CompactionCallbacks {
onError?: (error: Error) => void;
}
export interface CompactionOptions {
callbacks?: CompactionCallbacks;
abortController?: AbortController;
systemMessageTokens?: number;
}
/**
* Compacts a chat history into a summarized form
* @param chatHistory The current chat history to compact
* @param model The model configuration
* @param llmApi The LLM API instance
* @param callbacks Optional callbacks for streaming updates
* @param abortController Optional abort controller for cancellation
* @param options Optional configuration including callbacks, abort controller, and system message tokens
* @returns The compacted history with compaction index
*/
export async function compactChatHistory(
chatHistory: ChatHistoryItem[],
model: ModelConfig,
llmApi: BaseLlmApi,
callbacks?: CompactionCallbacks,
abortController?: AbortController,
options?: CompactionOptions,
): Promise<CompactionResult> {
const { callbacks, abortController, systemMessageTokens = 0 } = options || {};
// Create a prompt to summarize the conversation
const compactionPrompt: ChatHistoryItem = {
message: {
@ -56,7 +61,11 @@ export async function compactChatHistory(
const maxTokens = model.defaultCompletionOptions?.maxTokens;
const reservedForOutput =
maxTokens === undefined ? Math.ceil(contextLimit * 0.35) : maxTokens;
const availableForInput = contextLimit - reservedForOutput;
// Account for system message AND safety buffer
const SAFETY_BUFFER = 100;
const availableForInput =
contextLimit - reservedForOutput - systemMessageTokens - SAFETY_BUFFER;
// Check if we need to prune to fit within context
while (

View file

@ -23,6 +23,7 @@ vi.mock("../session.js", () => ({
vi.mock("../util/tokenizer.js", () => ({
shouldAutoCompact: vi.fn(),
getAutoCompactMessage: vi.fn(),
countChatHistoryItemTokens: vi.fn(() => 100), // Mock return value
}));
vi.mock("../util/formatError.js", () => ({
@ -38,6 +39,17 @@ vi.mock("../util/logger.js", () => ({
},
}));
vi.mock("../services/index.js", () => ({
services: {
systemMessage: {
getSystemMessage: vi.fn(() => Promise.resolve("System message")),
},
toolPermissions: {
getState: vi.fn(() => ({ currentMode: "enabled" })),
},
},
}));
vi.mock("os", async (importOriginal) => {
const actual = (await importOriginal()) as object;
return {
@ -137,7 +149,10 @@ describe("handleAutoCompaction", () => {
mockChatHistory,
mockModel,
mockLlmApi,
expect.any(Object),
expect.objectContaining({
callbacks: expect.any(Object),
systemMessageTokens: expect.any(Number),
}),
);
expect(updateSessionHistory).toHaveBeenCalledWith(
mockCompactionResult.compactedHistory,

View file

@ -26,6 +26,7 @@ interface AutoCompactionOptions {
isHeadless?: boolean;
format?: "json";
callbacks?: AutoCompactionCallbacks;
systemMessage?: string;
}
/**
@ -128,7 +129,11 @@ export async function handleAutoCompaction(
compactionIndex: number | null;
wasCompacted: boolean;
}> {
const { isHeadless = false, callbacks } = options;
const {
isHeadless = false,
callbacks,
systemMessage: providedSystemMessage,
} = options;
if (!model || !shouldAutoCompact(chatHistory, model)) {
return { chatHistory, compactionIndex: null, wasCompacted: false };
@ -142,18 +147,38 @@ export async function handleAutoCompaction(
notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks);
try {
// Get system message to calculate its token count for compaction pruning
// Use provided message if available, otherwise fetch it (for backward compatibility)
const systemMessage =
providedSystemMessage ??
(async () => {
const { services } = await import("../services/index.js");
return services.systemMessage.getSystemMessage(
services.toolPermissions.getState().currentMode,
);
})();
const resolvedSystemMessage =
typeof systemMessage === "string" ? systemMessage : await systemMessage;
const { countChatHistoryItemTokens } = await import("../util/tokenizer.js");
const systemMessageTokens = countChatHistoryItemTokens({
message: {
role: "system",
content: resolvedSystemMessage,
},
contextItems: [],
});
// Compact the history
const result = await compactChatHistory(
chatHistory,
model,
llmApi,
isHeadless
const result = await compactChatHistory(chatHistory, model, llmApi, {
callbacks: isHeadless
? undefined
: {
onStreamContent: callbacks?.onContent,
onStreamComplete: () => {},
},
);
systemMessageTokens,
});
// Save the compacted session
updateSessionHistory(result.compactedHistory);

View file

@ -0,0 +1,197 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import type { ChatHistoryItem } from "core/index.js";
import { services } from "../services/index.js";
import { ToolCall } from "../tools/index.js";
import { logger } from "../util/logger.js";
import { validateContextLength } from "../util/tokenizer.js";
import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
import { StreamCallbacks } from "./streamChatResponse.types.js";
export interface CompactionHelperOptions {
model: ModelConfig;
llmApi: BaseLlmApi;
isCompacting: boolean;
isHeadless: boolean;
callbacks?: StreamCallbacks;
systemMessage: string;
}
/**
* Handle pre-API auto-compaction if needed
*/
export async function handlePreApiCompaction(
chatHistory: ChatHistoryItem[],
options: CompactionHelperOptions,
): Promise<{ chatHistory: ChatHistoryItem[]; wasCompacted: boolean }> {
const { model, llmApi, isCompacting, isHeadless, callbacks, systemMessage } =
options;
if (isCompacting) {
return { chatHistory, wasCompacted: false };
}
const { wasCompacted, chatHistory: preCompactHistory } =
await handleAutoCompaction(chatHistory, model, llmApi, {
isHeadless,
callbacks: {
onSystemMessage: callbacks?.onSystemMessage,
onContent: callbacks?.onContent,
},
systemMessage,
});
if (wasCompacted) {
logger.debug("Pre-API compaction occurred, updating chat history");
const chatHistorySvc = services.chatHistory;
if (
typeof chatHistorySvc?.isReady === "function" &&
chatHistorySvc.isReady()
) {
chatHistorySvc.setHistory(preCompactHistory);
return { chatHistory: chatHistorySvc.getHistory(), wasCompacted: true };
}
return { chatHistory: [...preCompactHistory], wasCompacted: true };
}
return { chatHistory, wasCompacted: false };
}
/**
* Validate and handle context overflow after tool execution
*/
export async function handlePostToolValidation(
toolCalls: ToolCall[],
chatHistory: ChatHistoryItem[],
options: CompactionHelperOptions,
): Promise<ChatHistoryItem[]> {
const { model, llmApi, isHeadless, callbacks, systemMessage } = options;
if (toolCalls.length === 0) {
return chatHistory;
}
// Get updated history after tool execution
const chatHistorySvc = services.chatHistory;
if (
typeof chatHistorySvc?.isReady === "function" &&
chatHistorySvc.isReady()
) {
chatHistory = chatHistorySvc.getHistory();
}
// Validate with system message to catch tool result overflow
const postToolSystemItem: ChatHistoryItem = {
message: {
role: "system",
content: systemMessage,
},
contextItems: [],
};
const SAFETY_BUFFER = 100;
const postToolValidation = validateContextLength(
[postToolSystemItem, ...chatHistory],
model,
SAFETY_BUFFER,
);
// If tool results pushed us over limit, force compaction regardless of threshold
if (!postToolValidation.isValid) {
logger.warn("Tool execution caused context overflow, forcing compaction", {
inputTokens: postToolValidation.inputTokens,
contextLimit: postToolValidation.contextLimit,
});
// Force compaction (compaction now accounts for system message during pruning)
const { wasCompacted, chatHistory: compactedHistory } =
await handleAutoCompaction(chatHistory, model, llmApi, {
isHeadless,
callbacks: {
onSystemMessage: callbacks?.onSystemMessage,
onContent: callbacks?.onContent,
},
systemMessage,
});
if (wasCompacted && chatHistorySvc) {
chatHistorySvc.setHistory(compactedHistory);
chatHistory = chatHistorySvc.getHistory();
// Verify compaction brought us under the limit
const postCompactionValidation = validateContextLength(
[postToolSystemItem, ...compactedHistory],
model,
SAFETY_BUFFER,
);
if (!postCompactionValidation.isValid) {
logger.error(
"Compaction failed to bring context under limit, stopping execution",
{
inputTokens: postCompactionValidation.inputTokens,
contextLimit: postCompactionValidation.contextLimit,
},
);
throw new Error(
`Context limit exceeded even after compaction: ${postCompactionValidation.error}`,
);
}
logger.info("Successfully compacted after tool overflow", {
inputTokens: postCompactionValidation.inputTokens,
contextLimit: postCompactionValidation.contextLimit,
});
} else {
// Compaction failed, cannot continue
logger.error("Failed to compact history after tool execution overflow");
throw new Error(
"Context limit exceeded and compaction failed. Unable to continue.",
);
}
}
return chatHistory;
}
/**
* Handle normal auto-compaction check at 80% threshold
*/
export async function handleNormalAutoCompaction(
chatHistory: ChatHistoryItem[],
shouldContinue: boolean,
options: CompactionHelperOptions,
): Promise<ChatHistoryItem[]> {
const { model, llmApi, isHeadless, callbacks, systemMessage } = options;
if (!shouldContinue) {
return chatHistory;
}
const chatHistorySvc = services.chatHistory;
if (
typeof chatHistorySvc?.isReady === "function" &&
chatHistorySvc.isReady()
) {
chatHistory = chatHistorySvc.getHistory();
}
const { wasCompacted, chatHistory: updatedChatHistory } =
await handleAutoCompaction(chatHistory, model, llmApi, {
isHeadless,
callbacks: {
onSystemMessage: callbacks?.onSystemMessage,
onContent: callbacks?.onContent,
},
systemMessage,
});
if (wasCompacted && chatHistorySvc) {
chatHistorySvc.setHistory(updatedChatHistory);
return chatHistorySvc.getHistory();
}
return chatHistory;
}

View file

@ -0,0 +1,199 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import type { ChatHistoryItem } from "core/index.js";
import { processStreamingResponse } from "./streamChatResponse.js";
import { services } from "../services/index.js";
// Mock services
vi.mock("../services/index.js", () => ({
services: {
systemMessage: {
getSystemMessage: vi.fn(),
},
toolPermissions: {
getState: vi.fn(() => ({ currentMode: "enabled" })),
isHeadless: vi.fn(() => false),
},
chatHistory: {
isReady: vi.fn(() => false),
},
},
}));
// Mock logger
vi.mock("../util/logger.js", () => ({
logger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
}));
// Mock tokenizer
vi.mock("../util/tokenizer.js", async () => {
const actual = await vi.importActual("../util/tokenizer.js");
return {
...actual,
countChatHistoryTokens: vi.fn((history: ChatHistoryItem[]) => {
// Simple mock: count based on content length
return history.reduce((sum, item) => {
const content =
typeof item.message.content === "string"
? item.message.content
: JSON.stringify(item.message.content);
return sum + Math.ceil(content.length / 4); // ~4 chars per token
}, 0);
}),
};
});
describe("streamChatResponse system message validation", () => {
let mockLlmApi: BaseLlmApi;
let abortController: AbortController;
beforeEach(() => {
vi.clearAllMocks();
mockLlmApi = {} as BaseLlmApi;
abortController = new AbortController();
});
it("should validate system message is retrieved before validation", async () => {
const model = {
model: "test-model",
defaultCompletionOptions: {
contextLength: 1000,
maxTokens: 100,
},
} as ModelConfig;
// Mock system message
const systemMessage = "System instructions";
vi.mocked(services.systemMessage.getSystemMessage).mockResolvedValue(
systemMessage,
);
// Small chat history
const chatHistory: ChatHistoryItem[] = [
{
message: { role: "user", content: "test" },
contextItems: [],
},
];
// Mock the streaming response to avoid actual API call
const mockStream = {
[Symbol.asyncIterator]: async function* () {
yield {
choices: [{ delta: { content: "test" } }],
};
},
};
mockLlmApi.chatCompletionStream = vi.fn().mockResolvedValue(mockStream);
// Execute the function with systemMessage parameter
await processStreamingResponse({
chatHistory,
model,
llmApi: mockLlmApi,
abortController,
systemMessage,
});
// Verify the function uses the provided system message (no fetch needed)
// The system message is now provided by the caller
expect(services.systemMessage.getSystemMessage).not.toHaveBeenCalled();
});
it("should pass validation when system message + history fits", async () => {
const model = {
model: "test-model",
defaultCompletionOptions: {
contextLength: 1000,
maxTokens: 100,
},
} as ModelConfig;
// Small system message (50 tokens worth)
const smallSystemMessage = "x".repeat(200); // ~50 tokens
// Small chat history (200 tokens worth)
const chatHistory: ChatHistoryItem[] = [
{
message: { role: "user", content: "x".repeat(800) }, // ~200 tokens
contextItems: [],
},
];
// Available: 1000 - 100 (maxTokens) - 100 (buffer) = 800 tokens
// System: ~50 tokens
// History: ~200 tokens
// Total: ~250 tokens < 800 available
// Should pass validation
// Mock the streaming response to avoid actual API call
const mockStream = {
[Symbol.asyncIterator]: async function* () {
yield {
choices: [{ delta: { content: "test" } }],
};
},
};
mockLlmApi.chatCompletionStream = vi.fn().mockResolvedValue(mockStream);
// This should not throw
const result = await processStreamingResponse({
chatHistory,
model,
llmApi: mockLlmApi,
abortController,
systemMessage: smallSystemMessage,
});
expect(result).toBeDefined();
// System message is now provided by caller, not fetched
expect(services.systemMessage.getSystemMessage).not.toHaveBeenCalled();
});
it("should use safety buffer in validation", async () => {
const model = {
model: "test-model",
defaultCompletionOptions: {
contextLength: 1000,
maxTokens: 100,
},
} as ModelConfig;
// System message + history that's exactly at limit without buffer
// but fails with buffer
const systemMessage = "x".repeat(800); // ~200 tokens
const chatHistory: ChatHistoryItem[] = [
{
message: { role: "user", content: "x".repeat(2400) }, // ~600 tokens
contextItems: [],
},
];
// Available without buffer: 1000 - 100 = 900 tokens
// Available with buffer: 1000 - 100 - 100 = 800 tokens
// System: ~200 tokens
// History: ~600 tokens
// Total: ~800 tokens
// Should exactly hit the limit with buffer and pass/prune
await expect(
processStreamingResponse({
chatHistory,
model,
llmApi: mockLlmApi,
abortController,
systemMessage,
}),
).rejects.toThrow(); // Will fail because we can't prune enough
});
});

View file

@ -22,7 +22,11 @@ import { logger } from "../util/logger.js";
import { validateContextLength } from "../util/tokenizer.js";
import { getRequestTools, handleToolCalls } from "./handleToolCalls.js";
import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
import {
handleNormalAutoCompaction,
handlePostToolValidation,
handlePreApiCompaction,
} from "./streamChatResponse.compactionHelpers.js";
import {
processChunkContent,
processToolCallDelta,
@ -128,6 +132,7 @@ interface ProcessStreamingResponseOptions {
callbacks?: StreamCallbacks;
isHeadless?: boolean;
tools?: ChatCompletionTool[];
systemMessage: string;
}
// Process a single streaming response and return whether we need to continue
@ -140,30 +145,56 @@ export async function processStreamingResponse(
toolCalls: ToolCall[];
shouldContinue: boolean;
}> {
const { model, llmApi, abortController, callbacks, isHeadless, tools } =
options;
const {
model,
llmApi,
abortController,
callbacks,
isHeadless,
tools,
systemMessage,
} = options;
let chatHistory = options.chatHistory;
// Validate context length before making the request
let validation = validateContextLength(chatHistory, model);
// Create temporary system message item for validation
const systemMessageItem: ChatHistoryItem = {
message: {
role: "system",
content: systemMessage,
},
contextItems: [],
};
// Prune last messages until valid
// Safety buffer to account for tokenization estimation errors
const SAFETY_BUFFER = 100;
// Validate context length INCLUDING system message
let historyWithSystem = [systemMessageItem, ...chatHistory];
let validation = validateContextLength(
historyWithSystem,
model,
SAFETY_BUFFER,
);
// Prune last messages until valid (excluding system message)
while (chatHistory.length > 1 && !validation.isValid) {
const prunedChatHistory = pruneLastMessage(chatHistory);
if (prunedChatHistory.length === chatHistory.length) break;
if (prunedChatHistory.length === chatHistory.length) {
break;
}
chatHistory = prunedChatHistory;
validation = validateContextLength(chatHistory, model);
// Re-validate with system message
historyWithSystem = [systemMessageItem, ...chatHistory];
validation = validateContextLength(historyWithSystem, model, SAFETY_BUFFER);
}
if (!validation.isValid) {
throw new Error(`Context length validation failed: ${validation.error}`);
}
// Get fresh system message and inject it
const systemMessage = await services.systemMessage.getSystemMessage(
services.toolPermissions.getState().currentMode,
);
// Create OpenAI format history with validated system message
const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage(
chatHistory,
systemMessage,
@ -329,7 +360,7 @@ export async function processStreamingResponse(
}
// Main function that handles the conversation loop
// eslint-disable-next-line complexity, max-params
// eslint-disable-next-line max-params
export async function streamChatResponse(
chatHistory: ChatHistoryItem[],
model: ModelConfig,
@ -368,34 +399,21 @@ export async function streamChatResponse(
logger.debug("debug1 streamChatResponse history", { chatHistory });
// avoid pre-compaction when compaction is in progress
// this also avoids infinite compaction call stacks
if (!isCompacting) {
// Pre-API auto-compaction checkpoint
const { wasCompacted: preCompacted, chatHistory: preCompactHistory } =
await handleAutoCompaction(chatHistory, model, llmApi, {
isHeadless,
callbacks: {
onSystemMessage: callbacks?.onSystemMessage,
onContent: callbacks?.onContent,
},
});
// Get system message once per iteration (can change based on tool permissions mode)
const systemMessage = await services.systemMessage.getSystemMessage(
services.toolPermissions.getState().currentMode,
);
if (preCompacted) {
logger.debug("Pre-API compaction occurred, updating chat history");
// Update chat history after pre-compaction
const chatHistorySvc2 = services.chatHistory;
if (
typeof chatHistorySvc2?.isReady === "function" &&
chatHistorySvc2.isReady()
) {
chatHistorySvc2.setHistory(preCompactHistory);
chatHistory = chatHistorySvc2.getHistory();
} else {
chatHistory = [...preCompactHistory];
}
}
}
// Pre-API auto-compaction checkpoint
const preCompactionResult = await handlePreApiCompaction(chatHistory, {
model,
llmApi,
isCompacting,
isHeadless,
callbacks,
systemMessage,
});
chatHistory = preCompactionResult.chatHistory;
// Recompute tools on each iteration to handle mode changes during streaming
const tools = await getRequestTools(isHeadless);
@ -415,6 +433,7 @@ export async function streamChatResponse(
abortController,
callbacks,
tools,
systemMessage,
});
if (abortController?.signal.aborted) {
@ -447,33 +466,29 @@ export async function streamChatResponse(
return finalResponse || content || fullResponse;
}
// Check for auto-compaction after tool execution
if (shouldContinue) {
const { wasCompacted, chatHistory: updatedChatHistory } =
await handleAutoCompaction(chatHistory, model, llmApi, {
isHeadless,
callbacks: {
onSystemMessage: callbacks?.onSystemMessage,
onContent: callbacks?.onContent,
},
});
// After tool execution, validate that we haven't exceeded context limit
chatHistory = await handlePostToolValidation(toolCalls, chatHistory, {
model,
llmApi,
isCompacting,
isHeadless,
callbacks,
systemMessage,
});
// Only update chat history if compaction actually occurred
if (wasCompacted) {
// Always prefer service; local copy is for temporary reads only
const chatHistorySvc2 = services.chatHistory;
if (
typeof chatHistorySvc2?.isReady === "function" &&
chatHistorySvc2.isReady()
) {
chatHistorySvc2.setHistory(updatedChatHistory);
chatHistory = chatHistorySvc2.getHistory();
} else {
// Fallback only when service is unavailable
chatHistory = [...updatedChatHistory];
}
}
}
// Normal auto-compaction check at 80% threshold
chatHistory = await handleNormalAutoCompaction(
chatHistory,
shouldContinue,
{
model,
llmApi,
isCompacting,
isHeadless,
callbacks,
systemMessage,
},
);
// Check if we should continue
if (!shouldContinue) {

View file

@ -44,13 +44,9 @@ export async function handleCompactCommand({
try {
// Compact the chat history directly (already in unified format) with abort controller
const result = await compactChatHistory(
chatHistory,
model,
llmApi,
undefined,
compactionController,
);
const result = await compactChatHistory(chatHistory, model, llmApi, {
abortController: compactionController,
});
// Check if operation was aborted before proceeding with success actions
if (compactionController.signal.aborted) {
@ -153,13 +149,9 @@ export async function handleAutoCompaction({
logger.info("Auto-compaction triggered for TUI mode");
// Compact the unified history
const result = await compactChatHistory(
chatHistory,
model,
llmApi,
undefined,
const result = await compactChatHistory(chatHistory, model, llmApi, {
abortController,
);
});
// Keep the system message and append the compaction summary
// This replaces the old messages with a summary to reduce context size

View file

@ -22,6 +22,69 @@ export function getModelContextLimit(model: ModelConfig): number {
);
}
/**
* Count tokens in message content (string or multimodal array)
*/
function countContentTokens(content: string | any[]): number {
if (typeof content === "string") {
return encode(content).length;
}
if (Array.isArray(content)) {
let tokenCount = 0;
for (const part of content) {
if (part.type === "text" && part.text) {
tokenCount += encode(part.text).length;
}
if (part.type === "imageUrl") {
tokenCount += 1024; // Rough estimate for image tokens
}
}
return tokenCount;
}
return 0;
}
/**
* Count tokens in a single tool call function
*/
function countToolCallFunctionTokens(
toolCallFunction: { name?: string; arguments?: string } | undefined,
): number {
if (!toolCallFunction) {
return 0;
}
let tokenCount = 0;
tokenCount += encode(toolCallFunction.name ?? "").length + 10; // Function name and structure overhead
tokenCount += encode(toolCallFunction.arguments ?? "").length; // Arguments
return tokenCount;
}
/**
* Count tokens in tool call outputs
*/
function countToolOutputTokens(
output: Array<{ content?: string; name?: string }> | undefined,
): number {
if (!output) {
return 0;
}
let tokenCount = 0;
for (const item of output) {
if (item.content) {
tokenCount += encode(item.content).length;
}
if (item.name) {
tokenCount += encode(item.name).length;
}
tokenCount += 5; // Output structure overhead
}
return tokenCount;
}
/**
* Estimate the token count for a single ChatHistoryItem
* @param historyItem The ChatHistoryItem to count tokens for
@ -36,35 +99,20 @@ export function countChatHistoryItemTokens(
const message = historyItem.message;
// Count tokens in content
if (typeof message.content === "string") {
tokenCount += encode(message.content).length;
} else if (Array.isArray(message.content)) {
// Handle array content (e.g., multimodal messages)
for (const part of message.content) {
if (part.type === "text" && part.text) {
tokenCount += encode(part.text).length;
}
// Images and other content types have their own token costs
// but we'll use a rough estimate for now
if (part.type === "imageUrl") {
tokenCount += 1024; // Rough estimate for image tokens
}
}
}
tokenCount += countContentTokens(message.content);
// Add tokens for role (roughly 1-2 tokens)
tokenCount += 2;
// Add tokens for tool calls if present
if ("toolCalls" in message && message.toolCalls) {
// Skip if toolCallStates exists to avoid double-counting (toolCallStates includes the tool calls)
if (
"toolCalls" in message &&
message.toolCalls &&
!historyItem.toolCallStates
) {
for (const toolCall of message.toolCalls) {
if (!toolCall.function) {
continue;
}
// Function name and structure overhead
tokenCount += encode(toolCall.function.name ?? "").length + 10;
// Arguments
tokenCount += encode(toolCall.function.arguments ?? "").length;
tokenCount += countToolCallFunctionTokens(toolCall.function);
}
}
@ -80,6 +128,16 @@ export function countChatHistoryItemTokens(
tokenCount += 5; // Context item structure overhead
}
// Add tokens for tool call states (tool results/outputs)
if (historyItem.toolCallStates) {
for (const toolState of historyItem.toolCallStates) {
// Count tokens in tool call function (name + arguments)
tokenCount += countToolCallFunctionTokens(toolState.toolCall?.function);
// Count tokens in tool outputs (can be very large - thousands of tokens)
tokenCount += countToolOutputTokens(toolState.output);
}
}
return tokenCount;
} catch (error) {
logger.error("Error counting tokens for history item", error);
@ -197,11 +255,13 @@ export function getAutoCompactMessage(model: ModelConfig): string {
* Validates that the input tokens + max_tokens don't exceed context limit
* @param chatHistory The chat history to validate
* @param model The model configuration
* @param safetyBuffer Additional token buffer to account for estimation errors (default: 0)
* @returns Validation result with error details if invalid
*/
export function validateContextLength(
chatHistory: ChatHistoryItem[],
model: ModelConfig,
safetyBuffer: number = 0,
): {
isValid: boolean;
error?: string;
@ -216,12 +276,12 @@ export function validateContextLength(
// If maxTokens is not set, use 35% default reservation for output
const reservedForOutput =
maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35);
const totalRequired = inputTokens + reservedForOutput;
const totalRequired = inputTokens + reservedForOutput + safetyBuffer;
if (totalRequired > contextLimit) {
return {
isValid: false,
error: `Context length exceeded: input (${inputTokens.toLocaleString()}) + max_tokens (${reservedForOutput.toLocaleString()}) = ${totalRequired.toLocaleString()} > context_limit (${contextLimit.toLocaleString()})`,
error: `Context length exceeded: input (${inputTokens.toLocaleString()}) + max_tokens (${reservedForOutput.toLocaleString()})${safetyBuffer > 0 ? ` + buffer (${safetyBuffer})` : ""} = ${totalRequired.toLocaleString()} > context_limit (${contextLimit.toLocaleString()})`,
inputTokens,
contextLimit,
maxTokens: reservedForOutput,