Execute a batch of tool calls and append results to messages.
(
self,
tool_manager: Any,
tool_calls: list[Any],
messages: list[dict[str, Any]],
raw: bool,
)
| 397 | return response_text |
| 398 | |
| 399 | async def _execute_tool_call_batch( |
| 400 | self, |
| 401 | tool_manager: Any, |
| 402 | tool_calls: list[Any], |
| 403 | messages: list[dict[str, Any]], |
| 404 | raw: bool, |
| 405 | ) -> None: |
| 406 | """Execute a batch of tool calls and append results to messages.""" |
| 407 | for tool_call in tool_calls: |
| 408 | tool_name, tool_args_str, tool_call_id = _parse_tool_call(tool_call) |
| 409 | |
| 410 | try: |
| 411 | tool_args = ( |
| 412 | json.loads(tool_args_str) |
| 413 | if isinstance(tool_args_str, str) |
| 414 | else tool_args_str |
| 415 | ) |
| 416 | except json.JSONDecodeError: |
| 417 | messages.append({ |
| 418 | "role": "tool", |
| 419 | "tool_call_id": tool_call_id, |
| 420 | "name": tool_name, |
| 421 | "content": f"Error: Invalid JSON in tool arguments: {tool_args_str}", |
| 422 | }) |
| 423 | continue |
| 424 | |
| 425 | if not raw: |
| 426 | output.info(f"Executing tool: {tool_name}") |
| 427 | |
| 428 | try: |
| 429 | result = await tool_manager.execute_tool(tool_name, tool_args) |
| 430 | if result.success: |
| 431 | result_data = to_serializable( |
| 432 | unwrap_tool_result(result.result) |
| 433 | ) |
| 434 | else: |
| 435 | result_data = f"Error: {result.error}" |
| 436 | result_str = ( |
| 437 | json.dumps(result_data) |
| 438 | if not isinstance(result_data, str) |
| 439 | else result_data |
| 440 | ) |
| 441 | messages.append({ |
| 442 | "role": "tool", |
| 443 | "tool_call_id": tool_call_id, |
| 444 | "name": tool_name, |
| 445 | "content": result_str, |
| 446 | }) |
| 447 | except Exception as e: |
| 448 | output.error(f"Tool execution failed: {e}") |
| 449 | messages.append({ |
| 450 | "role": "tool", |
| 451 | "tool_call_id": tool_call_id, |
| 452 | "name": tool_name, |
| 453 | "content": f"Error: {e}", |
| 454 | }) |
| 455 | |
| 456 |