/** * AI SDK UI - Streaming Structured Data * * Demonstrates: * - useObject hook for streaming structured data * - Partial object updates (live as schema fields fill in) * - Zod schema validation * - Loading states * - Error handling * * Use cases: * - Forms generation * - Recipe creation * - Product specs * - Structured content generation * * Usage: * 1. Copy this component * 2. Create /api/object route with streamObject * 3. Define Zod schema matching your needs */ 'use client'; import { useObject } from 'ai/react'; import { z } from 'zod'; import { FormEvent, useState } from 'react'; // Define the schema for the object const recipeSchema = z.object({ recipe: z.object({ name: z.string().describe('Recipe name'), description: z.string().describe('Short description'), prepTime: z.number().describe('Preparation time in minutes'), cookTime: z.number().describe('Cooking time in minutes'), servings: z.number().describe('Number of servings'), difficulty: z.enum(['easy', 'medium', 'hard']), ingredients: z.array( z.object({ item: z.string(), amount: z.string(), }) ), instructions: z.array(z.string()), }), }); export default function ObjectStreaming() { const { object, submit, isLoading, error, stop } = useObject({ api: '/api/recipe', schema: recipeSchema, }); const [input, setInput] = useState(''); const handleSubmit = (e: FormEvent) => { e.preventDefault(); if (!input.trim()) return; submit(input); setInput(''); }; return (
Streaming structured data with live updates
{object.recipe.description}
)}{isLoading ? 'Loading ingredients...' : 'No ingredients yet'}
)}{isLoading ? 'Loading instructions...' : 'No instructions yet'}
)}