Skip to content

fix(anthropic): avoid Pydantic warnings for message_stop events#2044

Open
opieter-aws wants to merge 4 commits intomainfrom
agent-tasks/1746
Open

fix(anthropic): avoid Pydantic warnings for message_stop events#2044
opieter-aws wants to merge 4 commits intomainfrom
agent-tasks/1746

Conversation

@opieter-aws
Copy link
Copy Markdown

Motivation

When using AnthropicModel, Pydantic emits PydanticSerializationUnexpectedValue warnings when the Anthropic SDK returns ParsedTextBlock objects in the message content during message_stop events. This is because ParsedTextBlock is a Pydantic BaseModel that cannot be cleanly serialized against the TypedDict union variants in the ContentBlock type.

The warnings do not break functionality but create noise in user applications and may mask other legitimate warnings.

Resolves #1746

Public API Changes

No public API changes.

Technical Approach

Instead of suppressing warnings with warnings=False, this fix addresses the root cause by avoiding unnecessary serialization entirely. For message_stop events, we build the dict directly from event.message.stop_reason instead of calling event.model_dump(), since format_chunk only needs the stop_reason field for this event type.

# Before (causes warnings - serializes entire message including content)
async for event in stream:
    if event.type in AnthropicModel.EVENT_TYPES:
        yield self.format_chunk(event.model_dump())

# After (fixes root cause - only extracts what we need)
async for event in stream:
    if event.type in AnthropicModel.EVENT_TYPES:
        if event.type == "message_stop":
            yield self.format_chunk({
                "type": "message_stop",
                "message": {"stop_reason": event.message.stop_reason},
            })
        else:
            yield self.format_chunk(event.model_dump())

This approach is cleaner than warning suppression because it:

  • Fixes the actual problem rather than hiding it
  • Avoids masking other legitimate Pydantic warnings
  • Is more efficient (less data serialized)
  • Makes the code explicit about what data is needed

For message_stop events, build the event dict directly from
event.message.stop_reason instead of calling model_dump() which
serializes the entire message including ParsedTextBlock objects
that cause PydanticSerializationUnexpectedValue warnings.

Resolves #1746
@codecov
Copy link
Copy Markdown

codecov bot commented Apr 3, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

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] PydanticSerializationUnexpectedValue warnings when Anthropic SDK returns ParsedTextBlock in message content

3 participants