Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions pydantic_ai_slim/pydantic_ai/models/anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ def _get_tools(self, model_request_parameters: ModelRequestParameters) -> list[B
tools += [self._map_tool_definition(r) for r in model_request_parameters.output_tools]
return tools

async def _map_message(self, messages: list[ModelMessage]) -> tuple[str, list[BetaMessageParam]]:
async def _map_message(self, messages: list[ModelMessage]) -> tuple[str, list[BetaMessageParam]]: # noqa: C901
"""Just maps a `pydantic_ai.Message` to a `anthropic.types.MessageParam`."""
system_prompt_parts: list[str] = []
anthropic_messages: list[BetaMessageParam] = []
Expand Down Expand Up @@ -322,7 +322,8 @@ async def _map_message(self, messages: list[ModelMessage]) -> tuple[str, list[Be
assistant_content_params: list[BetaTextBlockParam | BetaToolUseBlockParam] = []
for response_part in m.parts:
if isinstance(response_part, TextPart):
assistant_content_params.append(BetaTextBlockParam(text=response_part.content, type='text'))
if response_part.content: # Only add non-empty text
assistant_content_params.append(BetaTextBlockParam(text=response_part.content, type='text'))
else:
tool_use_block_param = BetaToolUseBlockParam(
id=_guard_tool_call_id(t=response_part),
Expand All @@ -331,7 +332,8 @@ async def _map_message(self, messages: list[ModelMessage]) -> tuple[str, list[Be
input=response_part.args_as_dict(),
)
assistant_content_params.append(tool_use_block_param)
anthropic_messages.append(BetaMessageParam(role='assistant', content=assistant_content_params))
if len(assistant_content_params) > 0:
anthropic_messages.append(BetaMessageParam(role='assistant', content=assistant_content_params))
else:
assert_never(m)
system_prompt = '\n\n'.join(system_prompt_parts)
Expand All @@ -344,11 +346,13 @@ async def _map_user_prompt(
part: UserPromptPart,
) -> AsyncGenerator[BetaContentBlockParam]:
if isinstance(part.content, str):
yield BetaTextBlockParam(text=part.content, type='text')
if part.content: # Only yield non-empty text
yield BetaTextBlockParam(text=part.content, type='text')
else:
for item in part.content:
if isinstance(item, str):
yield BetaTextBlockParam(text=item, type='text')
if item: # Only yield non-empty text
yield BetaTextBlockParam(text=item, type='text')
elif isinstance(item, BinaryContent):
if item.is_image:
yield BetaImageBlockParam(
Expand Down
50 changes: 50 additions & 0 deletions tests/models/test_anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1063,3 +1063,53 @@ async def test_anthropic_model_empty_message_on_history(allow_model_requests: No

What specifically would you like to know about potatoes?\
""")


async def test_anthropic_empty_content_filtering(env: TestEnv):
"""Test the empty content filtering logic directly."""

from pydantic_ai.messages import (
ModelMessage,
ModelRequest,
ModelResponse,
SystemPromptPart,
TextPart,
UserPromptPart,
)

# Initialize model for all tests
env.set('ANTHROPIC_API_KEY', 'test-key')
model = AnthropicModel('claude-3-5-sonnet-latest', provider='anthropic')

# Test _map_message with empty string in user prompt
messages_empty_string: list[ModelMessage] = [
ModelRequest(parts=[UserPromptPart(content='')], kind='request'),
]
_, anthropic_messages = await model._map_message(messages_empty_string) # type: ignore[attr-defined]
assert anthropic_messages == snapshot([]) # Empty content should be filtered out

# Test _map_message with list containing empty strings in user prompt
messages_mixed_content: list[ModelMessage] = [
ModelRequest(parts=[UserPromptPart(content=['', 'Hello', '', 'World'])], kind='request'),
]
_, anthropic_messages = await model._map_message(messages_mixed_content) # type: ignore[attr-defined]
assert anthropic_messages == snapshot(
[{'role': 'user', 'content': [{'text': 'Hello', 'type': 'text'}, {'text': 'World', 'type': 'text'}]}]
)

# Test _map_message with empty assistant response
messages: list[ModelMessage] = [
ModelRequest(parts=[SystemPromptPart(content='You are helpful')], kind='request'),
ModelResponse(parts=[TextPart(content='')], kind='response'), # Empty response
ModelRequest(parts=[UserPromptPart(content='Hello')], kind='request'),
]
_, anthropic_messages = await model._map_message(messages) # type: ignore[attr-defined]
# The empty assistant message should be filtered out
assert anthropic_messages == snapshot([{'role': 'user', 'content': [{'text': 'Hello', 'type': 'text'}]}])

# Test with only empty assistant parts
messages_resp: list[ModelMessage] = [
ModelResponse(parts=[TextPart(content=''), TextPart(content='')], kind='response'),
]
_, anthropic_messages = await model._map_message(messages_resp) # type: ignore[attr-defined]
assert len(anthropic_messages) == 0 # No messages should be added