Pydantic Validation for each Step
To see a more detailed guide, check the docs here.
You now have three ways to handle agent outputs in ClientAI:
- Regular text output (default)
- JSON-formatted output (
json_output=True
) - Validated output with Pydantic models (
json_output=True
withreturn_type
)
Let's look at when to use each approach.
Simple Text Output
When you just need text responses, use the default configuration:
class SimpleAgent(Agent):
@think("analyze")
def analyze_text(self, input_text: str) -> str:
return f"Please analyze this text: {input_text}"
# Usage
agent = SimpleAgent(client=client, default_model="gpt-4")
result = agent.run("Hello world") # Returns plain text
This is perfect for general text generation, summaries, or when you don't need structured data.
JSON-Formatted Output
When you need structured data but don't want strict validation, use json_output=True
:
class StructuredAgent(Agent):
@think(
name="analyze",
json_output=True # Ensures JSON output
)
def analyze_data(self, input_data: str) -> str:
return """
Analyze this data and return as JSON with these fields:
- summary: brief overview
- key_points: list of main points
- sentiment: positive, negative, or neutral
Data: {input_data}
"""
# Usage
agent = StructuredAgent(client=client, default_model="gpt-4")
result = agent.run("Great product, highly recommend!")
# Returns parsed JSON like:
# {
# "summary": "Positive product review",
# "key_points": ["Strong recommendation", "General satisfaction"],
# "sentiment": "positive"
# }
This approach gives you structured data while maintaining flexibility in the output format.
Validated Output with Pydantic
When you need guaranteed output structure and type safety, combine json_output
with Pydantic models:
from pydantic import BaseModel, Field
from typing import List, Optional
class ProductAnalysis(BaseModel):
summary: str = Field(
min_length=10,
description="Brief overview of the analysis"
)
key_points: List[str] = Field(
min_items=1,
description="Main points from the analysis"
)
sentiment: str = Field(
pattern="^(positive|negative|neutral)$",
description="Overall sentiment"
)
confidence: float = Field(
ge=0, le=1,
description="Confidence score between 0 and 1"
)
categories: Optional[List[str]] = Field(
default=None,
description="Product categories if mentioned"
)
class ValidatedAgent(Agent):
@think(
name="analyze",
json_output=True, # Required for validation
return_type=ProductAnalysis # Enables Pydantic validation
)
def analyze_review(self, review: str) -> ProductAnalysis:
return """
Analyze this product review and return a JSON object with:
- summary: at least 10 characters
- key_points: non-empty list of strings
- sentiment: exactly "positive", "negative", or "neutral"
- confidence: number between 0 and 1
- categories: optional list of product categories
Review: {review}
"""
# Usage
agent = ValidatedAgent(client=client, default_model="gpt-4")
try:
result = agent.run("This laptop is amazing! Great battery life and performance.")
print(f"Summary: {result.summary}")
print(f"Sentiment: {result.sentiment}")
print(f"Confidence: {result.confidence}")
for point in result.key_points:
print(f"- {point}")
except ValidationError as e:
print("Output validation failed:", e)