Home / Learn / Claude with the Vercel AI SDK: createAnthropic baseURL, streaming and fixes

Claude with the Vercel AI SDK: createAnthropic baseURL, streaming and fixes

The AI SDK's Anthropic provider, @ai-sdk/anthropic, talks to the Messages API. Its baseURL defaults to https://api.anthropic.com/v1, so for a gateway you replace that whole prefix, including /v1. OpenCode, Kilo Code and many agent frameworks use this same provider underneath, which is why the same rule shows up in their configs.

Install

terminal
npm i ai @ai-sdk/anthropic

Create the provider

lib/anthropic.ts
import { createAnthropic } from '@ai-sdk/anthropic';

export const anthropic = createAnthropic({
  baseURL: 'https://aiprimetech.io/v1',                 // replaces https://api.anthropic.com/v1
  apiKey: process.env.AIPRIME_API_KEY,  // sent as x-api-key; defaults to ANTHROPIC_API_KEY
});
There is no environment variable for the base URL in @ai-sdk/anthropic: pass baseURL in code. The plain anthropic import always targets Anthropic's own endpoint.

generateText and streamText

generate.ts
import { generateText } from 'ai';
import { anthropic } from './lib/anthropic';

const { text, usage } = await generateText({
  model: anthropic('claude-sonnet-5'),
  prompt: 'Explain idempotency keys in two sentences.',
});
console.log(text, usage);
stream.ts
import { streamText } from 'ai';
import { anthropic } from './lib/anthropic';

const result = streamText({
  model: anthropic('claude-sonnet-5'),
  prompt: 'Write a haiku about load balancers.',
});

for await (const chunk of result.textStream) process.stdout.write(chunk);

Both calls accept maxRetries (2 by default) for transient failures such as 429 and 5xx.

Thinking and prompt caching

Anthropic-specific options go in providerOptions.anthropic. Current models use adaptive thinking:

thinking.ts
const { text } = await generateText({
  model: anthropic('claude-sonnet-5'),
  providerOptions: { anthropic: { thinking: { type: 'adaptive' } } },
  prompt: 'Plan a zero-downtime database migration in five steps.',
});

Cache a long, stable system prompt with cacheControl; cache reads then show up in usage.inputTokenDetails.cacheReadTokens. Prompts below the model's minimum length are not cached.

cache.ts
const result = await generateText({
  model: anthropic('claude-sonnet-5'),
  messages: [
    {
      role: 'system',
      content: longStableInstructions,
      providerOptions: { anthropic: { cacheControl: { type: 'ephemeral' } } },
    },
    { role: 'user', content: question },
  ],
});

The OpenAI-compatible alternative

The gateway also serves the OpenAI Chat Completions shape, so @ai-sdk/openai-compatible works with the same /v1 base URL. It is the route for GPT models on the same key; for Claude, the native provider above keeps thinking and cache control.

lib/gateway.ts
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';

const gateway = createOpenAICompatible({
  name: 'aiprime',
  baseURL: 'https://aiprimetech.io/v1',
  apiKey: process.env.AIPRIME_API_KEY,
});

// gateway('claude-sonnet-5') or a GPT model ID

Troubleshooting

What you see Cause Fix
A JSON parse error, response starting with <baseURL without /v1: the request hit the websitebaseURL: 'https://aiprimetech.io/v1'
404 page not found/v1 twiceExactly one /v1
Invalid API keyprocess.env value undefined in that runtime (serverless and edge functions have their own env), so the SDK fell back to ANTHROPIC_API_KEYSet the variable in the deployment's environment
Model not supportedOld or misspelled model IDUse an ID from the table below
Concurrency limit exceeded for userPromise.all over a large arrayLimit parallel calls, e.g. with p-limit
No available accounts / 503Temporary upstream capacityRetried automatically; raise maxRetries
Model ID Use it for
claude-sonnet-5Default for coding and agent work: fast, strong, mid-priced.
claude-opus-5-5Harder reasoning, large refactors, long agent runs.
claude-fable-5-1Most capable and most expensive; save it for the hardest tasks.
claude-haiku-4-5Cheap and quick: titles, summaries, classification, small steps.

Frequently asked questions

What is the default baseURL of @ai-sdk/anthropic?
https://api.anthropic.com/v1. A gateway replaces the whole prefix, so it must end in /v1, e.g. https://aiprimetech.io/v1.
Is there an environment variable for the AI SDK Anthropic base URL?
No. The provider reads ANTHROPIC_API_KEY (or ANTHROPIC_AUTH_TOKEN) from the environment, but the base URL is set with createAnthropic({ baseURL }).
Why does the AI SDK fail with a parse error when calling Claude?
Usually the baseURL lacks /v1, so the request reaches a website and gets HTML back instead of JSON.
Should I use @ai-sdk/anthropic or @ai-sdk/openai-compatible for Claude?
@ai-sdk/anthropic: it speaks the native Messages API, so thinking and prompt caching work. Use the OpenAI-compatible provider for GPT models.
Start using Claude in minutes

Get an API key — no Anthropic account or waitlist required.

Get your API key

AI Prime Tech is an independent API gateway. It is not affiliated with, endorsed by, or a reseller of Anthropic. Claude and related model names are trademarks of their respective owners.

More Claude API guides

How to Get a Claude API KeyClaude API Pricing, ExplainedThe Cheapest Way to Use the Claude APIUnlimited Cursor with the Claude APIUnlimited Claude Code AccessClaude API Gateway vs. Anthropic DirectUsing Claude Through an OpenAI-Compatible APIClaude models explained: a Claude model comparison of Claude Opus vs Sonnet vs Haiku vs Fable — all Claude API models, Anthropic model names and prices (2026)Paying for the Claude API with CryptoClaude API Access Without a WaitlistHow to Reduce Claude Token UsageUnlimited Cline with the Claude APIUnlimited Roo Code with the Claude APIUnlimited Claude in JetBrains IDEsUnlimited Aider with the Claude APIUnlimited Claude in VS CodeOpenCode config for Claude: opencode.json setup, models and common errorsRunning an Unlimited Hermes Agent on ClaudeRunning Unlimited OpenClaw on ClaudeWhat an Anthropic-Compatible API MeansClaude Code API key — ANTHROPIC_API_KEY: how to get it, set it up, and when to use claude setup-token insteadClaude Code API Costs — Pricing and How to Cut ThemClaude API errors explained: server error 500, overloaded 529, rate limit 429, bad request 400 — and the fix for eachHow to buy Claude API credits — and why a Claude credit beats any "buy Claude account" offerClaude free API: is there a free Claude API key, and what is actually free in 2026?Claude API vs Claude Pro/Max Subscription — Which to ChooseRunning the Codex CLI on ClaudeConnecting Claude to n8nRouting LiteLLM to ClaudeUsing Claude in Kilo CodeBring Claude into GitHub CopilotWire Zed to Claude Through the GatewayConnect Cherry Studio to ClaudeChatAnthropic in LangChain: import, base_url, streaming, tools and errorsAnthropic Python SDK: install, set base_url, stream, and handle errorsRun Factory Droid on ClaudeThe Claude Code API, ExplainedIntegrating the Claude API Into Your ApplicationHow to get unlimited Claude usage — and why there is no "Claude Code cracked"