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

openrouter.md

836 lines28.4 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​
62### Retry rate limits
63​
64A 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:
65​
66```typescript
67import { createOpenRouterText } from "@tanstack/ai-openrouter";
68​
69const adapter = createOpenRouterText(
70 "openai/gpt-5",
71 process.env.OPENROUTER_API_KEY!,
72 {
73 retryConfig: {
74 strategy: "backoff",
75 backoff: {
76 initialInterval: 500,
77 maxInterval: 60000,
78 exponent: 1.5,
79 maxElapsedTime: 120000,
80 },
81 retryConnectionErrors: true,
82 },
83 retryCodes: ["429", "5XX"],
84 },
85);
86```
87​
88- `retryCodes`: the HTTP status codes to retry. `"5XX"` matches every 5xx code.
89- `retryConfig`: how long to wait between tries. When the response has a `Retry-After` header, the SDK waits that long.
90​
91Now a 429 waits, then retries, and the chat continues with the next response.
92​
93## Available Models
94​
95OpenRouter provides access to 300+ models from various providers. Models use the format `provider/model-name`:
96​
97```text
98model: "openai/gpt-5.1"
99model: "anthropic/claude-sonnet-4.5"
100model: "google/gemini-3.1-pro-preview"
101model: "meta-llama/llama-4-maverick"
102model: "deepseek/deepseek-v3.2"
103```
104​
105See the full list at [openrouter.ai/models](https://openrouter.ai/models).
106​
107## Example: Chat Completion
108​
109```typescript
110import { chat, toServerSentEventsResponse } from "@tanstack/ai";
111import { openRouterText } from "@tanstack/ai-openrouter";
112​
113export async function POST(request: Request) {
114 const { messages } = await request.json();
115​
116 const stream = chat({
117 adapter: openRouterText("openai/gpt-5"),
118 messages,
119 });
120​
121 return toServerSentEventsResponse(stream);
123```
124​
125## Example: With Tools
126​
127```typescript
128import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
129import { openRouterText } from "@tanstack/ai-openrouter";
130import { z } from "zod";
131​
132const getWeatherDef = toolDefinition({
133 name: "get_weather",
134 description: "Get the current weather",
135 inputSchema: z.object({
136 location: z.string(),
137 }),
138});
139​
140const getWeather = getWeatherDef.server(async ({ location }) => {
141 return { temperature: 72, conditions: "sunny" };
142});
143​
144export async function POST(request: Request) {
145 const { messages } = await request.json();
146​
147 const stream = chat({
148 adapter: openRouterText("openai/gpt-5"),
149 messages,
150 tools: [getWeather],
151 });
152​
153 return toServerSentEventsResponse(stream);
155```
156​
157## Tools and structured output together
158​
159You can pass both `tools` and `outputSchema` on one `chat()` call. For some
160upstream models OpenRouter can return the typed object in that same streaming
161request, so the engine does not make a second finalization call.
162​
163That happens only when **every** model that can receive the request is in
164`OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS`. The set is generated from
165OpenRouter's catalog on every model sync: every chat model whose
166`supported_parameters` include `structured_outputs`, `tools` and `tool_choice`
167(Claude 4.5+, Gemini 2.5+, GPT-4o+, Grok 4, DeepSeek V3+, Llama 3.1+, and so
168on). Models OpenRouter does not flag, such as `anthropic/claude-opus-4.1`, stay
169on the legacy two-call path.
170​
171If any fallback in `modelOptions.models` is outside that set, OpenRouter keeps
172the two-call path. Routing suffixes such as `:nitro` do not change the gate.
173​
174Import the set from `@tanstack/ai-openrouter/model-meta` if you need to check a
175model before you send:
176​
177```typescript
178import { OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS } from "@tanstack/ai-openrouter/model-meta";
179​
180OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS.has("openai/gpt-5.5");
181```
182​
183Chat Completions (`openRouterText`) and Responses (`openRouterResponsesText`)
184both attach the schema on this path. The client does not change: `useChat({
185outputSchema })` still reads `partial` and `final`.
186​
187Server (Chat Completions):
188​
189```typescript
190import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
191import { openRouterText } from "@tanstack/ai-openrouter";
192import { z } from "zod";
193​
194const getWeather = toolDefinition({
195 name: "get_weather",
196 description: "Get the current weather",
197 inputSchema: z.object({ location: z.string() }),
198}).server(async ({ location }) => {
199 return { temperature: 72, conditions: "sunny", location };
200});
201​
202const AnswerSchema = z.object({
203 summary: z.string(),
204 location: z.string(),
205});
206​
207export async function POST(request: Request) {
208 const { messages } = await request.json();
209​
210 const stream = chat({
211 adapter: openRouterText("openai/gpt-5.5"),
212 messages,
213 tools: [getWeather],
214 outputSchema: AnswerSchema,
215 stream: true,
216 });
217​
218 return toServerSentEventsResponse(stream);
220```
221​
222Server (Responses). Same `tools` and `outputSchema` as the Chat Completions
223example, with `openRouterResponsesText`:
224​
225```typescript
226import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
227import { openRouterResponsesText } from "@tanstack/ai-openrouter";
228import { z } from "zod";
229​
230const getWeather = toolDefinition({
231 name: "get_weather",
232 description: "Get the current weather",
233 inputSchema: z.object({ location: z.string() }),
234}).server(async ({ location }) => {
235 return { temperature: 72, conditions: "sunny", location };
236});
237​
238const AnswerSchema = z.object({
239 summary: z.string(),
240 location: z.string(),
241});
242​
243export async function POST(request: Request) {
244 const { messages } = await request.json();
245​
246 const stream = chat({
247 adapter: openRouterResponsesText("openai/gpt-5.5"),
248 messages,
249 tools: [getWeather],
250 outputSchema: AnswerSchema,
251 stream: true,
252 });
253​
254 return toServerSentEventsResponse(stream);
256```
257​
258Client:
259​
260```tsx
261import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
262import { z } from "zod";
263​
264const AnswerSchema = z.object({
265 summary: z.string(),
266 location: z.string(),
267});
268​
269const { sendMessage, partial, final } = useChat({
270 connection: fetchServerSentEvents("/api/chat"),
271 outputSchema: AnswerSchema,
272});
273```
274​
275See [Structured Outputs with tools](../structured-outputs/with-tools) for the
276event order, and [Middleware](../advanced/middleware) for how
277`structuredOutput` phase behaves on this path.
278​
279To try this in a browser, run `examples/ts-react-chat` and open
280`/generations/openrouter-combined`. The page shows the tool call, the typed
281object, and the adapter call counts. `structuredOutputStream` must stay at 0.
282​
283## Environment Variables
284​
285Set your API key in environment variables:
286​
287```bash
288OPENROUTER_API_KEY=sk-or-...
289```
290​
291## Model Routing
292​
293OpenRouter can automatically route requests to the best available provider:
294​
295```typescript
296import { chat, toServerSentEventsResponse } from "@tanstack/ai";
297import { openRouterText } from "@tanstack/ai-openrouter";
298​
299export async function POST(request: Request) {
300 const { messages } = await request.json();
301​
302 const stream = chat({
303 adapter: openRouterText("openrouter/auto"),
304 messages,
305 modelOptions: {
306 models: [
307 "openai/gpt-5.5",
308 "anthropic/claude-sonnet-4.5",
309 "google/gemini-3.1-pro-preview",
310 ],
311 },
312 });
313​
314 return toServerSentEventsResponse(stream);
316```
317​
318`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.
319​
320### Provider preferences
321​
322`provider` controls which upstream providers may serve the request and in what order. Pin one provider and disable fallbacks:
323​
324```typescript
325import { chat } from "@tanstack/ai";
326import { openRouterText } from "@tanstack/ai-openrouter";
327​
328const stream = chat({
329 adapter: openRouterText("meta-llama/llama-4-maverick"),
330 messages: [{ role: "user", content: "Hello!" }],
331 modelOptions: {
332 provider: {
333 order: ["groq", "together"], // provider slugs, in priority order
334 allowFallbacks: false, // fail instead of routing elsewhere
335 },
336 },
337});
338```
339​
340Provider slugs are the lowercase ids shown on OpenRouter's model pages (`"anthropic"`, `"openai"`, `"groq"`, …). Other fields on `provider`:
341​
342- `only` / `ignore`: allow-list or deny-list of provider slugs, merged with your account-wide provider settings for this request.
343- `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.
344- `sort`: `"price"`, `"throughput"`, or `"latency"`, or an object with `by` and `partition`, applied when `order` is not set. Setting it disables load balancing.
345- `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.
346- `quantizations`: restrict to providers serving the model at given quantization levels (e.g. `"fp8"`, `"int4"`).
347- `dataCollection`: `"deny"` to use only providers that do not collect user data.
348- `zdr`: `true` to restrict routing to zero-data-retention endpoints.
349​
350### Model variants
351​
352`variant` appends OpenRouter's `:variant` suffix to the model id. It is adapter metadata only and is never sent in the request body:
353​
354```typescript
355import { chat } from "@tanstack/ai";
356import { openRouterText } from "@tanstack/ai-openrouter";
357​
358const stream = chat({
359 adapter: openRouterText("deepseek/deepseek-v4-pro"),
360 messages: [{ role: "user", content: "Hello!" }],
361 modelOptions: {
362 variant: "free", // requests deepseek/deepseek-v4-pro:free
363 },
364});
365```
366​
367Accepted values are `"free"`, `"nitro"`, `"online"`, `"exacto"`, `"extended"`, and `"thinking"`. Which of them a model actually offers is up to OpenRouter's catalog.
368​
369### Plugins
370​
371`plugins` enables OpenRouter's request-level plugins. Each entry is identified by `id`, with plugin-specific options alongside:
372​
373```typescript
374import { chat } from "@tanstack/ai";
375import { openRouterText } from "@tanstack/ai-openrouter";
376​
377const stream = chat({
378 adapter: openRouterText("openai/gpt-6-astra"),
379 messages: [{ role: "user", content: "Hello!" }],
380 modelOptions: {
381 plugins: [{ id: "web", maxResults: 5 }],
382 },
383});
384```
385​
386Plugin 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.
387​
388### Reasoning
389​
390`reasoning` is OpenRouter's unified reasoning configuration:
391​
392```typescript
393import { chat } from "@tanstack/ai";
394import { openRouterText } from "@tanstack/ai-openrouter";
395​
396const stream = chat({
397 adapter: openRouterText("anthropic/claude-sonnet-5"),
398 messages: [{ role: "user", content: "Hello!" }],
399 modelOptions: {
400 reasoning: { effort: "high" },
401 },
402});
403```
404​
405`effort` accepts `"none"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"`, and `"max"`. To switch reasoning off for a request, pass `reasoning: { enabled: false }`; the adapter sends it as `effort: "none"` because the SDK's request schema drops `enabled`.
406​
407### Session and metadata
408​
409`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.
410​
411## Model Options
412​
413OpenRouter 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()`:
414​
415```typescript
416import { chat, toServerSentEventsResponse } from "@tanstack/ai";
417import { openRouterText } from "@tanstack/ai-openrouter";
418​
419export async function POST(request: Request) {
420 const { messages } = await request.json();
421​
422 const stream = chat({
423 adapter: openRouterText("anthropic/claude-sonnet-4.5"),
424 messages,
425 modelOptions: {
426 temperature: 0.7,
427 topP: 0.9,
428 maxCompletionTokens: 1024,
429 },
430 });
431​
432 return toServerSentEventsResponse(stream);
434```
435​
436> If you previously passed `temperature` / `topP` / `maxTokens` at the root of `chat()`, see [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
437​
438## Chat Completions vs Responses (beta)
439​
440OpenRouter exposes two OpenAI-compatible wire formats, and the adapter
441package ships one of each:
442​
443| Adapter | Endpoint | Status | When to use |
444| ------------------------- | ---------------------- | ------ | ----------------------------------------------------------------------------------------- |
445| `openRouterText` | `/v1/chat/completions` | Stable | Default for almost everything. Broadest model + tool support. |
446| `openRouterResponsesText` | `/v1/responses` | Beta | OpenAI Responses-shaped request/response; richer multi-turn state on OpenAI-style models. |
447​
448Both adapters route to any underlying model OpenRouter supports
449(`anthropic/...`, `google/...`, `meta-llama/...`, etc.) — the wire format
450describes how your client talks to OpenRouter, not which provider answers.
451`/v1/responses` is OpenAI's newer API surface; OpenRouter implements it so
452clients that prefer that wire format can use it across the same 300+
453model catalogue.
454​
455```typescript
456import { chat } from "@tanstack/ai";
457import { openRouterResponsesText } from "@tanstack/ai-openrouter";
458​
459const stream = chat({
460 adapter: openRouterResponsesText("anthropic/claude-sonnet-4.5"),
461 messages: [{ role: "user", content: "Hello!" }],
462});
463```
464​
465Caveats while the Responses adapter is in beta:
466​
467- Function tools are supported; OpenRouter's branded server-tools (web
468 search, file search, …) are not yet wired through this path — use
469 `openRouterText` if you need those.
470- If in doubt, prefer `openRouterText`. The Chat Completions endpoint has
471 broader provider coverage and feature parity today.
472​
473## Cost Tracking
474​
475OpenRouter reports the actual cost of each request inline on the streamed
476response. When present, the adapter forwards it on the terminal `RUN_FINISHED`
477event under `usage.cost`, with OpenRouter's per-request breakdown under
478`usage.costDetails`. This is the cost OpenRouter itself reports for the
479request — it is **not** computed locally from token counts, so it already
480accounts for routing, fallback providers, BYOK, and cached-token pricing. See
481OpenRouter's [Usage Accounting](https://openrouter.ai/docs/use-cases/usage-accounting)
482docs for the meaning and units of these fields.
483​
484```typescript ignore
485import { chat, type RunFinishedEvent, type StreamChunk } from "@tanstack/ai";
486import { openRouterText } from "@tanstack/ai-openrouter";
487​
488function isRunFinished(chunk: StreamChunk): chunk is RunFinishedEvent {
489 return "finishReason" in chunk;
491​
492for await (const chunk of chat({
493 adapter: openRouterText("openai/gpt-5"),
494 messages: [{ role: "user", content: "Hello!" }],
495})) {
496 if (isRunFinished(chunk)) {
497 console.log("cost:", chunk.usage?.cost);
498 console.log("breakdown:", chunk.usage?.costDetails);
499 }
501```
502​
503The same `usage` (including `cost` / `costDetails`) is passed to middleware via
504the `onUsage` and `onFinish` hooks. When OpenRouter does not report a cost, the
505fields are simply absent and the stream completes normally. Both
506`openRouterText` and `openRouterResponsesText` populate cost when OpenRouter
507returns it.
508​
509## Reranking
510​
511OpenRouter exposes rerank models through its unified `/v1/rerank` endpoint
512(served via the `@openrouter/sdk` SDK). Any rerank model OpenRouter offers works
513by passing its slug — for example `cohere/rerank-v3.5`, `cohere/rerank-4-fast`,
514`cohere/rerank-4-pro`, or `nvidia/llama-nemotron-rerank-vl-1b-v2`. Use
515`openRouterRerank` with the `rerank()` activity to reorder candidate documents
516by relevance to a query:
517​
518```typescript
519import { rerank } from "@tanstack/ai";
520import { openRouterRerank } from "@tanstack/ai-openrouter";
521​
522const { rerankedDocuments } = await rerank({
523 adapter: openRouterRerank("cohere/rerank-v3.5"),
524 query: "talk about rain",
525 documents: ["sunny day at the beach", "rainy afternoon in the city"],
526 topN: 2,
527});
528​
529console.log(rerankedDocuments[0]); // 'rainy afternoon in the city'
530```
531​
532`openRouterRerank` reads `OPENROUTER_API_KEY` from the environment; pass a key
533explicitly with `createOpenRouterRerank("cohere/rerank-v3.5", "sk-or-...")`. The
534optional `httpReferer` / `appTitle` config fields are forwarded as OpenRouter
535attribution headers, just like the chat adapter.
536​
537See the [Reranking guide](../rerank/rerank) for object documents, RAG
538pipelines, options, and the result shape.
539​
540## Evaluate
541​
542OpenRouter exposes TypeSafe Jev through `POST /api/alpha/decisions`.
543Use `openRouterDecider` with `decide()` to ask typed questions about a
544shared `state`:
545​
546```typescript
547import { decide, choice, score, boolean } from "@tanstack/ai";
548import { openRouterDecider } from "@tanstack/ai-openrouter";
549​
550const ticket = {
551 subject: "Charged twice for the same invoice",
552 body: "Please refund the extra payment.",
553};
554​
555const result = await decide({
556 adapter: openRouterDecider("~typesafe/jev-latest"),
557 state: ticket,
558 questions: {
559 queue: choice({
560 instructions: "Which team should handle this ticket?",
561 options: {
562 billing: "Payments, invoices, refunds",
563 tech: "Bugs, outages, integrations",
564 sales: "Pricing, upgrades, new accounts",
565 },
566 }),
567 urgency: score({
568 instructions: "How urgent is this ticket?",
569 levels: ["low", "medium", "high"],
570 }),
571 refund: boolean({
572 instructions: "Is the customer asking for a refund?",
573 }),
574 },
575});
576​
577console.log(result.queue.value);
578console.log(result.queue.probability);
579console.log(result.queue.confidence);
580console.log(result.meta.usage);
581```
582​
583To 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.
584​
585`openRouterDecider` reads `OPENROUTER_API_KEY` from the environment. Pass a
586key explicitly with `createOpenRouterDecider("~typesafe/jev-latest", "sk-or-...")`.
587​
588Known slugs:
589​
590- `~typesafe/jev-latest`
591- `typesafe/jev-1.13`
592- `typesafe/jev-1.13.0`
593​
594See the [Evaluate guide](../evaluate/evaluate) for question helpers, the result
595shape, abort, and middleware.
596​
597## Image Generation
598​
599For a React + Start walkthrough with `useGenerateImage`, open [Generate Image](../tutorials/generate-image).
600​
601`openRouterImage` routes image generation through OpenRouter's
602chat-completions surface (`modalities: ['image']`). Multimodal prompts are
603supported — text and image parts are forwarded in order for
604image-conditioned generation:
605​
606```typescript
607import { generateImage } from "@tanstack/ai";
608import { openRouterImage } from "@tanstack/ai-openrouter";
609​
610const result = await generateImage({
611 adapter: openRouterImage("google/gemini-2.5-flash-image"),
612 prompt: "A watercolor lighthouse at dusk",
613 size: "1344x768", // mapped to image_config.aspect_ratio ('16:9')
614 modelOptions: {
615 image_size: "2K", // resolution (Gemini models)
616 strength: 0.35, // image-to-image influence, i2i-capable models only
617 },
618});
619```
620​
621Notes:
622​
623- The pathway returns **exactly one image per request** — `numberOfImages > 1`
624 throws instead of silently under-delivering. Make multiple requests if you
625 need multiple candidates.
626- `size` must be one of the ten supported `WIDTHxHEIGHT` values (it is
627 converted to `image_config.aspect_ratio`); anything else throws with the
628 supported list.
629​
630## Video Generation (Experimental)
631​
632`openRouterVideo` targets OpenRouter's dedicated **async video API**
633(`POST /api/v1/videos`) — Seedance, Veo 3.1, Wan, Kling, and Sora 2 Pro
634through your one OpenRouter key. It follows the jobs/polling architecture
635shared by all TanStack AI video adapters:
636​
637```typescript
638// Server: create the job, then poll
639import { generateVideo, getVideoJobStatus } from "@tanstack/ai";
640import { openRouterVideo } from "@tanstack/ai-openrouter";
641​
642const adapter = openRouterVideo("bytedance/seedance-2.0");
643​
644const { jobId } = await generateVideo({
645 adapter,
646 prompt: [
647 { type: "text", content: "Animate this product shot, slow push-in" },
648 {
649 type: "image",
650 source: { type: "url", value: "https://your-cdn.com/product.png" },
651 metadata: { role: "start_frame" },
652 },
653 ],
654 size: "1280x720",
655 // `duration` is typed per model from the published metadata; coerce raw
656 // seconds with adapter.snapDuration() or enumerate via adapter.availableDurations().
657 duration: 8,
658});
659​
660let status = await getVideoJobStatus({ adapter, jobId });
661while (status.status !== "completed" && status.status !== "failed") {
662 await new Promise((r) => setTimeout(r, 5000));
663 status = await getVideoJobStatus({ adapter, jobId });
665// status.url is a data: URL (OpenRouter download URLs require the API key,
666// so the adapter downloads server-side); status.usage?.cost is the real
667// billed cost reported by the gateway.
668```
669​
670```tsx
671// Client: track the job with the useGenerateVideo hook
672import { useGenerateVideo, fetchServerSentEvents } from "@tanstack/ai-react";
673​
674const { generate, result, videoStatus, isLoading } = useGenerateVideo({
675 connection: fetchServerSentEvents("/api/generate/video"),
676});
677// result?.url renders directly: <video src={result.url} controls />
678```
679​
680Sizes, durations, and per-model options (`resolution`, `aspectRatio`,
681`generateAudio`, `seed`, …) are typed and validated per model from
682OpenRouter's video model metadata. See
683[Video Generation](../media/video-generation.md) for the full lifecycle,
684streaming mode, and the image-to-video role-mapping table.
685​
686## Next Steps
687​
688- [Getting Started](../getting-started/quick-start) - Learn the basics
689- [Tools Guide](../tools/tools) - Learn about tools
690- [Reranking](../rerank/rerank) - Reorder documents by relevance
691- [Evaluate](../evaluate/evaluate) - Ask typed questions about shared state
692​
693## Provider Tools
694​
695> **Migrated from `createWebSearchTool`?** This factory was renamed to
696> `webSearchTool` and moved to the `/tools` subpath in this release.
697> See [Migration Guide §6](../migration/migration.md#6-provider-tools-moved-to-tools-subpath)
698> for the exact before/after.
699​
700OpenRouter's gateway exposes web search via a plugin that works across
701any proxied chat model. Import it from `@tanstack/ai-openrouter/tools`.
702​
703> For the full concept, a comparison matrix, and type-gating details, see
704> [Provider Tools](../tools/provider-tools.md).
705​
706### `webSearchTool`
707​
708Adds web search capability to any OpenRouter-proxied chat model. The factory
709accepts OpenRouter's `WebSearchConfig` directly — pick the `engine`
710(`auto`, `native`, `exa`, `firecrawl`, or `parallel`), cap results with
711`maxResults` / `maxTotalResults`, restrict which sites can appear in results
712with `allowedDomains` / `excludedDomains`, and optionally pass
713`searchContextSize` or `userLocation` for finer control.
714​
715```typescript
716import { chat } from "@tanstack/ai";
717import { openRouterText } from "@tanstack/ai-openrouter";
718import { webSearchTool } from "@tanstack/ai-openrouter/tools";
719​
720const stream = chat({
721 adapter: openRouterText("openai/gpt-5"),
722 messages: [{ role: "user", content: "What's new in AI this week?" }],
723 tools: [
724 webSearchTool({
725 engine: "exa",
726 maxResults: 5,
727 allowedDomains: ["arxiv.org", "openai.com"],
728 }),
729 ],
730});
731```
732​
733**Supported models:** all OpenRouter chat models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
734​
735### `webFetchTool`
736​
737Lets any OpenRouter-proxied chat model fetch the full contents of a URL the
738model chooses, instead of running a search. The factory accepts OpenRouter's
739`WebFetchServerToolConfig` directly — pick the fetch `engine` (`auto` — the
740default, `native`, `openrouter`, `exa`, or `firecrawl`), cap how much page
741content the model receives with `maxContentTokens`, cap how many fetches the
742model can make per request with `maxUses`, and restrict which URLs the model
743can fetch with `allowedDomains` / `blockedDomains`.
744​
745> The `native` engine routes to the underlying provider's own fetch (for
746> example, Anthropic's `web_fetch` on Claude models). Native fetch
747> capabilities vary, so `allowedDomains` and `blockedDomains` may be
748> ignored. Use `openrouter`, `exa`, or `firecrawl` if you need consistent
749> behaviour across models.
750​
751```typescript
752import { chat } from "@tanstack/ai";
753import { openRouterText } from "@tanstack/ai-openrouter";
754import { webFetchTool } from "@tanstack/ai-openrouter/tools";
755​
756const stream = chat({
757 adapter: openRouterText("openai/gpt-5"),
758 messages: [
759 { role: "user", content: "Summarize https://example.com/article" },
760 ],
761 tools: [
762 webFetchTool({
763 engine: "openrouter",
764 maxContentTokens: 4000,
765 allowedDomains: ["example.com"],
766 }),
767 ],
768});
769```
770​
771**Supported models:** all OpenRouter chat models. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
772​
773## Sign in with OpenRouter (BYOK)
774​
775OpenRouter 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`.
776​
777Client: start login, then on return save the key into `defineByok`.
778​
779```tsx
780import { useEffect } from "react";
781import { defineByok, defaultByokStorage } from "@tanstack/ai-client/byok";
782import {
783 completeOpenRouterPkceIntoByok,
784 startOpenRouterPkceLogin,
785} from "@tanstack/ai-openrouter/pkce";
786​
787const byok = defineByok({
788 storage: defaultByokStorage(),
789});
790​
791export function OpenRouterSignIn() {
792 useEffect(() => {
793 void completeOpenRouterPkceIntoByok(byok);
794 }, []);
795​
796 return (
797 <button
798 type="button"
799 onClick={() => {
800 void startOpenRouterPkceLogin();
801 }}
802 >
803 Sign in with OpenRouter
804 </button>
805 );
807```
808​
809Server: read the same slug the PKCE helper wrote.
810​
811```typescript
812import {
813 chat,
814 chatParamsFromRequest,
815 toServerSentEventsResponse,
816} from "@tanstack/ai";
817import { byokMissing, getByokKey } from "@tanstack/ai/byok/server";
818import { createOpenRouterText } from "@tanstack/ai-openrouter";
819import { openrouterByok } from "@tanstack/ai-openrouter/byok";
820​
821export async function POST(request: Request) {
822 const params = await chatParamsFromRequest(request);
823 const apiKey = getByokKey(request, openrouterByok);
824 if (!apiKey) return byokMissing(openrouterByok);
825​
826 const stream = chat({
827 adapter: createOpenRouterText("openai/gpt-5.5", apiKey),
828 messages: params.messages,
829 threadId: params.threadId,
830 runId: params.runId,
831 });
832 return toServerSentEventsResponse(stream);
834```
835​
836See [Bring Your Own Key](../advanced/byok) for the keyring and passkey storage.