Agent with Structured Outputs
Request a MovieScript response and handle validated output from a Mercury 2 agent.
The first agent requests JSON Object mode and attempts local validation. The second explicitly enables Mercury 2 JSON Schema output, overriding the adapter's default capability setting. Both use MovieScript as the expected response type.
Code
from typing import List
from agno.agent import Agent, RunOutput # noqa
from agno.models.inception import Inception
from pydantic import BaseModel, Field
from rich.pretty import pprint # noqa
class MovieScript(BaseModel):
setting: str = Field(
..., description="Provide a nice setting for a blockbuster movie."
)
ending: str = Field(
...,
description="Ending of the movie. If not available, provide a happy ending.",
)
genre: str = Field(
...,
description="Genre of the movie. If not available, select action, thriller or romantic comedy.",
)
name: str = Field(..., description="Give a name to this movie")
characters: List[str] = Field(..., description="Name of characters for this movie.")
storyline: str = Field(
..., description="3 sentence storyline for the movie. Make it exciting!"
)
# Request JSON Object mode and validate locally with Pydantic.
json_mode_agent = Agent(
model=Inception(id="mercury-2"),
description="You write movie scripts.",
output_schema=MovieScript,
use_json_mode=True,
)
# Request provider-enforced JSON Schema with Mercury 2.
structured_output_agent = Agent(
model=Inception(id="mercury-2", supports_native_structured_outputs=True),
description="You write movie scripts.",
output_schema=MovieScript,
)
# Get the response in a variable
# response: RunOutput = json_mode_agent.run("New York")
# pprint(response.content)
if __name__ == "__main__":
json_mode_agent.print_response("New York")
structured_output_agent.print_response("New York")output_schema describes the expected type. If parsing or validation fails, result.content can remain a string. Before accessing schema fields in a run result, use isinstance(result.content, YourSchema), replacing YourSchema with the class you passed as output_schema.
Usage
Set up your virtual environment
uv venv --python 3.12
source .venv/bin/activateSet your API key
export INCEPTION_API_KEY=xxxInstall dependencies
uv pip install -U openai agnoRun Agent
Save the code above as structured_output.py, then run:
python structured_output.py