Repository navigation
Carry image, document and redacted reasoning bytes across the Strands model and MCP activities - #150
Conversation
… model activity Strands content blocks hold raw bytes in image and document sources and in reasoningContent.redactedContent. The JSON payload converter fails on non-UTF-8 bytes and turns ASCII bytes into str, so a prompt with an image never reached the model and a redacted reasoning block made invoke_model fail on every attempt. The activity input tags bytes in the messages as base64 with Strands' encode_bytes_values and the worker restores them before calling the model. Stream events are returned and published in the same form and restored in TemporalModel.stream. Messages without bytes encode to the same JSON as before.
An MCP tool that returns an image produces a ToolResult holding raw bytes, which the call-tool activity could not serialize. The activity failed after the tool had run, so every retry ran the tool again. The result is tagged as base64 in the activity and restored in TemporalMCPTool.
brianstrauch
left a comment
There was a problem hiding this comment.
Two correctness issues reproduced during review. make lint passes and all 62 existing tests pass; the inline comments describe cases outside that coverage.
|
|
||
| def decode_event(event: dict[str, Any]) -> StreamEvent: | ||
| """Restore the ``bytes`` that ``invoke_model`` tagged in a returned stream event.""" | ||
| return decode_bytes_values(event) # type: ignore[no-any-return] |
There was a problem hiding this comment.
[P1] Preserve decoding of previously recorded reasoning bytes
Changing the activity return type from list[StreamEvent] to list[dict[str, Any]] changes how existing activity results decode. On the base commit, UTF-8 redactedContent bytes serialize as JSON strings and the StreamEvent type hint restores them to bytes. With this change, those old untagged values remain strings, and decode_bytes_values leaves them unchanged. I recorded a successful workflow on base commit 5e91c26 with redactedContent=b"ASCII-redacted": its history replays successfully on the base version but fails on this PR with TypeError: can't concat str to bytes in Strands' handle_content_block_delta. Existing workflows with such results will fail workflow tasks after upgrading. Please preserve legacy redactedContent decoding after restoring tagged values and add a replay regression using a history recorded before this change.
| def _stream(model: Model, input: _InvokeModelInput) -> AsyncIterable[StreamEvent]: | ||
| return model.stream( | ||
| input.messages, | ||
| decode_bytes_values(input.messages), |
There was a problem hiding this comment.
[P2] Avoid interpreting ordinary tool JSON as encoded bytes
decode_bytes_values interprets any dictionary containing __bytes_encoded__: true and data as binary, including arbitrary JSON under toolUse.input or toolResult.content[].json. encode_bytes_values does not escape ordinary dictionaries with those keys, so this is not a lossless round trip. Through the plugin converter and a real ModelActivity, I verified that {"__bytes_encoded__": true, "data": "SGVsbG8=", "other": "retained"} reaches the model as b"Hello", discarding the other field; making data a JSON object instead raises TypeError before the model runs. The new decoder in TemporalMCPTool.stream has the same problem for MCP structured content and metadata. Please escape colliding dictionaries or restrict decoding to binary content fields, with coverage for ordinary JSON matching the marker.
…alues The previous change walked every dict with Strands' decode_bytes_values, so ordinary JSON shaped like its marker (a tool input, a tool result json block, MCP structured content or metadata) was turned into bytes, lost its other keys, or raised on a non-string data value. Bytes are now tagged and restored only at the fields Strands types as bytes: the source of image, document, video and audio blocks, tool result content, and reasoningContent.redactedContent. Everything else reaches the model and the agent unchanged. The model activity input, its stream events, the streaming topic and the MCP call-tool result all use the same helpers in _bytes_values. Changing invoke_model to return plain dicts also stopped the StreamEvent type hint from restoring redactedContent in results recorded before the change, so replaying them raised TypeError in Strands. A value in a bytes field that is a string (pydantic converter) or a list of ints (default converter) now decodes to bytes, which is what the type hint did. The same applies to image bytes in recorded MCP results. Tests replay four histories recorded on 5e91c26, cover marker-shaped JSON in the model input, the stream events and an MCP result, and check each bytes field round trips.
brianstrauch
left a comment
There was a problem hiding this comment.
The two earlier findings are addressed. One remaining streaming issue reproduced with both supported data converters; make lint and all 101 PR tests pass.
| encoded = encode_event(event) | ||
| events.append(encoded) | ||
| topic.publish(encoded) |
There was a problem hiding this comment.
[P2] Preserve typed stream subscriptions
Publishing the tagged event breaks the README's WorkflowStreamClient.subscribe(..., result_type=StreamEvent) when a model emits redactedContent: StreamEvent requires bytes | None there, but now receives a marker dictionary. I reproduced this against a local Temporal server by running the new streaming-bytes test with result_type=StreamEvent: the default converter raises TypeError, and the plugin's Pydantic converter raises ValidationError, so the subscription stops before receiving the remaining events. The new test uses dict[str, Any], which bypasses this failure. Please preserve decoding for typed stream subscribers and add coverage using the documented subscription type.
…bscribers read The streaming activity published the base64-tagged event, which a subscriber typed with StreamEvent, as the README documents, cannot validate: redactedContent must be bytes and arrived as a marker dictionary, so the default converter raised TypeError and the Pydantic converter ValidationError, and the subscription ended before the remaining events. The topic now carries the event as the payload converter writes it, as it did before the tagging, so typed and untyped subscribers see what they saw then. The activity result the workflow decodes stays tagged. bytes that the converter cannot write (non-UTF-8 under the Pydantic converter, which a StreamEvent subscriber could not read back either) are published as b"" in redactedContent instead of failing the activity or ending the subscription. The default converter carries any bytes, so its subscribers get them intact. The README says so. Tests subscribe with result_type=StreamEvent, dict[str, Any] and no type under both converters, for UTF-8 and non-UTF-8 redactedContent and for events without bytes.
What was changed
_InvokeModelInputtags everybytesvalue inmessagesas base64 with Strands'encode_bytes_valueswhen it is built (__post_init__, so the streaming subclass gets it too), andModelActivityrestores them before callingModel.stream.invoke_modelandinvoke_model_streamingreturn their stream events in the same tagged form,TemporalModel.streamrestores them, and the streaming activity publishes the tagged events to the WorkflowStream topic. The activities' return type is nowlist[dict[str, Any]]instead oflist[StreamEvent]: the JSON on the wire is unchanged, but the tagged form would not validate as aStreamEvent(redactedContentisbytes).{server}-call-toolactivity tags thebytesin the MCP tool result (images) andTemporalMCPToolrestores them before handing the result to Strands.Why?
A prompt with an image failed the workflow task on every attempt, an ASCII-only document reached the model as
str, aredactedContentblock in the reply madeinvoke_modelfail on every attempt, and an MCP tool that returns an image was re-run on every retry because its result could not be recorded. Details and a repro in the issue.Checklist
Closes [Bug] strands_agents: images, documents and redactedContent bytes cannot cross the model activity, and an MCP image result re-runs the tool on every retry #149
How was this tested:
New tests in
tests/test_model_bytes.pyandtests/test_mcp_image.py. Round trips through the plugin's payload converter and a realModelActivityrun for an image block, a document block (ASCII bytes, which used to come back asstr) andredactedContentas input, and forredactedContentin the activity result; text-only messages encode to the same JSON as before; the caller's messages are not modified. Workflow tests send an image and a document, getredactedContentback, and send the whole history back on a second turn (the model sees the same bytes, the workflow holdsbytes), with and withoutstreaming_topic(subscribers get the tagged events), each replayed withReplayer. One workflow test runs an MCP image tool with the plugin on the Client and a 3-attempt retry policy: the tool runs once, and the workflow and the model both get the PNG. Onmain(install rebuilt withmake syncand checked against the source) 9 of the 10 new tests fail (the 10th checks that text-only messages are unchanged) and the MCP tool runs 3 times; with the changemake lintis clean andmake testpasses (62, 10 of them new). A workflow history recorded onmainwith an ASCII csv document replays on the new code. Not run against a real Bedrock or vision model.Any docs updates needed?
No. The README does not mention image or document content.