fix: account for different tokenizers

This commit is contained in:
Dallin Romney 2026-01-21 16:35:52 -08:00
parent 8494a27b0e
commit b4bc3aedaa
7 changed files with 110 additions and 50 deletions

View file

@ -248,7 +248,10 @@ async function handleAutoCompaction(
message: "Auto-compacting triggered",
contextUsage:
calculateContextUsagePercentage(
countChatHistoryTokens(services.chatHistory.getHistory()),
countChatHistoryTokens(
services.chatHistory.getHistory(),
model,
),
model,
) + "%",
}) + "\n",

View file

@ -23,6 +23,12 @@ describe("compaction", () => {
model: "test-model",
} as ModelConfig;
const claudeModel: ModelConfig = {
name: "claude-3-5-sonnet",
provider: "anthropic",
model: "claude-3-5-sonnet-20241022",
} as ModelConfig;
const mockLlmApi = {} as BaseLlmApi;
describe("findCompactionIndex", () => {

View file

@ -83,11 +83,11 @@ export async function compactChatHistory(
// Check if we need to prune to fit within context
while (
countChatHistoryTokens(historyForCompaction) > availableForInput &&
countChatHistoryTokens(historyForCompaction, model) > availableForInput &&
historyToUse.length > 0
) {
logger.debug("Compaction history too long, pruning last message", {
tokenCount: countChatHistoryTokens(historyForCompaction),
tokenCount: countChatHistoryTokens(historyForCompaction, model),
availableForInput,
historyLength: historyToUse.length,
});

View file

@ -172,13 +172,16 @@ export async function handleAutoCompaction(
typeof systemMessage === "string" ? systemMessage : await systemMessage;
const { countChatHistoryItemTokens } = await import("../util/tokenizer.js");
const systemMessageTokens = countChatHistoryItemTokens({
message: {
role: "system",
content: resolvedSystemMessage,
const systemMessageTokens = countChatHistoryItemTokens(
{
message: {
role: "system",
content: resolvedSystemMessage,
},
contextItems: [],
},
contextItems: [],
});
model,
);
// Compact the history
const result = await compactChatHistory(chatHistory, model, llmApi, {

View file

@ -28,7 +28,7 @@ export function useContextPercentage({
}
// Calculate token count and percentage
const tokenCount = countChatHistoryTokens(chatHistory);
const tokenCount = countChatHistoryTokens(chatHistory, model);
const percentage = calculateContextUsagePercentage(tokenCount, model);
return {

View file

@ -8,7 +8,6 @@ import {
calculateContextUsagePercentage,
countChatHistoryItemTokens,
countChatHistoryTokens,
countMessageTokens,
countToolDefinitionTokens,
getModelContextLimit,
shouldAutoCompact,
@ -69,7 +68,13 @@ describe("tokenizer", () => {
contextItems: [],
};
const tokenCount = countChatHistoryItemTokens(historyItem);
const model: ModelConfig = {
name: "test-model",
model: "test",
provider: "openai",
};
const tokenCount = countChatHistoryItemTokens(historyItem, model);
expect(tokenCount).toBeGreaterThan(0);
expect(tokenCount).toBe(5); // 3 content tokens + 2 role tokens
});
@ -86,7 +91,13 @@ describe("tokenizer", () => {
contextItems: [],
};
const tokenCount = countChatHistoryItemTokens(historyItem);
const model: ModelConfig = {
name: "test-model",
model: "test",
provider: "openai",
};
const tokenCount = countChatHistoryItemTokens(historyItem, model);
expect(tokenCount).toBe(1028); // 2 + 1024 + 2 role tokens
});
@ -109,7 +120,13 @@ describe("tokenizer", () => {
contextItems: [],
};
const tokenCount = countChatHistoryItemTokens(historyItem);
const model: ModelConfig = {
name: "test-model",
model: "test",
provider: "openai",
};
const tokenCount = countChatHistoryItemTokens(historyItem, model);
expect(tokenCount).toBeGreaterThan(20);
});
@ -129,7 +146,13 @@ describe("tokenizer", () => {
],
};
const tokenCount = countChatHistoryItemTokens(historyItem);
const model: ModelConfig = {
name: "test-model",
model: "test",
provider: "openai",
};
const tokenCount = countChatHistoryItemTokens(historyItem, model);
// 2 (content) + 2 (role) + 4 (context content) + 3 (context name) + 5 (context overhead) = 16
expect(tokenCount).toBe(16);
});
@ -141,21 +164,6 @@ describe("tokenizer", () => {
});
});
describe("countMessageTokens (legacy)", () => {
it("should call countChatHistoryItemTokens", () => {
const historyItem: ChatHistoryItem = {
message: {
role: "user",
content: "Hello world",
},
contextItems: [],
};
const tokenCount = countMessageTokens(historyItem);
expect(tokenCount).toBe(5); // Same as countChatHistoryItemTokens
});
});
describe("countChatHistoryTokens", () => {
it("should count tokens for multiple messages", () => {
const chatHistory: ChatHistoryItem[] = [
@ -173,14 +181,26 @@ describe("tokenizer", () => {
},
];
const tokenCount = countChatHistoryTokens(chatHistory);
const model: ModelConfig = {
name: "test-model",
model: "test",
provider: "openai",
};
const tokenCount = countChatHistoryTokens(chatHistory, model);
expect(tokenCount).toBeGreaterThan(0);
// Should include message overhead (3 * 3 = 9 tokens)
expect(tokenCount).toBeGreaterThan(9);
});
it("should handle empty chat history", () => {
const tokenCount = countChatHistoryTokens([]);
const model: ModelConfig = {
name: "test-model",
model: "test",
provider: "openai",
};
const tokenCount = countChatHistoryTokens([], model);
expect(tokenCount).toBe(0);
});
});

View file

@ -23,12 +23,43 @@ export function getModelContextLimit(model: ModelConfig): number {
);
}
// Importing a bunch of tokenizers can be very resource intensive (MB-scale per tokenizer)
// Using token counting APIs (e.g. for anthropic) can be complicated and unreliable in many environments
// So for now we will just use super fast gpt-tokenizer and apply safety buffers
// I'm using rough estimates from this article to apply safety buffers to common tokenizers
// which will have HIGHER token counts than gpt. Roughly using token ratio from article + 10%
// https://medium.com/@disparate-ai/not-all-tokens-are-created-equal-7347d549af4d
const ANTHROPIC_TOKEN_MULTIPLIER = 1.23;
const GEMINI_TOKEN_MULTIPLIER = 1.18;
const MISTRAL_TOKEN_MULTIPLIER = 1.26;
function getAdjustedTokenCountFromModel(
baseTokens: number,
model: ModelConfig,
) {
let multiplier = 1;
const modelName = model.model?.toLowerCase() ?? "";
if (modelName.includes("claude")) {
multiplier = ANTHROPIC_TOKEN_MULTIPLIER;
} else if (modelName.includes("gemini")) {
multiplier = GEMINI_TOKEN_MULTIPLIER;
} else if (modelName.includes("stral")) {
// devstral, mixtral, mistral, etc
multiplier = MISTRAL_TOKEN_MULTIPLIER;
}
return Math.ceil(baseTokens * multiplier);
}
/**
* Count tokens in message content (string or multimodal array)
*/
function countContentTokens(content: string | any[]): number {
function countContentTokens(
content: string | any[],
model: ModelConfig,
): number {
if (typeof content === "string") {
return encode(content).length;
const count = encode(content).length;
return getAdjustedTokenCountFromModel(count, model);
}
if (Array.isArray(content)) {
@ -41,7 +72,7 @@ function countContentTokens(content: string | any[]): number {
tokenCount += 1024; // Rough estimate for image tokens
}
}
return tokenCount;
return getAdjustedTokenCountFromModel(tokenCount, model);
}
return 0;
@ -91,6 +122,7 @@ function countToolOutputTokens(
*/
export function countChatHistoryItemTokens(
historyItem: ChatHistoryItem,
model: ModelConfig,
): number {
try {
let tokenCount = 0;
@ -98,7 +130,7 @@ export function countChatHistoryItemTokens(
const message = historyItem.message;
// Count tokens in content
tokenCount += countContentTokens(message.content);
tokenCount += countContentTokens(message.content, model);
// Add tokens for role (roughly 1-2 tokens)
tokenCount += 2;
@ -154,26 +186,19 @@ export function countChatHistoryItemTokens(
}
}
/**
* Estimate the token count for a single message (legacy compatibility)
* @param message The message to count tokens for
* @returns The estimated token count
* @deprecated Use countChatHistoryItemTokens instead
*/
export function countMessageTokens(message: ChatHistoryItem): number {
return countChatHistoryItemTokens(message);
}
/**
* Estimate the total token count for a chat history
* @param chatHistory The chat history to count tokens for
* @returns The estimated total token count
*/
export function countChatHistoryTokens(chatHistory: ChatHistoryItem[]): number {
export function countChatHistoryTokens(
chatHistory: ChatHistoryItem[],
model: ModelConfig,
): number {
let totalTokens = 0;
for (const historyItem of chatHistory) {
totalTokens += countChatHistoryItemTokens(historyItem);
totalTokens += countChatHistoryItemTokens(historyItem, model);
}
// Add some overhead for message structure (roughly 3 tokens per message)
@ -291,6 +316,7 @@ export function countToolDefinitionTokens(tools: ChatCompletionTool[]): number {
*/
export interface TotalInputTokenParams {
chatHistory: ChatHistoryItem[];
model: ModelConfig;
systemMessage?: string;
tools?: ChatCompletionTool[];
}
@ -304,7 +330,7 @@ export interface TotalInputTokenParams {
export function countTotalInputTokens(params: TotalInputTokenParams): number {
const { chatHistory, systemMessage, tools } = params;
let totalTokens = countChatHistoryTokens(chatHistory);
let totalTokens = countChatHistoryTokens(chatHistory, params.model);
// Add system message tokens if provided and not already in history
if (systemMessage) {
@ -348,6 +374,7 @@ export function shouldAutoCompact(params: AutoCompactParams): boolean {
chatHistory,
systemMessage,
tools,
model,
});
const contextLimit = getModelContextLimit(model);
const maxTokens = model.defaultCompletionOptions?.maxTokens || 0;
@ -373,7 +400,7 @@ export function shouldAutoCompact(params: AutoCompactParams): boolean {
logger.debug("Context usage check", {
inputTokens,
historyTokens: countChatHistoryTokens(chatHistory),
historyTokens: countChatHistoryTokens(chatHistory, model),
systemTokens,
toolTokens,
contextLimit,
@ -428,6 +455,7 @@ export function validateContextLength(params: ValidateContextLengthParams): {
chatHistory,
systemMessage,
tools,
model,
});
const contextLimit = getModelContextLimit(model);
const maxTokens = model.defaultCompletionOptions?.maxTokens || 0;