TemplatesAgent Patterns

Structured Agent Output: Output.choice

Loading pattern preview

Problems solved

Technical challenges this implementation handles out of the box.
  • Constrain ToolLoopAgent output to Output.choice options
  • Return predictable enum-like agent answers
  • Combine constrained outputs with tool-calling agents

Use cases

Products and workflows this pattern is designed to support.
  • Recommendation agents with fixed option sets
  • Triage bots that must pick from known labels
  • Form-like agent decisions
  • Guaranteed-format agent API responses

Setup

Requirements, wiring steps, and what this pattern adds to your project.

Getting started

Pick how you want to pull this pattern in. Then wire env vars and routes the same way.

  1. 1

    Download → Next.js app

    Use Download → Next.js app in the preview toolbar. You get a zip scaffold (Pro downloads rewrite preview `/view/.../api/*` paths to `/api/*` automatically).

  2. 2

    Extract the zip and install dependencies

    Unzip the archive, then run `pnpm install` (or npm / yarn) in the project folder.

  3. 3

    Fill .env.local

    The download includes .env.local placeholders when needed. Add real values for: OPENAI_API_KEY.

  4. 4

    Customize the agent and tool files

    Adapt prompts, tools, and stop conditions in the generated project for your product.

  5. 5

    Run the app and open the pattern route

    Run `pnpm dev`, open the setup/checklist page if present, then navigate to the generated pattern route and verify responses.

Environment variables

Capabilities

AI SDK APIs

ToolLoopAgentOutput.choiceagent.generatetool

Providers

OpenAI

Files added

7 files
  • app/page.tsx
  • app/layout.tsx
  • app/api/choice/route.ts
  • components/structured-choice-demo.tsx
  • components/output-display.tsx
  • lib/choice-agent.ts
  • tools/weather.ts

Dependencies

14 total

npm packages

5
AISDKlucide-reactNext.jsReactZod

Shadcn IconRegistry components

9
alertbadgebuttoncardcollapsibleinputskeletontabstooltip

Critical files

  • lib/choice-agent.ts

    Core agent definition using ToolLoopAgent with Output.choice() to constrain LLM output to predefined string options.

  • tools/weather.ts

    Tool definition using ai SDK tool() with zod inputSchema and execute function. Provides the tool the agent calls before producing its constrained choice output.

  • choice/route.ts

    API route showing how to call ToolLoopAgent.generate() for non-streaming structured output and extract the result.

Requirements

Complexity
Intermediate
Setup time
~5 minutes
Node
24+
Memory
512MB