Stream Object
Learn how to stream object using the AI TOOLKIT and Next.js
Object generation can sometimes take a long time to complete, especially when you're generating a large schema. In such cases, it is useful to stream the object generation process to the client in real-time. This allows the client to display the generated object as it is being generated, rather than have users wait for it to complete before displaying the result. stream object={{ notifications: [ { name: 'Jamie Roberts', message: "Hey! How's the study grind going? Need a coffee boost?", minutesAgo: 15, }, { name: 'Prof. Morgan', message: 'Reminder: Your term paper is due promptly at 8 AM tomorrow. Please ensure it meets the submission guidelines outlined.', minutesAgo: 46, }, { name: 'Alex Chen', message: "Dude, urgent! Borrow your notes for tomorrow's exam? I swear mine got eaten by my dog!", minutesAgo: 30, }, ], }} />
Run it locally
$ npm install aiObject Mode
The streamObject function allows you to specify different output strategies using the output parameter. By default, the output mode is set to object, which will generate exactly the structured object that you specify in the schema option.
### Schema
It is helpful to set up the schema in a separate file that is imported on both the client and server.
import { z } from 'zod';
// define a schema for the notifications
export const notificationSchema = z.object({
notifications: z.array(
z.object({
name: z.string().describe('Name of a fictional person.'),
message: z.string().describe('Message. Do not use emojis or links.'),
}),
),
});
### Client
The client uses `useObject` to stream the object generation process.
The results are partial and are displayed as they are received.
Please note the code for handling undefined values in the JSX.
'use client';
import { experimental_useObject as useObject } from '@ai-toolkit/react';
import { notificationSchema } from './api/use-object/schema';
export default function Page() {
const { object, submit } = useObject({
api: '/api/use-object',
schema: notificationSchema,
});
return (
<div>
<button onClick={() => submit('Messages during finals week.')}>
Generate notifications
</button>
{object?.notifications?.map((notification, index) => (
<div key={index}>
<p>{notification?.name}</p>
<p>{notification?.message}</p>
</div>
))}
</div>
);
}
### Server
On the server, we use `streamObject` to stream the object generation process.
import { streamObject } from 'ai-toolkit';
import { notificationSchema } from './schema';
// Allow streaming responses up to 30 seconds
export const maxDuration = 30;
export async function POST(req: Request) {
const context = await req.json();
const result = streamObject({
model: 'openai/gpt-4.1',
schema: notificationSchema,
prompt:
Generate 3 notifications for a messages app in this context: + context,
});
return result.toTextStreamResponse();
}
- 1import { z } from 'zod';
- 2// define a schema for the notifications
- 3export const notificationSchema = z.object({
- 4 notifications: z.array(
- 5 z.object({
- 6 name: z.string().describe('Name of a fictional person.'),
- 7 message: z.string().describe('Message. Do not use emojis or links.'),
- 8 }),
- 9 ),
- 10});
- 1'use client';
- 2import { experimental_useObject as useObject } from '@ai-toolkit/react';
- 3import { notificationSchema } from './api/use-object/schema';
- 4export default function Page() {
- 5 const { object, submit } = useObject({
- 6 api: '/api/use-object',
- 7 schema: notificationSchema,
- 8 });
- 9 return (
- 10 <div>
- 11 <button onClick={() => submit('Messages during finals week.')}>
- 12 Generate notifications
- 13 </button>
- 14 {object?.notifications?.map((notification, index) => (
- 15 <div key={index}>
- 16 <p>{notification?.name}</p>
- 17 <p>{notification?.message}</p>
- 18 </div>
- 19 ))}
- 20 </div>
- 21 );
- 22}
- 1import { streamObject } from 'ai-toolkit';
- 2import { notificationSchema } from './schema';
- 3// Allow streaming responses up to 30 seconds
- 4export const maxDuration = 30;
- 5export async function POST(req: Request) {
- 6 const context = await req.json();
- 7 const result = streamObject({
- 8 model: 'openai/gpt-4.1',
- 9 schema: notificationSchema,
- 10 prompt:
- 11 `Generate 3 notifications for a messages app in this context:` + context,
- 12 });
- 13 return result.toTextStreamResponse();
- 14}
Loading State and Stopping the Stream
You can use the loading state to display a loading indicator while the object is being generated.
You can also use the stop function to stop the object generation process.
'use client';
import { experimental_useObject as useObject } from '@ai-toolkit/react';
import { notificationSchema } from './api/use-object/schema';
export default function Page() {
const { object, submit, isLoading, stop } = useObject({
api: '/api/use-object',
schema: notificationSchema,
});
return (
<div>
<button
onClick={() => submit('Messages during finals week.')}
disabled={isLoading}
>
Generate notifications
</button>
{isLoading && (
<div>
<div>Loading...</div>
<button type="button" onClick={() => stop()}>
Stop
</button>
</div>
)}
{object?.notifications?.map((notification, index) => (
<div key={index}>
<p>{notification?.name}</p>
<p>{notification?.message}</p>
</div>
))}
</div>
);
}
- 1'use client';
- 2import { experimental_useObject as useObject } from '@ai-toolkit/react';
- 3import { notificationSchema } from './api/use-object/schema';
- 4export default function Page() {
- 5 const { object, submit, isLoading, stop } = useObject({
- 6 api: '/api/use-object',
- 7 schema: notificationSchema,
- 8 });
- 9 return (
- 10 <div>
- 11 <button
- 12 onClick={() => submit('Messages during finals week.')}
- 13 disabled={isLoading}
- 14 >
- 15 Generate notifications
- 16 </button>
- 17 {isLoading && (
- 18 <div>
- 19 <div>Loading...</div>
- 20 <button type="button" onClick={() => stop()}>
- 21 Stop
- 22 </button>
- 23 </div>
- 24 )}
- 25 {object?.notifications?.map((notification, index) => (
- 26 <div key={index}>
- 27 <p>{notification?.name}</p>
- 28 <p>{notification?.message}</p>
- 29 </div>
- 30 ))}
- 31 </div>
- 32 );
- 33}
Array Mode
The "array" output mode allows you to stream an array of objects one element at a time. This is particularly useful when generating lists of items.
### Schema
First, update the schema to generate a single object (remove the z.array()).
import { z } from 'zod';
// define a schema for a single notification
export const notificationSchema = z.object({
name: z.string().describe('Name of a fictional person.'),
message: z.string().describe('Message. Do not use emojis or links.'),
});
### Client
On the client, you wrap the schema in z.array() to generate an array of objects.
'use client';
import { experimental_useObject as useObject } from '@ai-toolkit/react';
import { notificationSchema } from '../api/use-object/schema';
import z from 'zod';
export default function Page() {
const { object, submit, isLoading, stop } = useObject({
api: '/api/use-object',
schema: z.array(notificationSchema),
});
return (
<div>
<button
onClick={() => submit('Messages during finals week.')}
disabled={isLoading}
>
Generate notifications
</button>
{isLoading && (
<div>
<div>Loading...</div>
<button type="button" onClick={() => stop()}>
Stop
</button>
</div>
)}
{object?.map((notification, index) => (
<div key={index}>
<p>{notification?.name}</p>
<p>{notification?.message}</p>
</div>
))}
</div>
);
}
### Server
On the server, specify output: 'array' to generate an array of objects.
import { streamObject } from 'ai-toolkit';
import { notificationSchema } from './schema';
export const maxDuration = 30;
export async function POST(req: Request) {
const context = await req.json();
const result = streamObject({
model: 'openai/gpt-4.1',
output: 'array',
schema: notificationSchema,
prompt:
Generate 3 notifications for a messages app in this context: + context,
});
return result.toTextStreamResponse();
}
- 1import { z } from 'zod';
- 2// define a schema for a single notification
- 3export const notificationSchema = z.object({
- 4 name: z.string().describe('Name of a fictional person.'),
- 5 message: z.string().describe('Message. Do not use emojis or links.'),
- 6});
- 1'use client';
- 2import { experimental_useObject as useObject } from '@ai-toolkit/react';
- 3import { notificationSchema } from '../api/use-object/schema';
- 4import z from 'zod';
- 5export default function Page() {
- 6 const { object, submit, isLoading, stop } = useObject({
- 7 api: '/api/use-object',
- 8 schema: z.array(notificationSchema),
- 9 });
- 10 return (
- 11 <div>
- 12 <button
- 13 onClick={() => submit('Messages during finals week.')}
- 14 disabled={isLoading}
- 15 >
- 16 Generate notifications
- 17 </button>
- 18 {isLoading && (
- 19 <div>
- 20 <div>Loading...</div>
- 21 <button type="button" onClick={() => stop()}>
- 22 Stop
- 23 </button>
- 24 </div>
- 25 )}
- 26 {object?.map((notification, index) => (
- 27 <div key={index}>
- 28 <p>{notification?.name}</p>
- 29 <p>{notification?.message}</p>
- 30 </div>
- 31 ))}
- 32 </div>
- 33 );
- 34}
- 1import { streamObject } from 'ai-toolkit';
- 2import { notificationSchema } from './schema';
- 3export const maxDuration = 30;
- 4export async function POST(req: Request) {
- 5 const context = await req.json();
- 6 const result = streamObject({
- 7 model: 'openai/gpt-4.1',
- 8 output: 'array',
- 9 schema: notificationSchema,
- 10 prompt:
- 11 `Generate 3 notifications for a messages app in this context:` + context,
- 12 });
- 13 return result.toTextStreamResponse();
- 14}
No Schema Mode
The "no-schema" output mode can be used when you don't want to specify a schema, for example when the data structure is defined by a dynamic user request. When using this mode, omit the schema parameter and set output: 'no-schema'. The model will still attempt to generate JSON data based on the prompt.
### Client
On the client, you wrap the schema in z.array() to generate an array of objects.
'use client';
import { experimental_useObject as useObject } from '@ai-toolkit/react';
import { z } from 'zod';
export default function Page() {
const { object, submit, isLoading, stop } = useObject({
api: '/api/use-object',
schema: z.unknown(),
});
return (
<div>
<button
onClick={() => submit('Messages during finals week.')}
disabled={isLoading}
>
Generate notifications
</button>
{isLoading && (
<div>
<div>Loading...</div>
<button type="button" onClick={() => stop()}>
Stop
</button>
</div>
)}
{JSON.stringify(object, null, 2)}
</div>
);
}
### Server
On the server, specify output: 'no-schema'.
import { streamObject } from 'ai-toolkit';
export const maxDuration = 30;
export async function POST(req: Request) {
const context = await req.json();
const result = streamObject({
model: 'openai/gpt-4o',
output: 'no-schema',
prompt:
Generate 3 notifications (in JSON) for a messages app in this context: +
context,
});
return result.toTextStreamResponse();
}
- 1'use client';
- 2import { experimental_useObject as useObject } from '@ai-toolkit/react';
- 3import { z } from 'zod';
- 4export default function Page() {
- 5 const { object, submit, isLoading, stop } = useObject({
- 6 api: '/api/use-object',
- 7 schema: z.unknown(),
- 8 });
- 9 return (
- 10 <div>
- 11 <button
- 12 onClick={() => submit('Messages during finals week.')}
- 13 disabled={isLoading}
- 14 >
- 15 Generate notifications
- 16 </button>
- 17 {isLoading && (
- 18 <div>
- 19 <div>Loading...</div>
- 20 <button type="button" onClick={() => stop()}>
- 21 Stop
- 22 </button>
- 23 </div>
- 24 )}
- 25 {JSON.stringify(object, null, 2)}
- 26 </div>
- 27 );
- 28}
- 1import { streamObject } from 'ai-toolkit';
- 2export const maxDuration = 30;
- 3export async function POST(req: Request) {
- 4 const context = await req.json();
- 5 const result = streamObject({
- 6 model: 'openai/gpt-4o',
- 7 output: 'no-schema',
- 8 prompt:
- 9 `Generate 3 notifications (in JSON) for a messages app in this context:` +
- 10 context,
- 11 });
- 12 return result.toTextStreamResponse();
- 13}