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

guide.md

434 lines14.4 KB

1---
2title: "Community Adapters Guide"
3slug: /community-adapters/guide
4order: 1
5description: "Build, publish, and list a community adapter for TanStack AI: a minimal text adapter, then model metadata, typed options, reasoning, and BYOK."
6keywords:
7 - tanstack ai
8 - community adapters
9 - build adapter
10 - custom adapter
11 - provider integration
12 - adapter authoring
13 - contribute
14---
15​
16A community adapter is an npm package that maps one AI service onto `chat()`, `generateImage()`, and the other TanStack AI functions.
17​
18You build, publish, and maintain the adapter. The TanStack AI core team does not.
19​
20## 1. Create the package
21​
22Create an npm package, for example `@acme/tanstack-ai-adapter`. Add `@tanstack/ai` as a peer dependency, so your adapter uses the same copy as the app.
23​
24For reference, read the [adapters in the TanStack AI repository](https://github.com/tanstack/ai/tree/main/packages). The [OpenAI adapter](https://github.com/tanstack/ai/tree/main/packages/ai-openai) has the most features.
25​
26## 2. Write a minimal text adapter
27​
28A text adapter extends `BaseTextAdapter` and implements two methods:
29​
30- `chatStream()`: calls your service and yields AG-UI events.
31- `structuredOutput()`: returns JSON for a schema.
32​
33This sample calls a JSON API that returns the whole answer at once:
34​
35```typescript
36// src/index.ts
37import { EventType } from "@tanstack/ai";
38import { BaseTextAdapter } from "@tanstack/ai/adapters";
39import type {
40 AdapterYieldChunk,
41 DefaultMessageMetadataByModality,
42 ModelMessage,
43 Modality,
44 TextOptions,
45} from "@tanstack/ai";
46import type {
47 StructuredOutputOptions,
48 StructuredOutputResult,
49} from "@tanstack/ai/adapters";
50​
51export const ACME_MODELS = ["acme-small", "acme-large"] as const;
52export type AcmeModel = (typeof ACME_MODELS)[number];
53​
54type AcmeOptions = Record<string, never>;
55​
56async function callAcme(
57 apiKey: string,
58 body: Record<string, unknown>,
59 signal: AbortSignal | undefined,
60): Promise<string> {
61 const response = await fetch("https://api.acme.example/v1/chat", {
62 method: "POST",
63 headers: {
64 authorization: `Bearer ${apiKey}`,
65 "content-type": "application/json",
66 },
67 body: JSON.stringify(body),
68 signal,
69 });
70 const json: unknown = await response.json();
71 if (
72 typeof json === "object" &&
73 json !== null &&
74 "text" in json &&
75 typeof json.text === "string"
76 ) {
77 return json.text;
78 }
79 throw new Error(`Acme returned no text (status ${response.status})`);
81​
82function toAcmeMessages(messages: Array<ModelMessage>) {
83 return messages.map((message) => ({
84 role: message.role,
85 content: typeof message.content === "string" ? message.content : "",
86 }));
88​
89export class AcmeTextAdapter<TModel extends AcmeModel> extends BaseTextAdapter<
90 TModel,
91 AcmeOptions,
92 ReadonlyArray<Modality>,
93 DefaultMessageMetadataByModality
94> {
95 readonly name = "acme";
96 private readonly apiKey: string;
97​
98 constructor(model: TModel, apiKey: string) {
99 super({}, model);
100 this.apiKey = apiKey;
101 }
102​
103 async *chatStream(
104 options: TextOptions<AcmeOptions>,
105 ): AsyncIterable<AdapterYieldChunk> {
106 const runId = options.runId ?? this.generateId();
107 const threadId = options.threadId;
108 const messageId = this.generateId();
109​
110 yield { type: EventType.RUN_STARTED, runId, threadId, timestamp: Date.now() };
111​
112 const text = await callAcme(
113 this.apiKey,
114 { model: this.model, messages: toAcmeMessages(options.messages) },
115 options.abortController?.signal,
116 );
117​
118 yield {
119 type: EventType.TEXT_MESSAGE_START,
120 messageId,
121 role: "assistant",
122 timestamp: Date.now(),
123 };
124 yield {
125 type: EventType.TEXT_MESSAGE_CONTENT,
126 messageId,
127 delta: text,
128 timestamp: Date.now(),
129 };
130 yield { type: EventType.TEXT_MESSAGE_END, messageId, timestamp: Date.now() };
131 yield {
132 type: EventType.RUN_FINISHED,
133 runId,
134 threadId,
135 finishReason: "stop",
136 timestamp: Date.now(),
137 };
138 }
139​
140 async structuredOutput(
141 options: StructuredOutputOptions<AcmeOptions>,
142 ): Promise<StructuredOutputResult<unknown>> {
143 const rawText = await callAcme(
144 this.apiKey,
145 {
146 model: this.model,
147 messages: toAcmeMessages(options.chatOptions.messages),
148 schema: options.outputSchema,
149 },
150 options.chatOptions.abortController?.signal,
151 );
152 const data: unknown = JSON.parse(rawText);
153 return { data, rawText };
154 }
156​
157export function acmeText<TModel extends AcmeModel>(
158 model: TModel,
159 apiKey: string = process.env.ACME_API_KEY ?? "",
160) {
161 return new AcmeTextAdapter(model, apiKey);
163```
164​
165## 3. Call it with `chat()`
166​
167```typescript
168// src/demo.ts
169import { chat } from "@tanstack/ai";
170import { acmeText } from "./index";
171​
172const stream = chat({
173 adapter: acmeText("acme-large"),
174 messages: [{ role: "user", content: "Hello!" }],
175 threadId: "thread-1",
176});
177​
178for await (const chunk of stream) {
179 if (chunk.type === "TEXT_MESSAGE_CONTENT") {
180 process.stdout.write(chunk.delta);
181 }
183```
184​
185The answer of your service prints in the terminal. Your adapter now works with `chat()`, `useChat`, and the rest of TanStack AI.
186​
187## How it works
188​
189- `chat()` calls `chatStream()` with the messages, tools, and options of the call.
190- `chatStream()` yields AG-UI events in order: `RUN_STARTED`, then `TEXT_MESSAGE_START`, `TEXT_MESSAGE_CONTENT`, and `TEXT_MESSAGE_END`, then `RUN_FINISHED`.
191- If your service streams, yield one `TEXT_MESSAGE_CONTENT` for each piece. For tool calls, yield `TOOL_CALL_START`, `TOOL_CALL_ARGS`, and `TOOL_CALL_END`.
192- When a call sets `outputSchema`, `chat()` calls `structuredOutput()` with the JSON Schema.
193​
194The minimal adapter skips tools, system prompts, and images. A full adapter maps them the same way. For a full example, see the [OpenAI text adapter](https://github.com/TanStack/ai/blob/main/packages/ai-openai/src/adapters/text.ts).
195​
196Adapters are split by capability. Implement only what your service supports:
197​
198- Text (chat)
199- Image
200- Embeddings
201- Video
202​
203## Publish and list your adapter
204​
2051. Publish the package to npm.
2062. Add a page for your adapter to [`docs/community-adapters`](https://github.com/TanStack/ai/tree/main/docs/community-adapters) in the TanStack AI repository.
2073. Run `pnpm run sync-docs-config` in the root of the monorepo. This puts your page in the docs navigation.
2084. Open a [pull request](https://github.com/TanStack/ai/pulls) with the page and the generated changes.
209​
210## Maintain your adapter
211​
212You are responsible for the adapter after you publish it:
213​
214- Follow API changes of your service.
215- Stay compatible with new TanStack AI releases.
216- Answer issues and feedback from users.
217- Update your docs page when features change. Open a follow-up pull request for it.
218​
219## Advanced
220​
221These steps make your adapter type-safe per model, like the built-in adapters.
222​
223### Model metadata
224​
225Model metadata describes what each model can do. TanStack AI uses it for compatibility checks and feature selection. For each model, define at least:
226​
227- The model name and id.
228- The input and output modalities.
229- The features, for example streaming, tools, and structured output.
230- The price, if you know it.
231- Notes and limits that are special to your service.
232​
233For a concrete example, see the [OpenAI model metadata](https://github.com/TanStack/ai/blob/main/packages/ai-openai/src/model-meta.ts).
234​
235### Model lists per capability
236​
237Group the models by what they support, in exported arrays. Put a model in an array only when it fully supports that capability:
238​
239```typescript ignore
240export const OPENAI_CHAT_MODELS = [
241 // Frontier models
242 GPT5_2.name,
243 GPT5_2_PRO.name,
244 GPT5_2_CHAT.name,
245 GPT5_1.name,
246 GPT5_1_CODEX.name,
247 GPT5.name,
248 GPT5_MINI.name,
249 GPT5_NANO.name,
250 GPT5_PRO.name,
251 GPT5_CODEX.name,
252 // ...other models
253] as const
254export const OPENAI_IMAGE_MODELS = [
255 GPT_IMAGE_1.name,
256 GPT_IMAGE_1_MINI.name,
257 DALL_E_3.name,
258 DALL_E_2.name,
259] as const
260​
261export const OPENAI_VIDEO_MODELS = [SORA2.name, SORA2_PRO.name] as const
262```
263​
264### Option fragments
265​
266Models take different options. Build the options from small reusable fragments, not one copy per model:
267​
268- Base options that every model takes.
269- Feature fragments that you combine for each model.
270​
271Based on the [OpenAI options](https://github.com/TanStack/ai/blob/main/packages/ai-openai/src/text/text-provider-options.ts):
272​
273```typescript
274export interface OpenAIBaseOptions {
275 // base options that every chat model supports
277​
278// Feature fragments that can be stitched per-model
279​
280/**
281 * Tools options for models.
282 */
283export interface OpenAIToolsOptions {
284 //...
286​
287/**
288 * Structured output options for models.
289 */
290export interface OpenAIStructuredOutputOptions {
291 //...
293```
294​
295There is no single correct split. Match the features of your service.
296​
297### Typed options per model
298​
299Type the options by model name, so users see only the options of the selected model. A model gets only the fragments it supports:
300​
301```typescript ignore
302export type OpenAIChatModelProviderOptionsByName = {
303 [GPT5_2.name]: OpenAIBaseOptions &
304 OpenAIStructuredOutputOptions &
305 OpenAIToolsOptions &
306 OpenAIStreamingOptions &
307 OpenAIMetadataOptions
308 [GPT5_2_CHAT.name]: OpenAIBaseOptions &
309 OpenAIStructuredOutputOptions &
310 OpenAIToolsOptions &
311 OpenAIStreamingOptions &
312 OpenAIMetadataOptions
313 // ... repeat for each model
315```
316​
317### Input modalities per model
318​
319Define the input kinds (text, images, audio) of each model, so invalid input is a type error:
320​
321```typescript ignore
322export type OpenAIModelInputModalitiesByName = {
323 [GPT5_2.name]: typeof GPT5_2.supports.input
324 [GPT5_2_PRO.name]: typeof GPT5_2_PRO.supports.input
325 [GPT5_2_CHAT.name]: typeof GPT5_2_CHAT.supports.input
326 // ... repeat for each model
328```
329​
330To also set `inputModalities` at run time, see [Set inputModalities in your own adapter](../advanced/extend-adapter-advanced#set-inputmodalities-in-your-own-adapter).
331​
332### Reasoning levels
333​
334Does your service have a thinking model? Users set it with `chat({ reasoning })`, and the types take only the levels of the selected model. Put a `reasoning` field on the metadata of each model, then build two maps from it:
335​
336```typescript ignore
337import type { ModelReasoning } from '@tanstack/ai'
338import type { ModelReasoningCapability } from '@tanstack/ai/adapter-internals'
339​
340const EFFORT_NONE_LOW_TO_XHIGH = {
341 levels: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },
342 budget: false,
343} as const
344​
345const GPT5_2 = {
346 name: 'gpt-5.2',
347 // ...supports, pricing
348 reasoning: EFFORT_NONE_LOW_TO_XHIGH,
349} as const
350​
351// One object lists each model once.
352const OPENAI_REASONING = {
353 [GPT5_2.name]: GPT5_2.reasoning,
355​
356// The levels per model, for the types.
357export type OpenAIModelReasoningByName = {
358 [K in keyof typeof OPENAI_REASONING]: ModelReasoningCapability<
359 (typeof OPENAI_REASONING)[K]
360 >
362​
363// The same data at run time.
364export const OPENAI_MODEL_REASONING: Readonly<Record<string, ModelReasoning>> =
365 OPENAI_REASONING
366```
367​
368- `levels` lists only the levels that the model has, with the value your service takes for each. A level that is not in the list is not supported.
369- `budget` is `true` when the model takes a thinking token budget.
370- Many models share the same levels. Define each shape once, and point each model at it.
371- A model that does not reason gets no `reasoning` field.
372​
373Then send `options.reasoning` as the thinking field of your service. Pass `OpenAIModelReasoningByName[TModel]` as the last type parameter of the adapter class, so `chat({ reasoning })` is typed. See [Add reasoning to your adapter](../advanced/extend-adapter-advanced#add-reasoning-to-your-adapter).
374​
375### Prompt cache and mid-conversation changes
376​
377`chat()` also passes two optional fields to a text adapter. Your adapter works without them, but they make repeated requests cheaper:
378​
379- `options.promptCache`: map it to the cache fields of your service. See [Send the prompt cache](../advanced/extend-adapter-advanced#send-the-prompt-cache).
380- `options.midConversationChanges`: send added tools and prompts inside the conversation. See [Send mid-conversation changes](../advanced/extend-adapter-advanced#send-mid-conversation-changes).
381​
382### Keep history valid across models
383​
384A user can switch to your adapter in the middle of a thread. The history then holds signatures and tool call IDs from another provider, and your API rejects them.
385​
3861. Name the source of your text adapter. `chat()` records it on each answer as `metadata.tanstack.source`:
387 - `name`: the adapter name.
388 - `provider`: optional. Defaults to `name`.
389 - `api`: optional, the wire API. Defaults to the adapter kind.
3902. Before you build the request, run the history through `transformMessagesForReplay`. Pass your source and a rule for tool call IDs:
391​
392```typescript
393import { hashToolCallId, transformMessagesForReplay } from '@tanstack/ai/adapter-internals'
394import type { ModelMessage } from '@tanstack/ai'
395​
396export function prepareMessages(messages: ReadonlyArray<ModelMessage>, model: string) {
397 const { messages: replay } = transformMessagesForReplay(
398 messages,
399 { provider: 'example-provider', api: 'example-messages', model },
400 (id, { attempt }) => {
401 const clean = id.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64)
402 return attempt === 0 ? clean : `${clean.slice(0, 40)}_${hashToolCallId(id)}_${attempt}`
403 },
404 )
405 return replay
407```
408​
409For history from another source, the helper:
410​
411- Drops signatures and redacted thinking. Turns readable thinking into text.
412- Calls your ID rule for each tool call, and gives each result the new ID of its call. If the new ID is taken, it calls the rule again with a higher `attempt`.
413​
414`chat()` already drops failed answers and adds `No result provided` for unanswered tool calls before it calls your adapter. Your saved history does not change.
415​
416### Export a BYOK provider
417​
418Can users paste an API key for your adapter? Then export a `defineByokProvider` object from a `/byok` subpath (`@scope/ai-acme/byok`):
419​
420```typescript
421import { defineByokProvider } from "@tanstack/ai/byok";
422​
423export const acmeByok = defineByokProvider({
424 id: "acme",
425 label: "Acme",
426 env: "ACME_API_KEY",
427});
428```
429​
430- Do not export it from the main entry of the package. That pulls your provider SDK into the browser.
431- `id` is required. It is the slug in the `x-byok-<id>` header.
432- `env` is the **name** of the environment variable that your adapter already reads. Put only names here, because the client imports this object.
433​
434Apps import `{ acmeByok } from "@scope/ai-acme/byok"`. A relay calls `getByokKey(request, acmeByok)` from `@tanstack/ai/byok/server` to read the `x-byok-acme` header.