Structured Output

Code

1from typing import List
2
3from kern.agent import Agent
4from kern.models.xai.xai import xAI
5from kern.run.agent import RunOutput
6from pydantic import BaseModel, Field
7from rich.pretty import pprint # noqa
8
9class MovieScript(BaseModel):
10 name: str = Field(..., description="Give a name to this movie")
11 setting: str = Field(
12 ..., description="Provide a nice setting for a blockbuster movie."
13 )
14 ending: str = Field(
15 ...,
16 description="Ending of the movie. If not available, provide a happy ending.",
17 )
18 genre: str = Field(
19 ...,
20 description="Genre of the movie. If not available, select action, thriller or romantic comedy.",
21 )
22 characters: List[str] = Field(..., description="Name of characters for this movie.")
23 storyline: str = Field(
24 ..., description="3 sentence storyline for the movie. Make it exciting!"
25 )
26
27# Agent that returns a structured output
28structured_output_agent = Agent(
29 model=xAI(id="grok-2-latest"),
30 description="You write movie scripts.",
31 output_schema=MovieScript,
32)
33
34# Run the agent synchronously
35structured_output_response: RunOutput = structured_output_agent.run(
36 "Llamas ruling the world"
37)
38pprint(structured_output_response.content)

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

Install dependencies

1uv pip install -U xai kern-ai

Run Agent

1python cookbook/11_models/xai/structured_output.py