Structured Output Agent

Request a MovieScript response and handle validated output from a DashScope agent.

This qwen-plus example requests JSON Object mode, then Agno attempts to validate the response against MovieScript with Pydantic. Provider-enforced JSON Schema support depends on the selected model; see Qwen structured output.

Code

from typing import List

from agno.agent import Agent
from agno.models.dashscope import DashScope
from pydantic import BaseModel, Field

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=DashScope(id="qwen-plus"),
    description="You write movie scripts and return them as structured JSON data.",
    output_schema=MovieScript,
    use_json_mode=True,
)

structured_output_agent.print_response(
    "Create a movie script about llamas ruling the world. "
    "Return a JSON object with: name (movie title), setting, ending, genre, "
    "characters (list of character names), and storyline (3 sentences)."
)

The default endpoint is Singapore (https://dashscope-intl.aliyuncs.com/compatible-mode/v1). Use a DASHSCOPE_API_KEY issued for that service region and a model available there. Keys and endpoints must match the service region, regardless of your physical location. For another region, pass its base_url to DashScope; see Model Studio API keys and regional endpoints.

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/activate

Set your API key

export DASHSCOPE_API_KEY=xxx

Install dependencies

uv pip install -U openai agno

Run Agent

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

python structured_output.py