Skip to main content

Build a Multi-Model AI Chatbot with OpenRouter and Next.js (Model Switcher, Fallbacks and Real Costs)

Step-by-step guide to an OpenRouter chatbot in Next.js with a model switcher, automatic fallbacks, token limits and real cost examples per model.

Amit Verma9 min readUpdated
Build a Multi-Model AI Chatbot with OpenRouter and Next.js (Model Switcher, Fallbacks and Real Costs)

One API key, hundreds of models, and a dropdown that lets users pick. This guide builds a production-shaped chatbot on OpenRouter with a model switcher, automatic fallbacks and hard cost limits, and shows exactly what each conversation costs, with real prices.

Most chatbot tutorials hard-wire one model. That's fine until you want to compare models, keep the bot working when a provider has an outage, or let users trade speed for quality. Each provider has its own SDK, key, billing account and quirks, so supporting three of them usually means three integrations.

OpenRouter removes that problem. It gives you one OpenAI-compatible API and one key in front of hundreds of models from OpenAI, Anthropic, Google, DeepSeek, Meta, Mistral and others, with prepaid credits as the single billing account.

In this guide we'll build a Next.js chatbot with:

  • A model switcher that lets users pick from a curated list, with live prices
  • Streaming responses using the Vercel AI SDK
  • Automatic fallbacks when a model is down or rate limited
  • Cost controls: an allowlist, a token cap and trimmed history
  • Per-message cost tracking, so you always know what you're spending

Then we'll work out what it actually costs to run.

How OpenRouter pricing works

Before writing code, it's worth knowing how you'll pay, because it shapes the design:

  • Prepaid credits. You buy credits up front and each request is deducted from your balance.
  • A 5.5% fee when you buy credits on the standard plan, not on individual requests. Buying $20 of credits costs about $21.10.
  • No markup on models. OpenRouter bills inference at each provider's list price.
  • Per-token pricing, separately for input and output. Every model has a price per million input tokens (what you send) and per million output tokens (what it writes back). Output is usually several times more expensive.
  • Free models exist, marked with a :free suffix. They're limited to 20 requests per minute and 50 per day, rising to 1,000 per day once your account has bought at least $10 of credits. They're great for prototyping, but too limited and too changeable for a production chatbot.

A token is a chunk of text, roughly three-quarters of an English word on average. A 300-word reply is about 400 tokens.

Step 1: Create an account and an API key

  1. Sign up at openrouter.ai and add a small amount of credit to start, for example $5–10.
  2. Create an API key under Keys.
  3. Add it to .env.local in your Next.js project:
1OPENROUTER_API_KEY=sk-or-v1-...

The key must only ever be used on the server. Anyone who sees it can spend your credits.

Step 2: Install the packages

We'll use the Vercel AI SDK with OpenRouter's official provider. The provider version must match your AI SDK version:

1# AI SDK 7 (current)
2npm install ai @ai-sdk/react @openrouter/ai-sdk-provider
3
4# Still on AI SDK 6? Use the 2.x provider line instead
5npm install @openrouter/ai-sdk-provider@2

The 3.x provider needs Node.js 22 or newer. The code below was tested with ai 7.0, @ai-sdk/react 4.0 and @openrouter/ai-sdk-provider 3.1.

Step 3: A curated model list with live prices

Don't expose OpenRouter's full catalogue to users. Hundreds of models means hundreds of different prices, behaviours and failure modes. Pick a short list you've tested, and fetch their current prices from OpenRouter's public models endpoint, which doesn't need an API key:

