Appearance
Structured Output
Force the agent to return a typed Pydantic model instead of free-form text. Useful for pipelines that consume the agent's output programmatically.
Basic usage
Define a Pydantic model and pass it as structured_output_model:
python
from pydantic import BaseModel
from elsai import Agent
class MovieReview(BaseModel):
title: str
rating: float # 0–10
summary: str
recommended: bool
agent = Agent()
result = agent(
"Review the movie Inception",
structured_output_model=MovieReview,
)
review: MovieReview = result.structured_output
print(f"{review.title}: {review.rating}/10")
print(f"Recommended: {review.recommended}")Agent-level default
Set structured_output_model on the agent to apply it to every call:
python
agent = Agent(structured_output_model=MovieReview)
result = agent("Review Interstellar")
review = result.structured_output # MovieReview instanceComplex schemas
Pydantic models support nesting, optional fields, enums, and validators:
python
from pydantic import BaseModel, Field
from typing import Optional
from enum import Enum
class Sentiment(str, Enum):
positive = "positive"
neutral = "neutral"
negative = "negative"
class Keyword(BaseModel):
word: str
relevance: float = Field(ge=0, le=1)
class ContentAnalysis(BaseModel):
sentiment: Sentiment
confidence: float = Field(ge=0, le=1)
keywords: list[Keyword]
summary: str
language: Optional[str] = None
agent = Agent()
result = agent(
"Analyse: 'Elsai makes building agents incredibly easy and intuitive!'",
structured_output_model=ContentAnalysis,
)
analysis = result.structured_output
print(f"Sentiment: {analysis.sentiment.value} ({analysis.confidence:.0%})")Custom prompt override
For smaller models that need extra guidance to produce structured output:
python
result = agent(
"List the planets in the solar system",
structured_output_model=PlanetList,
structured_output_prompt=(
"Please respond ONLY with the structured JSON data — no explanations."
),
)Checking for structured output
python
result = agent("What is 2+2?", structured_output_model=MathAnswer)
if result.structured_output:
answer = result.structured_output
else:
print("Model did not return structured output")Tips
- Use descriptive field names — the model reads field names and their docstrings to understand what to fill in.
- Add
Field(description=...)annotations for better accuracy on complex schemas. - Simpler is more reliable — deeply nested schemas with many optional fields can confuse smaller models; test with your target model.
- Combine with tools — the agent can still call tools before generating the final structured output.
python
class ResearchResult(BaseModel):
topic: str
key_findings: list[str] = Field(description="3-5 concise bullet points")
sources_consulted: int
confidence: float = Field(ge=0, le=1, description="How confident you are in the findings")
agent = Agent(
tools=[web_search, wikipedia_lookup],
structured_output_model=ResearchResult,
)
result = agent("Research the current state of quantum computing")
print(result.structured_output.key_findings)