feat(agent): make structured output part of the agent loop #670
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
Title:
feat: Enable agent loop retry mechanism for structured output extraction
Description:
Summary
Modifies the
structured_output_async
method to leverage the agent's event loop retry mechanism, allowing the model toattempt structured data extraction multiple times until successful. Previously, the method used direct model inference
without retry capabilities.
Key Change: Agent Loop Integration
Before: Direct model call → single attempt → return or fail
Why This Matters
Implementation Approach
Behavioral Improvements
Example Scenario
Agent may now iterate like this internally:
1st attempt: Model provides incomplete data → validation fails → retry
2nd attempt: Model uses tools to gather missing info → validation fails → retry
3rd attempt: Model provides complete valid data → success!
profile = await agent.structured_output_async(UserProfile, prompt) -- Returns validated result after however many attempts needed
Files Modified
Backward Compatibility
Hybrid Approach: Structured output now attempts tool-based execution first, then falls back to the original
model.structured_output() method for backward compatibility
output execution modifies conversation history
Implementation Details:
Test Updates:
preserve_conversation=False
Backward Compatibility: All existing structured output functionality preserved while adding new tool-based capabilities
for future extensibility.
Function signature unchanged - existing code continues to work
Return type unchanged - still returns validated Pydantic models
Error handling improved - more robust failure modes
Related Issues
#348
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
hatch run prepare
Checklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.