1// lib/models.ts
2export const CHAT_MODELS = [
3  { id: 'anthropic/claude-haiku-5.5', label: 'Claude Haiku 5.5', note: 'Fast and cheap' },
4  { id: 'openai/gpt-5-mini', label: 'GPT-5 mini', note: 'Balanced' },
5  { id: 'deepseek/deepseek-v3.2', label: 'DeepSeek V3.2', note: 'Low cost' },
6  { id: 'anthropic/claude-sonnet-5.5', label: 'Claude Sonnet 5.5', note: 'Most capable' },
7] as const
8
9export type ChatModelId = (typeof CHAT_MODELS)[number]['id']
10
11export const DEFAULT_MODEL: ChatModelId = 'anthropic/claude-haiku-5.5'
12
13// If the chosen model errors (outage, rate limit), OpenRouter tries these next, in order.
14export const FALLBACKS: Record<ChatModelId, string[]> = {
15  'anthropic/claude-haiku-5.5': ['openai/gpt-5-mini'],
16  'openai/gpt-5-mini': ['anthropic/claude-haiku-5.5'],
17  'deepseek/deepseek-v3.2': ['openai/gpt-5-mini'],
18  'anthropic/claude-sonnet-5.5': ['openai/gpt-5-mini'],
19}
20
21export function isAllowedModel(id: unknown): id is ChatModelId {
22  return CHAT_MODELS.some((m) => m.id === id)
23}
24
25type OpenRouterModel = {
26  id: string
27  context_length: number
28  pricing: { prompt: string; completion: string }
29}
30
31/** Live prices for the curated models, in USD per million tokens. Cached for an hour. */
32export async function getModelCatalog() {
33  const res = await fetch('https://openrouter.ai/api/v1/models', { next: { revalidate: 3600 } })
34  if (!res.ok) throw new Error(`OpenRouter models request failed: ${res.status}`)
35  const { data } = (await res.json()) as { data: OpenRouterModel[] }
36
37  return CHAT_MODELS.flatMap((m) => {
38    const info = data.find((d) => d.id === m.id)
39    if (!info) return [] // model retired or renamed: hide it rather than break the UI
40    return [
41      {
42        ...m,
43        contextLength: info.context_length,
44        // Prices come back as strings, in USD per token.
45        inputPerMillion: Number(info.pricing.prompt) * 1_000_000,
46        outputPerMillion: Number(info.pricing.completion) * 1_000_000,
47      },
48    ]
49  })
50}

A small route hands that catalogue to the browser:

1// app/api/models/route.ts
2import { getModelCatalog } from '@/lib/models'
3
4export async function GET() {
5  return Response.json(await getModelCatalog())
6}

Two details matter here. Prices in the models API are strings in USD per token, so multiply by a million to get the familiar "per million tokens" figure. And models get retired or renamed over time: filtering out any ID the API no longer returns keeps the dropdown working instead of crashing.

Step 4: The chat route

This is where the cost and safety decisions live:

1// app/api/chat/route.ts
2import { createOpenRouter } from '@openrouter/ai-sdk-provider'
3import { convertToModelMessages, streamText, type UIMessage } from 'ai'
4
5import { DEFAULT_MODEL, FALLBACKS, isAllowedModel } from '@/lib/models'
6
7const openrouter = createOpenRouter({
8  apiKey: process.env.OPENROUTER_API_KEY,
9  // Optional: identifies your app in OpenRouter's rankings and dashboards.
10  headers: { 'HTTP-Referer': 'https://example.com', 'X-OpenRouter-Title': 'My Chatbot' },
11})
12
13export async function POST(req: Request) {
14  const { messages, model } = (await req.json()) as { messages: UIMessage[]; model?: string }
15
16  // Never pass a client-supplied model ID straight through: that lets anyone pick your
17  // most expensive model. Only allow the curated list.
18  const modelId = isAllowedModel(model) ? model : DEFAULT_MODEL
19
20  const result = streamText({
21    model: openrouter(modelId),
22    system: 'You are a concise, friendly assistant.',
23    // Only the recent conversation: every earlier message is re-sent (and billed) on every turn.
24    messages: await convertToModelMessages(messages.slice(-12)),
25    maxOutputTokens: 800,
26    providerOptions: {
27      openrouter: { models: [modelId, ...FALLBACKS[modelId]] },
28    },
29    onFinish({ usage, providerMetadata }) {
30      const cost = (providerMetadata?.openrouter?.usage as { cost?: number } | undefined)?.cost
31      console.info('chat', { modelId, input: usage.inputTokens, output: usage.outputTokens, costUsd: cost })
32    },
33  })
34
35  return result.toUIMessageStreamResponse()
36}

