@@ -276,7 +276,7 @@ def _get_tools(self, model_request_parameters: ModelRequestParameters) -> list[B
276
276
tools += [self ._map_tool_definition (r ) for r in model_request_parameters .output_tools ]
277
277
return tools
278
278
279
- async def _map_message (self , messages : list [ModelMessage ]) -> tuple [str , list [BetaMessageParam ]]:
279
+ async def _map_message (self , messages : list [ModelMessage ]) -> tuple [str , list [BetaMessageParam ]]: # noqa: C901
280
280
"""Just maps a `pydantic_ai.Message` to a `anthropic.types.MessageParam`."""
281
281
system_prompt_parts : list [str ] = []
282
282
anthropic_messages : list [BetaMessageParam ] = []
@@ -315,7 +315,8 @@ async def _map_message(self, messages: list[ModelMessage]) -> tuple[str, list[Be
315
315
assistant_content_params : list [BetaTextBlockParam | BetaToolUseBlockParam ] = []
316
316
for response_part in m .parts :
317
317
if isinstance (response_part , TextPart ):
318
- assistant_content_params .append (BetaTextBlockParam (text = response_part .content , type = 'text' ))
318
+ if response_part .content : # Only add non-empty text
319
+ assistant_content_params .append (BetaTextBlockParam (text = response_part .content , type = 'text' ))
319
320
else :
320
321
tool_use_block_param = BetaToolUseBlockParam (
321
322
id = _guard_tool_call_id (t = response_part ),
@@ -324,7 +325,8 @@ async def _map_message(self, messages: list[ModelMessage]) -> tuple[str, list[Be
324
325
input = response_part .args_as_dict (),
325
326
)
326
327
assistant_content_params .append (tool_use_block_param )
327
- anthropic_messages .append (BetaMessageParam (role = 'assistant' , content = assistant_content_params ))
328
+ if len (assistant_content_params ) > 0 :
329
+ anthropic_messages .append (BetaMessageParam (role = 'assistant' , content = assistant_content_params ))
328
330
else :
329
331
assert_never (m )
330
332
system_prompt = '\n \n ' .join (system_prompt_parts )
@@ -337,11 +339,13 @@ async def _map_user_prompt(
337
339
part : UserPromptPart ,
338
340
) -> AsyncGenerator [BetaContentBlockParam ]:
339
341
if isinstance (part .content , str ):
340
- yield BetaTextBlockParam (text = part .content , type = 'text' )
342
+ if part .content : # Only yield non-empty text
343
+ yield BetaTextBlockParam (text = part .content , type = 'text' )
341
344
else :
342
345
for item in part .content :
343
346
if isinstance (item , str ):
344
- yield BetaTextBlockParam (text = item , type = 'text' )
347
+ if item : # Only yield non-empty text
348
+ yield BetaTextBlockParam (text = item , type = 'text' )
345
349
elif isinstance (item , BinaryContent ):
346
350
if item .is_image :
347
351
yield BetaImageBlockParam (
0 commit comments