Overview
This lecture covers how to use AI to generate structured arrays (using the Pokémon example) and classify text with enums (sentiment analysis), explaining the code and UI patterns for each.
Generating Arrays with AI (Pokémon Example)
- Define a single Pokémon schema with name (string) and abilities (array of strings).
- The schema is wrapped with Z.array to specify an array of Pokémon objects.
- In the API route, set the output property to "array" when calling the streamObject function.
- Pass the single Pokémon schema to streamObject, not the array schema.
- The Pokémon type (e.g., fire, water) is taken from the request body for prompt generation.
- The response is streamed to the UI, returning a structured array of Pokémon and their abilities.
- The UI uses useObject hook with the /api/structured-array endpoint and Pokémon schema for form submission.
- The UI maps over the array to render each Pokémon’s name and abilities dynamically.
Working with Enums (Sentiment Classifier)
- In the API, use generateObject (not streamObject) with output set to "enum".
- Define possible enum values directly using the enum property: positive, negative, or neutral.
- No separate schema is needed for enums.
- Use a more capable AI model (e.g., gpt-4.1-mini) for reliable enum outputs.
- The API returns a single value (no streaming), so use toJSONResponse instead of toTextStreamResponse.
- The UI uses a standard fetch request and useState to manage input, sentiment, loading state, and errors.
- On form submission, send the input text to the endpoint and display the classified sentiment.
- No useObject hook is needed for enums.
Summary of Key Patterns
- Arrays: wrap schemas in ZOD array, use streamObject with output="array", and display using useObject in the UI.
- Enums: no schema required, use generateObject with output="enum", manage UI state manually.
- Arrays return lists of objects; enums return a single classified value.
Key Terms & Definitions
- ZOD — A TypeScript-first schema validation library for defining structured data types.
- Schema — Blueprint describing the structure and types expected in data objects.
- Enum — A set of named constants representing a limited set of possible values.
- useObject hook — A custom hook for managing AI-generated object or array responses in React UIs.
- streamObject — Function to stream arrays/objects from AI to the UI.
- generateObject — Function to synchronously generate a single value (including enums) from AI.
Action Items / Next Steps
- Try generating arrays with different Pokémon types in the example UI.
- Experiment with various texts in the sentiment analysis UI to observe AI handling of edge cases.
- Review and explore the provided code examples on GitHub.