import * as plugins from './plugins.js'; import type { IAnthropicMessagesFailure, IAnthropicMessagesModel, TAnthropicMessagesErrorType, } from './interfaces.js'; /** * A request this service refuses, in the Anthropic error shape. Callbacks throw it to answer with their * own status and message, for example an `authenticate` that refuses a credential with 401. */ export class AnthropicMessagesError extends Error { public readonly failure: Readonly; constructor( statusArg: number, typeArg: TAnthropicMessagesErrorType, messageArg: string, detailsArg: { retryAfterSeconds?: number; shouldRetry?: boolean } = {}, optionsArg?: ErrorOptions, ) { super(messageArg, optionsArg); this.name = 'AnthropicMessagesError'; this.failure = Object.freeze({ status: statusArg, type: typeArg, message: messageArg, ...detailsArg }); } } export const invalidRequest = (messageArg: string): AnthropicMessagesError => new AnthropicMessagesError(400, 'invalid_request_error', messageArg); /** The one wording an Anthropic client compacts its conversation on. */ export const promptTooLong = (detailArg: string): IAnthropicMessagesFailure => ({ status: 400, type: 'invalid_request_error', message: `prompt is too long: ${detailArg}`, }); const maximumMessageLength = 1024; const bounded = (textArg: string): string => textArg.length > maximumMessageLength ? `${textArg.slice(0, maximumMessageLength)}...` : textArg; const isAbort = (errorArg: unknown): boolean => errorArg instanceof Error && (errorArg.name === 'AbortError' || errorArg.name === 'TimeoutError'); const fromLimit = (errorArg: unknown): IAnthropicMessagesFailure | undefined => { if (!plugins.isModelLimitError(errorArg)) return undefined; const limit = errorArg.limit; const waitMs = limit.retryAfterMs ?? (limit.resetsAt === undefined ? undefined : limit.resetsAt - Date.now()); return { status: 429, type: 'rate_limit_error', message: errorArg.message, ...(waitMs === undefined ? {} : { retryAfterSeconds: Math.max(1, Math.ceil(waitMs / 1000)) }), shouldRetry: limit.kind === 'rate_limit', }; }; const fromApiCall = (errorArg: unknown): IAnthropicMessagesFailure | undefined => { if (!plugins.APICallError.isInstance(errorArg)) return undefined; const status = errorArg.statusCode; const detail = bounded(errorArg.message); if (status === 400 || status === 422) { return { status: 400, type: 'invalid_request_error', message: `The model provider refused the request: ${detail}` }; } if (status === 401 || status === 403) { return { status: 403, type: 'permission_error', message: `The model provider refused this account's credentials: ${detail}`, shouldRetry: false, }; } if (status === 404) { return { status: 404, type: 'not_found_error', message: `The model provider does not know this model: ${detail}` }; } if (status === 413) { return { status: 413, type: 'request_too_large', message: `The model provider refused the request size: ${detail}` }; } if (status === 429) { return { status: 429, type: 'rate_limit_error', message: `The model provider is rate limiting: ${detail}`, shouldRetry: true }; } return { status: 500, type: 'api_error', message: `The model provider failed${status === undefined ? '' : ` with HTTP ${status}`}: ${detail}`, shouldRetry: errorArg.isRetryable, }; }; /** * States a failure of a request in the Anthropic shape: a refusal a callback threw, the model's own dialect, * a usage or rate limit, a provider HTTP failure, and anything else as an `api_error` naming the error. */ export const describeFailure = ( errorArg: unknown, modelArg?: IAnthropicMessagesModel, ): IAnthropicMessagesFailure => { if (errorArg instanceof AnthropicMessagesError) return errorArg.failure; return modelArg?.classifyFailure?.(errorArg) ?? fromLimit(errorArg) ?? fromApiCall(errorArg) ?? (isAbort(errorArg) ? { status: 499, type: 'api_error', message: 'The request was aborted.' } : { status: 500, type: 'api_error', message: `The model call failed: ${bounded(errorArg instanceof Error ? `${errorArg.name}: ${errorArg.message}` : String(errorArg))}`, }); }; export const failureBody = (failureArg: IAnthropicMessagesFailure, requestIdArg: string): string => JSON.stringify({ type: 'error', error: { type: failureArg.type, message: failureArg.message }, request_id: requestIdArg, }); export const failureHeaders = (failureArg: IAnthropicMessagesFailure): Record => ({ ...(failureArg.retryAfterSeconds === undefined ? {} : { 'retry-after': String(failureArg.retryAfterSeconds) }), ...(failureArg.shouldRetry === undefined ? {} : { 'x-should-retry': String(failureArg.shouldRetry) }), });