Generate Object

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

1 min readnodestructured dataView source

Earlier functions like generateText and streamText gave us the ability to generate unstructured text. However, if you want to generate structured data like JSON, you can provide a schema that describes the structure of your desired object to the generateObject function. The function requires you to provide a schema using zod, a library for defining schemas for JavaScript objects. By using zod, you can also use it to validate the generated object and ensure that it conforms to the specified structure. import { generateObject } from 'ai-toolkit'; import { z } from 'zod'; const result = await generateObject({ model: 'openai/gpt-4.1', schema: z.object({ recipe: z.object({ name: z.string(), ingredients: z.array( z.object({ name: z.string(), amount: z.string(), }), ), steps: z.array(z.string()), }), }), prompt: 'Generate a lasagna recipe.', }); console.log(JSON.stringify(result.object.recipe, null, 2));

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

Run it locally

$ npm install ai