| 1 | import { ModelConfig } from "@continuedev/config-yaml"; |
| 2 | import { encode } from "gpt-tokenizer"; |
| 3 | import { ChatCompletionMessageParam } from "openai/resources.mjs"; |
| 4 | |
| 5 | import { logger } from "./logger.js"; |
| 6 | |
| 7 | // Global auto-compact threshold (80% of context limit) |
| 8 | // This is intentionally not configurable to ensure consistent behavior |
| 9 | // across all usage scenarios. Change this value only for testing purposes. |
| 10 | export const AUTO_COMPACT_THRESHOLD = 0.8; |
| 11 | |
| 12 | const DEFAULT_CONTEXT_LENGTH_FOR_COMPACTION = 200_000; |
| 13 | /** |
| 14 | * Get the context length limit for a model |
| 15 | * @param modelName The model name |
| 16 | * @returns The context length limit in tokens |
| 17 | */ |
| 18 | export function getModelContextLimit(model: ModelConfig): number { |
| 19 | return ( |
| 20 | model.defaultCompletionOptions?.contextLength ?? |
| 21 | DEFAULT_CONTEXT_LENGTH_FOR_COMPACTION |
| 22 | ); |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * Estimate the token count for a single message |
| 27 | * @param message The message to count tokens for |
| 28 | * @returns The estimated token count |
| 29 | */ |
| 30 | export function countMessageTokens( |
| 31 | message: ChatCompletionMessageParam, |
| 32 | ): number { |
| 33 | try { |
| 34 | let tokenCount = 0; |
| 35 | |
| 36 | // Count tokens in content |
| 37 | if (typeof message.content === "string") { |
| 38 | tokenCount += encode(message.content).length; |
| 39 | } else if (Array.isArray(message.content)) { |
| 40 | // Handle array content (e.g., multimodal messages) |
| 41 | for (const part of message.content) { |
| 42 | if (part.type === "text" && part.text) { |
| 43 | tokenCount += encode(part.text).length; |
| 44 | } |
| 45 | // Images and other content types have their own token costs |
| 46 | // but we'll use a rough estimate for now |
| 47 | if (part.type === "image_url") { |
| 48 | tokenCount += 85; // Rough estimate for image tokens |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | // Add tokens for role (roughly 1-2 tokens) |
| 54 | tokenCount += 2; |
| 55 | |
| 56 | // Add tokens for tool calls if present |
| 57 | if ("tool_calls" in message && message.tool_calls) { |
| 58 | for (const toolCall of message.tool_calls) { |
| 59 | // Function name and structure overhead |
| 60 | tokenCount += encode(toolCall.function.name).length + 10; |
| 61 | // Arguments |
| 62 | tokenCount += encode(toolCall.function.arguments).length; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | // Add tokens for tool call results |
| 67 | if (message.role === "tool" && "content" in message) { |
| 68 | tokenCount += 5; // Tool message structure overhead |
| 69 | } |
| 70 | |
| 71 | return tokenCount; |
| 72 | } catch (error) { |
| 73 | logger.error("Error counting tokens for message", error); |
| 74 | // Return a rough estimate based on character count |
| 75 | const content = |
| 76 | typeof message.content === "string" |
| 77 | ? message.content |
| 78 | : JSON.stringify(message.content); |
| 79 | return Math.ceil(content.length / 4); // Rough estimate: 4 chars per token |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /** |
| 84 | * Estimate the total token count for a chat history |
| 85 | * @param chatHistory The chat history to count tokens for |
| 86 | * @returns The estimated total token count |
| 87 | */ |
| 88 | export function countChatHistoryTokens( |
| 89 | chatHistory: ChatCompletionMessageParam[], |
| 90 | ): number { |
| 91 | let totalTokens = 0; |
| 92 | |
| 93 | for (const message of chatHistory) { |
| 94 | totalTokens += countMessageTokens(message); |
| 95 | } |
| 96 | |
| 97 | // Add some overhead for message structure (roughly 3 tokens per message) |
| 98 | totalTokens += chatHistory.length * 3; |
| 99 | |
| 100 | return totalTokens; |
| 101 | } |
| 102 | |
| 103 | /** |
| 104 | * Calculate the percentage of context used |
| 105 | * @param tokenCount Current token count |
| 106 | * @param modelName The model name |
| 107 | * @returns The percentage of context used (0-100) |
| 108 | */ |
| 109 | export function calculateContextUsagePercentage( |
| 110 | tokenCount: number, |
| 111 | model: ModelConfig, |
| 112 | ): number { |
| 113 | const limit = getModelContextLimit(model); |
| 114 | return Math.min(100, Math.round((tokenCount / limit) * 100)); |
| 115 | } |
| 116 | |
| 117 | /** |
| 118 | * Check if the chat history exceeds the auto-compact threshold |
| 119 | * @param chatHistory The chat history to check |
| 120 | * @param model The model configuration |
| 121 | * @returns Whether auto-compacting should be triggered |
| 122 | */ |
| 123 | export function shouldAutoCompact( |
| 124 | chatHistory: ChatCompletionMessageParam[], |
| 125 | model: ModelConfig, |
| 126 | ): boolean { |
| 127 | const inputTokens = countChatHistoryTokens(chatHistory); |
| 128 | const contextLimit = getModelContextLimit(model); |
| 129 | const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; |
| 130 | |
| 131 | // Calculate available space considering max_tokens reservation |
| 132 | // If maxTokens is not set, reserve 35% of context for output as a safe default |
| 133 | // (64k/200k with claude = 32%, round up to give a buffer) |
| 134 | const reservedForOutput = |
| 135 | maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); |
| 136 | const availableForInput = contextLimit - reservedForOutput; |
| 137 | |
| 138 | // Ensure we have positive space available for input |
| 139 | if (availableForInput <= 0) { |
| 140 | throw new Error( |
| 141 | `max_tokens is larger than context_length, which should not be possible. Please check your configuration.`, |
| 142 | ); |
| 143 | } |
| 144 | |
| 145 | const usage = inputTokens / availableForInput; |
| 146 | |
| 147 | logger.debug("Context usage check", { |
| 148 | inputTokens, |
| 149 | contextLimit, |
| 150 | maxTokens, |
| 151 | reservedForOutput, |
| 152 | availableForInput, |
| 153 | usage: `${Math.round(usage * 100)}%`, |
| 154 | threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`, |
| 155 | shouldCompact: usage >= AUTO_COMPACT_THRESHOLD, |
| 156 | }); |
| 157 | |
| 158 | return usage >= AUTO_COMPACT_THRESHOLD; |
| 159 | } |
| 160 | |
| 161 | /** |
| 162 | * Get a descriptive message for auto-compaction that shows the context limit |
| 163 | * @param model The model configuration |
| 164 | * @returns A descriptive message explaining why compaction is needed |
| 165 | */ |
| 166 | export function getAutoCompactMessage(model: ModelConfig): string { |
| 167 | const limit = getModelContextLimit(model); |
| 168 | return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`; |
| 169 | } |