linshenkx/prompt-optimizer · error · APIError

Anthropic API error (${error.status}): ${error.message}

Error message

Anthropic API error (${error.status}): ${error.message}

What it means

Anthropic's API returned a non-2xx status; the caught error has a numeric status property and the adapter formats it as 'Anthropic API error (status): message'. This maps directly to Anthropic's documented HTTP error codes (401 invalid key, 403 blocked region, 429 rate limit, 5xx server errors).

Source

Thrown at packages/core/src/services/llm/adapters/anthropic-adapter.ts:152

        console.log(`[AnthropicAdapter] Successfully fetched ${models.length} models`)
        return models
      }

      throw new APIError('Unexpected API response format')
    } catch (error: any) {
      console.error('[AnthropicAdapter] Failed to fetch models:', error)

      // 连接错误处理(包括跨域检测)
      if (error.message && (error.message.includes('Failed to fetch') ||
          error.message.includes('NetworkError') ||
          error.message.includes('ECONNREFUSED') ||
          error.message.includes('CORS'))) {
        throw new APIError(`Network error: ${error.message}`)
      }

      // API 错误处理
      if (error.status) {
        throw new APIError(`Anthropic API error (${error.status}): ${error.message}`)
      }

      // 其他错误
      throw error
    }
  }

  // ===== 参数定义(用于buildDefaultModel) =====

  /**
   * 获取参数定义
   */
  protected getParameterDefinitions(modelId: string): readonly ParameterDefinition[] {
    const samplingDefinitions: ParameterDefinition[] = [
      {
        name: 'temperature',
        labelKey: 'params.temperature.label',
        descriptionKey: 'params.temperature.description',

View on GitHub (pinned to 3e677b1d9f)

Solutions

  1. Check the status number in the message: 401/403 → rotate/reissue the API key and verify key permissions
  2. 429 → add backoff/retry and reduce request frequency
  3. 5xx → check status.anthropic.com and retry with exponential backoff
  4. Confirm the key is passed via connectionConfig.apiKey and matches the account/environment

Example fix

// before
const models = await adapter.getModelsAsync()

// after
try {
  const models = await adapter.getModelsAsync()
} catch (e: any) {
  const m = /Anthropic API error \((\d+)\)/.exec(e.message)
  if (m && Number(m[1]) === 429) return backoffRetry(() => adapter.getModelsAsync())
  throw e
}
Defensive patterns

Strategy: retry

Validate before calling

null

Type guard

function isAnthropicHttpError(e: unknown): e is APIError & { status?: number } {
  return e instanceof APIError && /Anthropic API error \(\d+\)/.test(e.message)
}

Try / catch

try { await adapter.getModelsAsync() }
catch (e) {
  if (isAnthropicHttpError(e)) {
    const status = Number(/\((\d+)\)/.exec(e.message)![1])
    if (status === 429 || status >= 500) return backoffRetry(() => adapter.getModelsAsync())
  }
  throw e
}

Prevention

When it happens

Trigger: getModelsAsync() with an invalid/expired x-api-key (401), hitting rate limits (429), region-blocked access (403), or an Anthropic outage (5xx).

Common situations: Revoked API key, wrong key environment variable, free-tier rate limiting, calling from a blocked geography without a proxy.

Related errors


AI-assisted analysis of linshenkx/prompt-optimizer@3e677b1d9f (2026-08-27). Data as JSON: /api/errors/29b2262ce9ca9afd. Report an issue: GitHub.