Skip to content
Docs

AI Gateway SDKs and APIs

Use AI Gateway with the AI SDK, the AI SDK for Python beta, or compatible OpenAI and Anthropic APIs. Keep your client library, set the AI Gateway base URL, and choose a model. Request fields and supported features vary by API.

To work with images, files, audio, video, or application functions, see Inputs & Tools.

See the AI SDK documentation and Python beta documentation for SDK installation and core concepts.

These examples use AI SDK 7 and the AI SDK for Python beta. Set AI_GATEWAY_API_KEY before running them. See API format differences for setup, request fields, and response handling.

quickstart.ts
import { generateText } from 'ai';
 
const { text } = await generateText({
  model: "anthropic/claude-sonnet-5",
  prompt: "Hello!",
});
 
console.log(text);
quickstart_ai.py
import asyncio
import ai
 
async def main():
    model = ai.get_model("anthropic/claude-sonnet-5")
    messages = [ai.user_message("Hello!")]
    async with ai.stream(model, messages) as stream:
        async for event in stream:
            if isinstance(event, ai.events.TextDelta):
                print(event.chunk, end="", flush=True)
    print()
 
asyncio.run(main())
quickstart-chat.ts
import OpenAI from 'openai';
 
const client = new OpenAI({
  apiKey: process.env.AI_GATEWAY_API_KEY,
  baseURL: 'https://ai-gateway.vercel.sh/v1',
});
 
const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-5",
  messages: [{ "role": "user", "content": "Hello!" }],
});
 
console.log(response.choices[0]?.message.content);
quickstart_chat.py
import os
from openai import OpenAI
 
client = OpenAI(
    api_key=os.environ["AI_GATEWAY_API_KEY"],
    base_url="https://ai-gateway.vercel.sh/v1",
)
 
response = client.chat.completions.create(
    model="anthropic/claude-sonnet-5",
    messages=[{"role": "user", "content": "Hello!"}],
)
 
print(response.choices[0].message.content)
quickstart-chat.sh
curl --fail-with-body https://ai-gateway.vercel.sh/v1/chat/completions \
  -H "Authorization: Bearer $AI_GATEWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "anthropic/claude-sonnet-5",
  "messages": [
    {
      "role": "user",
      "content": "Hello!"
    }
  ]
}'
quickstart-messages.ts
import Anthropic from '@anthropic-ai/sdk';
 
const client = new Anthropic({
  apiKey: process.env.AI_GATEWAY_API_KEY,
  baseURL: 'https://ai-gateway.vercel.sh',
});
 
const response = await client.messages.create({
  model: "anthropic/claude-sonnet-5",
  messages: [{ "role": "user", "content": "Hello!" }],
  max_tokens: 1024,
});
 
for (const block of response.content) {
  if (block.type === 'text') console.log(block.text);
}
quickstart_messages.py
import os
from anthropic import Anthropic
 
client = Anthropic(
    api_key=os.environ["AI_GATEWAY_API_KEY"],
    base_url="https://ai-gateway.vercel.sh",
)
 
response = client.messages.create(
    model="anthropic/claude-sonnet-5",
    messages=[{"role": "user", "content": "Hello!"}],
    max_tokens=1024,
)
 
for block in response.content:
    if block.type == "text":
        print(block.text)
quickstart-messages.sh
curl --fail-with-body https://ai-gateway.vercel.sh/v1/messages \
  -H "Authorization: Bearer $AI_GATEWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
  "model": "anthropic/claude-sonnet-5",
  "messages": [
    {
      "role": "user",
      "content": "Hello!"
    }
  ],
  "max_tokens": 1024
}'
quickstart-responses.ts
import OpenAI from 'openai';
 
const client = new OpenAI({
  apiKey: process.env.AI_GATEWAY_API_KEY,
  baseURL: 'https://ai-gateway.vercel.sh/v1',
});
 
const response = await client.responses.create({
  model: "anthropic/claude-sonnet-5",
  input: "Hello!",
});
 
console.log(response.output_text);
quickstart_responses.py
import os
from openai import OpenAI
 
client = OpenAI(
    api_key=os.environ["AI_GATEWAY_API_KEY"],
    base_url="https://ai-gateway.vercel.sh/v1",
)
 
response = client.responses.create(
    model="anthropic/claude-sonnet-5",
    input="Hello!",
)
 
print(response.output_text)
quickstart-responses.sh
curl --fail-with-body https://ai-gateway.vercel.sh/v1/responses \
  -H "Authorization: Bearer $AI_GATEWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "anthropic/claude-sonnet-5",
  "input": "Hello!"
}'

AI Gateway shares authentication, model naming, and routing across these API formats. Capability support, request fields, and response metadata vary as described below:

