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

openrouter.md

397 lines13.4 KB

1---
2title: OpenRouter Adapter
3id: openrouter-adapter
4description: "Use 300+ models from OpenAI, Anthropic, Google, Meta, Mistral, and more in TanStack AI with one OpenRouter API key."
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​
17`openRouterText` calls 300+ models from OpenAI, Anthropic, Google, Meta, Mistral, and others with one API key.
18​
19## 1. Install
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## 2. Set the API key
35​
36Put the key in the environment of your server:
37​
38```bash
39OPENROUTER_API_KEY=sk-or-...
40```
41​
42`openRouterText` and the other short factories read `OPENROUTER_API_KEY`. To pass the key in code, use the `create*` factory of the same adapter:
43​
44```typescript
45import { createOpenRouterText } from "@tanstack/ai-openrouter";
46​
47const adapter = createOpenRouterText("openai/gpt-6.1-sol", process.env.OPENROUTER_API_KEY!);
48```
49​
50## 3. Stream a chat from the server
51​
52```typescript
53import {
54 chat,
55 chatParamsFromRequest,
56 toServerSentEventsResponse,
57} from "@tanstack/ai";
58import { openRouterText } from "@tanstack/ai-openrouter";
59​
60export async function POST(request: Request) {
61 const { messages, threadId, runId } = await chatParamsFromRequest(request);
62​
63 const stream = chat({
64 adapter: openRouterText("openai/gpt-6.1-sol"),
65 messages,
66 threadId,
67 runId,
68 });
69​
70 return toServerSentEventsResponse(stream);
72```
73​
74To use a different model, change the id. Ids have the shape `provider/model-name`, for example `anthropic/claude-sonnet-5.5` or `google/gemini-3.1-pro-preview`.
75​
76## 4. Render the chat
77​
78The client is the same for every provider. Point `useChat` at your route:
79​
80```tsx
81import { useState } from "react";
82import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
83​
84export function Chat() {
85 const [input, setInput] = useState("");
86 const { messages, sendMessage } = useChat({
87 connection: fetchServerSentEvents("/api/chat"),
88 threadId: "support-chat",
89 });
90​
91 return (
92 <form
93 onSubmit={(event) => {
94 event.preventDefault();
95 sendMessage(input);
96 setInput("");
97 }}
98 >
99 {messages.map((message) => (
100 <p key={message.id}>
101 {message.parts
102 .map((part) => (part.type === "text" ? part.content : ""))
103 .join("")}
104 </p>
105 ))}
106 <input value={input} onChange={(event) => setInput(event.target.value)} />
107 </form>
108 );
110```
111​
112For Vue, Solid, Svelte, Angular, and the other frameworks, see [Quick Start](../getting-started/quick-start#3-render-the-chat).
113​
114You now have a streaming chat on OpenRouter. [Tools](../tools/tools) and [Structured Outputs](../structured-outputs/overview) work the same as with every adapter.
115​
116## Model routing
117​
118A model can be down, or slow on one provider. Give OpenRouter a fallback list in `models`. When the primary model is not available, OpenRouter tries the models in order:
119​
120```typescript
121import { chat } from "@tanstack/ai";
122import { openRouterText } from "@tanstack/ai-openrouter";
123​
124const stream = chat({
125 adapter: openRouterText("openrouter/auto"),
126 messages: [{ role: "user", content: "Hello!" }],
127 threadId: "thread-1",
128 modelOptions: {
129 models: [
130 "openai/gpt-6.1-sol",
131 "anthropic/claude-sonnet-5.5",
132 "google/gemini-3.1-pro-preview",
133 ],
134 },
135});
136```
137​
138To pick which upstream providers serve a model, set `modelOptions.provider`:
139​
140```typescript
141import { chat } from "@tanstack/ai";
142import { openRouterText } from "@tanstack/ai-openrouter";
143​
144const stream = chat({
145 adapter: openRouterText("meta-llama/llama-4-maverick"),
146 messages: [{ role: "user", content: "Hello!" }],
147 threadId: "thread-1",
148 modelOptions: {
149 provider: {
150 order: ["groq", "together"], // provider slugs, in priority order
151 allowFallbacks: false, // fail instead of routing elsewhere
152 },
153 },
154});
155```
156​
157For all the `provider` fields, model variants such as `:free`, and plugins, see [OpenRouter: Advanced](./openrouter-advanced#provider-preferences).
158​
159## Provider tools
160​
161OpenRouter runs web search and web fetch for any chat model. Import the tools from `@tanstack/ai-openrouter/tools`:
162​
163```typescript
164import { chat } from "@tanstack/ai";
165import { openRouterText } from "@tanstack/ai-openrouter";
166import { webSearchTool } from "@tanstack/ai-openrouter/tools";
167​
168const stream = chat({
169 adapter: openRouterText("openai/gpt-6.1-sol"),
170 messages: [{ role: "user", content: "What's new in AI this week?" }],
171 threadId: "thread-1",
172 tools: [
173 webSearchTool({
174 engine: "exa",
175 maxResults: 5,
176 allowedDomains: ["arxiv.org", "openai.com"],
177 }),
178 ],
179});
180```
181​
182- `webSearchTool`: search the web.
183- `webFetchTool`: read the full page at a URL that the model picks.
184​
185Both work on all OpenRouter chat models. For every option of each tool, see [OpenRouter: Advanced](./openrouter-advanced#provider-tools). For how provider tools compare across adapters, see [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
186​
187## Tools and structured output together
188​
189You can pass `tools` and `outputSchema` on one `chat()` call. On some models, OpenRouter returns the typed object in the same streaming request. Then no second call is necessary.
190​
191This happens only when every model that can get the request is in `OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS`. To check a model before you send:
192​
193```typescript
194import { OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS } from "@tanstack/ai-openrouter/model-meta";
195​
196console.log(OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS.has("openai/gpt-6.1-sol")); // true
197```
198​
199For the full server and client code and the rules of the set, see [OpenRouter: Advanced](./openrouter-advanced#tools-and-structured-output-in-one-call).
200​
201## Images
202​
203```typescript
204import { generateImage } from "@tanstack/ai";
205import { openRouterImage } from "@tanstack/ai-openrouter";
206​
207const result = await generateImage({
208 adapter: openRouterImage("google/gemini-nano-banana-2.1"),
209 prompt: "A watercolor lighthouse at dusk",
210 threadId: "thread-1",
211 size: "1344x768", // sent as image_config.aspect_ratio ("16:9")
212 modelOptions: {
213 image_size: "2K", // resolution (Gemini models)
214 },
215});
216​
217console.log(result.images);
218```
219​
220- You get one image for each request. `numberOfImages` more than 1 throws an error.
221- `size` takes one of ten `WIDTHxHEIGHT` values. Other values throw an error that lists the valid sizes.
222- The prompt can mix text and image parts, for image-to-image work. `modelOptions.strength` sets how much the input image controls the result, on models that support it.
223​
224For a React and TanStack Start walkthrough with `useGenerateImage`, see [Generate Image](../tutorials/generate-image). See also [Image Generation](../media/image-generation).
225​
226## Video
227​
228`openRouterVideo` makes videos with Seedance, Veo 3.1, Wan, Kling, and more, through the async video API of OpenRouter (`POST /api/v1/videos`). Video generation is experimental. For the full server and client code, see [OpenRouter: Advanced](./openrouter-advanced#video-generation).
229​
230## Reranking
231​
232`openRouterRerank` puts documents in order of how well they match a query:
233​
234```typescript
235import { rerank } from "@tanstack/ai";
236import { openRouterRerank } from "@tanstack/ai-openrouter";
237​
238const { rerankedDocuments } = await rerank({
239 adapter: openRouterRerank("cohere/rerank-4-pro"),
240 query: "talk about rain",
241 documents: ["sunny day at the beach", "rainy afternoon in the city"],
242 topN: 2,
243});
244​
245console.log(rerankedDocuments[0]); // "rainy afternoon in the city"
246```
247​
248Any rerank model on OpenRouter works. Known ids: `cohere/rerank-v3.5`, `cohere/rerank-4-fast`, `cohere/rerank-4-pro`, `nvidia/llama-nemotron-rerank-vl-1b-v2`. See the [Reranking guide](../rerank/rerank).
249​
250## Evaluate
251​
252Sometimes you need an answer that your code can branch on, not chat text. Use `openRouterDecider` with `decide()` to ask typed questions about one shared `state`. The adapter calls TypeSafe Jev through `POST /api/alpha/decisions`:
253​
254```typescript
255import { decide, choice, score, boolean } from "@tanstack/ai";
256import { openRouterDecider } from "@tanstack/ai-openrouter";
257​
258const ticket = {
259 subject: "Charged twice for the same invoice",
260 body: "Please refund the extra payment.",
261};
262​
263const result = await decide({
264 adapter: openRouterDecider("~typesafe/jev-latest"),
265 state: ticket,
266 questions: {
267 queue: choice({
268 instructions: "Which team should handle this ticket?",
269 options: {
270 billing: "Payments, invoices, refunds",
271 tech: "Bugs, outages, integrations",
272 sales: "Pricing, upgrades, new accounts",
273 },
274 }),
275 urgency: score({
276 instructions: "How urgent is this ticket?",
277 levels: ["low", "medium", "high"],
278 }),
279 refund: boolean({
280 instructions: "Is the customer asking for a refund?",
281 }),
282 },
283});
284​
285console.log(result.queue.value);
286console.log(result.queue.probability);
287console.log(result.queue.confidence);
288console.log(result.meta.usage);
289```
290​
291- `result.meta.usage.cost`: the cost of the request, to bill per request.
292- `result.meta.id`: the id to look the request up later with `GET /api/v1/generation?id=`.
293- `result.meta.provider`: the upstream provider that served the request.
294​
295Known ids: `~typesafe/jev-latest`, `typesafe/jev-1.13`, `typesafe/jev-1.13.0`. See the [Evaluate guide](../evaluate/evaluate).
296​
297## Summarization
298​
299```typescript
300import { summarize } from "@tanstack/ai";
301import { openRouterSummarize } from "@tanstack/ai-openrouter";
302​
303const result = await summarize({
304 adapter: openRouterSummarize("google/gemini-3.8-flash"),
305 text: "Your long text to summarize...",
306 threadId: "thread-1",
307 maxLength: 100,
308 style: "concise", // "concise" | "bullet-points" | "paragraph"
309});
310​
311console.log(result.summary);
312```
313​
314## Cost tracking
315​
316OpenRouter reports the real cost of each request. The adapter puts it on the last `RUN_FINISHED` event as `usage.cost`, with the breakdown in `usage.costDetails`. This cost includes routing, fallback providers, BYOK, and cached-token prices. See [Cost tracking](./openrouter-advanced#cost-tracking) for a sample.
317​
318## Sign in with OpenRouter (BYOK)
319​
320Your users can sign in with their own OpenRouter account. Then the requests use their key and their credit. The helpers are in `@tanstack/ai-openrouter/pkce`. For the browser and the CLI flows, see [OpenRouter: Advanced](./openrouter-advanced#sign-in-with-openrouter-byok).
321​
322## Models and options
323​
324### Model options
325​
326Provider options go in `modelOptions`. This includes sampling options such as `temperature` and `maxCompletionTokens` (the token limit of the chat adapter). The type only allows the options that the selected model supports. For example, Claude Sonnet 5.5 does not take `topP`, so `topP` is a type error for that model:
327​
328```typescript
329import { chat } from "@tanstack/ai";
330import { openRouterText } from "@tanstack/ai-openrouter";
331​
332const stream = chat({
333 adapter: openRouterText("anthropic/claude-sonnet-5.5"),
334 messages: [{ role: "user", content: "Hello!" }],
335 threadId: "thread-1",
336 modelOptions: {
337 temperature: 0.7,
338 maxCompletionTokens: 1024,
339 },
340});
341```
342​
343The option names are the camelCase names of the OpenRouter SDK. Sampling options do not go at the root of `chat()`. See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
344​
345### Reasoning
346​
347Set `reasoning` on `chat()`. OpenRouter gets it as `reasoning.effort`:
348​
349```typescript
350import { chat } from "@tanstack/ai";
351import { openRouterText } from "@tanstack/ai-openrouter";
352​
353const stream = chat({
354 adapter: openRouterText("anthropic/claude-opus-5.5"),
355 messages: [{ role: "user", content: "Hello!" }],
356 threadId: "thread-1",
357 reasoning: "high",
358});
359```
360​
361- `off` sends `effort: "none"`.
362- `openRouterText` takes no `budgetTokens`. `openRouterResponsesText` sends `budgetTokens` as `reasoning.maxTokens`, and adds `summary: "auto"` so that the thinking text streams.
363- The types know the levels of each model. Your editor shows them when you type `reasoning`.
364​
365See [Reasoning](../chat/reasoning).
366​
367### Models
368​
369Model ids have the shape `provider/model-name`:
370​
371```text
372openai/gpt-6.1-sol
373anthropic/claude-sonnet-5.5
374google/gemini-3.1-pro-preview
375meta-llama/llama-4-maverick
376deepseek/deepseek-v4-pro
377```
378​
379See the full list at [openrouter.ai/models](https://openrouter.ai/models). The package exports the known ids:
380​
381- `@tanstack/ai-openrouter/model-meta`: `OPENROUTER_CHAT_MODELS`, `OPENROUTER_IMAGE_MODELS`, `OPENROUTER_VIDEO_MODELS`.
382- `@tanstack/ai-openrouter`: `OPENROUTER_RERANK_MODELS`, `OPENROUTER_EVALUATE_MODELS`.
383​
384`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).
385​
386## Advanced
387​
388These topics are on [OpenRouter: Advanced](./openrouter-advanced):
389​
390- Configuration: base URL, app attribution headers, and `wrapFetch`.
391- Retries for rate limits, and for an error in the stream.
392- The Responses adapter (`openRouterResponsesText`, beta).
393- Provider preferences, model variants, plugins, and session metadata.
394- Prompt caching and JSON mode.
395- Tools and structured output in one call, with the full code.
396- `webFetchTool`, cost tracking, video generation, and Sign in with OpenRouter.
397- The API reference.