Elffuss BraidHub

kikocis/continue public

feat: add more robust context length validation (#7817)

Changeset0bee98b44db879c63e13987da08cd06ebc0df21f66c5c410773e8d4e6084f695
AuthorTing-Wai <40179554+tingwai@users.noreply.github.com> · 2025-09-17 16:03 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-17 16:03 -07:00
Parentsf98b68abc084

Browse the files at this changeset

6 files changed

modified core/llm/countTokens.ts +1 −1
@@ -85,7 +85,7 @@
8585
8686 function countImageTokens(content: MessagePart): number {
8787 if (content.type === "imageUrl") {
88- return 85;
88+ return 1024;
8989 }
9090 throw new Error("Non-image content type");
9191 }
modified extensions/cli/src/stream/streamChatResponse.ts +15 −0
@@ -16,9 +16,11 @@
1616 import { ToolCall } from "../tools/index.js";
1717 import {
1818 chatCompletionStreamWithBackoff,
19+ isContextLengthError,
1920 withExponentialBackoff,
2021 } from "../util/exponentialBackoff.js";
2122 import { logger } from "../util/logger.js";
23+import { validateContextLength } from "../util/tokenizer.js";
2224
2325 import { getAllTools, handleToolCalls } from "./handleToolCalls.js";
2426 import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
@@ -148,6 +150,12 @@
148150 tools,
149151 } = options;
150152
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+
151159 // Get fresh system message and inject it
152160 const systemMessage = await systemMessageService.getSystemMessage();
153161 const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage(
@@ -277,6 +285,13 @@
277285 shouldContinue: false,
278286 };
279287 }
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+
280295 throw error;
281296 }
282297
modified extensions/cli/src/util/exponentialBackoff.ts +30 −0
@@ -77,10 +77,40 @@
7777 );
7878 }
7979
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+
80105 /**
81106 * Determines if an error is retryable based on the error type and status code
82107 */
83108 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+
84114 // Network errors are retryable
85115 if (isNetworkError(error)) {
86116 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 @@
7878 role: "user",
7979 content: [
8080 { 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
8282 ],
8383 },
8484 contextItems: [],
8585 };
8686
8787 const tokenCount = countChatHistoryItemTokens(historyItem);
88- expect(tokenCount).toBe(89); // 2 + 85 + 2 role tokens
88+ expect(tokenCount).toBe(1028); // 2 + 1024 + 2 role tokens
8989 });
9090
9191 it("should count tokens for tool calls", () => {
modified extensions/cli/src/util/tokenizer.ts +44 −1
@@ -47,7 +47,7 @@
4747 // Images and other content types have their own token costs
4848 // but we'll use a rough estimate for now
4949 if (part.type === "imageUrl") {
50- tokenCount += 85; // Rough estimate for image tokens
50+ tokenCount += 1024; // Rough estimate for image tokens
5151 }
5252 }
5353 }
@@ -192,3 +192,46 @@
192192 const limit = getModelContextLimit(model);
193193 return `Approaching context limit (${(limit / 1000).toFixed(0)}K tokens). Auto-compacting chat history...`;
194194 }
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+}