fix(types): implement custom serializer for Anthropic content blocks#1907
Open
golevishal wants to merge 1 commit intostrands-agents:mainfrom
Open
fix(types): implement custom serializer for Anthropic content blocks#1907golevishal wants to merge 1 commit intostrands-agents:mainfrom
golevishal wants to merge 1 commit intostrands-agents:mainfrom
Conversation
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.
Motivation
The Anthropic SDK v0.84.0 introduced
ParsedTextBlock, which causes Pydantic to emitPydanticSerializationUnexpectedValuewarnings whenevent.model_dump()is called during model stream processing. The previous workaround usingwarnings.catch_warnings()was overly broad and risked silencing other legitimate warnings.This PR implements a native serialization fix by applying a
PlainSerializerto the content field in src/strands/types/content.py and manually extracting fields in AnthropicModel to cleanly bypass Pydantic's core validation on problematic Anthropic-specific block variants.Resolves #1865
Public API Changes
No public API changes.
The internal serialization of
AnthropicModel.stream()and the Message TypedDict have been updated:Annotated[list[ContentBlock], PlainSerializer(...)]tostrands.types.content.Message.event.model_dump()within src/strands/models/anthropic.py using a custom _serialize_anthropic_event() helper function.Testing Validation
PydanticSerializationUnexpectedValuewarnings no longer appear without needing acatch_warningsblock.hatch test).hatch test tests/strands/models/specifically to ensure no side-effects impacted other model integrations (OpenAI, Gemini, etc.).Files Changed:
src/strands/models/anthropic.py