linshenkx/prompt-optimizer · error · APIError

Network error: ${error.message}

Error message

Network error: ${error.message}

What it means

The fetch to Anthropic's models endpoint failed at the network level (message contains 'Failed to fetch', 'NetworkError', 'ECONNREFUSED', or 'CORS') and the adapter re-wraps it as an APIError prefixed with 'Network error:'. This is a browser/runtime connectivity problem, not an Anthropic-side API error.

Source

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

        if (models.length === 0) {
          throw new APIError('API returned empty model list')
        }

        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[] {

View on GitHub (pinned to 3e677b1d9f)

Solutions

  1. If running in a browser, route requests through a server-side proxy — Anthropic's API does not send CORS headers
  2. Check the gateway/local service is up: curl $BASE_URL/v1/models from the same machine
  3. Ensure the base URL scheme/port are correct (https vs http, right port) and no VPN/firewall blocks it
  4. For self-hosted proxies, enable CORS headers for your app origin

Example fix

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

// after
const models = await withRetry(
  () => adapter.getModelsAsync(),
  { retries: 2, isRetryable: (e) => e instanceof APIError && e.message.startsWith('Network error') }
)
Defensive patterns

Strategy: retry

Validate before calling

async function canReach(url: string) {
  try { await fetch(url, { method: 'HEAD', mode: 'no-cors' }); return true }
  catch { return false }
}

Type guard

function isNetworkError(e: unknown): e is APIError {
  return e instanceof APIError && e.message.startsWith('Network error')
}

Try / catch

try { models = await adapter.getModelsAsync() }
catch (e) {
  if (isNetworkError(e)) return withBackoff(() => adapter.getModelsAsync(), 3)
  throw e
}

Prevention

When it happens

Trigger: Running getModelsAsync() in a browser where the target host is unreachable, CORS headers are missing on a self-hosted proxy, the service is down (ECONNREFUSED on localhost), or a firewall/VPN blocks api.anthropic.com.

Common situations: Calling the Anthropic API directly from a web app (CORS is not allowed by Anthropic), local LLM gateway not running on the configured port, corporate proxy interference, offline development.

Related errors


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