From 976e9273b27eedb01c2c43b6bea2597ec4dd54b7 Mon Sep 17 00:00:00 2001 From: Marjan Ahmed Date: Sat, 25 Oct 2025 16:12:22 +0500 Subject: [PATCH] expose tool call id lifecyle hooks --- examples/basic/lifecycle_example.py | 25 +++++++++++++++++++------ tests/test_tool_call_id_in_hooks.py | 0 2 files changed, 19 insertions(+), 6 deletions(-) create mode 100644 tests/test_tool_call_id_in_hooks.py diff --git a/examples/basic/lifecycle_example.py b/examples/basic/lifecycle_example.py index 874ff629b..f85dedd22 100644 --- a/examples/basic/lifecycle_example.py +++ b/examples/basic/lifecycle_example.py @@ -15,6 +15,7 @@ function_tool, ) from agents.items import ModelResponse, TResponseInputItem +from agents.tool_context import ToolContext class LoggingHooks(AgentHooks[Any]): @@ -71,17 +72,29 @@ async def on_agent_end(self, context: RunContextWrapper, agent: Agent, output: A async def on_tool_start(self, context: RunContextWrapper, agent: Agent, tool: Tool) -> None: self.event_counter += 1 - print( - f"### {self.event_counter}: Tool {tool.name} started. name={context.tool_name}, call_id={context.tool_call_id}, args={context.tool_arguments}. Usage: {self._usage_to_str(context.usage)}" # type: ignore[attr-defined] - ) + # During tool execution, context will be a ToolContext with tool metadata + if isinstance(context, ToolContext): + print( + f"### {self.event_counter}: Tool {tool.name} started. name={context.tool_name}, call_id={context.tool_call_id}, args={context.tool_arguments}. Usage: {self._usage_to_str(context.usage)}" + ) + else: + print( + f"### {self.event_counter}: Tool {tool.name} started. Usage: {self._usage_to_str(context.usage)}" + ) async def on_tool_end( self, context: RunContextWrapper, agent: Agent, tool: Tool, result: str ) -> None: self.event_counter += 1 - print( - f"### {self.event_counter}: Tool {tool.name} finished. result={result}, name={context.tool_name}, call_id={context.tool_call_id}, args={context.tool_arguments}. Usage: {self._usage_to_str(context.usage)}" # type: ignore[attr-defined] - ) + # During tool execution, context will be a ToolContext with tool metadata + if isinstance(context, ToolContext): + print( + f"### {self.event_counter}: Tool {tool.name} finished. result={result}, name={context.tool_name}, call_id={context.tool_call_id}, args={context.tool_arguments}. Usage: {self._usage_to_str(context.usage)}" + ) + else: + print( + f"### {self.event_counter}: Tool {tool.name} finished. result={result}. Usage: {self._usage_to_str(context.usage)}" + ) async def on_handoff( self, context: RunContextWrapper, from_agent: Agent, to_agent: Agent diff --git a/tests/test_tool_call_id_in_hooks.py b/tests/test_tool_call_id_in_hooks.py new file mode 100644 index 000000000..e69de29bb