generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 449
feat: Add Structured Output as part of the agent loop #943
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
afarntrog
merged 41 commits into
strands-agents:main
from
afarntrog:strucuted_output_891_pr
Oct 22, 2025
Merged
feat: Add Structured Output as part of the agent loop #943
afarntrog
merged 41 commits into
strands-agents:main
from
afarntrog:strucuted_output_891_pr
Oct 22, 2025
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
zastrowm
requested changes
Sep 30, 2025
This comment was marked as resolved.
This comment was marked as resolved.
Unshure
reviewed
Sep 30, 2025
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.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
.
awsarron
approved these changes
Oct 22, 2025
dbschmigelski
approved these changes
Oct 22, 2025
This was referenced Oct 23, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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_modelfield, 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 theAgentResultobject. Callers can use different pydantic models per invocation, or the same, or for some invocations usestructured_output_modeland for others ignore it.Examples
Structured Output on the agent invocation
Structured Output when initializing the agent
See the README.md for more examples.
Key Features:
•
structured_output_modelparameter 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_modelis the parameter name we agreed toStructuredOutputEventwe added a new Typed Event calledStructuredOutputEventOpen questions:
gettextbut that would be hard to scaleRelated 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.