diff --git a/extensions/cli/src/compaction.infiniteLoop.test.ts b/extensions/cli/src/compaction.infiniteLoop.test.ts index 68319b4a0..d31734d6d 100644 --- a/extensions/cli/src/compaction.infiniteLoop.test.ts +++ b/extensions/cli/src/compaction.infiniteLoop.test.ts @@ -14,6 +14,7 @@ vi.mock("./stream/streamChatResponse.js", () => ({ vi.mock("./util/tokenizer.js", () => ({ countChatHistoryTokens: vi.fn(), getModelContextLimit: vi.fn(), + getModelMaxTokens: vi.fn(), })); describe("compaction infinite loop prevention", () => { diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index 00c6ea3f5..4132bb97f 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -1,21 +1,23 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { ChatHistoryItem } from "core/index.js"; +import { encode } from "gpt-tokenizer"; +import { ChatCompletionTool } from "openai/resources.mjs"; import { streamChatResponse } from "./stream/streamChatResponse.js"; import { StreamCallbacks } from "./stream/streamChatResponse.types.js"; import { logger } from "./util/logger.js"; import { countChatHistoryTokens, + countToolDefinitionTokens, + countTotalInputTokens, getModelContextLimit, + getModelMaxTokens, } from "./util/tokenizer.js"; -// Buffer cap for auto-compaction threshold calculation -// Threshold formula: contextLength - maxTokens - Min(maxTokens, AUTO_COMPACT_BUFFER_CAP) +// Buffer cap/ratio for auto-compaction threshold calculation export const AUTO_COMPACT_BUFFER_CAP = 15_000; - -// Default context length when model config doesn't specify one -export const DEFAULT_CONTEXT_LENGTH = 200_000; +export const AUTO_COMPACT_BUFFER_RATIO = 0.8; export interface CompactionResult { compactedHistory: ChatHistoryItem[]; @@ -69,12 +71,7 @@ export async function compactChatHistory( let historyForCompaction = [...historyToUse, compactionPrompt]; const contextLimit = getModelContextLimit(model); - const maxTokens = model.defaultCompletionOptions?.maxTokens; - const reservedForOutput = - maxTokens === undefined ? Math.ceil(contextLimit * 0.35) : maxTokens; - // Additional buffer matching the auto-compaction threshold formula: - // contextLength - maxTokens - Min(maxTokens, 20k) - const compactionBuffer = Math.min(reservedForOutput, AUTO_COMPACT_BUFFER_CAP); + const maxTokens = getModelMaxTokens(model); // Check if system message is already in the history to avoid double-counting const hasSystemMessageInHistory = chatHistory.some( @@ -85,10 +82,10 @@ export async function compactChatHistory( const systemMessageReservation = hasSystemMessageInHistory ? 0 : systemMessageTokens; + const availableForInput = contextLimit - - reservedForOutput - - compactionBuffer - + maxTokens - systemMessageReservation - COMPACTION_PROMPT_TOKENS; @@ -239,3 +236,80 @@ export function getHistoryForLLM( ? [systemMessage, ...messagesFromCompaction] : messagesFromCompaction; } + +/** + * Parameters for auto-compaction check + */ +export interface AutoCompactParams { + chatHistory: ChatHistoryItem[]; + model: ModelConfig; + systemMessage?: string; + tools?: ChatCompletionTool[]; +} + +/** + * Get a descriptive message for auto-compaction that shows the context limit + * @param model The model configuration + * @returns A descriptive message explaining why compaction is needed + */ +export function getAutoCompactMessage(model: ModelConfig): string { + const limit = getModelContextLimit(model); + return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`; +} + +/** + * Check if the chat history exceeds the auto-compact threshold. + * Accounts for system message and tool definitions in the calculation. + * @param params Object containing chatHistory, model, optional systemMessage, and optional tools + * @returns Whether auto-compacting should be triggered + */ +export function shouldAutoCompact(params: AutoCompactParams): boolean { + const { chatHistory, model, systemMessage, tools } = params; + + const inputTokens = countTotalInputTokens({ + chatHistory, + systemMessage, + tools, + model, + }); + const contextLimit = getModelContextLimit(model); + const maxTokens = getModelMaxTokens(model); + + // Additional buffer matching the auto-compaction threshold formula + const ratioCompactionBuffer = Math.ceil( + (1 - AUTO_COMPACT_BUFFER_RATIO) * (contextLimit - maxTokens), + ); + const safeCompactionBuffer = Math.max(maxTokens, ratioCompactionBuffer); + const compactionBuffer = Math.min( + safeCompactionBuffer, + AUTO_COMPACT_BUFFER_CAP, + ); + + const compactionThreshold = contextLimit - maxTokens - compactionBuffer; + + // Ensure we have positive space available for input + if (compactionThreshold <= 0) { + throw new Error( + `max_tokens is larger than context_length, which should not be possible. Please check your configuration.`, + ); + } + + const toolTokens = tools ? countToolDefinitionTokens(tools) : 0; + const systemTokens = systemMessage ? encode(systemMessage).length : 0; + const shouldCompact = inputTokens >= compactionThreshold; + + logger.debug("Context usage check", { + inputTokens, + historyTokens: countChatHistoryTokens(chatHistory, model), + systemTokens, + toolTokens, + contextLimit, + maxTokens, + reservedForOutput: maxTokens, + compactionBuffer, + compactionThreshold, + shouldCompact, + }); + + return shouldCompact; +} diff --git a/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts index 20c654c40..21b0a5651 100644 --- a/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts @@ -7,6 +7,8 @@ import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; // Mock dependencies vi.mock("../compaction.js", () => ({ compactChatHistory: vi.fn(), + shouldAutoCompact: vi.fn(), + getAutoCompactMessage: vi.fn(), })); vi.mock("../session.js", () => ({ @@ -22,8 +24,6 @@ vi.mock("../session.js", () => ({ })); vi.mock("../util/tokenizer.js", () => ({ - shouldAutoCompact: vi.fn(), - getAutoCompactMessage: vi.fn(), countChatHistoryItemTokens: vi.fn(() => 100), // Mock return value })); @@ -82,7 +82,7 @@ describe("handleAutoCompaction", () => { }); it("should return original history when auto-compaction is not needed", async () => { - const { shouldAutoCompact } = await import("../util/tokenizer.js"); + const { shouldAutoCompact } = await import("../compaction.js"); const mockedShouldAutoCompact = shouldAutoCompact as any; mockedShouldAutoCompact.mockReturnValue(false); @@ -108,10 +108,8 @@ describe("handleAutoCompaction", () => { }); it("should perform auto-compaction when context limit is approaching", async () => { - const { shouldAutoCompact, getAutoCompactMessage } = await import( - "../util/tokenizer.js" - ); - const { compactChatHistory } = await import("../compaction.js"); + const { compactChatHistory, shouldAutoCompact, getAutoCompactMessage } = + await import("../compaction.js"); const { updateSessionHistory } = await import("../session.js"); vi.mocked(shouldAutoCompact).mockReturnValue(true); @@ -184,10 +182,8 @@ describe("handleAutoCompaction", () => { }); it("should handle compaction errors gracefully", async () => { - const { shouldAutoCompact, getAutoCompactMessage } = await import( - "../util/tokenizer.js" - ); - const { compactChatHistory } = await import("../compaction.js"); + const { compactChatHistory, shouldAutoCompact, getAutoCompactMessage } = + await import("../compaction.js"); const { logger } = await import("../util/logger.js"); vi.mocked(shouldAutoCompact).mockReturnValue(true); @@ -227,10 +223,8 @@ describe("handleAutoCompaction", () => { }); it("should not call system message callback in headless mode", async () => { - const { shouldAutoCompact, getAutoCompactMessage } = await import( - "../util/tokenizer.js" - ); - const { compactChatHistory } = await import("../compaction.js"); + const { compactChatHistory, shouldAutoCompact, getAutoCompactMessage } = + await import("../compaction.js"); vi.mocked(shouldAutoCompact).mockReturnValue(true); vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); diff --git a/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts index 3086de9eb..156e9fa35 100644 --- a/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts +++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts @@ -4,11 +4,14 @@ import type { ChatHistoryItem } from "core/index.js"; import type { ChatCompletionTool } from "openai/resources/chat/completions.mjs"; import React from "react"; -import { compactChatHistory } from "../compaction.js"; +import { + compactChatHistory, + getAutoCompactMessage, + shouldAutoCompact, +} from "../compaction.js"; import { updateSessionHistory } from "../session.js"; import { formatError } from "../util/formatError.js"; import { logger } from "../util/logger.js"; -import { getAutoCompactMessage, shouldAutoCompact } from "../util/tokenizer.js"; interface AutoCompactionCallbacks { // For streaming mode diff --git a/extensions/cli/src/stream/streamChatResponse.autoContinuation.test.ts b/extensions/cli/src/stream/streamChatResponse.autoContinuation.test.ts index 42a6ec05f..8f4e95a2b 100644 --- a/extensions/cli/src/stream/streamChatResponse.autoContinuation.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.autoContinuation.test.ts @@ -11,6 +11,8 @@ import { streamChatResponse } from "./streamChatResponse.js"; vi.mock("../compaction.js", () => ({ compactChatHistory: vi.fn(), pruneLastMessage: vi.fn((history) => history.slice(0, -1)), + shouldAutoCompact: vi.fn(), + getAutoCompactMessage: vi.fn(() => "Auto-compacting..."), })); vi.mock("../session.js", () => ({ @@ -19,8 +21,6 @@ vi.mock("../session.js", () => ({ })); vi.mock("../util/tokenizer.js", () => ({ - shouldAutoCompact: vi.fn(), - getAutoCompactMessage: vi.fn(() => "Auto-compacting..."), countChatHistoryItemTokens: vi.fn(() => 100), validateContextLength: vi.fn(() => ({ isValid: true })), })); diff --git a/extensions/cli/src/util/tokenizer.test.ts b/extensions/cli/src/util/tokenizer.test.ts index aa532f86c..acd1c7428 100644 --- a/extensions/cli/src/util/tokenizer.test.ts +++ b/extensions/cli/src/util/tokenizer.test.ts @@ -4,17 +4,18 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { AUTO_COMPACT_BUFFER_CAP, - DEFAULT_CONTEXT_LENGTH, + AUTO_COMPACT_BUFFER_RATIO, + shouldAutoCompact, } from "../compaction.js"; import { logger } from "./logger.js"; import { + DEFAULT_CONTEXT_LENGTH, calculateContextUsagePercentage, countChatHistoryItemTokens, countChatHistoryTokens, countToolDefinitionTokens, getModelContextLimit, - shouldAutoCompact, } from "./tokenizer.js"; // Mock the logger @@ -251,9 +252,29 @@ describe("tokenizer", () => { ]; }; + // Helper to calculate threshold using the new formula + const calculateThreshold = ( + contextLength: number, + maxTokens: number, + ): number => { + const ratioCompactionBuffer = Math.ceil( + (1 - AUTO_COMPACT_BUFFER_RATIO) * (contextLength - maxTokens), + ); + const safeCompactionBuffer = Math.max(maxTokens, ratioCompactionBuffer); + const compactionBuffer = Math.min( + safeCompactionBuffer, + AUTO_COMPACT_BUFFER_CAP, + ); + return contextLength - maxTokens - compactionBuffer; + }; + it("should compact when input tokens exceed threshold with maxTokens", () => { const model = createModel(1000, 200); // 1000 context, 200 max output - // Threshold: 1000 - 200 - min(200, 15k) = 1000 - 200 - 200 = 600 + // ratioBuffer = ceil(0.2 * 800) = 160, safeBuffer = max(200, 160) = 200 + // compactionBuffer = min(200, 15k) = 200 + // Threshold: 1000 - 200 - 200 = 600 + const threshold = calculateThreshold(1000, 200); + expect(threshold).toBe(600); const chatHistory = createChatHistory(650); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -261,16 +282,20 @@ describe("tokenizer", () => { it("should not compact when input tokens are below threshold with maxTokens", () => { const model = createModel(1000, 200); // 1000 context, 200 max output - // Threshold: 1000 - 200 - min(200, 15k) = 600 - const chatHistory = createChatHistory(550); // Below threshold + const threshold = calculateThreshold(1000, 200); + const chatHistory = createChatHistory(threshold - 100); // Below threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(false); }); it("should use 35% default reservation when maxTokens is not set", () => { const model = createModel(1000); // No maxTokens - // Reserved: 1000 * 0.35 = 350 - // Threshold: 1000 - 350 - min(350, 15k) = 1000 - 350 - 350 = 300 + // Default maxTokens = min(1000 * 0.35, 64k) = 350 + // ratioBuffer = ceil(0.2 * 650) = 130, safeBuffer = max(350, 130) = 350 + // compactionBuffer = min(350, 15k) = 350 + // Threshold: 1000 - 350 - 350 = 300 + const threshold = calculateThreshold(1000, 350); + expect(threshold).toBe(300); const chatHistory = createChatHistory(350); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -278,14 +303,26 @@ describe("tokenizer", () => { it("should not compact when below default threshold without maxTokens", () => { const model = createModel(1000); // No maxTokens - // Reserved: 1000 * 0.35 = 350 - // Threshold: 1000 - 350 - min(350, 15k) = 300 + // Threshold: 300 (calculated above) const chatHistory = createChatHistory(250); // Below threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(false); }); - it("should throw error when maxTokens >= contextLength", () => { + it("should throw error when threshold becomes zero or negative", () => { + // With extremely high maxTokens relative to context, threshold can become <= 0 + const model = createModel(1000, 800); // maxTokens is 80% of context + // ratioBuffer = ceil(0.2 * 200) = 40, safeBuffer = max(800, 40) = 800 + // compactionBuffer = min(800, 15k) = 800 + // Threshold: 1000 - 800 - 800 = -600 (negative!) + const chatHistory = createChatHistory(1); // Minimal input + + expect(() => shouldAutoCompact({ chatHistory, model })).toThrow( + "max_tokens is larger than context_length, which should not be possible. Please check your configuration.", + ); + }); + + it("should throw error when maxTokens equals contextLength", () => { const model = createModel(1000, 1000); // maxTokens equals contextLength const chatHistory = createChatHistory(1); // Minimal input @@ -294,7 +331,7 @@ describe("tokenizer", () => { ); }); - it("should throw error when maxTokens > contextLength", () => { + it("should throw error when maxTokens exceeds contextLength", () => { const model = createModel(1000, 1200); // maxTokens exceeds contextLength const chatHistory = createChatHistory(1); // Minimal input @@ -305,7 +342,11 @@ describe("tokenizer", () => { it("should handle edge case with very small context limit", () => { const model = createModel(200, 50); // Small context - // Threshold: 200 - 50 - min(50, 15k) = 200 - 50 - 50 = 100 + // ratioBuffer = ceil(0.2 * 150) = 30, safeBuffer = max(50, 30) = 50 + // compactionBuffer = min(50, 15k) = 50 + // Threshold: 200 - 50 - 50 = 100 + const threshold = calculateThreshold(200, 50); + expect(threshold).toBe(100); const chatHistory = createChatHistory(110); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); @@ -314,6 +355,8 @@ describe("tokenizer", () => { it("should log debug information correctly", () => { const model = createModel(1000, 200); const chatHistory = createChatHistory(550); + const expectedBuffer = 200; // max(200, ceil(0.2*800)=160) = 200, min(200, 15k) = 200 + const expectedThreshold = 1000 - 200 - expectedBuffer; shouldAutoCompact({ chatHistory, model }); @@ -325,17 +368,21 @@ describe("tokenizer", () => { contextLimit: 1000, maxTokens: 200, reservedForOutput: 200, - compactionBuffer: 200, - compactionThreshold: 600, + compactionBuffer: expectedBuffer, + compactionThreshold: expectedThreshold, shouldCompact: expect.any(Boolean), }); }); it("should handle model with zero maxTokens correctly", () => { const model = createModel(1000, 0); // Explicit zero - // Should use default 35% reservation: 1000 * 0.35 = 350 - // Threshold: 1000 - 350 - min(350, 15k) = 300 - const chatHistory = createChatHistory(350); // Above threshold + // When maxTokens is 0, getModelMaxTokens returns 0 (not the default) + // ratioBuffer = ceil(0.2 * 1000) = 200, safeBuffer = max(0, 200) = 200 + // compactionBuffer = min(200, 15k) = 200 + // Threshold: 1000 - 0 - 200 = 800 + const threshold = calculateThreshold(1000, 0); + expect(threshold).toBe(800); + const chatHistory = createChatHistory(threshold + 50); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); @@ -344,8 +391,12 @@ describe("tokenizer", () => { it("should prevent Claude 3.5 Sonnet context overflow", () => { // Claude 3.5 Sonnet: 200k context, often uses 4k max_tokens const model = createModel(200_000, 4_000); - // Threshold: 200k - 4k - min(4k, 15k) = 200k - 4k - 4k = 192k - const chatHistory = createChatHistory(193_000); // Above threshold + // ratioBuffer = ceil(0.2 * 196k) = 39200, safeBuffer = max(4k, 39200) = 39200 + // compactionBuffer = min(39200, 15k) = 15000 + // Threshold: 200k - 4k - 15k = 181k + const threshold = calculateThreshold(200_000, 4_000); + expect(threshold).toBe(181_000); + const chatHistory = createChatHistory(threshold + 1000); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); @@ -353,8 +404,12 @@ describe("tokenizer", () => { it("should prevent GPT-4 context overflow", () => { // GPT-4: 128k context, often uses 4k max_tokens const model = createModel(128_000, 4_000); - // Threshold: 128k - 4k - min(4k, 15k) = 128k - 4k - 4k = 120k - const chatHistory = createChatHistory(121_000); // Above threshold + // ratioBuffer = ceil(0.2 * 124k) = 24800, safeBuffer = max(4k, 24800) = 24800 + // compactionBuffer = min(24800, 15k) = 15000 + // Threshold: 128k - 4k - 15k = 109k + const threshold = calculateThreshold(128_000, 4_000); + expect(threshold).toBe(109_000); + const chatHistory = createChatHistory(threshold + 1000); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); @@ -362,26 +417,41 @@ describe("tokenizer", () => { it("should handle models with very high max_tokens", () => { // Some models allow very high max_tokens (e.g., 64k) const model = createModel(200_000, 64_000); - // Threshold: 200k - 64k - min(64k, 15k) = 200k - 64k - 15k = 121k - const chatHistory = createChatHistory(125_000); // Above threshold + // ratioBuffer = ceil(0.2 * 136k) = 27200, safeBuffer = max(64k, 27200) = 64000 + // compactionBuffer = min(64k, 15k) = 15000 + // Threshold: 200k - 64k - 15k = 121k + const threshold = calculateThreshold(200_000, 64_000); + expect(threshold).toBe(121_000); + const chatHistory = createChatHistory(threshold + 1000); // Above threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(true); }); it("should cap buffer at AUTO_COMPACT_BUFFER_CAP for large maxTokens", () => { - // When maxTokens > AUTO_COMPACT_BUFFER_CAP, buffer should be capped + // When computed buffer > AUTO_COMPACT_BUFFER_CAP, buffer should be capped const contextLength = 200_000; const maxTokens = 64_000; const model = createModel(contextLength, maxTokens); - // Threshold: contextLength - maxTokens - min(maxTokens, AUTO_COMPACT_BUFFER_CAP) - const threshold = - contextLength - - maxTokens - - Math.min(maxTokens, AUTO_COMPACT_BUFFER_CAP); + const threshold = calculateThreshold(contextLength, maxTokens); const chatHistory = createChatHistory(threshold - 1000); // Below threshold expect(shouldAutoCompact({ chatHistory, model })).toBe(false); }); + + it("should use ratio-based buffer when maxTokens is small", () => { + // When maxTokens is small, ratio-based buffer should take precedence + const contextLength = 100_000; + const maxTokens = 1_000; + const model = createModel(contextLength, maxTokens); + // ratioBuffer = ceil(0.2 * 99k) = 19800, safeBuffer = max(1k, 19800) = 19800 + // compactionBuffer = min(19800, 15k) = 15000 + // Threshold: 100k - 1k - 15k = 84k + const threshold = calculateThreshold(contextLength, maxTokens); + expect(threshold).toBe(84_000); + const chatHistory = createChatHistory(threshold + 1000); // Above threshold + + expect(shouldAutoCompact({ chatHistory, model })).toBe(true); + }); }); }); diff --git a/extensions/cli/src/util/tokenizer.ts b/extensions/cli/src/util/tokenizer.ts index 8faf13aba..24317d47f 100644 --- a/extensions/cli/src/util/tokenizer.ts +++ b/extensions/cli/src/util/tokenizer.ts @@ -3,12 +3,13 @@ import type { ChatHistoryItem } from "core/index.js"; import { encode } from "gpt-tokenizer"; import type { ChatCompletionTool } from "openai/resources/chat/completions.mjs"; -import { - AUTO_COMPACT_BUFFER_CAP, - DEFAULT_CONTEXT_LENGTH, -} from "../compaction.js"; - import { logger } from "./logger.js"; + +const DEFAULT_MAX_TOKENS_RATIO = 0.35; +const MAX_MAX_TOKENS = 64_000; +// Default context length when model config doesn't specify one +export const DEFAULT_CONTEXT_LENGTH = 200_000; + /** * Get the context length limit for a model * @param modelName The model name @@ -20,6 +21,17 @@ export function getModelContextLimit(model: ModelConfig): number { ); } +export function getModelMaxTokens(model: ModelConfig): number { + const contextLimit = getModelContextLimit(model); + const maxTokens = model.defaultCompletionOptions?.maxTokens; + + return maxTokens === undefined + ? Math.ceil( + Math.min(contextLimit * DEFAULT_MAX_TOKENS_RATIO, MAX_MAX_TOKENS), + ) + : maxTokens; +} + // 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 @@ -348,82 +360,6 @@ export function countTotalInputTokens(params: TotalInputTokenParams): number { return totalTokens; } -/** - * Parameters for auto-compaction check - */ -export interface AutoCompactParams { - chatHistory: ChatHistoryItem[]; - model: ModelConfig; - systemMessage?: string; - tools?: ChatCompletionTool[]; -} - -/** - * Check if the chat history exceeds the auto-compact threshold. - * Accounts for system message and tool definitions in the calculation. - * @param params Object containing chatHistory, model, optional systemMessage, and optional tools - * @returns Whether auto-compacting should be triggered - */ -export function shouldAutoCompact(params: AutoCompactParams): boolean { - const { chatHistory, model, systemMessage, tools } = params; - - const inputTokens = countTotalInputTokens({ - chatHistory, - systemMessage, - tools, - model, - }); - const contextLimit = getModelContextLimit(model); - const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; - - // Calculate available space considering max_tokens reservation - // If maxTokens is not set, reserve 35% of context for output as a safe default - // (64k/200k with claude = 32%, round up to give a buffer) - const reservedForOutput = - maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); - // Additional buffer to trigger compaction before hitting context limit - // Threshold formula: contextLength - maxTokens - Min(maxTokens, 20k) - const compactionBuffer = Math.min(reservedForOutput, AUTO_COMPACT_BUFFER_CAP); - const compactionThreshold = - contextLimit - reservedForOutput - compactionBuffer; - - // Ensure we have positive space available for input - if (compactionThreshold <= 0) { - throw new Error( - `max_tokens is larger than context_length, which should not be possible. Please check your configuration.`, - ); - } - - const toolTokens = tools ? countToolDefinitionTokens(tools) : 0; - const systemTokens = systemMessage ? encode(systemMessage).length : 0; - const shouldCompact = inputTokens >= compactionThreshold; - - logger.debug("Context usage check", { - inputTokens, - historyTokens: countChatHistoryTokens(chatHistory, model), - systemTokens, - toolTokens, - contextLimit, - maxTokens, - reservedForOutput, - compactionBuffer, - compactionThreshold, - shouldCompact, - }); - - return shouldCompact; -} - -/** - * Get a descriptive message for auto-compaction that shows the context limit - * @param model The model configuration - * @returns A descriptive message explaining why compaction is needed - */ -export function getAutoCompactMessage(model: ModelConfig): string { - const limit = getModelContextLimit(model); - return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`; -} - /** * Parameters for context length validation */