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

streaming-structured-table.md

297 lines9.4 KB

1---
2title: Streaming Structured Table
3id: streaming-structured-table
4order: 2
5description: "Stream a typed table from chat({ outputSchema, stream: true }). useChat gives you partial.rows, so the table fills while the JSON arrives."
6keywords:
7 - tanstack ai
8 - tutorial
9 - structured output
10 - streaming
11 - useChat
12 - outputSchema
13 - table
14 - openrouter
15 - tanstack start
16---
17​
18This tutorial streams typed table rows. `partial.rows` updates while the model writes the JSON.
19​
20Pass one schema to `chat()` on the server and to `useChat` on the client. The hook gives you `partial.rows` while the JSON streams, so rows show up as the model writes them. It takes about 10 minutes.
21​
22This tutorial uses React and TanStack Start. For other frameworks, open [Quick Start](../getting-started/quick-start). To skip the setup, paste a key in the sandbox in step 5.
23​
24If you already built [Basic Chat](./basic-chat), keep the app and the key form. Install `zod`, then go to step 2.
25​
26## 1. Create a Start app
27​
28```bash
29npx @tanstack/cli@latest create
30```
31​
32Pick React. For more options, see [Start getting started](https://tanstack.com/start/latest/docs/framework/react/quick-start).
33​
34Install the TanStack AI packages and Zod:
35​
36<!-- ::start:tabs variant="package-manager" mode="install" -->
37​
38react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openrouter zod
39​
40<!-- ::end:tabs -->
41​
42Get an OpenRouter key from [openrouter.ai](https://openrouter.ai).
43​
44## 2. Share one schema
45​
46Create `src/lib/table-schema.ts`. The client and the server both import this file. The field descriptions tell the model what to put in each column.
47​
48```typescript
49import { z } from 'zod'
50​
51export const tableSchema = z.object({
52 title: z.string().meta({ description: 'Short title for the table' }),
53 rows: z.array(
54 z.object({
55 name: z.string().meta({ description: 'Row name' }),
56 year: z.number().meta({ description: 'First release year' }),
57 kind: z.string().meta({ description: 'Category or paradigm' }),
58 note: z.string().meta({ description: 'One-line typical use' }),
59 }),
60 ),
61})
62```
63​
64## 3. Keep the key in the tab
65​
66Create `src/lib/byok.ts`. `memoryStorage()` keeps the key in this tab only.
67​
68```typescript
69import { defineByok, memoryStorage } from '@tanstack/ai-react/byok'
70import { openrouterByok } from '@tanstack/ai-openrouter/byok'
71​
72export const byok = defineByok({
73 storage: memoryStorage(),
74 providers: [openrouterByok],
75})
76```
77​
78Create `src/components/open-router-key-form.tsx`. If you have this form from Basic Chat, use it again.
79​
80```tsx ignore
81import { useState } from 'react'
82import { openrouterByok } from '@tanstack/ai-openrouter/byok'
83import { useByok } from '@tanstack/ai-react'
84import { byok } from '@/lib/byok'
85​
86export function OpenRouterKeyForm() {
87 const snapshot = useByok(byok)
88 const [draft, setDraft] = useState('')
89 const [error, setError] = useState('')
90 const status = snapshot.status[openrouterByok.id]
91 const masked = status && 'masked' in status ? status.masked : undefined
92 const missingKey = snapshot.prompt?.reason === 'missing'
93​
94 return (
95 <form
96 onSubmit={(event) => {
97 event.preventDefault()
98 const next = draft.trim()
99 if (!next) return
100 setError('')
101 void byok
102 .update(openrouterByok.id, next)
103 .then(() => setDraft(''))
104 .catch((caught: unknown) =>
105 setError(
106 caught instanceof Error ? caught.message : 'Could not save key',
107 ),
108 )
109 }}
110 >
111 <input
112 type="password"
113 autoComplete="off"
114 placeholder={masked ? `Saved ${masked}` : 'Paste your OpenRouter key'}
115 value={draft}
116 onChange={(event) => setDraft(event.target.value)}
117 />
118 <button type="submit" disabled={!draft.trim()}>
119 Save key
120 </button>
121 {missingKey ? (
122 <p>Paste an OpenRouter key, then send again.</p>
123 ) : null}
124 {error ? <p>{error}</p> : null}
125 </form>
126 )
128```
129​
130For passkeys or other storage, open [Bring Your Own Key](../advanced/byok).
131​
132## 4. Show the table from `partial`
133​
134Replace `src/routes/index.tsx` with this file. Pass `byok` and `outputSchema: tableSchema` to `useChat`. Then show `partial.rows` as table rows.
135​
136```tsx ignore
137import { useState } from 'react'
138import { createFileRoute } from '@tanstack/react-router'
139import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
140import { OpenRouterKeyForm } from '@/components/open-router-key-form'
141import { byok } from '@/lib/byok'
142import { tableSchema } from '@/lib/table-schema'
143​
144function TablePage() {
145 const [input, setInput] = useState('')
146 const { sendMessage, isLoading, error, stop, partial, final } = useChat({
147 connection: fetchServerSentEvents('/api/chat'),
148 threadId: 'support-chat',
149 byok,
150 outputSchema: tableSchema,
151 })
152​
153 const rows = partial.rows ?? []
154 const title = partial.title
155​
156 const handleSendMessage = () => {
157 if (!input.trim()) return
158 sendMessage(input.trim())
159 setInput('')
160 }
161​
162 return (
163 <div>
164 <h1>Streaming structured table</h1>
165 <OpenRouterKeyForm />
166 {rows.length === 0 && !isLoading ? (
167 <p>Paste an OpenRouter key. Then ask for a comparison table.</p>
168 ) : (
169 <table aria-busy={isLoading}>
170 <caption>
171 {title ?? 'Results'}
172 {isLoading ? ' (streaming)' : final ? ' (complete)' : ''}
173 </caption>
174 <thead>
175 <tr>
176 <th scope="col">Name</th>
177 <th scope="col">Year</th>
178 <th scope="col">Kind</th>
179 <th scope="col">Note</th>
180 </tr>
181 </thead>
182 <tbody>
183 {rows.map((row, index) => (
184 <tr key={index}>
185 <th scope="row">{row.name ?? '…'}</th>
186 <td>{row.year ?? '…'}</td>
187 <td>{row.kind ?? '…'}</td>
188 <td>{row.note ?? '…'}</td>
189 </tr>
190 ))}
191 </tbody>
192 </table>
193 )}
194 {error ? <p>{error.message}</p> : null}
195 {isLoading ? (
196 <button type="button" onClick={stop}>
197 Stop
198 </button>
199 ) : null}
200 <label htmlFor="table-prompt">Prompt</label>
201 <textarea
202 id="table-prompt"
203 value={input}
204 onChange={(event) => setInput(event.target.value)}
205 placeholder="Compare 6 JavaScript frameworks"
206 disabled={isLoading}
207 />
208 <button
209 type="button"
210 onClick={handleSendMessage}
211 disabled={!input.trim() || isLoading}
212 >
213 Send
214 </button>
215 </div>
216 )
218​
219export const Route = createFileRoute('/')({
220 component: TablePage,
221})
222```
223​
224A cell shows `…` until its field arrives.
225​
226## 5. Add the server route
227​
228Create `src/routes/api.chat.ts`, next to `index.tsx`. Start maps this file name to the `/api/chat` path. Pass `outputSchema: tableSchema` and `stream: true` to `chat()`.
229​
230```typescript ignore
231import { createFileRoute } from '@tanstack/react-router'
232import {
233 chat,
234 chatParamsFromRequest,
235 toServerSentEventsResponse,
236} from '@tanstack/ai'
237import { createOpenRouterText } from '@tanstack/ai-openrouter'
238import { openrouterByok } from '@tanstack/ai-openrouter/byok'
239import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
240import { tableSchema } from '@/lib/table-schema'
241​
242export async function POST({ request }: { request: Request }) {
243 const params = await chatParamsFromRequest(request)
244 const apiKey = getByokKey(request, openrouterByok)
245 if (!apiKey) return byokMissing(openrouterByok)
246​
247 const stream = chat({
248 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
249 messages: params.messages,
250 threadId: params.threadId,
251 runId: params.runId,
252 outputSchema: tableSchema,
253 stream: true,
254 })
255 return toServerSentEventsResponse(stream)
257​
258export const Route = createFileRoute('/api/chat')({
259 server: {
260 handlers: {
261 POST,
262 },
263 },
264})
265```
266​
267Import `openrouterByok` from `@tanstack/ai-openrouter/byok`, not from the main entry of the adapter.
268​
269Then try it:
270​
2711. Run the app.
2722. Paste an OpenRouter key.
2733. Send `Compare 6 JavaScript frameworks`.
274​
275Rows show up while the JSON streams.
276​
277The same app is on the Examples tab at `/ai/latest/docs/framework/react/examples/streaming-structured-table`.
278​
279<!-- ::client-example library=ai framework=react slug=streaming-structured-table -->
280​
281You have a table that fills from streamed structured output, and the OpenRouter key never sits in a server env file.
282​
283## How it works
284​
285The server streams the JSON text in chunks. The hook parses that incomplete JSON into `partial`:
286​
287- A field shows up in `partial` as soon as it parses.
288- A new row can have empty cells until more text arrives.
289- `final` is the complete object. It stays `null` until the stream ends.
290​
291Show `partial.rows` while the model writes. Use `final` when you need the complete object, for example to save it. If you read only `final`, the table stays empty until the run is done.
292​
293On the server, `getByokKey` reads the `x-byok-openrouter` header first. If the header is empty, it reads `OPENROUTER_API_KEY` from the environment. If both are empty, `byokMissing` returns HTTP 401. If no key is saved in the tab, the hook does not send the POST, and the form shows "Paste an OpenRouter key, then send again."
294​
295The full example is on GitHub: [TanStack/ai `examples/react/streaming-structured-table`](https://github.com/TanStack/ai/tree/main/examples/react/streaming-structured-table).
296​
297For the API details, open [Streaming UIs](../structured-outputs/streaming).