@@ -268,19 +268,29 @@ def _parse_tools_from_response(self, response):
268
268
:rtype: List[dict]
269
269
"""
270
270
tool_calls = []
271
- tool_results = []
271
+ tool_results_map = {}
272
272
if isinstance (response , list ):
273
- for message in response :
274
- if message .get ("role" ) == "assistant" :
275
- tool_calls .extend ([content for content in message .get ("content" )
276
- if content .get ("type" ) == "tool_call" ])
277
- tool_results .extend ([content for content in message .get ("content" )
278
- if content .get ("type" ) == "tool_result" ])
279
- # Format the tool calls and results
280
- for i in range (min (len (tool_calls ), len (tool_results ))):
281
- if isinstance (tool_calls [i ], dict ) and tool_calls [i ].get ("type" ) == "tool_call" :
282
- if tool_results [i ]["tool_call_id" ] == tool_calls [i ]["tool_call_id" ]:
283
- tool_calls [i ]["tool_result" ] = tool_results [i ]
273
+ for message in response :
274
+ print (message )
275
+ # Extract tool calls from assistant messages
276
+ if message .get ("role" ) == "assistant" and isinstance (message .get ("content" ), list ):
277
+ for content_item in message .get ("content" ):
278
+ if isinstance (content_item , dict ) and content_item .get ("type" ) == "tool_call" :
279
+ tool_calls .append (content_item )
280
+
281
+ # Extract tool results from tool messages
282
+ elif message .get ("role" ) == "tool" and message .get ("tool_call_id" ):
283
+ tool_call_id = message .get ("tool_call_id" )
284
+ if isinstance (message .get ("content" ), list ) and len (message .get ("content" )) > 0 :
285
+ result_content = message .get ("content" )[0 ]
286
+ if isinstance (result_content , dict ) and result_content .get ("type" ) == "tool_result" :
287
+ tool_results_map [tool_call_id ] = result_content
288
+
289
+ # Attach results to their corresponding calls
290
+ for tool_call in tool_calls :
291
+ tool_call_id = tool_call .get ("tool_call_id" )
292
+ if tool_call_id in tool_results_map :
293
+ tool_call ["tool_result" ] = tool_results_map [tool_call_id ]['tool_result' ]
284
294
285
295
return tool_calls
286
296
@@ -297,7 +307,9 @@ def _extract_needed_tool_definitions(self, tool_calls, tool_definitions):
297
307
for tool_call in tool_calls :
298
308
if isinstance (tool_call , dict ) and tool_call .get ("type" ) == "tool_call" :
299
309
tool_name = tool_call .get ("name" )
300
- tool_definition = [tool for tool in tool_definitions if tool .get ("name" ) == tool_name and tool .get ("type" , "function" ) == "function" ]
310
+ tool_definition = [tool for tool in tool_definitions
311
+ if tool .get ("name" ) == tool_name and
312
+ tool .get ("type" , "function" ) == "function" ]
301
313
if len (tool_definition ) > 0 :
302
314
needed_tool_definitions .extend (tool_definition )
303
315
else :
0 commit comments