Each guard has a job:

  • The allowlist. The model ID comes from the browser, so treat it as untrusted. Without isAllowedModel, anyone could edit the request and run your most expensive model on your credits. Unknown IDs fall back to the default.
  • maxOutputTokens: 800. A hard ceiling on the most expensive part of every response.
  • messages.slice(-12). Chat models don't remember anything between requests: the whole conversation is sent every time, and billed as input every time. Trimming to the last 12 messages keeps long conversations from getting quietly expensive.
  • models: [...]. OpenRouter's fallback list. If the first model errors (downtime, rate limits, content too long), OpenRouter tries the next one automatically. You're billed for the model that actually answered.
  • onFinish. OpenRouter includes the token counts and the request's cost in every response, so you can log real spend per message without any extra API calls.

Step 5: The model switcher UI

The client fetches the catalogue, shows a dropdown with live prices, and sends the selected model with every message:

1// components/Chat.tsx
2'use client'
3
4import { useChat } from '@ai-sdk/react'
5import { DefaultChatTransport } from 'ai'
6import { useEffect, useState } from 'react'
7
8type CatalogModel = { id: string; label: string; note: string; inputPerMillion: number; outputPerMillion: number }
9
10export function Chat() {
11  const [models, setModels] = useState<CatalogModel[]>([])
12  const [model, setModel] = useState('anthropic/claude-haiku-5.5')
13  const [input, setInput] = useState('')
14  const { messages, sendMessage, status } = useChat({
15    transport: new DefaultChatTransport({ api: '/api/chat' }),
16  })
17
18  useEffect(() => {
19    fetch('/api/models').then((r) => r.json()).then(setModels)
20  }, [])
21
22  return (
23    <div>
24      <label>
25        Model{' '}
26        <select value={model} onChange={(e) => setModel(e.target.value)}>
27          {models.map((m) => (
28            <option key={m.id} value={m.id}>
29              {m.label} · {m.note} · ${m.inputPerMillion.toFixed(2)} / ${m.outputPerMillion.toFixed(2)} per 1M tokens
30            </option>
31          ))}
32        </select>
33      </label>
34
35      {messages.map((m) => (
36        <div key={m.id}>
37          <strong>{m.role === 'user' ? 'You' : 'AI'}:</strong>{' '}
38          {m.parts.map((part, i) => (part.type === 'text' ? <span key={i}>{part.text}</span> : null))}
39        </div>
40      ))}
41
42      <form
43        onSubmit={(e) => {
44          e.preventDefault()
45          if (!input.trim()) return
46          // The selected model travels with each message, so users can switch mid-conversation.
47          sendMessage({ text: input }, { body: { model } })
48          setInput('')
49        }}
50      >
51        <input value={input} onChange={(e) => setInput(e.target.value)} placeholder="Ask anything…" />
52        <button type="submit" disabled={status !== 'ready'}>
53          Send
54        </button>
55      </form>
56    </div>
57  )
58}

Because the model is sent with each message rather than fixed for the session, users can switch models mid-conversation and compare answers to the same question. Style it with your design system; the logic stays the same.

Step 6: Test it and watch the costs

Run npm run dev, send a few messages, and switch models between them. Your server log shows a line per message, for example { modelId: 'openai/gpt-5-mini', input: 1450, output: 380, costUsd: 0.0011225 }. OpenRouter's Activity page shows the same requests with their model, tokens and cost, which is useful for checking your numbers.

What does it actually cost?

Prices change, so treat these as an example from November 2026, fetched from OpenRouter's models API. Per million tokens, input and output:

  • Claude Haiku 5.5: $0.10 input, $0.50 output
  • DeepSeek V3.2: $0.26 input, $0.38 output
  • GPT-5 mini: $0.25 input, $2.00 output
  • Claude Sonnet 5.5: $2.00 input, $10.00 output

