99from .usage import Usage
1010
1111if TYPE_CHECKING :
12+ from .agent import AgentBase
1213 from .items import TResponseInputItem
1314 from .run_context import _ApprovalRecord
1415
@@ -44,6 +45,9 @@ class ToolContext(RunContextWrapper[TContext]):
4445 tool_call : ResponseFunctionToolCall | None = None
4546 """The tool call object associated with this invocation."""
4647
48+ agent : AgentBase [Any ] | None = None
49+ """The active agent for this tool call, when available."""
50+
4751 def __init__ (
4852 self ,
4953 context : TContext ,
@@ -52,6 +56,7 @@ def __init__(
5256 tool_call_id : str | object = _MISSING ,
5357 tool_arguments : str | object = _MISSING ,
5458 tool_call : ResponseFunctionToolCall | None = None ,
59+ agent : AgentBase [Any ] | None = None ,
5560 * ,
5661 turn_input : list [TResponseInputItem ] | None = None ,
5762 _approvals : dict [str , _ApprovalRecord ] | None = None ,
@@ -80,13 +85,15 @@ def __init__(
8085 else cast (str , tool_call_id )
8186 )
8287 self .tool_call = tool_call
88+ self .agent = agent
8389
8490 @classmethod
8591 def from_agent_context (
8692 cls ,
8793 context : RunContextWrapper [TContext ],
8894 tool_call_id : str ,
8995 tool_call : ResponseFunctionToolCall | None = None ,
96+ agent : AgentBase [Any ] | None = None ,
9097 ) -> ToolContext :
9198 """
9299 Create a ToolContext from a RunContextWrapper.
@@ -99,12 +106,16 @@ def from_agent_context(
99106 tool_args = (
100107 tool_call .arguments if tool_call is not None else _assert_must_pass_tool_arguments ()
101108 )
109+ tool_agent = agent
110+ if tool_agent is None and isinstance (context , ToolContext ):
111+ tool_agent = context .agent
102112
103113 tool_context = cls (
104114 tool_name = tool_name ,
105115 tool_call_id = tool_call_id ,
106116 tool_arguments = tool_args ,
107117 tool_call = tool_call ,
118+ agent = tool_agent ,
108119 ** base_values ,
109120 )
110121 return tool_context
0 commit comments