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

custom.md

326 lines11.6 KB

1---
2title: Custom Transports
3id: transports-custom
4order: 8
5description: "Build your own TanStack AI connection adapter: a request-scoped connect adapter, or a persistent subscribe/send adapter for WebSockets, BroadcastChannel, and workers."
6keywords:
7 - tanstack ai
8 - custom connection adapter
9 - ConnectConnectionAdapter
10 - SubscribeConnectionAdapter
11 - subscribe send
12 - persistent transport
13 - websocket
14 - runContext
15---
16​
17A custom connection adapter reads your protocol and writes chunks into `useChat`. Pick the shape from the channel:
18​
19- **`connect`**: one request per user message. See [Request-scoped adapters](#request-scoped-adapters).
20- **`subscribe` / `send`**: one channel that stays open for many messages. See [Persistent transports](#persistent-transports).
21​
22Check the [built-in transports](./overview#pick-a-transport) first. A server function with `stream()` takes less code than a custom adapter.
23​
24## Request-scoped adapters
25​
26If your transport makes one request per user message, implement `ConnectConnectionAdapter`.
27​
28### 1. Write the adapter
29​
30This adapter posts an AG-UI request body and reads newline-delimited JSON back. Replace the `fetch` call and the read loop with your own protocol:
31​
32```typescript
33// my-adapter.ts
34import type { ConnectConnectionAdapter } from "@tanstack/ai-react";
35import { restoreInboundChunk, uiMessagesToWire } from "@tanstack/ai/client";
36​
37export const myAdapter: ConnectConnectionAdapter = {
38 async *connect(messages, data, abortSignal, runContext) {
39 const response = await fetch("/api/chat", {
40 method: "POST",
41 headers: {
42 "Content-Type": "application/json",
43 ...runContext.headers,
44 },
45 body: JSON.stringify({
46 threadId: runContext.threadId,
47 runId: runContext.runId,
48 ...(runContext.resume ? { resume: runContext.resume } : {}),
49 state: {},
50 messages: uiMessagesToWire(messages),
51 tools: runContext.clientTools ?? [],
52 context: [],
53 forwardedProps: { ...runContext.forwardedProps, ...data },
54 }),
55 ...(abortSignal ? { signal: abortSignal } : {}),
56 });
57​
58 if (!response.ok) throw new Error(`HTTP ${response.status}`);
59 if (!response.body) throw new Error("Response has no body");
60​
61 // Newline-delimited JSON: one chunk per line.
62 const reader = response.body.getReader();
63 const decoder = new TextDecoder();
64 let buffer = "";
65 while (true) {
66 const { done, value } = await reader.read();
67 if (done) break;
68 buffer += decoder.decode(value, { stream: true });
69 const lines = buffer.split("\n");
70 buffer = lines.pop() ?? "";
71 for (const line of lines) {
72 if (line.trim()) {
73 yield restoreInboundChunk(JSON.parse(line));
74 }
75 }
76 }
77 },
78};
79```
80​
81Copy `runContext.headers` onto the request headers, not into the body. If your `connect` drops them, it drops BYOK keys (`x-byok-*`). See [Bring Your Own Key](../advanced/byok).
82​
83### 2. Pass it to `useChat`
84​
85```tsx
86import { useChat } from "@tanstack/ai-react";
87import { myAdapter } from "./my-adapter";
88​
89export function Chat() {
90 const { messages, sendMessage } = useChat({ connection: myAdapter, threadId: "support-chat" });
91​
92 return (
93 <div>
94 {messages.map((message) => (
95 <p key={message.id}>
96 {message.parts.map((part) =>
97 part.type === "text" ? part.content : "",
98 )}
99 </p>
100 ))}
101 <button onClick={() => void sendMessage("Hello")}>Send</button>
102 </div>
103 );
105```
106​
107### 3. Return NDJSON from the server
108​
109The body is a valid AG-UI `RunAgentInput`, so the standard server helpers read it:
110​
111```typescript
112// api/chat.ts
113import { chat, chatParamsFromRequest, toHttpResponse } from "@tanstack/ai";
114import { openaiText } from "@tanstack/ai-openai";
115​
116export async function POST(request: Request) {
117 const { messages, threadId, runId } = await chatParamsFromRequest(request);
118 const stream = chat({
119 adapter: openaiText("gpt-6.1-sol"),
120 messages,
121 threadId,
122 runId,
123 });
124 return toHttpResponse(stream);
126```
127​
128Click Send. The chunks from your adapter stream into `messages` like any built-in transport.
129​
130## Persistent transports
131​
132A WebSocket, a BroadcastChannel, postMessage between iframes, or a shared worker works in a different way from request and response. You open the channel once. Then you send and receive on it for the full life of the client. `connect` cannot model this, because it expects one async iterable per request.
133​
134For a resumable WebSocket, use the built-in [`webSocket()`](./websockets) transport. For other persistent channels, implement `SubscribeConnectionAdapter`:
135​
136- **`subscribe(abortSignal?)`**: the `ChatClient` calls it once. It returns a long-lived async iterable of every chunk that the channel produces.
137- **`send(messages, data, abortSignal, runContext)`**: the `ChatClient` calls it once per user message, to put a request frame on the channel. It returns when the frame is written. The chunks arrive separately through `subscribe()`.
138​
139The runtime connects the two. The chunks that arrive between `send()` and the next terminal event (`RUN_FINISHED` or `RUN_ERROR`) belong to that run.
140​
141### Custom WebSocket example
142​
143If `webSocket()` does not fit (a different wire format, no need for resume, or a server that you do not control), write the adapter yourself:
144​
145```tsx
146import { useChat, type SubscribeConnectionAdapter } from "@tanstack/ai-react";
147import type { StreamChunk } from "@tanstack/ai";
148​
149function websocketConnection(url: string): SubscribeConnectionAdapter {
150 const ws = new WebSocket(url);
151 const queue: Array<StreamChunk> = [];
152 let pending: ((chunk: StreamChunk | null) => void) | null = null;
153 let closed = false;
154​
155 const ready = new Promise<void>((resolve) => {
156 ws.addEventListener("open", () => resolve(), { once: true });
157 });
158​
159 function deliver(chunk: StreamChunk | null) {
160 const resolve = pending;
161 if (resolve) {
162 pending = null;
163 resolve(chunk);
164 } else if (chunk !== null) {
165 queue.push(chunk);
166 }
167 }
168​
169 ws.addEventListener("message", (event) => {
170 const chunk: StreamChunk = JSON.parse(event.data);
171 deliver(chunk);
172 });
173 ws.addEventListener("close", () => {
174 closed = true;
175 deliver(null);
176 });
177​
178 return {
179 async *subscribe(abortSignal) {
180 // Register the abort listener once (not per-iteration) so it can't
181 // accumulate on a long-lived socket.
182 const onAbort = () => deliver(null);
183 abortSignal?.addEventListener("abort", onAbort, { once: true });
184 try {
185 while (!abortSignal?.aborted) {
186 // Drain buffered chunks BEFORE honoring `closed`: a burst of messages
187 // followed by a close event (common within one macrotask) must still
188 // deliver the queued chunks (including a trailing RUN_FINISHED),
189 // otherwise the client would hang waiting for a terminal it dropped.
190 const buffered = queue.shift();
191 if (buffered !== undefined) {
192 yield buffered;
193 continue;
194 }
195 if (closed) return;
196 const chunk = await new Promise<StreamChunk | null>((resolve) => {
197 pending = resolve;
198 });
199 if (chunk === null) return;
200 yield chunk;
201 }
202 } finally {
203 abortSignal?.removeEventListener("abort", onAbort);
204 }
205 },
206​
207 async send(messages, data, _abortSignal, runContext) {
208 await ready;
209 ws.send(
210 JSON.stringify({
211 threadId: runContext.threadId,
212 runId: runContext.runId,
213 messages,
214 data,
215 }),
216 );
217 },
218 };
220​
221const connection = websocketConnection("wss://example.com/chat");
222​
223export function Chat() {
224 const { messages, sendMessage } = useChat({ connection, threadId: "support-chat" });
225​
226 return (
227 <div>
228 {messages.map((message) => (
229 <p key={message.id}>
230 {message.parts.map((part) =>
231 part.type === "text" ? part.content : "",
232 )}
233 </p>
234 ))}
235 <button onClick={() => void sendMessage("Hello")}>Send</button>
236 </div>
237 );
239```
240​
241> [!WARNING]
242> Make sure that your server emits `RUN_FINISHED` (or `RUN_ERROR`) at the end of each run. Without it, the client does not know that the assistant turn ended, and it waits forever. See [Stream Events](../chat/stream-events).
243​
244## How it works
245​
246The chat client gives your adapter a `runContext` on each send:
247​
248- `threadId`, `runId`, `clientTools`, `forwardedProps`: put these in your request payload, so that the server can build an AG-UI-compliant response.
249- `parentRunId` and `resume`: set on a child run and on a run that answers an interrupt.
250- `headers`: copy these onto the request headers, not into the body.
251​
252The built-in fetch and XHR transports copy `runContext.headers`. `stream()` and `rpcStream()` do not, because a server function call has no request headers. They pass the rest of the run as the 4th factory argument.
253​
254`restoreInboundChunk` rebuilds the TanStack fields of a chunk after the wire, such as token usage. The built-in transports call it on every chunk.
255​
256The runtime adds the terminal event of a `connect` stream for you:
257​
258- If your `connect` stream completes with no `RUN_FINISHED`, the runtime adds one.
259- If your `connect` stream throws, the runtime adds a `RUN_ERROR`.
260​
261## Advanced
262​
263### When to use a persistent transport
264​
265If one or more of these is true, use `subscribe` / `send`:
266​
267- One connection carries many runs (the chat thread keeps the socket open across messages).
268- The server pushes chunks outside of a request (presence updates, server-initiated tool calls, broadcast notifications).
269- You want to share one connection across tabs (BroadcastChannel) or workers.
270​
271In other cases, use `fetchServerSentEvents` or `stream()`. They are simpler, and you do not manage a connection lifecycle.
272​
273### The adapter interface
274​
275A `ConnectionAdapter` is a union. Give it `connect`, or give it both `subscribe` and `send`. Never give it both modes.
276​
277```typescript
278import type { RunAgentResumeItem, UIMessage } from "@tanstack/ai-client";
279import type { ModelMessage, StreamChunk } from "@tanstack/ai";
280​
281export interface RunAgentInputContext {
282 threadId: string;
283 runId: string;
284 parentRunId?: string;
285 resume?: Array<RunAgentResumeItem>;
286 clientTools?: Array<{ name: string; description: string; parameters: unknown }>;
287 forwardedProps?: Record<string, unknown>;
288 headers?: Record<string, string>;
290​
291export interface ConnectConnectionAdapter {
292 connect(
293 messages: UIMessage[] | ModelMessage[],
294 data: Record<string, any> | undefined,
295 abortSignal: AbortSignal | undefined,
296 runContext: RunAgentInputContext,
297 ): AsyncIterable<StreamChunk>;
299​
300export interface SubscribeConnectionAdapter {
301 subscribe(abortSignal?: AbortSignal): AsyncIterable<StreamChunk>;
302 send(
303 messages: UIMessage[] | ModelMessage[],
304 data: Record<string, any> | undefined,
305 abortSignal: AbortSignal | undefined,
306 runContext: RunAgentInputContext,
307 ): Promise<void>;
309​
310export type ConnectionAdapter =
311 | ConnectConnectionAdapter
312 | SubscribeConnectionAdapter;
313```
314​
315Both shapes can also carry optional persistence members:
316​
317- `hydrate`: loads a stored chat thread.
318- `joinRun`: replays a run by id.
319- `hydrateGeneration`: on `connect` adapters only, loads the last run of a generation.
320​
321The built-in fetch, JSON, and XHR transports have them. See [Server Functions: Persistence handlers](./server-functions#persistence-handlers).
322​
323Internally, `ChatClient` changes both shapes to one `subscribe` / `send` pair with `normalizeConnectionAdapter()`:
324​
325- **`connect`**: the client wraps it in an async queue. The wrapped `send()` waits until the active subscriber processes all events or exits.
326- **`subscribe` + `send`**: the client uses them as they are.