Switching surfaces is a client-side change. It does not change your billing, your keys, or which providers you reach.

  • No vendor lock-in: Switch between Claude, GPT, Gemini, and other models without changing your code
  • Unified billing: One invoice for all providers instead of managing multiple accounts
  • Built-in fallbacks: Automatic retry with alternative providers if one fails
  • Streaming support: Real-time responses with SSE across all compatible endpoints
  • Multiple API formats: Use the format your application supports, with the capability and parameter differences below
APIBest forDocumentation
AI SDK (recommended)Normalizes provider differences, works with AI Gateway automaticallyStreaming, Structured outputs, Tools
AI SDK for Python (public beta)Python apps and agents with a native SDKQuick start, Tools
OpenAI Chat Completions APIExisting OpenAI integrations, broad language supportChat, Tools, Embeddings
Anthropic Messages APIClaude Code, Anthropic SDK usersMessages, Tools, Images
OpenAI Responses APIOpenAI Responses API usersStreaming, Tools, Structured output
OpenResponsesNew projects, provider-agnostic designStreaming, Tools, Images
OpenAI-Compatible Decisions APIDecisions with the OpenAI SDK or plain HTTPQuestions, Provider options, Errors
Cohere Rerank APIReranking documents with the Cohere SDK or plain HTTPRerank, Provider routing
TypeSafe APIExisting TypeSafe clients, decisions over HTTPMigrating, Endpoints
PythonPython developersAsync, Streaming, Frameworks

Every cell links to that surface's page for the topic:

Embeddings use the OpenAI-compatible /v1/embeddings endpoint, or the TypeScript and Python AI SDKs. Decisions use the OpenAI-compatible /v1/decisions endpoint, the TypeSafe API, or the AI SDK. Reranking uses the Cohere-compatible Rerank API, or either AI SDK. These operations aren't Chat Completions, Messages, or Responses requests. See modalities for image, video, audio, and realtime APIs.

Whether a given model supports a capability is a separate question from whether the surface exposes it. Check the model list for per-model support.

The examples use AI SDK 7 for TypeScript and the AI SDK for Python public beta for Python. The Python package has its own version cycle. It doesn't use the TypeScript SDK's functions or version numbers.

Install the client for your tab:

TabRequirementsInstall
AI SDKNode.js 22 or later, ESMpnpm add ai@7
AI SDK for Python (beta)Python 3.12 or lateruv add ai
Chat Completions and Responses, TypeScriptOpenAI TypeScript SDKpnpm add openai
Chat Completions and Responses, PythonOpenAI Python SDKuv add openai
Messages API, TypeScriptAnthropic TypeScript SDKpnpm add @anthropic-ai/sdk
Messages API, PythonAnthropic Python SDKuv add anthropic
cURLA shell and cURLNo SDK required

Set AI_GATEWAY_API_KEY in your environment. Keep the key on the server. For Vercel deployments and local development with Vercel CLI, see OIDC authentication. TypeScript examples with top-level await run as ESM, for example with pnpm exec tsx example.ts. Python examples run with uv run example.py.

FormatInput and instructionsAI Gateway optionsText output
AI SDK 7prompt or messages; instructionsproviderOptions.gatewayresult.text or result.textStream
AI SDK for Python (beta)ai.user_message(...) and ai.stream(...)ai.InferenceRequestParams(extra_body={"providerOptions": {"gateway": ...}})TextDelta.chunk, or stream.text after consuming the stream
Chat Completionsmessages; a system or developer messageproviderOptions.gateway in the JSON bodychoices[0].message.content
Messages APImessages; top-level system; required max_tokensproviderOptions.gateway in the JSON bodyText blocks in content
Responses / OpenResponsesinput; instructionsproviderOptions.gateway in the JSON bodySDK output_text, or text blocks in raw output items

The OpenAI and Anthropic Python SDKs pass AI Gateway extensions through extra_body. The TypeScript examples spread providerOptions into the request because upstream SDK types don't declare AI Gateway extensions. Standard request fields still use the SDK's types.

Responses and OpenResponses share /v1/responses. Shared-feature examples use a single tab for both. Consult their reference pages for stateful conversations, compaction, and supported tools before porting native OpenAI code.

Structured output uses output in AI SDK 7, output_type in the Python beta, response_format in Chat Completions, output_config.format in Messages, and text.format in Responses. Tool definitions and tool-result messages also differ. Follow the linked examples in the capability table instead of copying a payload between formats.

Reasoning, search tools, and cache controls have model-specific and API-specific options. A successful generation alone doesn't establish that an optional setting took effect. Inspect usage and provider metadata when verifying routing, caching, service tiers, or compliance settings.

Use Vercel CLI to inspect models and configure coding agents:

Terminal
npx vercel ai-gateway models list
npx vercel ai-gateway setup

Management operations such as budgets, API keys, and routing rules use their management REST endpoints or the CLI. They aren't Chat Completions, Messages, or Responses requests.

The CLI setup commands complement the API examples. Each coding agent chooses its own API format; keep its configuration from the coding-agent guide.

Last updated October 7, 2026

Was this helpful?

supported.