Skip to content

Commit 17839aa

Browse files
authored
Fix BedrockConverseModel error when ModelResponse.parts is empty (#3689)
1 parent bf57565 commit 17839aa

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

pydantic_ai_slim/pydantic_ai/models/bedrock.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -584,7 +584,8 @@ async def _map_messages( # noqa: C901
584584
else:
585585
assert isinstance(item, ToolCallPart)
586586
content.append(self._map_tool_call(item))
587-
bedrock_messages.append({'role': 'assistant', 'content': content})
587+
if content:
588+
bedrock_messages.append({'role': 'assistant', 'content': content})
588589
else:
589590
assert_never(message)
590591

tests/models/test_bedrock.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1624,3 +1624,33 @@ async def test_cache_point_filtering():
16241624
# CachePoint should be filtered out, message should still be valid
16251625
assert len(messages) == 1
16261626
assert messages[0]['role'] == 'user'
1627+
1628+
1629+
async def test_bedrock_empty_model_response_skipped(bedrock_provider: BedrockProvider):
1630+
"""Test that ModelResponse with empty parts (e.g. content_filtered) is skipped in message mapping."""
1631+
model = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
1632+
1633+
# Create a message history that includes a ModelResponse with empty parts
1634+
req = [
1635+
ModelRequest(parts=[UserPromptPart(content='Hello')]),
1636+
ModelResponse(
1637+
parts=[],
1638+
usage=RequestUsage(input_tokens=100, output_tokens=1),
1639+
model_name='us.amazon.nova-micro-v1:0',
1640+
provider_name='bedrock',
1641+
provider_details={'finish_reason': 'content_filtered'},
1642+
finish_reason='content_filter',
1643+
),
1644+
ModelRequest(parts=[UserPromptPart(content='Follow up question')]),
1645+
]
1646+
1647+
# Call the mapping function directly
1648+
_, bedrock_messages = await model._map_messages(req, ModelRequestParameters()) # type: ignore[reportPrivateUsage]
1649+
1650+
# The empty ModelResponse should be skipped, so we should only have 2 user messages
1651+
# that get merged into one since they're consecutive after the empty response is skipped
1652+
assert bedrock_messages == snapshot(
1653+
[
1654+
{'role': 'user', 'content': [{'text': 'Hello'}, {'text': 'Follow up question'}]},
1655+
]
1656+
)

0 commit comments

Comments
 (0)