Open History to see the last commit
1---
2title: OpenAI-Compatible Adapter
3id: openai-compatible-adapter
4description: "Use any OpenAI-compatible provider in TanStack AI with one generic adapter: DeepSeek, Moonshot/Kimi, Together, Fireworks, Cerebras, Qwen, Perplexity, local servers, and more."
5keywords:
6 - tanstack ai
7 - openai compatible
8 - deepseek
9 - moonshot
10 - kimi
11 - together
12 - fireworks
13 - cerebras
14 - qwen
15 - perplexity
16 - lm studio
17 - vllm
18 - litellm
19 - adapter
20---
21
22`openaiCompatible` calls any server that speaks `/chat/completions` and has no `@tanstack/ai-*` package. Set `baseURL` and the model list, then call `chat()`.
23
24`openaiCompatible` is one generic adapter for all of them. Point it at the `baseURL`, list your models, and you get the same type-safe `chat()` as with the other adapters.
25
26If a dedicated adapter exists, use it, because it has curated metadata for each model:
27
28- [OpenAI](./openai), [Grok](./grok), [Groq](./groq), and [OpenRouter](./openrouter).
29- Vercel AI Gateway: `vercelGatewayText` from `@tanstack/ai-vercel-gateway`. See [Vercel AI Gateway](./vercel-gateway.md).
30- Lovable AI Gateway: `lovableText` (plus image, video, embeddings, and speech factories) from `@tanstack/ai-lovable`. See [Lovable AI Gateway](./lovable.md).
31
32Perplexity Sonar chat uses this adapter. [`@tanstack/ai-perplexity`](./perplexity.md) is for search and grounding only. To send the `X-Pplx-Integration` attribution header of Perplexity, pass `defaultHeaders: getPerplexityIntegrationHeaders()` from that package.
33
34## 1. Install
35
36The adapter is in `@tanstack/ai-openai`, under the `/compatible` subpath:
37
38<!-- ::start:tabs variant="package-manager" mode="install" -->
39
40react: @tanstack/ai-openai
41vue: @tanstack/ai-openai
42solid: @tanstack/ai-openai
43svelte: @tanstack/ai-openai
44preact: @tanstack/ai-openai
45angular: @tanstack/ai-openai
46vanilla: @tanstack/ai-openai
47octane: @tanstack/ai-openai
48
49<!-- ::end:tabs -->
50
51## 2. Set the API key
52
53Put the key of your provider in the environment of your server, with the variable name that you like:
54
55```bash
56DEEPSEEK_API_KEY=sk-...
57```
58
59The adapter reads no environment variable itself. You pass the key as `apiKey` in the next step.
60
61## 3. Stream a chat from the server
62
63Configure the provider one time with `openaiCompatible({ baseURL, apiKey, models })`. Then pick a model for each call:
64
65```typescript
66import {
67 chat,
68 chatParamsFromRequest,
69 toServerSentEventsResponse,
70} from "@tanstack/ai";
71import { openaiCompatible } from "@tanstack/ai-openai/compatible";
72
73const deepseek = openaiCompatible({
74 name: "deepseek", // optional label for devtools and errors (default: "openai-compatible")
75 baseURL: "https://api.deepseek.com/v1",
76 apiKey: process.env.DEEPSEEK_API_KEY!,
77 models: ["deepseek-chat", "deepseek-reasoner"],
78});
79
80export async function POST(request: Request) {
81 const { messages, threadId, runId } = await chatParamsFromRequest(request);
82
83 const stream = chat({
84 adapter: deepseek("deepseek-chat"),
85 messages,
86 threadId,
87 runId,
88 });
89
90 return toServerSentEventsResponse(stream);
91}
92```
93
94The model name is a type-safe union of the models that you declared. `deepseek("deepseek-reasoner")` is valid. `deepseek("gpt-4o")` is a type error.
95
96## 4. Render the chat
97
98The client is the same for every provider. Point `useChat` at your route:
99
100```tsx
101import { useState } from "react";
102import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
103
104export function Chat() {
105 const [input, setInput] = useState("");
106 const { messages, sendMessage } = useChat({
107 connection: fetchServerSentEvents("/api/chat"),
108 threadId: "support-chat",
109 });
110
111 return (
112 <form
113 onSubmit={(event) => {
114 event.preventDefault();
115 sendMessage(input);
116 setInput("");
117 }}
118 >
119 {messages.map((message) => (
120 <p key={message.id}>
121 {message.parts
122 .map((part) => (part.type === "text" ? part.content : ""))
123 .join("")}
124 </p>
125 ))}
126 <input value={input} onChange={(event) => setInput(event.target.value)} />
127 </form>
128 );
129}
130```
131
132For Vue, Solid, Svelte, Angular, and the other frameworks, see [Quick Start](../getting-started/quick-start#3-render-the-chat).
133
134You now have a streaming chat with any OpenAI-compatible provider. [Tools](../tools/tools) work the same as with every adapter, on models that support function calling.
135
136## One model only
137
138For a single model, skip the provider factory and build the adapter inline with `openaiCompatibleText`:
139
140```typescript
141import { chat } from "@tanstack/ai";
142import { openaiCompatibleText } from "@tanstack/ai-openai/compatible";
143
144const stream = chat({
145 adapter: openaiCompatibleText("deepseek-chat", {
146 baseURL: "https://api.deepseek.com/v1",
147 apiKey: process.env.DEEPSEEK_API_KEY!,
148 }),
149 messages: [{ role: "user", content: "Hello!" }],
150 threadId: "thread-1",
151});
152```
153
154## Local and self-hosted servers
155
156Point the adapter at any local OpenAI-compatible server. The API key is usually a placeholder:
157
158```typescript
159import { openaiCompatible } from "@tanstack/ai-openai/compatible";
160
161// LM Studio
162const lmstudio = openaiCompatible({
163 name: "lmstudio",
164 baseURL: "http://localhost:1234/v1",
165 apiKey: "lm-studio",
166 models: ["local-model"],
167});
168
169// vLLM
170const vllm = openaiCompatible({
171 name: "vllm",
172 baseURL: "http://localhost:8000/v1",
173 apiKey: "not-needed",
174 models: ["meta-llama/Llama-3.3-70B-Instruct"],
175});
176
177// The OpenAI-compatible endpoint of Ollama
178const ollama = openaiCompatible({
179 name: "ollama",
180 baseURL: "http://localhost:11434/v1",
181 apiKey: "ollama",
182 models: ["llama3.3"],
183});
184```
185
186Ollama also has a dedicated adapter, [`@tanstack/ai-ollama`](./ollama), for its native API. If you want the OpenAI-compatible surface of Ollama, use `openaiCompatible`.
187
188## LiteLLM proxy
189
190[LiteLLM](https://github.com/BerriAI/litellm) is a self-hosted gateway. It gives one OpenAI Chat Completions endpoint for 100+ providers (OpenAI, Anthropic, Google, Azure, AWS Bedrock, Mistral, Groq, and more). Point `openaiCompatible` at your proxy (default `http://localhost:4000/v1`). Pick a provider with the `provider/model` names of LiteLLM:
191
192```typescript
193import { openaiCompatible } from "@tanstack/ai-openai/compatible";
194
195const litellm = openaiCompatible({
196 name: "litellm",
197 baseURL: "http://localhost:4000/v1", // your LiteLLM proxy
198 apiKey: process.env.LITELLM_API_KEY!, // a virtual key issued by the proxy
199 models: [
200 "anthropic/claude-sonnet-5",
201 "openai/gpt-5.5",
202 "gemini/gemini-3.5-flash",
203 ],
204});
205```
206
207- `litellm("anthropic/claude-sonnet-5")` goes to Anthropic, and `litellm("openai/gpt-5.5")` goes to OpenAI, through the one proxy.
208- Declare only the routes that you configured on the proxy. For exact capabilities of each route, use `createModel`. See [Declaring models](#declaring-models).
209- The proxy holds the real credentials of each provider. The `apiKey` here is the virtual or master key of the proxy.
210
211## Models and options
212
213### Declaring models
214
215The `models` array takes two forms. You can mix them:
216
217- **A string** gets optimistic defaults: `text` and `image` input, with `streaming`, `function_calling`, and `structured_outputs`. Good for mainstream chat models.
218- **A `createModel(name, capabilities)` definition** declares the exact capabilities of a model, so the types match the model. An example is a reasoning model with no image input.
219
220```typescript
221import { openaiCompatible } from "@tanstack/ai-openai/compatible";
222import { createModel } from "@tanstack/ai";
223
224const provider = openaiCompatible({
225 baseURL: "https://api.deepseek.com/v1",
226 apiKey: process.env.DEEPSEEK_API_KEY!,
227 models: [
228 "deepseek-chat", // string: optimistic defaults
229 createModel("deepseek-reasoner", {
230 input: ["text"], // text only
231 features: ["reasoning", "structured_outputs"],
232 }),
233 ],
234});
235```
236
237The types enforce the `input` modalities, the `modelOptions`, and the provider `tools` you declare. They do not read `features`. Function tools and structured output are always allowed on this path. If a provider rejects one of them at run time (for example, tools on a model without tool support), do not pass it for that model.
238
239### Providers
240
241Any provider with the OpenAI Chat Completions API works. Common ones are below. **Check the `baseURL` and the model ids in the current docs of each provider**, because they change.
242
243| Provider | `baseURL` | Example model |
244| --- | --- | --- |
245| DeepSeek | `https://api.deepseek.com/v1` | `deepseek-chat`, `deepseek-reasoner` |
246| Moonshot / Kimi | `https://api.moonshot.ai/v1` | `kimi-k2-0711-preview` |
247| Alibaba Qwen (DashScope, intl) | `https://dashscope-intl.aliyuncs.com/compatible-mode/v1` | `qwen-max`, `qwen-plus` |
248| Alibaba Qwen (DashScope, China) | `https://dashscope.aliyuncs.com/compatible-mode/v1` | `qwen-max` |
249| Together AI | `https://api.together.xyz/v1` | `meta-llama/Llama-3.3-70B-Instruct-Turbo` |
250| Fireworks AI | `https://api.fireworks.ai/inference/v1` | `accounts/fireworks/models/llama-v3p3-70b-instruct` |
251| Cerebras | `https://api.cerebras.ai/v1` | `llama-3.3-70b` |
252| DeepInfra | `https://api.deepinfra.com/v1/openai` | `meta-llama/Llama-3.3-70B-Instruct` |
253| Perplexity | `https://api.perplexity.ai` | `sonar`, `sonar-pro` |
254| Mistral | `https://api.mistral.ai/v1` | `mistral-large-latest` |
255| Nebius | `https://api.studio.nebius.ai/v1` | `meta-llama/Llama-3.3-70B-Instruct` |
256| Z.AI (GLM) | `https://api.z.ai/api/paas/v4` | `glm-4.6` |
257| Baseten | `https://inference.baseten.co/v1` | depends on the model |
258| Hugging Face (router) | `https://router.huggingface.co/v1` | `meta-llama/Llama-3.3-70B-Instruct` |
259| NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | `meta/llama-3.3-70b-instruct` |
260| Kilo Gateway | `https://api.kilo.ai/api/gateway` | `anthropic/claude-opus-5.5` |
261| ZenMux | `https://zenmux.ai/api/v1` | `openai/gpt-5.5` |
262| Poe | `https://api.poe.com/v1` | `openai/gpt-5.5` |
263| DigitalOcean | `https://inference.do-ai.run/v1` | `openai-gpt-5.5` |
264| Modal | `https://inference.us-west.modal.direct/v1` | `moonshotai/Kimi-K3` |
265| Snowflake Cortex | `https://<account>.snowflakecomputing.com/api/v2/cortex/v1` | `claude-opus-5` |
266
267- Some providers sign the user in with OAuth, not with an API key. For Poe, DigitalOcean, and Snowflake Cortex, pass the access token from your sign-in code as `apiKey`.
268- On Chat Completions, `RUN_FINISHED.usage` carries the prompt cache counts that the provider reports. Cache reads go to `promptTokensDetails.cachedTokens`, and cache writes go to `promptTokensDetails.cacheWriteTokens`. Moonshot / Kimi reports both.
269
270## Advanced
271
272These topics are on [OpenAI-Compatible: Advanced](./openai-compatible-advanced):
273
274- Configuration: headers, query parameters, and `wrapFetch`.
275- The Responses API (`api: "responses"`).
276- Azure OpenAI.
277- GitHub Copilot: let users pay with their Copilot plan.
278- ChatGPT plan: let users pay with their ChatGPT plan.
279
280To add custom models to any adapter, see [Extending Adapters](../advanced/extend-adapter).