Agent with Structured Outputs Streaming

Code

1from typing import Dict, List
2
3from kern.agent import Agent
4from kern.models.anthropic import Claude
5from pydantic import BaseModel, Field
6
7class MovieScript(BaseModel):
8 setting: str = Field(
9 ..., description="Provide a nice setting for a blockbuster movie."
10 )
11 ending: str = Field(
12 ...,
13 description="Ending of the movie. If not available, provide a happy ending.",
14 )
15 genre: str = Field(
16 ...,
17 description="Genre of the movie. If not available, select action, thriller or romantic comedy.",
18 )
19 name: str = Field(..., description="Give a name to this movie")
20 characters: List[str] = Field(..., description="Name of characters for this movie.")
21 storyline: str = Field(
22 ..., description="3 sentence storyline for the movie. Make it exciting!"
23 )
24 rating: Dict[str, int] = Field(
25 ...,
26 description="Your own rating of the movie. 1-10. Return a dictionary with the keys 'story' and 'acting'.",
27 )
28
29# Agent that uses structured outputs
30structured_output_agent = Agent(
31 model=Claude(id="claude-sonnet-4-5-20250929"),
32 description="You write movie scripts.",
33 output_schema=MovieScript,
34)
35
36structured_output_agent.print_response("New York", stream=True)

Usage

Set up your virtual environment

1uv venv --python 3.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Set your API key

1export ANTHROPIC_API_KEY=xxx

Install dependencies

1uv pip install -U anthropic kern-ai

Run Agent

1python structured_output_stream.py