Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

openrouter.md

952 lines33.7 KB

1---
2title: OpenRouter Adapter
3id: openrouter-adapter
4description: "Access 300+ LLMs from OpenAI, Anthropic, Google, Meta, Mistral, and more through a single API with OpenRouter in TanStack AI."
5keywords:
6 - tanstack ai
7 - openrouter
8 - multi-provider
9 - unified api
10 - llm gateway
11 - 300 models
12 - adapter
13 - evaluate
14 - jev
15---
16​
17OpenRouter is TanStack AI's first official AI partner and the recommended starting point for most projects. It provides access to 300+ models from OpenAI, Anthropic, Google, Meta, Mistral, and many more — all through a single API key and unified interface.
18​
19## Installation
20​
21<!-- ::start:tabs variant="package-manager" mode="install" -->
22​
23react: @tanstack/ai-openrouter
24vue: @tanstack/ai-openrouter
25solid: @tanstack/ai-openrouter
26svelte: @tanstack/ai-openrouter
27preact: @tanstack/ai-openrouter
28angular: @tanstack/ai-openrouter
29vanilla: @tanstack/ai-openrouter
30octane: @tanstack/ai-openrouter
31​
32<!-- ::end:tabs -->
33​
34## Basic Usage
35​
36```typescript
37import { chat } from "@tanstack/ai";
38import { openRouterText } from "@tanstack/ai-openrouter";
39​
40const stream = chat({
41 adapter: openRouterText("openai/gpt-5"),
42 messages: [{ role: "user", content: "Hello!" }],
43});
44```
45​
46## Configuration
47​
48```typescript
49import { createOpenRouterText } from "@tanstack/ai-openrouter";
50​
51const adapter = createOpenRouterText(
52 "openai/gpt-5",
53 process.env.OPENROUTER_API_KEY!,
54 {
55 serverURL: "https://openrouter.ai/api/v1", // Optional
56 httpReferer: "https://your-app.com", // Optional, for rankings
57 appTitle: "Your App Name", // Optional, for rankings
58 },
59);
60```
61​
62Need a header on each request, or a log of each model call? Both text adapters support [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call). If you set an `httpClient`, each wrapped request still goes through it.
63​
64### Retry rate limits
65​
66A busy upstream provider can reply with HTTP 429. The adapter retries only 5XX errors by default. Add `"429"` to `retryCodes` to retry rate limits too:
67​
68```typescript
69import { createOpenRouterText } from "@tanstack/ai-openrouter";
70​
71const adapter = createOpenRouterText(
72 "openai/gpt-5",
73 process.env.OPENROUTER_API_KEY!,
74 {
75 retryConfig: {
76 strategy: "backoff",
77 backoff: {
78 initialInterval: 500,
79 maxInterval: 60000,
80 exponent: 1.5,
81 maxElapsedTime: 120000,
82 },
83 retryConnectionErrors: true,
84 },
85 retryCodes: ["429", "5XX"],
86 },
87);
88```
89​
90- `retryCodes`: the HTTP status codes to retry. `"5XX"` matches every 5xx code.
91- `retryConfig`: how long to wait between tries. When the response has a `Retry-After` header, the SDK waits that long.
92​
93Now a 429 waits, then retries, and the chat continues with the next response.
94​
95### Retry an error in the stream
96​
97Most provider errors come as an HTTP status, and the SDK retries them as shown above. But OpenRouter can send status 200 first. Then a provider error comes as an error chunk in the stream, and the SDK cannot retry it.
98​
99To retry that error, pass `retry` to `chat()`:
100​
101```typescript
102import { chat } from "@tanstack/ai";
103import { createOpenRouterText } from "@tanstack/ai-openrouter";
104​
105const adapter = createOpenRouterText(
106 "openai/gpt-5.5",
107 process.env.OPENROUTER_API_KEY!,
108 { retryCodes: ["429", "5XX"] },
109);
110​
111const stream = chat({
112 adapter,
113 messages: [{ role: "user", content: "Hello!" }],
114 retry: { maxRetries: 3 },
115});
116```
117​
118When `chat()` retries:
119​
120- Only for an error code in `retryCodes`. The default is 5XX only, so add `"429"` to retry a rate limit.
121- Only when the call streamed no output yet. An error after part of the answer reaches you as a `RUN_ERROR`.
122- Not when `retryConfig` has `strategy: "none"`.
123- Only with the Chat Completions adapter (`openRouterText`). The Responses adapter does not do this.
124​
125The wait is the `initialInterval` of `retryConfig` (default 500 ms). It is the same for each try and does not grow. See [Let `chat()` retry for you](../chat/stream-events#let-chat-retry-for-you).
126​
127## Available Models
128​
129OpenRouter provides access to 300+ models from various providers. Models use the format `provider/model-name`:
130​
131```text
132model: "openai/gpt-5.1"
133model: "anthropic/claude-sonnet-4.5"
134model: "google/gemini-3.1-pro-preview"
135model: "meta-llama/llama-4-maverick"
136model: "deepseek/deepseek-v3.2"
137```
138​
139See the full list at [openrouter.ai/models](https://openrouter.ai/models).
140​
141`adapter.inputModalities` lists the input kinds of the selected model. It is `undefined` for a model that this package does not know. See [Check what a model accepts](../advanced/extend-adapter#check-what-a-model-accepts).
142​
143## Example: Chat Completion
144​
145```typescript
146import { chat, toServerSentEventsResponse } from "@tanstack/ai";
147import { openRouterText } from "@tanstack/ai-openrouter";
148​
149export async function POST(request: Request) {
150 const { messages } = await request.json();
151​
152 const stream = chat({
153 adapter: openRouterText("openai/gpt-5"),
154 messages,
155 });
156​
157 return toServerSentEventsResponse(stream);
159```
160​
161## Example: With Tools
162​
163```typescript
164import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
165import { openRouterText } from "@tanstack/ai-openrouter";
166import { z } from "zod";
167​
168const getWeatherDef = toolDefinition({
169 name: "get_weather",
170 description: "Get the current weather",
171 inputSchema: z.object({
172 location: z.string(),
173 }),
174});
175​
176const getWeather = getWeatherDef.server(async ({ location }) => {
177 return { temperature: 72, conditions: "sunny" };
178});
179​
180export async function POST(request: Request) {
181 const { messages } = await request.json();
182​
183 const stream = chat({
184 adapter: openRouterText("openai/gpt-5"),
185 messages,
186 tools: [getWeather],
187 });
188​
189 return toServerSentEventsResponse(stream);
191```
192​
193## JSON mode
194​
195Some OpenRouter models reject strict JSON schema. For these models, `chat({ outputSchema })` sends `json_object` and adds your schema to the system prompt.
196​
197To send JSON mode to any other model, set `modelOptions.responseFormat`:
198​
199```typescript
200import { chat } from "@tanstack/ai";
201import { openRouterText } from "@tanstack/ai-openrouter";
202import { z } from "zod";
203​
204const person = await chat({
205 adapter: openRouterText("openai/gpt-5.6-sol"),
206 messages: [{ role: "user", content: "Return Ada Lovelace, age 36." }],
207 modelOptions: { responseFormat: { type: "json_object" } },
208 outputSchema: z.object({ name: z.string(), age: z.number() }),
209});
210```
211​
212Read [When strict JSON schema is rejected](../structured-outputs/overview.md#when-strict-json-schema-is-rejected).
213​
214## Tools and structured output together
215​
216You can pass both `tools` and `outputSchema` on one `chat()` call. For some
217upstream models OpenRouter can return the typed object in that same streaming
218request, so the engine does not make a second finalization call.
219​
220That happens only when **every** model that can receive the request is in
221`OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS`. The set is generated from
222OpenRouter's catalog on every model sync: every chat model whose
223`supported_parameters` include `structured_outputs`, `tools` and `tool_choice`
224(Claude 4.5+, Gemini 2.5+, GPT-4o+, Grok 4, DeepSeek V3+, Llama 3.1+, and so
225on). Models OpenRouter does not flag, such as `anthropic/claude-opus-4.1`, stay
226on the legacy two-call path.
227​
228If any fallback in `modelOptions.models` is outside that set, OpenRouter keeps
229the two-call path. Routing suffixes such as `:nitro` do not change the gate.
230​
231Import the set from `@tanstack/ai-openrouter/model-meta` if you need to check a
232model before you send:
233​
234```typescript
235import { OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS } from "@tanstack/ai-openrouter/model-meta";
236​
237OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS.has("openai/gpt-5.5");
238```
239​
240Chat Completions (`openRouterText`) and Responses (`openRouterResponsesText`)
241both attach the schema on this path. The client does not change: `useChat({
242outputSchema })` still reads `partial` and `final`.
243​
244Server (Chat Completions):
245​
246```typescript
247import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
248import { openRouterText } from "@tanstack/ai-openrouter";
249import { z } from "zod";
250​
251const getWeather = toolDefinition({
252 name: "get_weather",
253 description: "Get the current weather",
254 inputSchema: z.object({ location: z.string() }),
255}).server(async ({ location }) => {
256 return { temperature: 72, conditions: "sunny", location };
257});
258​
259const AnswerSchema = z.object({
260 summary: z.string(),
261 location: z.string(),
262});
263​
264export async function POST(request: Request) {
265 const { messages } = await request.json();
266​
267 const stream = chat({
268 adapter: openRouterText("openai/gpt-5.5"),
269 messages,
270 tools: [getWeather],
271 outputSchema: AnswerSchema,
272 stream: true,
273 });
274​
275 return toServerSentEventsResponse(stream);
277```
278​
279Server (Responses). Same `tools` and `outputSchema` as the Chat Completions
280example, with `openRouterResponsesText`:
281​
282```typescript
283import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
284import { openRouterResponsesText } from "@tanstack/ai-openrouter";
285import { z } from "zod";
286​
287const getWeather = toolDefinition({
288 name: "get_weather",
289 description: "Get the current weather",
290 inputSchema: z.object({ location: z.string() }),
291}).server(async ({ location }) => {
292 return { temperature: 72, conditions: "sunny", location };
293});
294​
295const AnswerSchema = z.object({
296 summary: z.string(),
297 location: z.string(),
298});
299​
300export async function POST(request: Request) {
301 const { messages } = await request.json();
302​
303 const stream = chat({
304 adapter: openRouterResponsesText("openai/gpt-5.5"),
305 messages,
306 tools: [getWeather],
307 outputSchema: AnswerSchema,
308 stream: true,
309 });
310​
311 return toServerSentEventsResponse(stream);
313```
314​
315Client:
316​
317```tsx
318import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
319import { z } from "zod";
320​
321const AnswerSchema = z.object({
322 summary: z.string(),
323 location: z.string(),
324});
325​
326const { sendMessage, partial, final } = useChat({
327 connection: fetchServerSentEvents("/api/chat"),
328 outputSchema: AnswerSchema,
329});
330```
331​
332See [Structured Outputs with tools](../structured-outputs/with-tools) for the
333event order, and [Middleware](../advanced/middleware) for how
334`structuredOutput` phase behaves on this path.
335​
336To try this in a browser, run `examples/ts-react-chat` and open
337`/generations/openrouter-combined`. The page shows the tool call, the typed
338object, and the adapter call counts. `structuredOutputStream` must stay at 0.
339​
340## Environment Variables
341​
342Set your API key in environment variables:
343​
344```bash
345OPENROUTER_API_KEY=sk-or-...
346```
347​
348## Model Routing
349​
350OpenRouter can automatically route requests to the best available provider:
351​
352```typescript
353import { chat, toServerSentEventsResponse } from "@tanstack/ai";
354import { openRouterText } from "@tanstack/ai-openrouter";
355​
356export async function POST(request: Request) {
357 const { messages } = await request.json();
358​
359 const stream = chat({
360 adapter: openRouterText("openrouter/auto"),
361 messages,
362 modelOptions: {
363 models: [
364 "openai/gpt-5.5",
365 "anthropic/claude-sonnet-4.5",
366 "google/gemini-3.1-pro-preview",
367 ],
368 },
369 });
370​
371 return toServerSentEventsResponse(stream);
373```
374​
375`models` is the fallback list: OpenRouter tries them in order when the primary model is unavailable. The rest of OpenRouter's routing surface is also exposed through `modelOptions` and forwarded to the request as-is. The option names are the camelCase ones from the OpenRouter SDK.
376​
377### Provider preferences
378​
379`provider` controls which upstream providers may serve the request and in what order. Pin one provider and disable fallbacks:
380​
381```typescript
382import { chat } from "@tanstack/ai";
383import { openRouterText } from "@tanstack/ai-openrouter";
384​
385const stream = chat({
386 adapter: openRouterText("meta-llama/llama-4-maverick"),
387 messages: [{ role: "user", content: "Hello!" }],
388 modelOptions: {
389 provider: {
390 order: ["groq", "together"], // provider slugs, in priority order
391 allowFallbacks: false, // fail instead of routing elsewhere
392 },
393 },
394});
395```
396​
397Provider slugs are the lowercase ids shown on OpenRouter's model pages (`"anthropic"`, `"openai"`, `"groq"`, …). Other fields on `provider`:
398​
399- `only` / `ignore`: allow-list or deny-list of provider slugs, merged with your account-wide provider settings for this request.
400- `requireParameters`: only route to providers that support every parameter in the request. Without it, OpenRouter sends each provider only the parameters it supports and silently drops the rest, so a `responseFormat` or a sampling option can be ignored without an error. When you stream with `requireParameters: true`, also set `modelOptions.streamOptions: { includeUsage: false }`. Without it, the adapter sends `stream_options`, and OpenRouter returns a 404 for providers that do not support that parameter.
401- `sort`: `"price"`, `"throughput"`, or `"latency"`, or an object with `by` and `partition`, applied when `order` is not set. Setting it disables load balancing.
402- `maxPrice`: the highest pricing you accept. It takes `prompt` and `completion` in USD per million tokens, plus `request` (per-request pricing) and `image` (per image) where a provider offers them. Providers above the limit are skipped.
403- `quantizations`: restrict to providers serving the model at given quantization levels (e.g. `"fp8"`, `"int4"`).
404- `dataCollection`: `"deny"` to use only providers that do not collect user data.
405- `zdr`: `true` to restrict routing to zero-data-retention endpoints.
406​
407### Model variants
408​
409`variant` appends OpenRouter's `:variant` suffix to the model id. It is adapter metadata only and is never sent in the request body:
410​
411```typescript
412import { chat } from "@tanstack/ai";
413import { openRouterText } from "@tanstack/ai-openrouter";
414​
415const stream = chat({
416 adapter: openRouterText("deepseek/deepseek-v4-pro"),
417 messages: [{ role: "user", content: "Hello!" }],
418 modelOptions: {
419 variant: "free", // requests deepseek/deepseek-v4-pro:free
420 },
421});
422```
423​
424Accepted values are `"free"`, `"nitro"`, `"online"`, `"exacto"`, `"extended"`, and `"thinking"`. Which of them a model actually offers is up to OpenRouter's catalog.
425​
426### Plugins
427​
428`plugins` enables OpenRouter's request-level plugins. Each entry is identified by `id`, with plugin-specific options alongside:
429​
430```typescript
431import { chat } from "@tanstack/ai";
432import { openRouterText } from "@tanstack/ai-openrouter";
433​
434const stream = chat({
435 adapter: openRouterText("openai/gpt-6-astra"),
436 messages: [{ role: "user", content: "Hello!" }],
437 modelOptions: {
438 plugins: [{ id: "web", maxResults: 5 }],
439 },
440});
441```
442​
443Plugin ids include `web`, `file-parser`, `response-healing`, `moderation`, and `auto-router`; see the OpenRouter documentation for each plugin's options. Web fetching is not a plugin but a server tool (`openrouter:web_fetch`); for web search and fetch as _tools_ the model can call, see [Provider Tools](#provider-tools) below.
444​
445### Reasoning
446​
447Set `reasoning` on `chat()`. OpenRouter gets it as `reasoning.effort`:
448​
449```typescript
450import { chat } from "@tanstack/ai";
451import { openRouterText } from "@tanstack/ai-openrouter";
452​
453const stream = chat({
454 adapter: openRouterText("anthropic/claude-opus-5.5"),
455 messages: [{ role: "user", content: "Hello!" }],
456 reasoning: "high",
457});
458```
459​
460- `off` sends `effort: "none"`.
461- `openRouterText` takes no `budgetTokens`. `openRouterResponsesText` sends `budgetTokens` as `reasoning.maxTokens`, and adds `summary: "auto"` so the thinking text streams.
462- The types take the levels of each model. Your editor shows them when you type `reasoning`.
463​
464### Session and metadata
465​
466`user` (a unique user identifier), `sessionId`, and `metadata` (up to 16 key-value pairs) are forwarded unchanged. `sessionId` doubles as OpenRouter's sticky routing key: requests that share it are routed to the same provider to maximize prompt-cache hits, and grouped together for observability.
467​
468### Prompt caching
469​
470`chat()` sets `sessionId` to the cache key by default, which is the `threadId` that you pass. So one conversation stays on one provider and reads its cache. `anthropic/*` models also get cache markers on the system message, the last tool, and the last message. `promptCache: 'long'` asks for the 1-hour cache, and `promptCache: 'none'` sends nothing. See [Prompt Caching](../advanced/prompt-caching).
471​
472Your own `modelOptions.sessionId` wins. A cache marker of your own turns the automatic markers off for that request.
473​
474## Model Options
475​
476OpenRouter supports various provider-specific options. Sampling parameters live here too — `temperature`, `topP`, and `maxCompletionTokens` (OpenRouter's token-limit key for the chat adapter) — rather than as root-level props on `chat()`:
477​
478```typescript
479import { chat, toServerSentEventsResponse } from "@tanstack/ai";
480import { openRouterText } from "@tanstack/ai-openrouter";
481​
482export async function POST(request: Request) {
483 const { messages } = await request.json();
484​
485 const stream = chat({
486 adapter: openRouterText("anthropic/claude-sonnet-4.5"),
487 messages,
488 modelOptions: {
489 temperature: 0.7,
490 topP: 0.9,
491 maxCompletionTokens: 1024,
492 },
493 });
494​
495 return toServerSentEventsResponse(stream);
497```
498​
499> If you previously passed `temperature` / `topP` / `maxTokens` at the root of `chat()`, see [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
500​
501## Chat Completions vs Responses (beta)
502​
503OpenRouter exposes two OpenAI-compatible wire formats, and the adapter
504package ships one of each:
505​
506| Adapter | Endpoint | Status | When to use |
507| ------------------------- | ---------------------- | ------ | ----------------------------------------------------------------------------------------- |
508| `openRouterText` | `/v1/chat/completions` | Stable | Default for almost everything. Broadest model + tool support. |
509| `openRouterResponsesText` | `/v1/responses` | Beta | OpenAI Responses-shaped request/response; richer multi-turn state on OpenAI-style models. |
510​
511Both adapters route to any underlying model OpenRouter supports
512(`anthropic/...`, `google/...`, `meta-llama/...`, etc.) — the wire format
513describes how your client talks to OpenRouter, not which provider answers.
514`/v1/responses` is OpenAI's newer API surface; OpenRouter implements it so
515clients that prefer that wire format can use it across the same 300+
516model catalogue.
517​
518```typescript
519import { chat } from "@tanstack/ai";
520import { openRouterResponsesText } from "@tanstack/ai-openrouter";
521​
522const stream = chat({
523 adapter: openRouterResponsesText("anthropic/claude-sonnet-4.5"),
524 messages: [{ role: "user", content: "Hello!" }],
525});
526```
527​
528Caveats while the Responses adapter is in beta:
529​
530- Function tools are supported; OpenRouter's branded server-tools (web
531 search, file search, …) are not yet wired through this path — use
532 `openRouterText` if you need those.
533- If in doubt, prefer `openRouterText`. The Chat Completions endpoint has
534 broader provider coverage and feature parity today.
535​
536## Cost Tracking
537​
538OpenRouter reports the actual cost of each request inline on the streamed
539response. When present, the adapter forwards it on the terminal `RUN_FINISHED`
540event under `usage.cost`, with OpenRouter's per-request breakdown under
541`usage.costDetails`. This is the cost OpenRouter itself reports for the
542request — it is **not** computed locally from token counts, so it already
543accounts for routing, fallback providers, BYOK, and cached-token pricing. See
544OpenRouter's [Usage Accounting](https://openrouter.ai/docs/use-cases/usage-accounting)
545docs for the meaning and units of these fields.
546​
547```typescript ignore
548import { chat, type RunFinishedEvent, type StreamChunk } from "@tanstack/ai";
549import { openRouterText } from "@tanstack/ai-openrouter";
550​
551function isRunFinished(chunk: StreamChunk): chunk is RunFinishedEvent {
552 return "finishReason" in chunk;
554​
555for await (const chunk of chat({
556 adapter: openRouterText("openai/gpt-5"),
557 messages: [{ role: "user", content: "Hello!" }],
558})) {
559 if (isRunFinished(chunk)) {
560 console.log("cost:", chunk.usage?.cost);
561 console.log("breakdown:", chunk.usage?.costDetails);
562 }
564```
565​
566The same `usage` (including `cost` / `costDetails`) is passed to middleware via
567the `onUsage` and `onFinish` hooks. When OpenRouter does not report a cost, the
568fields are simply absent and the stream completes normally. Both
569`openRouterText` and `openRouterResponsesText` populate cost when OpenRouter
570returns it.
571​
572The `openRouterText` adapter's `structuredOutputStream()` method includes
573received usage on its terminal `RUN_ERROR` event. This covers parse failures,
574truncated responses, empty responses, and SDK errors. When `chat()` uses this
575path, middleware `onChunk` receives the error event even if the promise rejects.
576The `onUsage` hook reports successful calls. Each adapter call reports usage on
577one terminal event.
578​
579A reported `completionTokensDetails.reasoningTokens` value of `0` stays zero.
580A missing count stays absent. Errors before any usage arrives have no `usage`
581field. If the consumer stops reading the stream, it cannot receive later events.
582​
583## Reranking
584​
585OpenRouter exposes rerank models through its unified `/v1/rerank` endpoint
586(served via the `@openrouter/sdk` SDK). Any rerank model OpenRouter offers works
587by passing its slug — for example `cohere/rerank-v3.5`, `cohere/rerank-4-fast`,
588`cohere/rerank-4-pro`, or `nvidia/llama-nemotron-rerank-vl-1b-v2`. Use
589`openRouterRerank` with the `rerank()` activity to reorder candidate documents
590by relevance to a query:
591​
592```typescript
593import { rerank } from "@tanstack/ai";
594import { openRouterRerank } from "@tanstack/ai-openrouter";
595​
596const { rerankedDocuments } = await rerank({
597 adapter: openRouterRerank("cohere/rerank-v3.5"),
598 query: "talk about rain",
599 documents: ["sunny day at the beach", "rainy afternoon in the city"],
600 topN: 2,
601});
602​
603console.log(rerankedDocuments[0]); // 'rainy afternoon in the city'
604```
605​
606`openRouterRerank` reads `OPENROUTER_API_KEY` from the environment; pass a key
607explicitly with `createOpenRouterRerank("cohere/rerank-v3.5", "sk-or-...")`. The
608optional `httpReferer` / `appTitle` config fields are forwarded as OpenRouter
609attribution headers, just like the chat adapter.
610​
611See the [Reranking guide](../rerank/rerank) for object documents, RAG
612pipelines, options, and the result shape.
613​
614## Evaluate
615​
616OpenRouter exposes TypeSafe Jev through `POST /api/alpha/decisions`.
617Use `openRouterDecider` with `decide()` to ask typed questions about a
618shared `state`:
619​
620```typescript
621import { decide, choice, score, boolean } from "@tanstack/ai";
622import { openRouterDecider } from "@tanstack/ai-openrouter";
623​
624const ticket = {
625 subject: "Charged twice for the same invoice",
626 body: "Please refund the extra payment.",
627};
628​
629const result = await decide({
630 adapter: openRouterDecider("~typesafe/jev-latest"),
631 state: ticket,
632 questions: {
633 queue: choice({
634 instructions: "Which team should handle this ticket?",
635 options: {
636 billing: "Payments, invoices, refunds",
637 tech: "Bugs, outages, integrations",
638 sales: "Pricing, upgrades, new accounts",
639 },
640 }),
641 urgency: score({
642 instructions: "How urgent is this ticket?",
643 levels: ["low", "medium", "high"],
644 }),
645 refund: boolean({
646 instructions: "Is the customer asking for a refund?",
647 }),
648 },
649});
650​
651console.log(result.queue.value);
652console.log(result.queue.probability);
653console.log(result.queue.confidence);
654console.log(result.meta.usage);
655```
656​
657To bill per request, read `result.meta.usage.cost`. To look the request up later with `GET /api/v1/generation?id=`, read `result.meta.id`. `result.meta.provider` names the upstream provider that served the request.
658​
659`openRouterDecider` reads `OPENROUTER_API_KEY` from the environment. Pass a
660key explicitly with `createOpenRouterDecider("~typesafe/jev-latest", "sk-or-...")`.
661​
662Known slugs:
663​
664- `~typesafe/jev-latest`
665- `typesafe/jev-1.13`
666- `typesafe/jev-1.13.0`
667​
668See the [Evaluate guide](../evaluate/evaluate) for question helpers, the result
669shape, abort, and middleware.
670​
671## Image Generation
672​
673For a React + Start walkthrough with `useGenerateImage`, open [Generate Image](../tutorials/generate-image).
674​
675`openRouterImage` routes image generation through OpenRouter's
676chat-completions surface (`modalities: ['image']`). Multimodal prompts are
677supported — text and image parts are forwarded in order for
678image-conditioned generation:
679​
680```typescript
681import { generateImage } from "@tanstack/ai";
682import { openRouterImage } from "@tanstack/ai-openrouter";
683​
684const result = await generateImage({
685 adapter: openRouterImage("google/gemini-2.5-flash-image"),
686 prompt: "A watercolor lighthouse at dusk",
687 size: "1344x768", // mapped to image_config.aspect_ratio ('16:9')
688 modelOptions: {
689 image_size: "2K", // resolution (Gemini models)
690 strength: 0.35, // image-to-image influence, i2i-capable models only
691 },
692});
693```
694​
695Notes:
696​
697- The pathway returns **exactly one image per request** — `numberOfImages > 1`
698 throws instead of silently under-delivering. Make multiple requests if you
699 need multiple candidates.
700- `size` must be one of the ten supported `WIDTHxHEIGHT` values (it is
701 converted to `image_config.aspect_ratio`); anything else throws with the
702 supported list.
703​
704## Video Generation (Experimental)
705​
706`openRouterVideo` targets OpenRouter's dedicated **async video API**
707(`POST /api/v1/videos`) — Seedance, Veo 3.1, Wan, Kling, and Sora 2 Pro
708through your one OpenRouter key. It follows the jobs/polling architecture
709shared by all TanStack AI video adapters:
710​
711```typescript
712// Server: create the job, then poll
713import { generateVideo, getVideoJobStatus } from "@tanstack/ai";
714import { openRouterVideo } from "@tanstack/ai-openrouter";
715import { withGenerationPersistence } from "@tanstack/ai-persistence";
716import { persistence } from "./persistence";
717​
718const adapter = openRouterVideo("bytedance/seedance-2.0");
719​
720// OpenRouter returns the finished video as a stream, not a URL. Persistence
721// stores the stream and sets `url`. Pass the same options to both calls.
722const hosting = {
723 threadId: "videos",
724 middleware: [
725 withGenerationPersistence(persistence, {
726 artifactUrl: (ref) => `/api/artifacts/${ref.artifactId}`,
727 }),
728 ],
729};
730​
731const { jobId } = await generateVideo({
732 adapter,
733 ...hosting,
734 prompt: [
735 { type: "text", content: "Animate this product shot, slow push-in" },
736 {
737 type: "image",
738 source: { type: "url", value: "https://your-cdn.com/product.png" },
739 metadata: { role: "start_frame" },
740 },
741 ],
742 size: "1280x720",
743 // `duration` is typed per model from the published metadata; coerce raw
744 // seconds with adapter.snapDuration() or enumerate via adapter.availableDurations().
745 duration: 8,
746});
747​
748let status = await getVideoJobStatus({ adapter, jobId, ...hosting });
749while (status.status !== "completed" && status.status !== "failed") {
750 await new Promise((r) => setTimeout(r, 5000));
751 status = await getVideoJobStatus({ adapter, jobId, ...hosting });
753// status.url is your artifact route. status.usage?.cost is the real billed
754// cost that the gateway reports.
755```
756​
757```tsx
758// Client: track the job with the useGenerateVideo hook
759import { useGenerateVideo, fetchServerSentEvents } from "@tanstack/ai-react";
760​
761const { generate, result, videoStatus, isLoading } = useGenerateVideo({
762 connection: fetchServerSentEvents("/api/generate/video"),
763});
764// result?.url renders directly: <video src={result.url} controls />
765```
766​
767Sizes, durations, and per-model options (`resolution`, `aspectRatio`,
768`generateAudio`, `seed`, …) are typed and validated per model from
769OpenRouter's video model metadata. See
770[Video Generation](../media/video-generation.md) for the full lifecycle,
771streaming mode, and the image-to-video role-mapping table.
772​
773## Next Steps
774​
775- [Getting Started](../getting-started/quick-start) - Learn the basics
776- [Tools Guide](../tools/tools) - Learn about tools
777- [Reranking](../rerank/rerank) - Reorder documents by relevance
778- [Evaluate](../evaluate/evaluate) - Ask typed questions about shared state
779​
780## Provider Tools
781​
782> **Migrated from `createWebSearchTool`?** This factory was renamed to
783> `webSearchTool` and moved to the `/tools` subpath in this release.
784> See [Migration Guide §6](../migration/migration.md#6-provider-tools-moved-to-tools-subpath)
785> for the exact before/after.
786​
787OpenRouter's gateway exposes web search via a plugin that works across
788any proxied chat model. Import it from `@tanstack/ai-openrouter/tools`.
789​
790> For the full concept, a comparison matrix, and type-gating details, see
791> [Provider Tools](../tools/provider-tools.md).
792​
793### `webSearchTool`
794​
795Adds web search capability to any OpenRouter-proxied chat model. The factory
796accepts OpenRouter's `WebSearchConfig` directly — pick the `engine`
797(`auto`, `native`, `exa`, `firecrawl`, or `parallel`), cap results with
798`maxResults` / `maxTotalResults`, restrict which sites can appear in results
799with `allowedDomains` / `excludedDomains`, and optionally pass
800`searchContextSize` or `userLocation` for finer control.
801​
802```typescript
803import { chat } from "@tanstack/ai";
804import { openRouterText } from "@tanstack/ai-openrouter";
805import { webSearchTool } from "@tanstack/ai-openrouter/tools";
806​
807const stream = chat({
808 adapter: openRouterText("openai/gpt-5"),
809 messages: [{ role: "user", content: "What's new in AI this week?" }],
810 tools: [
811 webSearchTool({
812 engine: "exa",
813 maxResults: 5,
814 allowedDomains: ["arxiv.org", "openai.com"],
815 }),
816 ],
817});
818```
819​
820**Supported models:** all OpenRouter chat models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
821​
822### `webFetchTool`
823​
824Lets any OpenRouter-proxied chat model fetch the full contents of a URL the
825model chooses, instead of running a search. The factory accepts OpenRouter's
826`WebFetchServerToolConfig` directly — pick the fetch `engine` (`auto` — the
827default, `native`, `openrouter`, `exa`, or `firecrawl`), cap how much page
828content the model receives with `maxContentTokens`, cap how many fetches the
829model can make per request with `maxUses`, and restrict which URLs the model
830can fetch with `allowedDomains` / `blockedDomains`.
831​
832> The `native` engine routes to the underlying provider's own fetch (for
833> example, Anthropic's `web_fetch` on Claude models). Native fetch
834> capabilities vary, so `allowedDomains` and `blockedDomains` may be
835> ignored. Use `openrouter`, `exa`, or `firecrawl` if you need consistent
836> behaviour across models.
837​
838```typescript
839import { chat } from "@tanstack/ai";
840import { openRouterText } from "@tanstack/ai-openrouter";
841import { webFetchTool } from "@tanstack/ai-openrouter/tools";
842​
843const stream = chat({
844 adapter: openRouterText("openai/gpt-5"),
845 messages: [
846 { role: "user", content: "Summarize https://example.com/article" },
847 ],
848 tools: [
849 webFetchTool({
850 engine: "openrouter",
851 maxContentTokens: 4000,
852 allowedDomains: ["example.com"],
853 }),
854 ],
855});
856```
857​
858**Supported models:** all OpenRouter chat models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
859​
860## Sign in with OpenRouter (BYOK)
861​
862OpenRouter can mint a user-owned API key via [OAuth PKCE](https://openrouter.ai/docs/guides/overview/auth/oauth). Import the helpers from `@tanstack/ai-openrouter/pkce`. The key is stored under `openrouterByok.id` (`openrouter`) and sent as `x-byok-openrouter`.
863​
864Client: start login, then on return save the key into `defineByok`.
865​
866```tsx
867import { useEffect } from "react";
868import { defineByok, defaultByokStorage } from "@tanstack/ai-client/byok";
869import {
870 completeOpenRouterPkceIntoByok,
871 startOpenRouterPkceLogin,
872} from "@tanstack/ai-openrouter/pkce";
873​
874const byok = defineByok({
875 storage: defaultByokStorage(),
876});
877​
878export function OpenRouterSignIn() {
879 useEffect(() => {
880 void completeOpenRouterPkceIntoByok(byok);
881 }, []);
882​
883 return (
884 <button
885 type="button"
886 onClick={() => {
887 void startOpenRouterPkceLogin();
888 }}
889 >
890 Sign in with OpenRouter
891 </button>
892 );
894```
895​
896Server: read the same slug the PKCE helper wrote.
897​
898```typescript
899import {
900 chat,
901 chatParamsFromRequest,
902 toServerSentEventsResponse,
903} from "@tanstack/ai";
904import { byokMissing, getByokKey } from "@tanstack/ai/byok/server";
905import { createOpenRouterText } from "@tanstack/ai-openrouter";
906import { openrouterByok } from "@tanstack/ai-openrouter/byok";
907​
908export async function POST(request: Request) {
909 const params = await chatParamsFromRequest(request);
910 const apiKey = getByokKey(request, openrouterByok);
911 if (!apiKey) return byokMissing(openrouterByok);
912​
913 const stream = chat({
914 adapter: createOpenRouterText("openai/gpt-5.5", apiKey),
915 messages: params.messages,
916 threadId: params.threadId,
917 runId: params.runId,
918 });
919 return toServerSentEventsResponse(stream);
921```
922​
923See [Bring Your Own Key](../advanced/byok) for the keyring and passkey storage.
924​
925### Sign in from a CLI
926​
927A CLI or a desktop app has no web page for the redirect, so the user would have to copy a key by hand. `openrouterSignIn()` signs the user in with the browser and gives your app the key:
928​
929```typescript
930import { chat } from "@tanstack/ai";
931import { createOpenRouterText } from "@tanstack/ai-openrouter";
932import { openrouterSignIn } from "@tanstack/ai-openrouter/pkce";
933​
934const signIn = openrouterSignIn();
935const apiKey = await signIn({
936 open: (url) => console.log(`Open this URL to sign in: ${url}`),
937});
938​
939const stream = chat({
940 adapter: createOpenRouterText("openai/gpt-6.1-sol", apiKey),
941 messages: [{ role: "user", content: "Hello!" }],
942});
943```
944​
9451. `signIn` starts a one-time listener on `127.0.0.1`, on a random port.
9462. It calls `open` with the OpenRouter sign-in URL. Open that URL in the browser.
9473. The user signs in and approves. The browser shows `You are signed in to OpenRouter. You can close this tab.`
9484. `signIn` resolves with the API key, and the listener closes.
949​
950The sign-in uses PKCE and a random state. It stops after 10 minutes. To change the time, pass `openrouterSignIn({ timeoutMs })`. To cancel it, pass `signal` to `signIn`.
951​
952The listener runs on the computer of your app. So the sign-in works only when your app and the browser are on the same computer. In a hosted app, use the browser flow above.