Stream partial objects
Render each field of a structured answer as soon as it arrives.
AI SDK docsai-sdk.dev
The results are partial and are displayed as they are received.
From ai-sdk and the Structured Data docs.
One recipe, two waits
Press Generate and watch the cards fill.
Whole objectBad
0 msIdle
First field –Done –
const { output } = await generateText(…)Partial objectGood
0 msIdle
First field –Done –
useObject → object?.ingredients?.map(…)// app/api/recipe/route.ts
import { streamText, Output, createTextStreamResponse, toTextStream } from 'ai';
import { recipeSchema } from './schema';
export async function POST(req: Request) {
const { dish } = await req.json();
const result = streamText({
model: 'anthropic/claude-sonnet-5',
output: Output.object({ schema: recipeSchema }),
prompt: `Write a recipe for ${dish}.`,
});
return createTextStreamResponse({ stream: toTextStream({ stream: result.stream }) });
}
// app/recipe.tsx
'use client';
import { useObject } from '@ai-sdk/react';
export function Recipe() {
const { object, submit, isLoading } = useObject({ api: '/api/recipe', schema: recipeSchema });
return (
<>
<button onClick={() => submit({ dish: 'lasagna' })} disabled={isLoading}>Generate</button>
<h3>{object?.name}</h3>
<ul>
{object?.ingredients?.map((item, i) => (
<li key={i}>{item?.amount} {item?.name}</li>
))}
</ul>
</>
);
}
Why it matters, pros and cons
Why it matters
A structured answer takes as long as prose to generate. Streaming it lets the first fields show while the rest is written.
Pros
- The title shows in under a second.
- Same schema, same final object.
useObjectparses the partial JSON for you.
Cons
- Partial objects are not validated; every field may be undefined.
- Don't save or act on it until the stream ends.
- Lists grow and reflow while the reader reads.