Agent with Structured Output

Code

1from typing import List
2
3from kern.agent import Agent, RunOutput # noqa
4from kern.models.perplexity import Perplexity
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
25# Agent that uses JSON mode
26structured_output_response = Agent(
27 model=Perplexity(id="sonar-pro"),
28 description="You write movie scripts.",
29 output_schema=MovieScript,
30 markdown=True,
31)
32
33# Get the response in a variable
34# structured_output_response: RunOutput = structured_output_agent.run("New York")
35# pprint(structured_output_response.content)
36
37structured_output_response.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 PERPLEXITY_API_KEY=xxx

Install dependencies

1uv pip install -U kern-ai openai

Run Agent

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