SDK Guide · As of 2026-11-25

Vercel AI SDK with a Custom Provider: Claude, GPT and Chinese Models Through One baseURL Setup

As of 2026-11-25 (AI SDK ai 7.0.181, @ai-sdk/anthropic 4.0.108, @ai-sdk/openai 4.0.123, @ai-sdk/openai-compatible 3.0.94), the AI SDK talks to QCode through three provider instances: createAnthropic({ baseURL: "https://api.qcode.cc/api/v1" }) for Claude, createOpenAI({ baseURL: "https://api.qcode.cc/openai/v1" }) for GPT, and createOpenAICompatible({ baseURL: "https://api.qcode.cc/openai/v1" }) for GLM, Kimi, DeepSeek and Qwen. The detail that trips most people: the AI SDK's Anthropic baseURL includes /v1, unlike the official Anthropic SDK, where you stop at /api. Everything else (generateText, streamText, tools, useChat) is written exactly as in the AI SDK docs.

QCode is an independent third-party API service. It is not operated by, endorsed by or partnered with Vercel, Anthropic, OpenAI or any model vendor. Provider option names below come from the published type definitions and source of each package.

Updated 2026-11-26

Key facts

  • Anthropic provider: baseURL: "https://api.qcode.cc/api/v1". The provider posts to ${baseURL}/messages; its default is https://api.anthropic.com/v1.
  • OpenAI provider: baseURL: "https://api.qcode.cc/openai/v1". provider("gpt-6.2-sol") uses the Responses API; provider.chat("gpt-6.2-sol") uses Chat Completions. If you rely on the Responses path, test tool calling with a small request first.
  • OpenAI-compatible provider for Chinese models: same base URL, name is required, and includeUsage: true asks for token usage in streaming responses; confirm it with a small test request. Chinese models are not served on Responses, so do not send them through the default createOpenAI model.
  • Env vars read automatically: ANTHROPIC_BASE_URL / ANTHROPIC_API_KEY and OPENAI_BASE_URL / OPENAI_API_KEY. If your shell exports Claude Code's ANTHROPIC_BASE_URL=https://api.qcode.cc/api, the AI SDK will call /api/messages and get a 404.
  • AI SDK 7 details: instructions replaces the deprecated system, isStepCount is the stop condition (stepCountIs is still exported as an alias), convertToModelMessages is async, and Node.js 22+ is required.

Which provider, which baseURL

Models Package / factory baseURL on QCode Request path the SDK builds
claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5, claude-fable-5-2 @ai-sdk/anthropic / createAnthropic https://api.qcode.cc/api/v1 /api/v1/messages
gpt-6.2-sol, gpt-6.2-astra, gpt-6.1-sol @ai-sdk/openai / createOpenAI https://api.qcode.cc/openai/v1 /openai/v1/responses (default) or /openai/v1/chat/completions (.chat())
glm-5.3, kimi-k3.1-pro, deepseek-v4-pro, deepseek-v4.1-flash, qwen3.8-max @ai-sdk/openai-compatible / createOpenAICompatible https://api.qcode.cc/openai/v1 /openai/v1/chat/completions

QCode's protocol rule: Claude models only on the Anthropic endpoint, GPT only on the OpenAI endpoint, Chinese models on both (Chat Completions only on the OpenAI side). See Anthropic Messages vs OpenAI Chat vs Responses for how the request shapes differ.

Install and environment

npm install ai @ai-sdk/anthropic @ai-sdk/openai @ai-sdk/openai-compatible @ai-sdk/react zod
node --version   # AI SDK 7 requires Node.js 22 or newer

.env.local in a Next.js project (server-only; never prefix with NEXT_PUBLIC_):

QCODE_API_KEY=cr_your_key

Use your own variable name rather than ANTHROPIC_API_KEY / ANTHROPIC_BASE_URL. That way the AI SDK cannot pick up a stale value meant for Claude Code or another tool.

One file that defines all three providers

// lib/qcode.ts
import { createAnthropic } from '@ai-sdk/anthropic';
import { createOpenAI } from '@ai-sdk/openai';
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';

const apiKey = process.env.QCODE_API_KEY;
if (!apiKey) throw new Error('QCODE_API_KEY is not set');

// Claude: note /v1 at the end. The provider appends /messages.
export const qAnthropic = createAnthropic({
  baseURL: 'https://api.qcode.cc/api/v1',
  apiKey, // sent as x-api-key; use authToken instead for Authorization: Bearer
});

