Skip to content

Conversation

@afarntrog
Copy link
Contributor

@afarntrog afarntrog commented Sep 29, 2025

Description

This PR implements a comprehensive structured output system that allows agents to return validated Pydantic models. Strands developers can pass in the structured_output_model field, set to a Pydantic model, when initializing an agent or when invoking the agent. The agent will attempt to populate the pydantic object and set it to a field, structured_output, that can be accessed from the AgentResult object. Callers can use different pydantic models per invocation, or the same, or for some invocations use structured_output_model and for others ignore it.

Examples

Structured Output on the agent invocation
from strands import Agent
from pydantic import BaseModel

class UserProfile(BaseModel):
    """Basic user profile model."""
    name: str
    age: int
    occupation: str

agent = Agent()
agent_res = agent(
    "Create a profile for John Doe who is a 25 year old dentist",
    structured_output_model=UserProfile
)
>>> agent_res.structured_output
UserProfile(name='John Doe', age=25, occupation='dentist')
Structured Output when initializing the agent
from strands import Agent
from pydantic import BaseModel

class UserProfile(BaseModel):
    """Basic user profile model."""
    name: str
    age: int
    occupation: str

agent = Agent(structured_output_model=UserProfile)
agent_res = agent("Create a profile for John Doe who is a 25 year old dentist")
>>> agent_res.structured_output
UserProfile(name='John Doe', age=25, occupation='dentist')

See the README.md for more examples.

Key Features:

structured_output_model parameter support in Agent class and call method
• Complete output module with base classes, modes, and utilities (src/strands/output/)
• Tool-based system with automatic retry logic
• Enhanced event loop integration for structured output processing and validation
• Comprehensive documentation with examples, use cases, and best practices
• Type safety with full typing support and Pydantic validation
• Backward compatibility with existing tool ecosystem

API-Bar raising

  • structured_output_model is the parameter name we agreed to
  • StructuredOutputEvent we added a new Typed Event called StructuredOutputEvent

Open questions:

Related Issues

Documentation PR

Type of Change

New feature

Testing

How have you tested the change? Verify that the changes do not break functionality or introduce warnings in consuming repositories: agents-docs, agents-tools, agents-cli

• [x] I ran hatch run prepare

Checklist

• [x] I have read the CONTRIBUTING document
• [x] I have added any necessary tests that prove my fix is effective or my feature works
• [ ] I have updated the documentation accordingly
• [ ] I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
• [ ] My changes generate no new warnings
• [x] Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

afarntrog and others added 3 commits September 29, 2025 14:41
feat: Implement comprehensive structured output system

This feature addition introduces a complete structured output system that allows agents to return validated Pydantic models instead of raw text responses, providing type safety and consistency for AI agent interactions.

## Key Features Added

### Core Structured Output System
- **New output module**: Complete structured output architecture with base classes, modes, and utilities
- **Agent integration**: Native structured_output_type parameter support in Agent class and __call__ method
- **Event loop integration**: Enhanced event loop to handle structured output processing and validation
- **Tool-based fallback**: Automatic fallback mechanism using structured output tools when native support unavailable

### Architecture Components
- **OutputMode base class**: Abstract interface for different structured output implementations
- **ToolMode implementation**: Tool-based structured output mode with caching and retry logic
- **OutputSchema resolution**: Centralized schema resolution utility with BASE_KEY constant
- **Structured output handler**: Comprehensive handler with logging, caching, and error handling

### Developer Experience
- **PydanticAI-style interface**: Familiar API pattern for structured output specification
- **Comprehensive documentation**: 400+ line README with examples, use cases, and best practices
- **Type safety**: Full typing support with proper generic types and validation
- **Streaming compatibility**: Works seamlessly with existing streaming functionality

### Tool Integration
- **Structured output tool**: Dedicated tool for handling structured output requests
- **Registry integration**: Enhanced tool registry to support structured output tools
- **Backward compatibility**: Maintains compatibility with existing tool ecosystem

## Technical Implementation

### Files Added
- `src/strands/output/`: Complete output module with base classes, modes, and utilities
- `src/strands/tools/structured_output/`: Dedicated structured output tool implementation
- `src/strands/types/output.py`: Type definitions for output system
- Comprehensive documentation and examples

### Files Modified
- Enhanced Agent class with structured_output_type parameter and default schema support
- Updated event loop for structured output processing and validation
- Improved AgentResult to include structured_output field
- Model provider updates for structured output compatibility

### Key Improvements
- **Error handling**: Robust error handling with fallback mechanisms
- **Performance**: Caching system for improved performance with repeated schema usage
- **Logging**: Enhanced logging for debugging and monitoring structured output operations
- **Code quality**: Comprehensive formatting, linting, and style improvements

## Usage Examples

python
# Basic structured output
from strands import Agent
from pydantic import BaseModel

class UserProfile(BaseModel):
   name: str
   age: int
   occupation: str

agent = Agent()
result = agent("Create a profile for John, 25, dentist", structured_output_type=UserProfile)
profile = result.structured_output  # Validated UserProfile instance


## Migration Notes
- Existing agents continue to work without changes
- New structured_output_type parameter is optional
- Legacy output modes are deprecated but still functional

Resolves: Multiple structured output related issues
Add explicit user message instructing the agent to format previous
response as structured output during forced structured output attempts.
@afarntrog afarntrog marked this pull request as ready for review September 30, 2025 13:59
@zastrowm zastrowm changed the title Strucuted output 891 pr Structured output Sep 30, 2025
@zastrowm

This comment was marked as resolved.

Replace StructuredOutputHandler with StructuredOutputContext to provide
better encapsulation and cleaner separation of concerns. This change:
- Introduces StructuredOutputContext to manage structured output state
- Updates Agent and event loop to use the new context-based approach
- Modifies tool executors to work with the context pattern
- Removes the handler-based implementation in favor of context
- Replace mode.get_tool_specs() calls with cached tool_specs property
- Improve code formatting and add trailing commas
Rename parameter throughout codebase for better clarity. This change improves API consistency and makes the parameter's purpose more explicit.
@afarntrog afarntrog changed the title Structured output feat: Add Structured Output as part of the agent loop Oct 1, 2025
Simplify output mode options by removing unused NativeMode and
PromptMode implementations, keeping only ToolMode for structured
output. This reduces complexity while maintaining full functionality
through the tool-based approach.
Copy link
Member

@dbschmigelski dbschmigelski left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.

@afarntrog afarntrog merged commit 648af22 into strands-agents:main Oct 22, 2025
14 of 15 checks passed
@afarntrog
Copy link
Contributor Author

#1026

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants