diff --git a/.changeset/slimy-goats-hide.md b/.changeset/slimy-goats-hide.md new file mode 100644 index 00000000..63d65439 --- /dev/null +++ b/.changeset/slimy-goats-hide.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Adding OpenAI context window exceeded error handling diff --git a/src/core/context/context-management/context-error-handling.ts b/src/core/context/context-management/context-error-handling.ts index ad63605a..c3c0a925 100644 --- a/src/core/context/context-management/context-error-handling.ts +++ b/src/core/context/context-management/context-error-handling.ts @@ -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 } } diff --git a/src/core/task/index.ts b/src/core/task/index.ts index e37db174..053f0e90 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -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 { + 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,