AI › AI Tools

Streaming Zod structured outputs in React with TanStack AI

Build Zod-typed structured outputs in React with TanStack AI v1.11.0, inspect local Ollama's batch emission, and handle schema or truncation errors.

Streaming Zod structured outputs in React with TanStack AI

Asking an LLM for raw JSON in a prompt and calling JSON.parse in React breaks on markdown fences, invalid enums, and truncated responses. Here is how TanStack AI v1.11.0 and Zod 4 outputSchema behave in a bug-triage dashboard backed by local Ollama qwen2.5:1.5b, including batch emission internals and failure boundaries.

Verified on Node.js v22.23.3, Next.js 15.5.29, React 19.3.1, @tanstack/ai@1.11.0, @tanstack/ai-react@1.3.0, @tanstack/ai-ollama@1.1.1, zod@4.6.7, and local Ollama 0.40.18 (qwen2.5:1.5b).

Why outputSchema beats prompt-only JSON

When you turn free-form incident reports into structured cards—severity (P0–P3), affected service, summary, reproduction steps, and suggested team—prompting for JSON and parsing it manually leaves every failure mode in your UI layer. One markdown json fence, one invented enum value, or one mid-object token cutoff forces you into regex stripping and fragile fallback branches.

TanStack AI moves that contract into a shared Zod schema passed to both chat() on the server and useChat() in React. The server converts the schema into JSON Schema for the model adapter and validates the final payload with Zod. On the client, useChat() separates partial (DeepPartial<T>, unverified preview) from final (T | null, validated output).

ApproachType safetyValidation ownershipStreaming previewBest fit
Prompt JSON + manual JSON.parseRuntime casts onlyApp code strips fences and validatesRequires a custom partial JSON parserQuick prototypes, mixed prose output
Plain text SSE streamingRaw stringNoneToken-by-token immediatelyChat answers, summaries, code walkthroughs
chat + useChat({ outputSchema })Inferred DeepPartial<T> and TAdapter constraint + server Zod checkpartial preview + final commit gateTriage cards, form autofill, ticket drafts

You shouldn’t use outputSchema everywhere. If users read long prose or markdown explanations as tokens arrive, plain text streaming gives lower perceived latency. As the local Ollama measurement below shows, @tanstack/ai-ollama@1.1.1 doesn’t emit partial JSON tokens incrementally, so structured output is a poor fit for long-form writing UIs on Ollama.

Sharing a Zod schema between server and React

Start by defining BugTriageSchema in a shared module so both the Next.js Route Handler and the React component enforce the exact same contract. Lock severity and suggestedTeam with z.enum, and require at least one reproduction step.

1
2
3
4
5
6
7
8
9
10
11
12
// src/lib/bug-triage-schema.ts
import { z } from 'zod'

export const BugTriageSchema = z.object({
  severity: z.enum(['P0', 'P1', 'P2', 'P3']),
  service: z.string().min(1),
  summary: z.string().min(5),
  reproductionSteps: z.array(z.string().min(1)).min(1),
  suggestedTeam: z.enum(['payments', 'checkout', 'platform', 'mobile-web']),
})

export type BugTriage = z.infer<typeof BugTriageSchema>

In the Next.js App Router Route Handler, parse the AG-UI request body with chatParamsFromRequest(request) and pass outputSchema: BugTriageSchema alongside stream: true. In @tanstack/ai@1.11.0, threadId is required. If the request body is malformed, chatParamsFromRequest throws a Response instance that you can return directly as HTTP 400.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// src/app/api/triage/route.ts
import {
  chat,
  chatParamsFromRequest,
  toServerSentEventsResponse,
} from '@tanstack/ai'
import { createOllamaChat } from '@tanstack/ai-ollama'
import { BugTriageSchema } from '@/lib/bug-triage-schema'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

