Structured Output

Request a MovieScript from an Ollama llama3.2 agent and validate the result with Pydantic.

Code

from typing import List
from agno.agent import Agent, RunOutput  # noqa
from agno.models.ollama import Ollama
from pydantic import BaseModel, Field
from rich.pretty import pprint  # noqa

class MovieScript(BaseModel):
    name: str = Field(..., description="Give a name to this movie")
    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.",
    )
    characters: List[str] = Field(..., description="Name of characters for this movie.")
    storyline: str = Field(
        ..., description="3 sentence storyline for the movie. Make it exciting!"
    )

# Agent that returns a structured output
structured_output_agent = Agent(
    model=Ollama(host="http://localhost:11434", api_key=None, id="llama3.2"),
    description="You write movie scripts.",
    output_schema=MovieScript,
)

# Check the parsed type before accessing schema fields.
response = structured_output_agent.run("New York")
if isinstance(response.content, MovieScript):
    pprint(response.content)
else:
    print("The model did not return a valid MovieScript:", response.content)

Usage

Set up your virtual environment

uv venv --python 3.12
source .venv/bin/activate

Start the local Ollama service

Install Ollama and start its desktop app or service on http://localhost:11434. If you start it manually with ollama serve, keep that process running in a separate terminal.

In the terminal where you will pull models and run Python, select that server and clear the direct-cloud key. The native Ollama client also reads this key independently of Agno.

export OLLAMA_HOST=http://localhost:11434
unset OLLAMA_API_KEY

Pull the model

ollama pull llama3.2

Install dependencies

uv pip install -U ollama agno

Run Agent

Save the code above as structured_output.py, then run:

python structured_output.py