Fixing context exceeded error (#5479)
* Detect OpenAI context window errors and auto-retry
- Add checkIsOpenAIContextWindowError to identify OpenAI context length issues (context_length_exceeded, 400 + context-length patterns)
- Integrate into Task: detect OpenAiHandler/OpenAiNativeHandler and handle first-chunk failures as context window overflows
- On detection, aggressively truncate history ("quarter"), persist changes, show truncation notice, wait 1s, then retry once
- Align behavior with Anthropic/OpenRouter handling to reduce failures from oversized prompts
* Fixing OpenAI context exceeded errors
* Fixing OpenAI context exceeded errors
* Fixing OpenAI context exceeded errors
* use OpenAI sdk error types
* Making errors for this generic and adding cerebras
* Making errors for this generic and adding cerebras
---------
Co-authored-by: abeatrix <beatrix@cline.bot>
This commit is contained in:
1 parent
2cf1d8628b
commit
44eb2cc65e
3 files changed
+85
-44
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"claude-dev": patch
|
||||
---
|
||||
|
||||
Adding OpenAI context window exceeded error handling
|
||||
@@ -1,15 +1,68 @@
|
||||
export function checkIsOpenRouterContextWindowError(error: any): boolean {
|
||||
import LengthFinishReasonError, { APIError } from "openai"
|
||||
|
||||
export function checkContextWindowExceededError(error: unknown): boolean {
|
||||
return (
|
||||
checkIsOpenAIContextWindowError(error) ||
|
||||
checkIsOpenRouterContextWindowError(error) ||
|
||||
checkIsAnthropicContextWindowError(error) ||
|
||||
checkIsCerebrasContextWindowError(error)
|
||||
)
|
||||
}
|
||||
|
||||
function checkIsOpenRouterContextWindowError(error: any): boolean {
|
||||
try {
|
||||
return error.code === 400 && error.message?.includes("context length")
|
||||
} catch (e: unknown) {
|
||||
const status = error?.status ?? error?.code ?? error?.error?.status ?? error?.response?.status
|
||||
const message: string = String(error?.message || error?.error?.message || "")
|
||||
|
||||
// Known OpenAI/OpenRouter-style signal (code 400 and message includes "context length")
|
||||
const CONTEXT_ERROR_PATTERNS = [
|
||||
/\bcontext\s*(?:length|window)\b/i,
|
||||
/\bmaximum\s*context\b/i,
|
||||
/\b(?:input\s*)?tokens?\s*exceed/i,
|
||||
/\btoo\s*many\s*tokens?\b/i,
|
||||
] as const
|
||||
|
||||
return String(status) === "400" && CONTEXT_ERROR_PATTERNS.some((pattern) => pattern.test(message))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export function checkIsAnthropicContextWindowError(response: any): boolean {
|
||||
// Docs: https://platform.openai.com/docs/guides/error-codes/api-errors
|
||||
function checkIsOpenAIContextWindowError(error: unknown): boolean {
|
||||
try {
|
||||
if (error instanceof LengthFinishReasonError) {
|
||||
return true
|
||||
}
|
||||
|
||||
const KNOWN_CONTEXT_ERROR_SUBSTRINGS = ["token", "context length"] as const
|
||||
|
||||
return (
|
||||
Boolean(error) &&
|
||||
error instanceof APIError &&
|
||||
error.code?.toString() === "400" &&
|
||||
KNOWN_CONTEXT_ERROR_SUBSTRINGS.some((substring) => error.message.includes(substring))
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function checkIsAnthropicContextWindowError(response: any): boolean {
|
||||
try {
|
||||
return response?.error?.error?.type === "invalid_request_error"
|
||||
} catch (e: unknown) {
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function checkIsCerebrasContextWindowError(response: any): boolean {
|
||||
try {
|
||||
const status = response?.status ?? response?.code ?? response?.error?.status ?? response?.response?.status
|
||||
const message: string = String(response?.message || response?.error?.message || "")
|
||||
|
||||
return String(status) === "400" && message.includes("Please reduce the length of the messages or completion")
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
+22
-39
@@ -3,6 +3,8 @@ import { ApiHandler, buildApiHandler } from "@api/index"
|
||||
import { AnthropicHandler } from "@api/providers/anthropic"
|
||||
import { ClineHandler } from "@api/providers/cline"
|
||||
import { OpenRouterHandler } from "@api/providers/openrouter"
|
||||
import { OpenAiHandler } from "@api/providers/openai"
|
||||
import { OpenAiNativeHandler } from "@api/providers/openai-native"
|
||||
import { ApiStream } from "@api/transform/stream"
|
||||
import { DIFF_VIEW_URI_SCHEME } from "@hosts/vscode/VscodeDiffViewProvider"
|
||||
import CheckpointTracker from "@integrations/checkpoints/CheckpointTracker"
|
||||
@@ -41,10 +43,7 @@ import { HostProvider } from "@/hosts/host-provider"
|
||||
import { ClineErrorType } from "@/services/error/ClineError"
|
||||
import { errorService } from "@/services/posthog/PostHogClientProvider"
|
||||
import { parseAssistantMessageV2, parseAssistantMessageV3, ToolUseName } from "@core/assistant-message"
|
||||
import {
|
||||
checkIsAnthropicContextWindowError,
|
||||
checkIsOpenRouterContextWindowError,
|
||||
} from "@core/context/context-management/context-error-handling"
|
||||
import { checkContextWindowExceededError } from "@core/context/context-management/context-error-handling"
|
||||
import { getContextWindowInfo } from "@core/context/context-management/context-window-utils"
|
||||
import { ContextManager } from "@core/context/context-management/ContextManager"
|
||||
import { FileContextTracker } from "@core/context/context-tracking/FileContextTracker"
|
||||
@@ -1689,6 +1688,21 @@ export class Task {
|
||||
return { modelId, providerId }
|
||||
}
|
||||
|
||||
private async handleContextWindowExceededError(): Promise<void> {
|
||||
this.taskState.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange(
|
||||
this.messageStateHandler.getApiConversationHistory(),
|
||||
this.taskState.conversationHistoryDeletedRange,
|
||||
"quarter", // Force aggressive truncation
|
||||
)
|
||||
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
|
||||
await this.contextManager.triggerApplyStandardContextTruncationNoticeChange(
|
||||
Date.now(),
|
||||
await ensureTaskDirectoryExists(this.getContext(), this.taskId),
|
||||
)
|
||||
|
||||
this.taskState.didAutomaticallyRetryFailedApiRequest = true
|
||||
}
|
||||
|
||||
async *attemptApiRequest(previousApiReqIndex: number): ApiStream {
|
||||
// Wait for MCP servers to be connected before generating system prompt
|
||||
await pWaitFor(() => this.mcpHub.isConnecting !== true, {
|
||||
@@ -1780,10 +1794,7 @@ export class Task {
|
||||
yield firstChunk.value
|
||||
this.taskState.isWaitingForFirstChunk = false
|
||||
} catch (error) {
|
||||
const isOpenRouter = this.api instanceof OpenRouterHandler || this.api instanceof ClineHandler
|
||||
const isAnthropic = this.api instanceof AnthropicHandler
|
||||
const isOpenRouterContextWindowError = checkIsOpenRouterContextWindowError(error) && isOpenRouter
|
||||
const isAnthropicContextWindowError = checkIsAnthropicContextWindowError(error) && isAnthropic
|
||||
const isContextWindowExceededError = checkContextWindowExceededError(error)
|
||||
const { modelId, providerId } = await this.getCurrentProviderInfo()
|
||||
const clineError = errorService.toClineError(error, modelId, providerId)
|
||||
|
||||
@@ -1792,41 +1803,13 @@ export class Task {
|
||||
errorService.logMessage(clineError.message)
|
||||
errorService.logException(clineError)
|
||||
|
||||
if (isAnthropic && isAnthropicContextWindowError && !this.taskState.didAutomaticallyRetryFailedApiRequest) {
|
||||
this.taskState.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange(
|
||||
this.messageStateHandler.getApiConversationHistory(),
|
||||
this.taskState.conversationHistoryDeletedRange,
|
||||
"quarter", // Force aggressive truncation
|
||||
)
|
||||
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
|
||||
await this.contextManager.triggerApplyStandardContextTruncationNoticeChange(
|
||||
Date.now(),
|
||||
await ensureTaskDirectoryExists(this.getContext(), this.taskId),
|
||||
)
|
||||
|
||||
this.taskState.didAutomaticallyRetryFailedApiRequest = true
|
||||
} else if (isOpenRouter && !this.taskState.didAutomaticallyRetryFailedApiRequest) {
|
||||
if (isOpenRouterContextWindowError) {
|
||||
this.taskState.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange(
|
||||
this.messageStateHandler.getApiConversationHistory(),
|
||||
this.taskState.conversationHistoryDeletedRange,
|
||||
"quarter", // Force aggressive truncation
|
||||
)
|
||||
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
|
||||
await this.contextManager.triggerApplyStandardContextTruncationNoticeChange(
|
||||
Date.now(),
|
||||
await ensureTaskDirectoryExists(this.getContext(), this.taskId),
|
||||
)
|
||||
}
|
||||
|
||||
console.log("first chunk failed, waiting 1 second before retrying")
|
||||
await setTimeoutPromise(1000)
|
||||
this.taskState.didAutomaticallyRetryFailedApiRequest = true
|
||||
if (isContextWindowExceededError && !this.taskState.didAutomaticallyRetryFailedApiRequest) {
|
||||
await this.handleContextWindowExceededError()
|
||||
} else {
|
||||
// request failed after retrying automatically once, ask user if they want to retry again
|
||||
// note that this api_req_failed ask is unique in that we only present this option if the api hasn't streamed any content yet (ie it fails on the first chunk due), as it would allow them to hit a retry button. However if the api failed mid-stream, it could be in any arbitrary state where some tools may have executed, so that error is handled differently and requires cancelling the task entirely.
|
||||
|
||||
if (isOpenRouterContextWindowError || isAnthropicContextWindowError) {
|
||||
if (isContextWindowExceededError) {
|
||||
const truncatedConversationHistory = this.contextManager.getTruncatedMessages(
|
||||
this.messageStateHandler.getApiConversationHistory(),
|
||||
this.taskState.conversationHistoryDeletedRange,
|
||||
|
||||
Reference in new issue
Block a user