Vercel AI SDK
Configure the Vercel AI SDK's OpenAI provider to stream and generate text through AnyRouter.
Build AI features in JavaScript and TypeScript with the Vercel AI SDK, routed through AnyRouter. Because AnyRouter is OpenAI-compatible, you configure the @ai-sdk/openai provider with a new base URL and key — everything else stays the same.
Before you start
- A JavaScript or TypeScript project.
- An AnyRouter API key (prefix
sk-ar-). Create one in the dashboard.
Set it up
Install the SDK and OpenAI provider
npm install ai @ai-sdk/openai
Prefer pnpm add ai @ai-sdk/openai or yarn add ai @ai-sdk/openai if that matches your project.
Point the provider at AnyRouter
Create the provider with createOpenAI, set baseURL to https://anyrouter.dev/api/v1, and pass your key.
import { createOpenAI } from "@ai-sdk/openai"
import { generateText } from "ai"
const anyrouter = createOpenAI({
baseURL: "https://anyrouter.dev/api/v1",
apiKey: process.env.ANYROUTER_API_KEY, // prefixed sk-ar-
})
async function main() {
const { text } = await generateText({
model: anyrouter("z-ai/glm-4.7-flash"),
prompt: "Write a short poem about routers.",
})
console.log(text)
}
main()
Stream responses (optional)
For real-time chat, swap generateText for streamText and iterate the token stream.
import { createOpenAI } from "@ai-sdk/openai"
import { streamText } from "ai"
const anyrouter = createOpenAI({
baseURL: "https://anyrouter.dev/api/v1",
apiKey: process.env.ANYROUTER_API_KEY,
})
const result = streamText({
model: anyrouter("anthropic/claude-sonnet-4.6"),
prompt: "Explain routing tables in simple terms.",
})
for await (const textPart of result.textStream) {
process.stdout.write(textPart)
}
Verify
Run the first snippet. A printed completion confirms the SDK is reaching AnyRouter. Set your key first if it comes from the environment:
export ANYROUTER_API_KEY="sk-ar-your-key-here"
Troubleshooting
401 Unauthorized
Ensure apiKey holds a key that starts with sk-ar-. Create and manage keys in the dashboard.
404 model not found
Pass the full provider/model id to anyrouter(...) (for example anthropic/claude-sonnet-4.6). Valid ids live in the catalog.
Related
- Streaming — how server-sent events work
- LangChain — chains and agents
- Chat Completions API — the underlying endpoint
- Models catalog — every model id you can pass