// GPT: qOpenAI('model') uses Responses, qOpenAI.chat('model') uses Chat Completions.
export const qOpenAI = createOpenAI({
  baseURL: 'https://api.qcode.cc/openai/v1',
  apiKey,
});

// GLM, Kimi, DeepSeek, Qwen over Chat Completions.
export const qChina = createOpenAICompatible({
  name: 'qcode',
  baseURL: 'https://api.qcode.cc/openai/v1',
  apiKey,
  includeUsage: true, // usage chunks while streaming
});

Pass either apiKey or authToken to createAnthropic, not both. Version 4.x throws Both apiKey and authToken were provided if you set both.

generateText: same call, any model

import { generateText } from 'ai';
import { qAnthropic, qOpenAI, qChina } from './lib/qcode';

const models = {
  sonnet: qAnthropic('claude-sonnet-5-5'),
  gptSol: qOpenAI('gpt-6.2-sol'),
  glm:    qChina('glm-5.3'),
  kimi:   qChina('kimi-k3.1-pro'),
  dsFlash: qChina('deepseek-v4.1-flash'),
};

for (const [label, model] of Object.entries(models)) {
  const { text, usage } = await generateText({
    model,
    instructions: 'You are a concise senior engineer.', // AI SDK 7: replaces `system`
    prompt: 'Explain idempotency in one sentence.',
    maxOutputTokens: 512,
  });
  console.log(label, text, usage.inputTokens, usage.outputTokens);
}

Opus 5.5 and Fable 5.2 run adaptive thinking that cannot be turned off. Control depth with the Anthropic provider option effort. If your pipeline depends on providerOptions.anthropic.effort reaching the model, test it with a small request first:

const { text } = await generateText({
  model: qAnthropic('claude-opus-5-5'),
  prompt: 'Review this function and list concrete bugs: ...',
  maxOutputTokens: 16000,
  providerOptions: { anthropic: { effort: 'high' } }, // low | medium | high | xhigh | max
});

List prices per million tokens on /models as of 2026-11-25: claude-sonnet-5-5 $2 / $10, claude-opus-5-5 $4 / $20, claude-haiku-5-5 $0.10 / $0.50 for prompts up to 100K tokens, gpt-6.2-sol $2 / $10. QCode bills official price × service multiplier, currently ×1.0 for Anthropic and OpenAI models.

streamText

import { streamText } from 'ai';

const result = streamText({
  model: qAnthropic('claude-sonnet-5-5'),
  prompt: 'Write a short checklist for reviewing a database migration.',
});

for await (const delta of result.textStream) {
  process.stdout.write(delta);
}
console.log('\nusage:', await result.totalUsage);

totalUsage sums every step of a multi-step run. For Chinese models, set includeUsage: true on the compatible provider and confirm the final usage with a small streaming test.

Tool calls and multi-step loops

import { generateText, tool, isStepCount } from 'ai';
import { z } from 'zod';

const lookupOrder = tool({
  description: 'Look up an order by ID and return its status.',
  inputSchema: z.object({ orderId: z.string().describe('Order ID such as A-1042') }),
  execute: async ({ orderId }) => {
    // Replace with a real database or API call.
    return { orderId, status: 'shipped', carrier: 'DHL' };
  },
});

const { text, steps } = await generateText({
  model: qAnthropic('claude-sonnet-5-5'),
  tools: { lookupOrder },
  stopWhen: isStepCount(5), // default is isStepCount(1): one step, then stop
  prompt: 'Where is order A-1042?',
});

console.log(text);
console.log(steps.map((s) => s.toolCalls.map((c) => c.toolName)));

The default stop condition is one step. Without stopWhen, the model calls the tool, the SDK runs execute, and the call returns with an empty text because no second step was allowed to write the answer. This is the most common "tools work but I get no reply" report.

Two Claude-specific rules. Opus 5.5, Sonnet 5.5 and Fable 5.2 do not accept a forced tool choice, so toolChoice: 'required' or { type: 'tool', toolName } returns HTTP 400 on those models; leave the default 'auto' and name the tool in the prompt. And keep message history append-only: on new Claude models, thinking blocks are tied to the conversation, and editing earlier turns invalidates them and the prompt cache.

The same tool works with qOpenAI('gpt-6.2-sol') or qChina('kimi-k3.1-pro'). Tool support for DeepSeek models through QCode's OpenAI endpoint is not listed on /models, so test before you depend on it.

A Next.js App Router chat route

