Structured outputs with Pydantic schemas
Guarantee a strict reply shape with output_pydantic
Pass a Pydantic BaseModel to output_pydantic= (or validate JSON directly) when downstream code needs typed attributes like result.topics or result.priority instead of free-form text.
Example
from pydantic import BaseModel
from praisonai import Agent
class ReleaseChecklist(BaseModel):
version: str
breaking_changes: bool
highlights: list[str]
agent = Agent(instructions='Extract version, breaking_changes, and highlights.')
parsed = agent.chat(
'Release v4.8.2: faster imports and new shims, no breaking changes.',
output_pydantic=ReleaseChecklist,
)
print(parsed.version, '| breaking:', parsed.breaking_changes, '| highlights:', parsed.highlights)Example explained
- class ReleaseChecklist(BaseModel) — Defines typed fields (str, bool, list[str]) enforced on the model reply.
- output_pydantic=ReleaseChecklist — Automatically parses and validates the reply into a ReleaseChecklist instance.
Live one-line output_pydantic with real models
With any hosted or Ollama model, pass output_pydantic=ReleaseChecklist directly to agent.chat(…) or Task(…, output_pydantic=ReleaseChecklist) so PraisonAI handles JSON parsing and retries automatically.
Example
from pydantic import BaseModel
from praisonai import Agent
class TopicList(BaseModel):
topics: list[str]
agent = Agent(instructions='Reply with the requested schema fields.')
result = agent.chat('List 3 AI agent patterns', output_pydantic=TopicList)
for topic in result.topics:
print('-', topic)Example explained
- output_pydantic=TopicList — Instructs PraisonAI to parse the LLM output straight into a TopicList instance.
Common pitfall: overly nested 20-field schemas on small models
Keep schemas flat (3–6 clear fields with descriptive names). If you need a complex report, split it into two focused tasks with small schemas.
Reference: documentation