The cost of one message is:

1cost = (input tokens × input price + output tokens × output price) / 1,000,000

Assume a typical turn sends about 1,500 input tokens (system prompt plus the recent conversation) and gets about 400 output tokens back. Per message, that's roughly:

  • Claude Haiku 5.5: $0.00035
  • DeepSeek V3.2: $0.00054
  • GPT-5 mini: $0.00118
  • Claude Sonnet 5.5: $0.007

For 10,000 messages a month, say 1,000 users sending 10 messages each, that's about $3.50, $5.42, $11.75 or $70, plus the 5.5% credit fee: roughly $3.69, $5.72, $12.40 or $73.85.

Two lessons stand out. First, the gap between the cheapest and most capable model here is about 20×, which is exactly why a sensible default matters more than any other cost decision. Second, output tokens dominate for chat: Sonnet's 400 output tokens cost more than its 1,500 input tokens.

Why trimming history matters

Every turn re-sends the conversation so far. Assume each turn adds about 500 tokens (a 100-token question and a 400-token answer). Over a 20-turn conversation, the input you pay for adds up to roughly 98,000 tokens without trimming, but about 52,500 tokens when only the last 12 messages are sent. That one line of code roughly halves input costs for long conversations.

How to keep costs under control

  1. Make the default cheap and fast, and let users opt in to premium models. Most messages don't need the most capable model.
  2. Allowlist models on the server, never trust the model ID from the browser.
  3. Cap output tokens with maxOutputTokens.
  4. Trim or summarise history instead of sending the entire conversation.
  5. Rate-limit per user or IP, for example with Upstash Ratelimit, so one person or script can't drain your credits.
  6. Log cost per message from onFinish and review it weekly, especially when you add a new model.
  7. Keep only the credits you're prepared to spend. Credits are prepaid, so unless you turn on automatic top-ups, your balance is your worst-case exposure.

Be careful with reasoning ("thinking") models too: they can produce many more tokens for the same question, which shows up in the usage numbers. Check those before making one available.

Fallbacks and automatic routing

The models array in Step 4 covers the most common failure: one provider being down or rate limited. OpenRouter tries each model in order, and the response tells you which model actually answered.

If you don't want to choose at all, OpenRouter also offers openrouter/auto, a router that picks a model for each request. There's no extra fee for it; you pay the normal price of whichever model it selects. It's useful for prototypes, but for a product, a curated list is more predictable in both quality and cost.

My recommendations

  • Start with three or four models, covering cheap, balanced and premium. More choice mostly confuses users.
  • Default to a fast, cheap model. Make the premium option visible but deliberate.
  • Show prices in the switcher, at least to admins. It keeps cost visible while you're tuning.
  • Re-check your list monthly. Models are added, renamed and retired constantly; the catalogue filter keeps your UI working, but you should still review what's available.
  • Measure before optimising. A week of real onFinish logs tells you more about your costs than any estimate, including mine.

FAQ

Is OpenRouter more expensive than calling providers directly?

Model prices are the same: OpenRouter bills at each provider's list price. You pay a 5.5% fee when buying credits on the standard plan. In exchange you get one key, one bill, automatic fallbacks and the ability to switch models without new integrations.

Can I use OpenRouter for free?

Yes, with models marked :free. They're limited to 20 requests per minute and 50 per day, or 1,000 per day once your account has bought at least $10 of credits. Failed requests count towards the daily limit. They're good for learning and prototypes, but not for a production chatbot.

How do I know how many tokens a message uses?

Roughly, one token is about three-quarters of an English word. For exact numbers, OpenRouter returns the token counts and cost with every response, which the AI SDK exposes in onFinish.

Can I switch models in the middle of a conversation?

Yes. Each request is independent and includes the conversation history, so the next message can go to a different model. That's what makes a model switcher easy to build.

Does streaming cost more?

No. Pricing is per token whether or not you stream.

Share this article

Found it helpful? Share it with your network.

Keep reading