Structured Output

Code

1from typing import List
2
3from kern.agent import Agent, RunOutput # noqa
4from kern.models.openai import OpenAIResponses
5from pydantic import BaseModel, Field
6from rich.pretty import pprint # noqa
7
8class MovieScript(BaseModel):
9 setting: str = Field(
10 ..., description="Provide a nice setting for a blockbuster movie."
11 )
12 ending: str = Field(
13 ...,
14 description="Ending of the movie. If not available, provide a happy ending.",
15 )
16 genre: str = Field(
17 ...,
18 description="Genre of the movie. If not available, select action, thriller or romantic comedy.",
19 )
20 name: str = Field(..., description="Give a name to this movie")
21 characters: List[str] = Field(..., description="Name of characters for this movie.")
22 storyline: str = Field(
23 ..., description="3 sentence storyline for the movie. Make it exciting!"
24 )
25
26# Agent that uses JSON mode
27json_mode_agent = Agent(
28 model=OpenAIResponses(id="gpt-5-mini"),
29 description="You write movie scripts.",
30 output_schema=MovieScript,
31 use_json_mode=True,
32)
33
34# Agent that uses structured outputs with strict_output=True (default)
35structured_output_agent = Agent(
36 model=OpenAIResponses(id="gpt-5-mini"),
37 description="You write movie scripts.",
38 output_schema=MovieScript,
39)
40
41# Agent with strict_output=False (guided mode)
42guided_output_agent = Agent(
43 model=OpenAIResponses(id="gpt-5-mini", strict_output=False),
44 description="You write movie scripts.",
45 output_schema=MovieScript,
46)
47
48# Get the response in a variable
49# json_mode_response: RunOutput = json_mode_agent.run("New York")
50# pprint(json_mode_response.content)
51# structured_output_response: RunOutput = structured_output_agent.run("New York")
52# pprint(structured_output_response.content)
53
54json_mode_agent.print_response("New York")
55structured_output_agent.print_response("New York")
56guided_output_agent.print_response("New York")

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 OPENAI_API_KEY=xxx

Install dependencies

1uv pip install -U openai kern-ai

Run Agent

1python cookbook/11_models/openai/responses/structured_output.py