| 1 | import { ModelConfig } from "@continuedev/config-yaml"; |
| 2 | import type { ChatHistoryItem } from "core/index.js"; |
| 3 | import { encode } from "gpt-tokenizer"; |
| 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 ChatHistoryItem |
| 27 | * @param historyItem The ChatHistoryItem to count tokens for |
| 28 | * @returns The estimated token count |
| 29 | */ |
| 30 | export function countChatHistoryItemTokens( |
| 31 | historyItem: ChatHistoryItem, |
| 32 | ): number { |
| 33 | try { |
| 34 | let tokenCount = 0; |
| 35 | |
| 36 | const message = historyItem.message; |
| 37 | |
| 38 | // Count tokens in content |
| 39 | if (typeof message.content === "string") { |
| 40 | tokenCount += encode(message.content).length; |
| 41 | } else if (Array.isArray(message.content)) { |
| 42 | // Handle array content (e.g., multimodal messages) |
| 43 | for (const part of message.content) { |
| 44 | if (part.type === "text" && part.text) { |
| 45 | tokenCount += encode(part.text).length; |
| 46 | } |
| 47 | // Images and other content types have their own token costs |
| 48 | // but we'll use a rough estimate for now |
| 49 | if (part.type === "imageUrl") { |
| 50 | tokenCount += 1024; // Rough estimate for image tokens |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // Add tokens for role (roughly 1-2 tokens) |
| 56 | tokenCount += 2; |
| 57 | |
| 58 | // Add tokens for tool calls if present |
| 59 | if ("toolCalls" in message && message.toolCalls) { |
| 60 | for (const toolCall of message.toolCalls) { |
| 61 | if (!toolCall.function) { |
| 62 | continue; |
| 63 | } |
| 64 | // Function name and structure overhead |
| 65 | tokenCount += encode(toolCall.function.name ?? "").length + 10; |
| 66 | // Arguments |
| 67 | tokenCount += encode(toolCall.function.arguments ?? "").length; |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // Add tokens for tool call results |
| 72 | if (message.role === "tool" && "content" in message) { |
| 73 | tokenCount += 5; // Tool message structure overhead |
| 74 | } |
| 75 | |
| 76 | // Add tokens for context items |
| 77 | for (const contextItem of historyItem.contextItems) { |
| 78 | tokenCount += encode(contextItem.content).length; |
| 79 | tokenCount += encode(contextItem.name).length; |
| 80 | tokenCount += 5; // Context item structure overhead |
| 81 | } |
| 82 | |
| 83 | return tokenCount; |
| 84 | } catch (error) { |
| 85 | logger.error("Error counting tokens for history item", error); |
| 86 | // Return a rough estimate based on character count |
| 87 | const message = historyItem.message; |
| 88 | const content = |
| 89 | typeof message.content === "string" |
| 90 | ? message.content |
| 91 | : JSON.stringify(message.content); |
| 92 | // Add rough estimate for context items |
| 93 | const contextContent = historyItem.contextItems |
| 94 | .map((item) => item.content + item.name) |
| 95 | .join(""); |
| 96 | return Math.ceil((content.length + contextContent.length) / 4); // Rough estimate: 4 chars per token |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | /** |
| 101 | * Estimate the token count for a single message (legacy compatibility) |
| 102 | * @param message The message to count tokens for |
| 103 | * @returns The estimated token count |
| 104 | * @deprecated Use countChatHistoryItemTokens instead |
| 105 | */ |
| 106 | export function countMessageTokens(message: ChatHistoryItem): number { |
| 107 | return countChatHistoryItemTokens(message); |
| 108 | } |
| 109 | |
| 110 | /** |
| 111 | * Estimate the total token count for a chat history |
| 112 | * @param chatHistory The chat history to count tokens for |
| 113 | * @returns The estimated total token count |
| 114 | */ |
| 115 | export function countChatHistoryTokens(chatHistory: ChatHistoryItem[]): number { |
| 116 | let totalTokens = 0; |
| 117 | |
| 118 | for (const historyItem of chatHistory) { |
| 119 | totalTokens += countChatHistoryItemTokens(historyItem); |
| 120 | } |
| 121 | |
| 122 | // Add some overhead for message structure (roughly 3 tokens per message) |
| 123 | totalTokens += chatHistory.length * 3; |
| 124 | |
| 125 | return totalTokens; |
| 126 | } |
| 127 | |
| 128 | /** |
| 129 | * Calculate the percentage of context used |
| 130 | * @param tokenCount Current token count |
| 131 | * @param modelName The model name |
| 132 | * @returns The percentage of context used (0-100) |
| 133 | */ |
| 134 | export function calculateContextUsagePercentage( |
| 135 | tokenCount: number, |
| 136 | model: ModelConfig, |
| 137 | ): number { |
| 138 | const limit = getModelContextLimit(model); |
| 139 | return Math.min(100, Math.round((tokenCount / limit) * 100)); |
| 140 | } |
| 141 | |
| 142 | /** |
| 143 | * Check if the chat history exceeds the auto-compact threshold |
| 144 | * @param chatHistory The chat history to check |
| 145 | * @param model The model configuration |
| 146 | * @returns Whether auto-compacting should be triggered |
| 147 | */ |
| 148 | export function shouldAutoCompact( |
| 149 | chatHistory: ChatHistoryItem[], |
| 150 | model: ModelConfig, |
| 151 | ): boolean { |
| 152 | const inputTokens = countChatHistoryTokens(chatHistory); |
| 153 | const contextLimit = getModelContextLimit(model); |
| 154 | const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; |
| 155 | |
| 156 | // Calculate available space considering max_tokens reservation |
| 157 | // If maxTokens is not set, reserve 35% of context for output as a safe default |
| 158 | // (64k/200k with claude = 32%, round up to give a buffer) |
| 159 | const reservedForOutput = |
| 160 | maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); |
| 161 | const availableForInput = contextLimit - reservedForOutput; |
| 162 | |
| 163 | // Ensure we have positive space available for input |
| 164 | if (availableForInput <= 0) { |
| 165 | throw new Error( |
| 166 | `max_tokens is larger than context_length, which should not be possible. Please check your configuration.`, |
| 167 | ); |
| 168 | } |
| 169 | |
| 170 | const usage = inputTokens / availableForInput; |
| 171 | |
| 172 | logger.debug("Context usage check", { |
| 173 | inputTokens, |
| 174 | contextLimit, |
| 175 | maxTokens, |
| 176 | reservedForOutput, |
| 177 | availableForInput, |
| 178 | usage: `${Math.round(usage * 100)}%`, |
| 179 | threshold: `${Math.round(AUTO_COMPACT_THRESHOLD * 100)}%`, |
| 180 | shouldCompact: usage >= AUTO_COMPACT_THRESHOLD, |
| 181 | }); |
| 182 | |
| 183 | return usage >= AUTO_COMPACT_THRESHOLD; |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * Get a descriptive message for auto-compaction that shows the context limit |
| 188 | * @param model The model configuration |
| 189 | * @returns A descriptive message explaining why compaction is needed |
| 190 | */ |
| 191 | export function getAutoCompactMessage(model: ModelConfig): string { |
| 192 | const limit = getModelContextLimit(model); |
| 193 | return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`; |
| 194 | } |
| 195 | |
| 196 | /** |
| 197 | * Validates that the input tokens + max_tokens don't exceed context limit |
| 198 | * @param chatHistory The chat history to validate |
| 199 | * @param model The model configuration |
| 200 | * @returns Validation result with error details if invalid |
| 201 | */ |
| 202 | export function validateContextLength( |
| 203 | chatHistory: ChatHistoryItem[], |
| 204 | model: ModelConfig, |
| 205 | ): { |
| 206 | isValid: boolean; |
| 207 | error?: string; |
| 208 | inputTokens?: number; |
| 209 | contextLimit?: number; |
| 210 | maxTokens?: number; |
| 211 | } { |
| 212 | const inputTokens = countChatHistoryTokens(chatHistory); |
| 213 | const contextLimit = getModelContextLimit(model); |
| 214 | const maxTokens = model.defaultCompletionOptions?.maxTokens || 0; |
| 215 | |
| 216 | // If maxTokens is not set, use 35% default reservation for output |
| 217 | const reservedForOutput = |
| 218 | maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35); |
| 219 | const totalRequired = inputTokens + reservedForOutput; |
| 220 | |
| 221 | if (totalRequired > contextLimit) { |
| 222 | return { |
| 223 | isValid: false, |
| 224 | error: `Context length exceeded: input (${inputTokens.toLocaleString()}) + max_tokens (${reservedForOutput.toLocaleString()}) = ${totalRequired.toLocaleString()} > context_limit (${contextLimit.toLocaleString()})`, |
| 225 | inputTokens, |
| 226 | contextLimit, |
| 227 | maxTokens: reservedForOutput, |
| 228 | }; |
| 229 | } |
| 230 | |
| 231 | return { |
| 232 | isValid: true, |
| 233 | inputTokens, |
| 234 | contextLimit, |
| 235 | maxTokens: reservedForOutput, |
| 236 | }; |
| 237 | } |