Skip to content

Don't send whitespace-only assistant message back to Bedrock #1710

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
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
24 changes: 17 additions & 7 deletions pydantic_ai_slim/pydantic_ai/models/bedrock.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,22 @@ def _map_inference_config(

return inference_config

def _map_model_response(self, message: ModelResponse) -> list[ContentBlockOutputTypeDef]:
"""Maps a `pydantic_ai.ModelResponse` to the Bedrock `ContentBlockOutputTypeDef`.

This is used to map the model response to the Bedrock format.
"""
content: list[ContentBlockOutputTypeDef] = []
for item in message.parts:
if isinstance(item, TextPart):
if not item.content.strip():
continue
content.append({'text': item.content})
else:
assert isinstance(item, ToolCallPart)
content.append(self._map_tool_call(item))
return content

async def _map_messages(
self, messages: list[ModelMessage]
) -> tuple[list[SystemContentBlockTypeDef], list[MessageUnionTypeDef]]:
Expand Down Expand Up @@ -420,13 +436,7 @@ async def _map_messages(
}
)
elif isinstance(message, ModelResponse):
content: list[ContentBlockOutputTypeDef] = []
for item in message.parts:
if isinstance(item, TextPart):
content.append({'text': item.content})
else:
assert isinstance(item, ToolCallPart)
content.append(self._map_tool_call(item))
content: list[ContentBlockOutputTypeDef] = self._map_model_response(message)
bedrock_messages.append({'role': 'assistant', 'content': content})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's now possible for content to be an empty list, in which case we should not append message at all, right?

else:
assert_never(message)
Expand Down
57 changes: 57 additions & 0 deletions tests/models/test_bedrock.py
Original file line number Diff line number Diff line change
Expand Up @@ -629,3 +629,60 @@ async def test_bedrock_group_consecutive_tool_return_parts(bedrock_provider: Bed
},
]
)


async def test_bedrock_handles_empty_content_blocks(bedrock_provider: BedrockProvider):
"""
Test that the Bedrock provider correctly handles empty content blocks without errors.
This test verifies that empty content in UserPromptPart, TextPart, and ToolReturnPart
are processed properly without causing issues.
"""
model = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
now = datetime.datetime.now()

req = [
ModelRequest(parts=[UserPromptPart(content=['Please use the tool'])]),
ModelResponse(
parts=[
TextPart(content=""" """),
ToolCallPart(
tool_name='normal_tool',
args={'param': 'value'},
tool_call_id='normal1',
),
]
),
ModelRequest(
parts=[
ToolReturnPart(tool_name='normal_tool', content='result', tool_call_id='normal1', timestamp=now),
]
),
]

_, bedrock_messages = await model._map_messages(req) # type: ignore[reportPrivateUsage]

assert bedrock_messages == snapshot(
[
{'role': 'user', 'content': [{'text': 'Please use the tool'}]},
{
'role': 'assistant',
'content': [
{
'toolUse': {
'input': {
'param': 'value',
},
'name': 'normal_tool',
'toolUseId': 'normal1',
},
},
],
},
{
'role': 'user',
'content': [
{'toolResult': {'toolUseId': 'normal1', 'content': [{'text': 'result'}], 'status': 'success'}}
],
},
]
)