Changesets · Branches · Tags · Compare
| Changeset | 0bee98b44db879c63e13987da08cd06ebc0df21f66c5c410773e8d4e6084f695 |
|---|---|
| Author | Ting-Wai <40179554+tingwai@users.noreply.github.com> · 2025-09-17 16:03 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-09-17 16:03 -07:00 |
| Parents | f98b68abc084 |
6 files changed
modified core/llm/countTokens.ts +1 −1
| @@ -85,7 +85,7 @@ | ||
| 85 | 85 | |
| 86 | 86 | function countImageTokens(content: MessagePart): number { |
| 87 | 87 | if (content.type === "imageUrl") { |
| 88 | - return 85; | |
| 88 | + return 1024; | |
| 89 | 89 | } |
| 90 | 90 | throw new Error("Non-image content type"); |
| 91 | 91 | } |
modified extensions/cli/src/stream/streamChatResponse.ts +15 −0
| @@ -16,9 +16,11 @@ | ||
| 16 | 16 | import { ToolCall } from "../tools/index.js"; |
| 17 | 17 | import { |
| 18 | 18 | chatCompletionStreamWithBackoff, |
| 19 | + isContextLengthError, | |
| 19 | 20 | withExponentialBackoff, |
| 20 | 21 | } from "../util/exponentialBackoff.js"; |
| 21 | 22 | import { logger } from "../util/logger.js"; |
| 23 | +import { validateContextLength } from "../util/tokenizer.js"; | |
| 22 | 24 | |
| 23 | 25 | import { getAllTools, handleToolCalls } from "./handleToolCalls.js"; |
| 24 | 26 | import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; |
| @@ -148,6 +150,12 @@ | ||
| 148 | 150 | tools, |
| 149 | 151 | } = options; |
| 150 | 152 | |
| 153 | + // Validate context length before making the request | |
| 154 | + const validation = validateContextLength(chatHistory, model); | |
| 155 | + if (!validation.isValid) { | |
| 156 | + throw new Error(`Context length validation failed: ${validation.error}`); | |
| 157 | + } | |
| 158 | + | |
| 151 | 159 | // Get fresh system message and inject it |
| 152 | 160 | const systemMessage = await systemMessageService.getSystemMessage(); |
| 153 | 161 | const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage( |
| @@ -277,6 +285,13 @@ | ||
| 277 | 285 | shouldContinue: false, |
| 278 | 286 | }; |
| 279 | 287 | } |
| 288 | + | |
| 289 | + // Handle context length errors with helpful message | |
| 290 | + if (isContextLengthError(error)) { | |
| 291 | + logger.debug(`Context length exceeded: ${error}`); | |
| 292 | + throw new Error(`Context length exceeded: ${error}`); | |
| 293 | + } | |
| 294 | + | |
| 280 | 295 | throw error; |
| 281 | 296 | } |
| 282 | 297 |
modified extensions/cli/src/util/exponentialBackoff.ts +30 −0
| @@ -77,10 +77,40 @@ | ||
| 77 | 77 | ); |
| 78 | 78 | } |
| 79 | 79 | |
| 80 | +/** | |
| 81 | + * Checks if the error indicates a context length issue (non-retryable) | |
| 82 | + */ | |
| 83 | +export function isContextLengthError(error: any): boolean { | |
| 84 | + const errorMessage = error.message?.toLowerCase() || ""; | |
| 85 | + const contextLengthPatterns = [ | |
| 86 | + // Anthropic Claude | |
| 87 | + "input length and max_tokens exceed context limit", | |
| 88 | + "decrease input length or max_tokens", | |
| 89 | + // OpenAI | |
| 90 | + "maximum context length", | |
| 91 | + "reduce the length of the messages", | |
| 92 | + // Mistral | |
| 93 | + "tokens in the prompt exceeds", | |
| 94 | + "use a shorter prompt", | |
| 95 | + // Generic patterns | |
| 96 | + "context_length_exceeded", | |
| 97 | + "invalid_request_error", | |
| 98 | + ]; | |
| 99 | + | |
| 100 | + return contextLengthPatterns.some((pattern) => | |
| 101 | + errorMessage.includes(pattern), | |
| 102 | + ); | |
| 103 | +} | |
| 104 | + | |
| 80 | 105 | /** |
| 81 | 106 | * Determines if an error is retryable based on the error type and status code |
| 82 | 107 | */ |
| 83 | 108 | function isRetryableError(error: any): boolean { |
| 109 | + // Context length errors are never retryable - they need user intervention | |
| 110 | + if (isContextLengthError(error)) { | |
| 111 | + return false; | |
| 112 | + } | |
| 113 | + | |
| 84 | 114 | // Network errors are retryable |
| 85 | 115 | if (isNetworkError(error)) { |
| 86 | 116 | return true; |
added extensions/cli/src/util/tokenizer.contextValidation.test.ts +62 −0
| @@ -0,0 +1,62 @@ | ||
| 1 | +import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | +import { describe, expect, it } from "vitest"; | |
| 3 | + | |
| 4 | +import { validateContextLength } from "./tokenizer.js"; | |
| 5 | + | |
| 6 | +describe("validateContextLength", () => { | |
| 7 | + const createMockModel = ( | |
| 8 | + contextLength: number, | |
| 9 | + maxTokens?: number, | |
| 10 | + ): ModelConfig => ({ | |
| 11 | + name: "test-model", | |
| 12 | + model: "test", | |
| 13 | + provider: "openai", | |
| 14 | + defaultCompletionOptions: { | |
| 15 | + contextLength, | |
| 16 | + maxTokens, | |
| 17 | + }, | |
| 18 | + }); | |
| 19 | + | |
| 20 | + const createMockHistory = (messageCount: number, contentLength = 100) => { | |
| 21 | + return Array.from({ length: messageCount }, (_, i) => ({ | |
| 22 | + message: { | |
| 23 | + role: "user" as const, | |
| 24 | + content: "x".repeat(contentLength), // Roughly contentLength/4 tokens | |
| 25 | + }, | |
| 26 | + contextItems: [], | |
| 27 | + })); | |
| 28 | + }; | |
| 29 | + | |
| 30 | + it("should pass validation when within context limits", () => { | |
| 31 | + const model = createMockModel(1000, 200); | |
| 32 | + const chatHistory = createMockHistory(5, 40); // ~50 tokens total | |
| 33 | + | |
| 34 | + const result = validateContextLength(chatHistory, model); | |
| 35 | + | |
| 36 | + expect(result.isValid).toBe(true); | |
| 37 | + expect(result.error).toBeUndefined(); | |
| 38 | + }); | |
| 39 | + | |
| 40 | + it("should fail validation when input + maxTokens exceeds context limit", () => { | |
| 41 | + const model = createMockModel(1000, 800); | |
| 42 | + const chatHistory = createMockHistory(20, 100); // ~500+ tokens | |
| 43 | + | |
| 44 | + const result = validateContextLength(chatHistory, model); | |
| 45 | + | |
| 46 | + expect(result.isValid).toBe(false); | |
| 47 | + expect(result.error).toContain("Context length exceeded"); | |
| 48 | + expect(result.error).toContain("input"); | |
| 49 | + expect(result.error).toContain("max_tokens"); | |
| 50 | + expect(result.error).toContain("context_limit"); | |
| 51 | + }); | |
| 52 | + | |
| 53 | + it("should handle large models with appropriate scaling", () => { | |
| 54 | + const model = createMockModel(200_000, 64_000); // Claude-like model | |
| 55 | + const chatHistory = createMockHistory(100, 1000); // Large conversation | |
| 56 | + | |
| 57 | + const result = validateContextLength(chatHistory, model); | |
| 58 | + | |
| 59 | + expect(result.contextLimit).toBe(200_000); | |
| 60 | + expect(result.maxTokens).toBe(64_000); | |
| 61 | + }); | |
| 62 | +}); |
modified extensions/cli/src/util/tokenizer.test.ts +2 −2
| @@ -78,14 +78,14 @@ | ||
| 78 | 78 | role: "user", |
| 79 | 79 | content: [ |
| 80 | 80 | { type: "text", text: "Hello" }, // 5 chars -> ~2 tokens |
| 81 | - { type: "imageUrl", imageUrl: { url: "test.jpg" } }, // +85 tokens | |
| 81 | + { type: "imageUrl", imageUrl: { url: "test.jpg" } }, // +1024 tokens | |
| 82 | 82 | ], |
| 83 | 83 | }, |
| 84 | 84 | contextItems: [], |
| 85 | 85 | }; |
| 86 | 86 | |
| 87 | 87 | const tokenCount = countChatHistoryItemTokens(historyItem); |
| 88 | - expect(tokenCount).toBe(89); // 2 + 85 + 2 role tokens | |
| 88 | + expect(tokenCount).toBe(1028); // 2 + 1024 + 2 role tokens | |
| 89 | 89 | }); |
| 90 | 90 | |
| 91 | 91 | it("should count tokens for tool calls", () => { |
modified extensions/cli/src/util/tokenizer.ts +44 −1
| @@ -47,7 +47,7 @@ | ||
| 47 | 47 | // Images and other content types have their own token costs |
| 48 | 48 | // but we'll use a rough estimate for now |
| 49 | 49 | if (part.type === "imageUrl") { |
| 50 | - tokenCount += 85; // Rough estimate for image tokens | |
| 50 | + tokenCount += 1024; // Rough estimate for image tokens | |
| 51 | 51 | } |
| 52 | 52 | } |
| 53 | 53 | } |
| @@ -192,3 +192,46 @@ | ||
| 192 | 192 | const limit = getModelContextLimit(model); |
| 193 | 193 | return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`; |
| 194 | 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 | +} |