1
1
import asyncio
2
+ import uuid
2
3
from collections .abc import AsyncGenerator , AsyncIterator , Callable
3
4
from contextlib import suppress
4
5
from copy import deepcopy
@@ -185,6 +186,7 @@ def __init__(
185
186
default_options: The default options for the agent run.
186
187
"""
187
188
super ().__init__ (default_options )
189
+ self .id = uuid .uuid4 ().hex [:8 ]
188
190
self .llm = llm
189
191
self .prompt = prompt
190
192
self .tools = [Tool .from_callable (tool ) for tool in tools or []]
@@ -493,9 +495,8 @@ async def _get_all_tools(self) -> dict[str, Tool]:
493
495
494
496
return tools_mapping
495
497
496
- @staticmethod
497
498
async def _execute_tool (
498
- tool_call : ToolCall , tools_mapping : dict [str , Tool ], context : AgentRunContext | None = None
499
+ self , tool_call : ToolCall , tools_mapping : dict [str , Tool ], context : AgentRunContext | None = None
499
500
) -> ToolCallResult :
500
501
if tool_call .type != "function" :
501
502
raise AgentToolNotSupportedError (tool_call .type )
@@ -505,18 +506,28 @@ async def _execute_tool(
505
506
506
507
tool = tools_mapping [tool_call .name ]
507
508
508
- try :
509
- call_args = tool_call .arguments .copy ()
510
- if tool .context_var_name :
511
- call_args [tool .context_var_name ] = context
512
-
513
- tool_output = (
514
- await tool .on_tool_call (** call_args )
515
- if iscoroutinefunction (tool .on_tool_call )
516
- else tool .on_tool_call (** call_args )
517
- )
518
- except Exception as e :
519
- raise AgentToolExecutionError (tool_call .name , e ) from e
509
+ with trace (agent_id = self .id , tool_name = tool_call .name , tool_arguments = tool_call .arguments ) as outputs :
510
+ try :
511
+ call_args = tool_call .arguments .copy ()
512
+ if tool .context_var_name :
513
+ call_args [tool .context_var_name ] = context
514
+
515
+ tool_output = (
516
+ await tool .on_tool_call (** call_args )
517
+ if iscoroutinefunction (tool .on_tool_call )
518
+ else tool .on_tool_call (** call_args )
519
+ )
520
+
521
+ outputs .result = {
522
+ "tool_output" : tool_output ,
523
+ "tool_call_id" : tool_call .id ,
524
+ }
525
+ except Exception as e :
526
+ outputs .result = {
527
+ "error" : str (e ),
528
+ "tool_call_id" : tool_call .id ,
529
+ }
530
+ raise AgentToolExecutionError (tool_call .name , e ) from e
520
531
521
532
return ToolCallResult (
522
533
id = tool_call .id ,
0 commit comments