// app/api/chat/route.ts
import { streamText, convertToModelMessages, isStepCount, tool, type UIMessage } from 'ai';
import { z } from 'zod';
import { qAnthropic, qChina } from '@/lib/qcode';

export const maxDuration = 60; // seconds; long answers need more than the default

const tools = {
  lookupOrder: tool({
    description: 'Look up an order by ID and return its status.',
    inputSchema: z.object({ orderId: z.string() }),
    execute: async ({ orderId }) => ({ orderId, status: 'shipped' }),
  }),
};

export async function POST(req: Request) {
  const { messages, model }: { messages: UIMessage[]; model?: string } = await req.json();

  const result = streamText({
    model: model === 'glm' ? qChina('glm-5.3') : qAnthropic('claude-sonnet-5-5'),
    instructions: 'You are a helpful support assistant for an online shop.',
    messages: await convertToModelMessages(messages), // async in AI SDK 7
    tools,
    stopWhen: isStepCount(5),
  });

  return result.toUIMessageStreamResponse();
}
// app/page.tsx
'use client';
import { useChat } from '@ai-sdk/react';
import { useState } from 'react';

export default function Chat() {
  const { messages, sendMessage, status } = useChat(); // posts to /api/chat by default
  const [input, setInput] = useState('');

  return (
    <main>
      {messages.map((m) => (
        <div key={m.id}>
          <b>{m.role}:</b>{' '}
          {m.parts.map((p, i) => (p.type === 'text' ? <span key={i}>{p.text}</span> : null))}
        </div>
      ))}
      <form
        onSubmit={(e) => {
          e.preventDefault();
          sendMessage({ text: input });
          setInput('');
        }}
      >
        <input value={input} onChange={(e) => setInput(e.target.value)} disabled={status !== 'ready'} />
      </form>
    </main>
  );
}

The key never reaches the browser: the client only talks to your /api/chat route, and the route talks to QCode. Do not accept arbitrary model IDs from the client; map a small allow-list (as above) so a user cannot switch your route to an expensive model.

baseURL mistakes and other errors

Symptom Usual cause Fix
404 on Claude calls Anthropic provider baseURL set to https://api.qcode.cc/api (copied from Claude Code or the Anthropic SDK), so the request goes to /api/messages Use https://api.qcode.cc/api/v1
404 with /v1/v1/ in the URL baseURL set to .../api/v1/v1 or .../openai/v1/v1 after adding /v1 twice One /v1, no trailing slash
404 when you pass no baseURL but expect QCode ANTHROPIC_BASE_URL=https://api.qcode.cc/api exported for Claude Code is read by the default provider Pass baseURL explicitly, or unset the variable for the app
Error "Received a Chat Completions stream while using the OpenAI Responses API" The default createOpenAI model (Responses) pointed at an endpoint or model that answers in Chat Completions format Use provider.chat('model'), or createOpenAICompatible for Chinese models
model_not_available_on_endpoint A Claude model sent through createOpenAI / createOpenAICompatible Use createAnthropic for Claude
Both apiKey and authToken were provided Both set on createAnthropic Keep one
Tools run but text is empty Default stopWhen is isStepCount(1) Set stopWhen: isStepCount(5) or similar
HTTP 400 on Opus 5.5 / Sonnet 5.5 Forced toolChoice, or thinking disabled Keep toolChoice: 'auto'; tune effort
No usage while streaming Chinese models includeUsage not set, or the endpoint does not return usage chunks Set includeUsage: true and confirm with a small request
401 Invalid API key Key missing in the deployed environment, or a space copied with it Set QCODE_API_KEY in the hosting dashboard and redeploy
402 daily_cost_limit_exceeded Plan's daily quota used up Resets at 00:00 Beijing time, or top up

To see the actual failing URL and body, catch the error:

import { APICallError } from 'ai';

try {
  await generateText({ model: qAnthropic('claude-sonnet-5-5'), prompt: 'ping' });
} catch (e) {
  if (APICallError.isInstance(e)) {
    console.error(e.statusCode, e.url, e.responseBody);
  } else {
    throw e;
  }
}

e.url shows the exact path the SDK built, which settles most baseURL questions in one look.

Production notes

  • Retries: generateText and streamText retry twice by default (maxRetries: 2). For user-facing routes, keep it low and show an error instead of making users wait through three attempts.
  • Concurrency: a busy chat route can hit your plan's concurrency limit; queue background jobs or move them to a separate key.
  • Regional hosts: asia.qcode.cc and us.qcode.cc take the same paths (/api/v1, /openai/v1). Measure from the region where your serverless functions run, not from your laptop.
  • Caching: keep instructions and tool definitions stable across requests so Claude's prompt cache can hit; a timestamp in the instructions defeats it.
  • Cost per route: log totalUsage with the route name. It makes month-end reconciliation with the QCode dashboard quick and shows which feature is driving spend.

