generateObject creates a structured, typed object from an AI model using a Zod schema. It sends a prompt, validates the response, and retries generation when validation fails up to a specified limit. section 4.3.3
A typical implementation combines these moving parts:
- Install Zod, define a schema such as a product with name, description, price, and category, and optionally wrap it in an array or parent object. section 4.3.3
- Pass the schema, an AI model such as Google Gemini, and a prompt to generateObject; read the validated result from its object property. section 4.3.3
- Return the structured result from a server action and render it in a React interface, such as a product table. section 4.3.4
Generate a product list
Define ProductSchema with string fields for name, description, and category plus a numeric price. Wrap it in a products array schema, then call generateObject with a Gemini model and a prompt requesting five products related to a user-supplied category. Return products and display them with console.table or a web table. Handle failures in the submit flow by logging the error and showing an error product row.
Listing 4.10 Generating structured responses with Zod
import { z } from 'zod';
import { google } from '@ai-sdk/google';
import { generateObject } from 'ai';
const ProductSchema = z.object({. #1
name: z.string(),
description: z.string(),
price: z.number(),
category: z.string()
});
const ProductListSchema = z.array(ProductSchema); #2
async function generateProductList(prompt) {
'use server';
const {
object: { products },
} = await generateObject({. #3
model: google("models/gemini-2.0-flash"),
schema: z.object({
products: ProductListSchema. #4
}),
prompt: `Generate a list of 5 products
related to: ${prompt}. Provide name, description, price,
and category for each product.`, #5
});
return products;
}
generateProductList('A list of cereal types').then(console.table);
Inspect the complete JavaScript listing showing Zod schemas, the Gemini model, the generateObject call, and the returned product list. section 4.3.3
