Stream Object

Learn how to stream structured data using the AI TOOLKIT and Node

1 min readnodestreamingstructured dataView source

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); }

index.ts
ts
  1. 1import { streamObject } from 'ai-toolkit';
  2. 2import { z } from 'zod';
  3. 3const { partialObjectStream } = streamObject({
  4. 4model: 'openai/gpt-4.1',
  5. 5schema: z.object({
  6. 6recipe: z.object({
  7. 7name: z.string(),
  8. 8ingredients: z.array(z.string()),
  9. 9steps: z.array(z.string()),
  10. 10}),
  11. 11}),
  12. 12prompt: 'Generate a lasagna recipe.',
  13. 13});
  14. 14for await (const partialObject of partialObjectStream) {
  15. 15console.clear();
  16. 16console.log(partialObject);
  17. 17}

Run it locally

$ npm install ai