export async function POST(request: Request) {
  let params: Awaited<ReturnType<typeof chatParamsFromRequest>>
  try {
    params = await chatParamsFromRequest(request)
  } catch (err) {
    if (err instanceof Response) {
      return err
    }
    throw err
  }

  const stream = chat({
    adapter: createOllamaChat('qwen2.5:1.5b', 'http://127.0.0.1:11434'),
    messages: params.messages,
    threadId: params.threadId,
    outputSchema: BugTriageSchema,
    systemPrompts: [
      'You are an incident triage classifier.',
      'Return ONLY a JSON object matching the exact schema with severity (P0/P1/P2/P3), service, summary, reproductionSteps (array of strings), and suggestedTeam (payments/checkout/platform/mobile-web).',
    ],
    stream: true,
  })

  return toServerSentEventsResponse(stream, {
    headers: { 'X-Accel-Buffering': 'no' },
  })
}

Here is how the request travels through the Ollama adapter and Zod validation back into React state.

flowchart TD
    A["React useChat(outputSchema)"] -->|"POST /api/triage"| B["chat(outputSchema, stream: true)"]
    B -->|"JSON Schema"| C["OllamaTextAdapter.structuredOutput"]
    C -->|"stream: false + format"| D["Server Zod validation"]
    D -->|"Valid"| E["Emit partial + final"]
    D -->|"Invalid / cut off"| F["Expose error, final: null"]

Separating partial previews from final commits in React

On the client, pass the same BugTriageSchema and threadId to useChat. The key design rule is to decouple what you render for preview (display) from what unlocks a write action (final).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// src/app/bug-triage/page.tsx (core excerpt)
'use client'

import { useMemo, useState } from 'react'
import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
import { BugTriageSchema } from '@/lib/bug-triage-schema'

export default function BugTriagePanel() {
  const [report, setReport] = useState('')
  const connection = useMemo(() => fetchServerSentEvents('/api/triage'), [])

  const { sendMessage, partial, final, isLoading, error, clear } = useChat({
    threadId: 'bug-triage-thread',
    connection,
    outputSchema: BugTriageSchema,
  })

  const display = final ?? partial ?? {}

  const handleRun = async () => {
    clear()
    await sendMessage(report)
  }

  return (
    <section>
      <textarea value={report} onChange={(e) => setReport(e.target.value)} />
      <button type="button" onClick={handleRun} disabled={isLoading || !report.trim()}>
        Classify Report
      </button>
      <button type="button" disabled={!final}>
        Create Incident Ticket (Requires final)
      </button>

      {error && <div role="alert">{error.message}</div>}

      <dl>
        <dt>Severity</dt>
        <dd>{display.severity ?? '—'}</dd>
        <dt>Affected Service</dt>
        <dd>{display.service ?? '—'}</dd>
        <dt>Suggested Team</dt>
        <dd>{display.suggestedTeam ?? '—'}</dd>
      </dl>
    </section>
  )
}

Read-only fields fall back to final ?? partial ?? {}, while the Create Incident Ticket button stays locked behind disabled={!final}. Never wire a persistence mutation to partial, because partial can hold unvalidated data before the server finishes checking the schema.

What local Ollama actually emits under the hood

Running the dashboard against live local Ollama 0.40.18 (qwen2.5:1.5b on 127.0.0.1:11434) with an unstructured iOS Safari 18 receipt-PDF 502 bug report produced a complete, validated object without any manual JSON.parse.

React Bug Report Auto-Triage Dashboard showing a verified final BugTriageSchema result from local Ollama qwen2.5:1.5b Figure 1. Live local Ollama qwen2.5:1.5b run: Schema Verified (final), safeParse: true, and partial updates: 1 all settle at 821ms, enabling the ticket creation button.

BugTriageSchema.safeParse(final).success returned true with severity: "P3", service: "Checkout", suggestedTeam: "checkout", summary: "HTTP 502 Bad Gateway during PDF receipt download in iOS Safari", and three reproduction steps.

Two observations stand out from this run:

  1. Schema compliance isn’t classification accuracy. A 502 error affecting roughly 14% of mobile checkout completions was labeled P3 by the small 1.5b model. outputSchema guarantees the shape and enum membership of the response, not business-level triage accuracy. If severity routing matters in production, pair the schema with a larger model or explicit severity criteria in the system prompt.
  2. @tanstack/ai-ollama@1.1.1 emits structured output as a single batch. The telemetry panel shows 1 partial snapshot at 821ms containing all five keys (severity, service, summary, reproductionSteps, suggestedTeam), and final arrives at the same 821ms timestamp.

