|
1 | 1 | import pytest |
2 | 2 | from openai.types.responses import ResponseFunctionToolCall |
3 | 3 |
|
| 4 | +from agents import Agent |
4 | 5 | from agents.run_context import RunContextWrapper |
5 | 6 | from agents.tool_context import ToolContext |
6 | 7 | from tests.utils.hitl import make_context_wrapper |
@@ -30,9 +31,75 @@ def test_tool_context_from_agent_context_populates_fields() -> None: |
30 | 31 | arguments='{"a": 1}', |
31 | 32 | ) |
32 | 33 | ctx = make_context_wrapper() |
| 34 | + agent = Agent(name="agent") |
33 | 35 |
|
34 | | - tool_ctx = ToolContext.from_agent_context(ctx, tool_call_id="call-123", tool_call=tool_call) |
| 36 | + tool_ctx = ToolContext.from_agent_context( |
| 37 | + ctx, |
| 38 | + tool_call_id="call-123", |
| 39 | + tool_call=tool_call, |
| 40 | + agent=agent, |
| 41 | + ) |
35 | 42 |
|
36 | 43 | assert tool_ctx.tool_name == "test_tool" |
37 | 44 | assert tool_ctx.tool_call_id == "call-123" |
38 | 45 | assert tool_ctx.tool_arguments == '{"a": 1}' |
| 46 | + assert tool_ctx.agent is agent |
| 47 | + |
| 48 | + |
| 49 | +def test_tool_context_agent_none_by_default() -> None: |
| 50 | + tool_call = ResponseFunctionToolCall( |
| 51 | + type="function_call", |
| 52 | + name="test_tool", |
| 53 | + call_id="call-1", |
| 54 | + arguments="{}", |
| 55 | + ) |
| 56 | + ctx = make_context_wrapper() |
| 57 | + |
| 58 | + tool_ctx = ToolContext.from_agent_context(ctx, tool_call_id="call-1", tool_call=tool_call) |
| 59 | + |
| 60 | + assert tool_ctx.agent is None |
| 61 | + |
| 62 | + |
| 63 | +def test_tool_context_constructor_accepts_agent_keyword() -> None: |
| 64 | + agent = Agent(name="direct-agent") |
| 65 | + tool_ctx: ToolContext[dict[str, object]] = ToolContext( |
| 66 | + context={}, |
| 67 | + tool_name="my_tool", |
| 68 | + tool_call_id="call-2", |
| 69 | + tool_arguments="{}", |
| 70 | + agent=agent, |
| 71 | + ) |
| 72 | + |
| 73 | + assert tool_ctx.agent is agent |
| 74 | + |
| 75 | + |
| 76 | +def test_tool_context_from_tool_context_inherits_agent() -> None: |
| 77 | + original_call = ResponseFunctionToolCall( |
| 78 | + type="function_call", |
| 79 | + name="test_tool", |
| 80 | + call_id="call-3", |
| 81 | + arguments="{}", |
| 82 | + ) |
| 83 | + derived_call = ResponseFunctionToolCall( |
| 84 | + type="function_call", |
| 85 | + name="test_tool", |
| 86 | + call_id="call-4", |
| 87 | + arguments="{}", |
| 88 | + ) |
| 89 | + agent = Agent(name="origin-agent") |
| 90 | + parent_context: ToolContext[dict[str, object]] = ToolContext( |
| 91 | + context={}, |
| 92 | + tool_name="test_tool", |
| 93 | + tool_call_id="call-3", |
| 94 | + tool_arguments="{}", |
| 95 | + tool_call=original_call, |
| 96 | + agent=agent, |
| 97 | + ) |
| 98 | + |
| 99 | + derived_context = ToolContext.from_agent_context( |
| 100 | + parent_context, |
| 101 | + tool_call_id="call-4", |
| 102 | + tool_call=derived_call, |
| 103 | + ) |
| 104 | + |
| 105 | + assert derived_context.agent is agent |
0 commit comments