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

json.md

242 lines7.6 KB

1---
2title: JSON
3id: transports-json
4order: 9
5description: "Send each chat run as one JSON response with fetchJson and toJsonResponse when your host buffers streams. Poll long runs with resumeJsonResponse."
6keywords:
7 - tanstack ai
8 - json transport
9 - non-streaming chat
10 - fetchJson
11 - toJsonResponse
12 - resumeJsonResponse
13 - polling
14 - serverless timeout
15---
16​
17`fetchJson` returns the whole run as one JSON body. `useChat` still renders messages, tool calls, approvals, and errors.
18​
19## Quick setup
20​
21### 1. Return JSON from the server
22​
23Run the chat to its end with `stream: false`. Then send the result with `toJsonResponse()`:
24​
25```typescript
26// api/chat.ts
27import { chat, chatParamsFromRequest, toJsonResponse } from "@tanstack/ai";
28import { openaiText } from "@tanstack/ai-openai";
29​
30export async function POST(request: Request) {
31 const { messages, threadId, runId } = await chatParamsFromRequest(request);
32 const result = await chat({
33 adapter: openaiText("gpt-6.1-sol"),
34 messages,
35 threadId,
36 runId,
37 stream: false,
38 });
39 return toJsonResponse(result);
41```
42​
43### 2. Connect from the client
44​
45Pass `fetchJson()` to `useChat`:
46​
47```tsx
48import { useChat, fetchJson } from "@tanstack/ai-react";
49​
50export function Chat() {
51 const { messages, sendMessage, isLoading } = useChat({
52 connection: fetchJson("/api/chat"),
53 threadId: "support-chat",
54 });
55​
56 return (
57 <div>
58 {messages.map((message) => (
59 <p key={message.id}>
60 {message.parts.map((part) =>
61 part.type === "text" ? part.content : "",
62 )}
63 </p>
64 ))}
65 <button disabled={isLoading} onClick={() => void sendMessage("Hello")}>
66 Send
67 </button>
68 </div>
69 );
71```
72​
73Click Send. When the run ends, the full reply appears in `messages`, with no stream between your server and the browser.
74​
75`fetchJson` sends the same POST body as `fetchHttpStream`. It takes the same options: `headers`, `body`, `credentials`, `fetchClient`, and dynamic functions. See [Request Options](./request-options).
76​
77## How it works
78​
79- `result.text` is the full reply on the server. `result.chunks` holds every chunk of the run.
80- `toJsonResponse()` sends the body `{ chunks, offset?, done }`. Without durability, `done` is always `true`, and the body holds the whole run.
81- `fetchJson` reads the chunks from the body and gives them to the chat client, one after the other.
82​
83## Advanced
84​
85### Send the stream from chat()
86​
87You can also pass the stream from `chat()` to `toJsonResponse()`. Then pass `request.signal`, so that the run stops when the client leaves:
88​
89```typescript
90// api/chat.ts
91import { chat, chatParamsFromRequest, toJsonResponse } from "@tanstack/ai";
92import { openaiText } from "@tanstack/ai-openai";
93​
94export async function POST(request: Request) {
95 const { messages, threadId, runId } = await chatParamsFromRequest(request);
96 const stream = chat({
97 adapter: openaiText("gpt-6.1-sol"),
98 messages,
99 threadId,
100 runId,
101 });
102 return toJsonResponse(stream, { signal: request.signal });
104```
105​
106### Send a structured output
107​
108`await chat({ outputSchema })` gives you the typed object on the server. You can save it or change it before the client sees it. To show it in `useChat`, pass the object to `toJsonResponse()`:
109​
110```typescript
111// api/extract-person.ts
112import { chat, chatParamsFromRequest, toJsonResponse } from "@tanstack/ai";
113import { openaiText } from "@tanstack/ai-openai";
114import { z } from "zod";
115​
116const PersonSchema = z.object({
117 name: z.string(),
118 age: z.number(),
119});
120​
121export async function POST(request: Request) {
122 const { messages, threadId } = await chatParamsFromRequest(request);
123 const person = await chat({
124 adapter: openaiText("gpt-6.1-sol"),
125 messages,
126 threadId,
127 outputSchema: PersonSchema,
128 });
129 // `person` is typed here. Save it before you send it.
130 return toJsonResponse(person);
132```
133​
134On the client, give `useChat` the same schema and read `final`:
135​
136```tsx
137import { useChat, fetchJson } from "@tanstack/ai-react";
138import { z } from "zod";
139​
140const PersonSchema = z.object({
141 name: z.string(),
142 age: z.number(),
143});
144​
145export function PersonExtractor() {
146 const { sendMessage, isLoading, final } = useChat({
147 connection: fetchJson("/api/extract-person"),
148 threadId: "support-chat",
149 outputSchema: PersonSchema,
150 });
151​
152 return (
153 <div>
154 <button
155 disabled={isLoading}
156 onClick={() => void sendMessage("Extract: John Doe is 30")}
157 >
158 Extract
159 </button>
160 {final && (
161 <p>
162 {final.name} is {final.age}
163 </p>
164 )}
165 </div>
166 );
168```
169​
170What happens:
171​
172- **One complete part**: the assistant message gets one `structured-output` part. `final` and `partial` get the object in the same reply.
173- **Next turn**: the client sends the object back to the model as the assistant reply.
174​
175To fill in the object field by field, pass the stream from `chat({ outputSchema, stream: true })` to `toJsonResponse()` instead.
176​
177### Long runs and reloads
178​
179A long agent run can take more time than your host lets one request live. Add durability, and the server replies before the timeout. The client then asks for the rest.
180​
1811. Pass a durability adapter, `request.signal`, and `maxWaitMs` to `toJsonResponse`.
1822. Add a `GET` handler with `resumeJsonResponse`.
183​
184```typescript
185// api/chat.ts
186import {
187 chat,
188 chatParamsFromRequest,
189 memoryStream,
190 resumeJsonResponse,
191 toJsonResponse,
192} from "@tanstack/ai";
193import { openaiText } from "@tanstack/ai-openai";
194​
195export async function POST(request: Request) {
196 const { messages, threadId, runId } = await chatParamsFromRequest(request);
197 const stream = chat({
198 adapter: openaiText("gpt-6.1-sol"),
199 messages,
200 threadId,
201 runId,
202 });
203 return toJsonResponse(stream, {
204 durability: { adapter: memoryStream(request) },
205 signal: request.signal,
206 maxWaitMs: 10_000,
207 });
209​
210// fetchJson polls GET ?runId=...&offset=... until the reply has done: true.
211export async function GET(request: Request) {
212 return resumeJsonResponse({ adapter: memoryStream(request) });
214```
215​
216What happens:
217​
218- **`maxWaitMs`**: after 10 seconds, the server replies with the chunks it has and `done: false`. The run keeps going and fills the log.
219- **Polling**: `fetchJson` waits `pollIntervalMs`, then sends `GET ?runId=<id>&offset=<offset>`. Each reply holds only new chunks. It stops at `done: true`.
220- **`signal`**: when the client leaves, the run does not stop. It keeps going in the log.
221- **Reloads**: after a reload, `joinRun` sends `GET ?runId=<id>&offset=-1` to the same handler and reads the run from the start.
222​
223`resumeJsonResponse` waits at most 1000 ms for new chunks before it replies. It never calls the model.
224​
225The client from step 2 needs no change. To set the wait between polls (default 250 ms), pass `pollIntervalMs`:
226​
227```typescript
228import { fetchJson } from "@tanstack/ai-react";
229​
230export const connection = fetchJson("/api/chat", { pollIntervalMs: 500 });
231```
232​
233Pass this `connection` to `useChat`.
234​
235`memoryStream(request)` keeps the log in one process. If your requests run on many processes, use a production adapter. See [Resumable Streams](../resumable-streams/overview).
236​
237### Limits
238​
239- **No live text.** The answer appears when a reply arrives. With `maxWaitMs`, it appears in parts, one part per reply.
240- **The run must outlive the reply.** After an early reply, the run continues in the same process. Your host must keep that work alive after the response goes out.
241- **The first POST is not retried.** A retry can start the run two times. A failed poll is retried with the `reconnect` option. See [Reconnection bounding](../resumable-streams/advanced#reconnection-bounding).
242- **Use `fetchJson`, not `fetcher`.** The chat client parses a `Response` from a `useChat` fetcher as SSE.