Checking OllamaTextAdapter.structuredOutput() inside @tanstack/ai-ollama@1.1.1 (dist/esm/adapters/text.js) explains why:

1
2
3
4
5
6
7
8
9
10
11
12
// node_modules/@tanstack/ai-ollama/dist/esm/adapters/text.js (lines 148-155)
const response = await this.clientFor(chatOptions).chat({
  ...mappedOptions,
  stream: false,
  format: outputSchema
});
usage = buildOllamaUsage(response);
if (response.done_reason === "length") {
  throw new Error(
    "ollama.structuredOutput: the response was cut off because the maximum token limit was reached (done_reason=length); raise modelOptions.options.num_predict"
  );
}

Even though the Route Handler calls chat({ outputSchema, stream: true }), the Ollama adapter’s structuredOutput() path sends stream: false and format: outputSchema to /api/chat. It waits for the complete response, parses it once, and hands it back to the core layer. For local Ollama UIs, plan for a clean loading skeleton rather than field-by-field typing animations.

Testing schema violations and truncated JSON

Because live models don’t fail deterministically on demand, I kept the exact same @tanstack/ai-ollama createOllamaChat adapter and pointed its host to a local Ollama-compatible mock server (127.0.0.1:11439) to inject two failure modes: an out-of-enum severity ("CRITICAL") and a truncated JSON response (done_reason: "length").

Bug Report Auto-Triage Dashboard showing a schema validation error for severity CRITICAL with final remaining null and the ticket button disabled Figure 2. Local Ollama-compatible mock (:11439) injecting severity: "CRITICAL": partial renders once at 15ms, then server Zod validation fails, keeping final: null, safeParse: false, and the save button disabled.

Both failure paths blocked final cleanly, though they surfaced at different points:

Failure case (local mock :11439)partial updatesfinal stateSave buttonuseChat error.message
Invalid enum (severity: "CRITICAL")1 (15ms, transient preview)nullDisabledValidation failed: Invalid option: expected one of "P0"\|"P1"\|"P2"\|"P3"
Truncated JSON (done_reason: "length")0nullDisabledStructured output generation failed: ollama.structuredOutput: the response was cut off because the maximum token limit was reached (done_reason=length); raise modelOptions.options.num_predict

The invalid enum case proves why partial can’t gate mutations. Because the response was syntactically valid JSON, partial updated once at 15ms and briefly displayed CRITICAL in the card. Server-side Zod validation then rejected the payload, left final as null, and populated error. Had the submit button checked disabled={!partial}, an invalid enum would have slipped through.

For the truncated response, OllamaTextAdapter.structuredOutput() caught done_reason === "length" before JSON.parse. partial stayed at 0 updates, final remained null, and the error message directly pointed to raising modelOptions.options.num_predict.

Production caveats and checklist

Treat partial as read-only preview state. Keep submit and save buttons disabled until final !== null, and re-run BugTriageSchema.safeParse inside your persistence endpoint so client state can never bypass server validation.

Before shipping outputSchema with local or cloud models, check these four items:

  • Handle both batch and progressive partial updates: @tanstack/ai-ollama@1.1.1 emits one batch snapshot at completion, while cloud adapters may emit multiple incremental updates. Write card components so missing nested fields render safely in both modes.
  • Budget num_predict for array fields: Schemas with reproductionSteps or long summaries hit done_reason=length quickly on default token caps. Raise modelOptions.options.num_predict and surface a retry action when error is set.
  • Keep schemas flat on small local models: Deeply nested objects and wide enum lists reduce classification quality on 1B–3B models even when format: outputSchema enforces valid JSON syntax.
  • Disable reverse-proxy buffering: Keep X-Accel-Buffering: no on the SSE response so proxies like Nginx don’t buffer events before they reach useChat.

References

Headless, type-safe, powerful utilities for complex workflows like Data Management, Data Visualization, Charts, Tables, and UI Components.
Run local open models with Ollama in TanStack AI with @tanstack/ai-ollama. No API key, no API cost, and your data stays on your hardware.
Introduction to Zod - TypeScript-first schema validation library with static type inference
This post is licensed under CC BY 4.0 by the author.