Skip to content

fix(types): implement custom serializer for Anthropic content blocks#1907

Open
golevishal wants to merge 1 commit intostrands-agents:mainfrom
golevishal:fix-anthropic-serialization
Open

fix(types): implement custom serializer for Anthropic content blocks#1907
golevishal wants to merge 1 commit intostrands-agents:mainfrom
golevishal:fix-anthropic-serialization

Conversation

@golevishal
Copy link

Motivation

The Anthropic SDK v0.84.0 introduced ParsedTextBlock, which causes Pydantic to emit PydanticSerializationUnexpectedValue warnings when event.model_dump() is called during model stream processing. The previous workaround using warnings.catch_warnings() was overly broad and risked silencing other legitimate warnings.

This PR implements a native serialization fix by applying a PlainSerializer to 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:

  • Added Annotated[list[ContentBlock], PlainSerializer(...)] to strands.types.content.Message.
  • Intercepted event.model_dump() within src/strands/models/anthropic.py using a custom _serialize_anthropic_event() helper function.

Testing Validation

  • Verified that the PydanticSerializationUnexpectedValue warnings no longer appear without needing a catch_warnings block.
  • Confirmed that 2375 tests passed perfectly across the full internal test suite (hatch test).
  • Ran hatch test tests/strands/models/ specifically to ensure no side-effects impacted other model integrations (OpenAI, Gemini, etc.).

Files Changed:

  • src/strands/types/content.py
  • src/strands/models/anthropic.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Strands Agent AnthropicModel emits Pydantic serialization warnings with Anthropic SDK v0.84.0

1 participant