{"record":{"id":"22f41ff7a54de93b","repo":"vercel/ai","slug":"cannot-connect-to-api-cause-message-22f41f","errorCode":null,"errorMessage":"Cannot connect to API: ${cause.message}","messagePattern":"Cannot connect to API: (.+?)","errorType":"exception","errorClass":"APICallError","httpStatus":null,"severity":"error","filePath":"packages/provider-utils/src/post-to-api.ts","lineNumber":164,"sourceCode":"      });\n    } catch (error) {\n      if (error instanceof Error) {\n        if (isAbortError(error) || APICallError.isInstance(error)) {\n          throw error;\n        }\n      }\n\n      throw new APICallError({\n        message: 'Failed to process successful response',\n        cause: error,\n        statusCode: response.status,\n        url,\n        responseHeaders,\n        requestBodyValues: body.values,\n      });\n    }\n  } catch (error) {\n    throw handleFetchError({ error, url, requestBodyValues: body.values });\n  }\n};\n","sourceCodeStart":146,"sourceCodeEnd":167,"githubUrl":"https://github.com/vercel/ai/blob/69428b1f8b037e4d118fb4853428d5c4e620493c/packages/provider-utils/src/post-to-api.ts#L146-L167","documentation":"postToApi catches fetch exceptions thrown while POSTing a request body (JSON or form data) and rethrows them through handleFetchError as an APICallError: 'Cannot connect to API: <cause.message>' with isRetryable: true. This is the SDK's normalization of transport-level failures — the request never received an HTTP response from the provider endpoint.","triggerScenarios":"Any provider call that uses postJsonToApi/postFormDataToApi (generateText, streamText, generateObject, embeddings, etc.) when fetch itself throws: connection refused/timeout/reset (ECONNREFUSED, ETIMEDOUT, ECONNRESET, UND_ERR_SOCKET), DNS resolution failure, or body upload interrupted mid-flight.","commonSituations":"Wrong or unreachable baseURL (self-hosted gateways, Azure resource URL typos); API endpoint down or rate-limited at load balancer level; VPN/proxy required but not configured; container DNS failures; long uploads hitting UND_ERR_HEADERS_TIMEOUT against slow gateways; intermittent network blips in serverless environments.","solutions":["Inspect error.cause for the underlying code and fix accordingly: ECONNREFUSED → endpoint not running; ENOTFOUND → hostname typo; ETIMEDOUT/ECONNRESET → network/firewall/load balancer issue.","Retry with exponential backoff — handleFetchError marks these isRetryable: true — or enable the SDK's maxRetries option (default 2).","Verify the provider baseURL (createOpenAI({ baseURL }), Azure deployment URLs) resolves from your runtime.","Configure proxy/dispatcher (undici ProxyAgent, HTTPS_PROXY) in corporate or containerized environments.","Increase fetch timeouts for slow gateways (UND_ERR_HEADERS_TIMEOUT/BODY_TIMEOUT) via a custom undici Agent."],"exampleFix":"// before\nconst openai = createOpenAI({ baseURL: 'http://localhost:8080/v1' });\n// after (gateway actually running on 8000)\nconst openai = createOpenAI({ baseURL: 'http://localhost:8000/v1' });\n// plus retry in the call\ngenerateText({ model: openai('gpt-4o'), prompt, maxRetries: 5 });","handlingStrategy":"retry","validationCode":"// before the call\nconst endpoint = new URL(baseURL);\nawait fetch(endpoint.origin, { method: 'HEAD', signal: AbortSignal.timeout(3000) }).catch(e => { throw new Error(`API endpoint not reachable from this host: ${e.cause?.code ?? e.message}`); });","typeGuard":"import { APICallError } from '@ai-sdk/provider';\nfunction isPostConnectionError(e: unknown): e is APICallError {\n  return APICallError.isInstance(e) && e.isRetryable === true && e.message.startsWith('Cannot connect to API:');\n}","tryCatchPattern":"try {\n  const result = await generateText({ model, prompt, maxRetries: 4 });\n} catch (error) {\n  if (APICallError.isInstance(error) && error.isRetryable && error.message.startsWith('Cannot connect to API:')) {\n    // inspect error.cause.code: ECONNREFUSED -> service down, ETIMEDOUT -> firewall/timeout\n    // escalate after exhausting retries\n  }\n  throw error;\n}","preventionTips":["Double-check baseURL configuration for self-hosted/Azure/custom gateways before deployment.","Use maxRetries (SDK built-in exponential backoff) for transient connection failures.","Ensure gateways (vLLM/LiteLLM/Ollama) are running and health-checked in orchestration configs.","Configure proxy/TLS setup (ProxyAgent, corporate CAs) in restricted networks.","Raise undici header/body timeouts for slow or large POST payloads."],"tags":["network","fetch-failed","connection","retry","timeout"],"backgroundTag":"cannot-connect-to-api","analyzedSha":"69428b1f8b037e4d118fb4853428d5c4e620493c","analyzedAt":"2026-08-30T12:32:21.016Z","schemaVersion":2},"datasetVersion":"2026-08-30T13:17:10.514Z"}