feat: add max_retries parameter to structured_output for self-healing #1026
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.
Fixes #1014
Description
This PR adds a
max_retries
parameter to thestructured_output()
andstructured_output_async()
methods to enable automatic self-healing retry attempts when validation errors occur.When
max_retries > 0
, the agent will automatically retry structured output generation if it encounters aValidationError
orValueError
. On each retry, the error message is appended to the temporary messages (not conversation history) so the model can self-correct based on what went wrong.Key changes:
max_retries: int = 0
parameter (default maintains backwards compatibility)ValidationError
andValueError
Related Issues
Fixes #1014
Documentation PR
No documentation PR needed at this time. The feature is self-explanatory through docstrings and follows existing patterns.
Type of Change
New feature
Testing
All tests pass successfully:
Added 3 new tests specifically for retry functionality:
test_agent_structured_output_with_retry_on_validation_error()
- validates retry on ValidationErrortest_agent_structured_output_with_retry_on_value_error()
- validates retry on ValueErrortest_agent_structured_output_retry_exhausted()
- validates exception raised after exhausting retriesUpdated existing test to expect new telemetry attribute
All 1136 tests pass (including 39 structured_output tests across the codebase)
No warnings introduced
I ran
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.