Agent with Structured Outputs
Constrain a local LM Studio agent to return a MovieScript Pydantic object instead of free-form text.
Code
from typing import List
from agno.agent import Agent
from agno.models.lmstudio import LMStudio
from agno.run.agent import RunOutput
from pydantic import BaseModel, Field
from rich.pretty import pprint
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=LMStudio(id="qwen2.5-7b-instruct-1m"),
description="You write movie scripts.",
output_schema=MovieScript,
)
# Run the agent synchronously
structured_output_response: RunOutput = structured_output_agent.run("New York")
pprint(structured_output_response.content)Use a model suitable for JSON schema output in LM Studio. Agno sends MovieScript as a JSON schema and parses the response into that Pydantic model.
Usage
Set up your virtual environment
uv venv --python 3.12
source .venv/bin/activateStart the LM Studio API server
Install LM Studio, download and load a model, then open Developer and start the API server on port 1234. Keep the server running while you run Python in a terminal.
Check the model list:
curl http://127.0.0.1:1234/v1/modelsSet LMStudio(id=...) in the example to the exact model id returned by your server. If you change the server port, set the matching base_url on LMStudio.
Install dependencies
uv pip install -U openai agnoRun Agent
Save the code above as structured_output.py, then run:
python structured_output.py