Learn how to stream object using the AI SDK 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.
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.
It is helpful to set up the schema in a separate file that is imported on both the client and server.
app/api/use-object/schema.ts
import { z } from 'zod';// define a schema for the notificationsexport 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.'), }), ),});
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.
First, update the schema to generate a single object (remove the z.array()).
app/api/use-object/schema.ts
import { z } from 'zod';// define a schema for a single notificationexport const notificationSchema = z.object({ name: z.string().describe('Name of a fictional person.'), message: z.string().describe('Message. Do not use emojis or links.'),});
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.