AI SDK or the vendor SDKs, and a migration map

The AI SDK's strength is uniformity: one set of generateText, streamText, tool and useChat, a one-line model swap, and streaming UI, tool states and message structure already handled. It suits full-stack web apps (Next.js, Nuxt, SvelteKit). The cost is an extra layer over the vendor APIs: a brand-new vendor parameter may only become available through providerOptions once the provider package is updated.

A simple way to choose:

  • Web chat UI, switching between several vendors: the AI SDK, with the three providers in this guide.
  • Claude only, and you want new beta parameters the day they ship: the official @anthropic-ai/sdk; see Anthropic SDK custom base_url.
  • GPT and Chinese models only, mostly backend scripts: one official openai SDK client; see OpenAI SDK for multiple models.

When migrating from the official Anthropic SDK, addresses and parameter names are where mistakes happen:

Item Official Anthropic SDK AI SDK (@ai-sdk/anthropic)
Address baseURL: "https://api.qcode.cc/api" baseURL: "https://api.qcode.cc/api/v1"
System prompt system instructions
Output limit max_tokens maxOutputTokens
Thinking depth output_config: { effort } providerOptions: { anthropic: { effort } }
Tool schema input_schema (JSON Schema) inputSchema (zod or jsonSchema())
Tool loop your own while loop stopWhen: isStepCount(n)

Run old and new code side by side on one route first, compare output and usage, and switch all traffic once they match.

FAQ

What baseURL do I use with createAnthropic?

https://api.qcode.cc/api/v1. The AI SDK's Anthropic provider appends /messages to the baseURL, and its own default is https://api.anthropic.com/v1. The official Anthropic SDK is different: there you stop at https://api.qcode.cc/api.

Why do I get a 404 even though Claude Code works with the same key?

Claude Code uses ANTHROPIC_BASE_URL=https://api.qcode.cc/api, and the AI SDK reads that same variable when you pass no baseURL. Without /v1, the AI SDK requests /api/messages, which does not exist. Pass baseURL: "https://api.qcode.cc/api/v1" explicitly.

Should I use createOpenAI or createOpenAICompatible for DeepSeek, Kimi, GLM and Qwen?

Use createOpenAICompatible. The default model from createOpenAI uses the Responses API, and QCode serves Chinese models only on Chat Completions on the OpenAI side. createOpenAI(...).chat('glm-5.3') also works, but the compatible provider is built for this case and has includeUsage.

Does gpt-6.2-sol work with the default openai('...') model?

QCode serves GPT models on the OpenAI endpoint. qOpenAI.chat('gpt-6.2-sol') uses Chat Completions; if you use the default Responses path, test tool calling end to end with a small request first. Pick Chat Completions if you want one request format across GPT and Chinese models.

Why are my tool calls executed but no answer is returned?

In AI SDK 7 the default stopWhen is isStepCount(1), so the run stops right after the tool step. Set stopWhen: isStepCount(5) (or another condition) so the model gets a step to write the answer.

Can I call Claude through the OpenAI provider?

No. On QCode, Claude models are served only on the Anthropic Messages endpoint; the OpenAI path returns model_not_available_on_endpoint. Use createAnthropic for Claude.

Is it safe to use the key in a Next.js app?

Yes, if it stays on the server. Read it in a route handler or server action from a non-public variable, and never expose it with NEXT_PUBLIC_. The browser should only call your own route.

Which plan fits AI SDK projects

For prototypes, demos and internal tools with uneven traffic, pay-as-you-go packs are the simplest: no subscription, 7-day validity, stackable, from $4 for $30 of usage per /pay-as-you-go as of 2026-11-25. Once a chat feature has steady daily traffic, compare the daily-quota plans on /pricing.

Which plan fits AI SDK projects

One key for both the Anthropic Messages API and OpenAI-compatible APIs. Claude and GPT are billed at the official price ×1.0; live rates are on /models.

Not sure where to start?

Try it for a week

Small Pack: $4 for $30 of quota, valid 7 days

Use it every day

Starter: $9.00/month with $5 of quota every day — just $0.060 per $1 of quota, vs about $0.113 for the Medium Pack