Stream Object
Learn how to stream structured data using the AI TOOLKIT and Node
Object generation can sometimes take a long time to complete, especially when you're generating a large schema. In Generative UI use cases, it is useful to stream the object to the client in real-time to render UIs as the object is being generated. You can use the `streamObject` function to generate partial object streams. import { streamObject } from 'ai-toolkit'; import { z } from 'zod'; const { partialObjectStream } = streamObject({ model: 'openai/gpt-4.1', schema: z.object({ recipe: z.object({ name: z.string(), ingredients: z.array(z.string()), steps: z.array(z.string()), }), }), prompt: 'Generate a lasagna recipe.', }); for await (const partialObject of partialObjectStream) { console.clear(); console.log(partialObject); }
- 1import { streamObject } from 'ai-toolkit';
- 2import { z } from 'zod';
- 3const { partialObjectStream } = streamObject({
- 4model: 'openai/gpt-4.1',
- 5schema: z.object({
- 6recipe: z.object({
- 7name: z.string(),
- 8ingredients: z.array(z.string()),
- 9steps: z.array(z.string()),
- 10}),
- 11}),
- 12prompt: 'Generate a lasagna recipe.',
- 13});
- 14for await (const partialObject of partialObjectStream) {
- 15console.clear();
- 16console.log(partialObject);
- 17}
Run it locally
$ npm install ai