@@ -310,7 +310,19 @@ async def process_single_turn_with_tools(
310
310
# Process tool calls one by one
311
311
for tool_call in final_tool_calls .values ():
312
312
function_name = tool_call .function .name
313
- function_args = json .loads (tool_call .function .arguments or "{}" )
313
+ try :
314
+ function_args = json .loads (tool_call .function .arguments or "{}" )
315
+ except json .JSONDecodeError as err :
316
+ tool_message = {
317
+ "role" : "tool" ,
318
+ "tool_call_id" : tool_call .id ,
319
+ "name" : function_name ,
320
+ "content" : f"Invalid JSON generated by the model: { err } " ,
321
+ }
322
+ tool_message_as_obj = ChatCompletionInputMessage .parse_obj_as_instance (tool_message )
323
+ messages .append (tool_message_as_obj )
324
+ yield tool_message_as_obj
325
+ continue # move to next tool call
314
326
315
327
tool_message = {"role" : "tool" , "tool_call_id" : tool_call .id , "content" : "" , "name" : function_name }
316
328
@@ -324,11 +336,13 @@ async def process_single_turn_with_tools(
324
336
# Execute tool call with the appropriate session
325
337
session = self .sessions .get (function_name )
326
338
if session is not None :
327
- result = await session .call_tool (function_name , function_args )
328
- tool_message ["content" ] = format_result (result )
339
+ try :
340
+ result = await session .call_tool (function_name , function_args )
341
+ tool_message ["content" ] = format_result (result )
342
+ except Exception as err :
343
+ tool_message ["content" ] = f"Error: MCP tool call failed with error message: { err } "
329
344
else :
330
- error_msg = f"Error: No session found for tool: { function_name } "
331
- tool_message ["content" ] = error_msg
345
+ tool_message ["content" ] = f"Error: No session found for tool: { function_name } "
332
346
333
347
# Yield tool message
334
348
tool_message_as_obj = ChatCompletionInputMessage .parse_obj_as_instance (tool_message )
0 commit comments