Fix custom state schema fields not accessible in middleware #34164
+158
−2
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.
Problem
Fixes #34156
When users provide a custom
state_schematocreate_agent()with additional fields that have default values (e.g.,requirements_gathered: bool = False), those fields raise aKeyErrorwhen accessed in middleware. This happens because TypedDict class attributes with default values are only type hints - they don't automatically populate runtime dictionaries.Before
Error
Solution
Extract default values from the state schema class and merge them with the runtime state before passing to middleware. This ensures custom fields are always accessible, even when not explicitly provided in the input.
Changes
_get_state_defaults()helper function - Extracts default values from state schema class by inspecting class attributes across the inheritance chainmodel_node()andamodel_node()- Merge state defaults with runtime state before creatingModelRequestAfter
Testing
Added comprehensive test coverage in
test_custom_state_schema.py:Backward Compatibility
state_schemais provided with default values