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

streaming-structured-table.md

302 lines9.5 KB

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