fix: prevent stream_async() from yielding non-serializable invocation_state fields#2066
Open
Zelys-DFKH wants to merge 1 commit intostrands-agents:mainfrom
Open
Conversation
ModelStreamEvent.prepare() merged the full invocation_state dict into the event dict before it was yielded to callers. Because invocation_state can contain non-JSON-serializable objects (Agent instance, OTel spans), those objects appeared in every streamed event, causing repr() serialization on the wire and hitting payload limits in runtimes like AgentCore. The fix snapshots the event data before prepare() is called and yields that snapshot instead of the merged dict. The callback_handler still receives the fully-merged dict for backward compatibility. Fixes strands-agents#1928
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
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
stream_async()yields each event dict directly after callingevent.prepare(invocation_state=...). Theprepare()method merges the fullinvocation_statemapping into the event dict, which includes non-serializable objects such as theAgentinstance, OTel span objects, message history, and the model object. Callers that attempt to serialize these events (for example, AgentCore's SSE stream) raiseTypeError: Object of type Agent is not JSON serializable.The fix snapshots
event.as_dict()beforeprepare()runs, so callers ofstream_async()only ever receive the serializable event fields. Thecallback_handlerstill receives the full merged dict (preserving existing behavior).Related Issues
Resolves #1928
Documentation PR
N/A
Type of Change
Bug fix
Testing
hatch run prepareChecklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.