forked from openai/openai-agents-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_apply_patch_tool.py
More file actions
388 lines (321 loc) · 13.2 KB
/
Copy pathtest_apply_patch_tool.py
File metadata and controls
388 lines (321 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import Any, cast
import pytest
from agents import (
Agent,
ApplyPatchTool,
RunConfig,
RunContextWrapper,
RunHooks,
set_tracing_disabled,
trace,
)
from agents.editor import ApplyPatchOperation, ApplyPatchResult
from agents.items import ToolApprovalItem, ToolCallOutputItem
from agents.run_internal.run_loop import ApplyPatchAction, ToolRunApplyPatchCall
from .testing_processor import SPAN_PROCESSOR_TESTING
from .utils.hitl import (
HITL_REJECTION_MSG,
make_context_wrapper,
make_on_approval_callback,
reject_tool_call,
require_approval,
)
def _get_function_span(tool_name: str) -> dict[str, Any]:
for span in SPAN_PROCESSOR_TESTING.get_ordered_spans(including_empty=True):
exported = span.export()
if not exported:
continue
span_data = exported.get("span_data")
if not isinstance(span_data, dict):
continue
if span_data.get("type") == "function" and span_data.get("name") == tool_name:
return exported
raise AssertionError(f"Function span for tool '{tool_name}' not found")
def _call(call_id: str, operation: dict[str, Any]) -> DummyApplyPatchCall:
return DummyApplyPatchCall(type="apply_patch_call", call_id=call_id, operation=operation)
def build_apply_patch_call(
tool: ApplyPatchTool,
call_id: str,
operation: dict[str, Any],
*,
context_wrapper: RunContextWrapper[Any] | None = None,
) -> tuple[Agent[Any], RunContextWrapper[Any], ToolRunApplyPatchCall]:
ctx = context_wrapper or make_context_wrapper()
agent = Agent(name="patcher", tools=[tool])
tool_run = ToolRunApplyPatchCall(tool_call=_call(call_id, operation), apply_patch_tool=tool)
return agent, ctx, tool_run
@dataclass
class DummyApplyPatchCall:
type: str
call_id: str
operation: dict[str, Any]
class RecordingEditor:
def __init__(self) -> None:
self.operations: list[ApplyPatchOperation] = []
def create_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:
self.operations.append(operation)
return ApplyPatchResult(output=f"Created {operation.path}")
def update_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:
self.operations.append(operation)
return ApplyPatchResult(status="completed", output=f"Updated {operation.path}")
def delete_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:
self.operations.append(operation)
return ApplyPatchResult(output=f"Deleted {operation.path}")
@pytest.mark.asyncio
async def test_apply_patch_tool_success() -> None:
editor = RecordingEditor()
tool = ApplyPatchTool(editor=editor)
agent, context_wrapper, tool_run = build_apply_patch_call(
tool, "call_apply", {"type": "update_file", "path": "tasks.md", "diff": "-a\n+b\n"}
)
result = await ApplyPatchAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
assert "Updated tasks.md" in result.output
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["type"] == "apply_patch_call_output"
assert raw_item["status"] == "completed"
assert raw_item["call_id"] == "call_apply"
assert editor.operations[0].type == "update_file"
assert editor.operations[0].ctx_wrapper is context_wrapper
assert isinstance(raw_item["output"], str)
assert raw_item["output"].startswith("Updated tasks.md")
input_payload = result.to_input_item()
assert isinstance(input_payload, dict)
payload_dict = cast(dict[str, Any], input_payload)
assert payload_dict["type"] == "apply_patch_call_output"
assert payload_dict["status"] == "completed"
@pytest.mark.asyncio
async def test_apply_patch_tool_failure() -> None:
class ExplodingEditor(RecordingEditor):
def update_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:
raise RuntimeError("boom")
tool = ApplyPatchTool(editor=ExplodingEditor())
agent, context_wrapper, tool_run = build_apply_patch_call(
tool, "call_apply_fail", {"type": "update_file", "path": "tasks.md", "diff": "-a\n+b\n"}
)
result = await ApplyPatchAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
assert "boom" in result.output
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["status"] == "failed"
assert isinstance(raw_item.get("output"), str)
input_payload = result.to_input_item()
assert isinstance(input_payload, dict)
payload_dict = cast(dict[str, Any], input_payload)
assert payload_dict["type"] == "apply_patch_call_output"
assert payload_dict["status"] == "failed"
@pytest.mark.asyncio
async def test_apply_patch_tool_emits_function_span() -> None:
editor = RecordingEditor()
tool = ApplyPatchTool(editor=editor)
agent, context_wrapper, tool_run = build_apply_patch_call(
tool, "call_apply_trace", {"type": "update_file", "path": "tasks.md", "diff": "-a\n+b\n"}
)
set_tracing_disabled(False)
with trace("apply-patch-span-test"):
result = await ApplyPatchAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
function_span = _get_function_span(tool.name)
span_data = cast(dict[str, Any], function_span["span_data"])
assert "tasks.md" in cast(str, span_data.get("input", ""))
assert "Updated tasks.md" in cast(str, span_data.get("output", ""))
@pytest.mark.asyncio
async def test_apply_patch_tool_redacts_span_error_when_sensitive_data_disabled() -> None:
secret_error = "patch secret output"
class ExplodingEditor(RecordingEditor):
def update_file(self, operation: ApplyPatchOperation) -> ApplyPatchResult:
raise RuntimeError(secret_error)
tool = ApplyPatchTool(editor=ExplodingEditor())
agent, context_wrapper, tool_run = build_apply_patch_call(
tool,
"call_apply_trace_redacted",
{"type": "update_file", "path": "tasks.md", "diff": "-a\n+b\n"},
)
set_tracing_disabled(False)
with trace("apply-patch-span-redaction-test"):
result = await ApplyPatchAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(trace_include_sensitive_data=False),
)
assert isinstance(result, ToolCallOutputItem)
function_span = _get_function_span(tool.name)
assert function_span.get("error") == {
"message": "Error running tool",
"data": {
"tool_name": tool.name,
"error": "Tool execution failed. Error details are redacted.",
},
}
assert secret_error not in json.dumps(function_span)
span_data = cast(dict[str, Any], function_span["span_data"])
assert span_data.get("input") is None
assert span_data.get("output") is None
@pytest.mark.asyncio
async def test_apply_patch_tool_accepts_mapping_call() -> None:
editor = RecordingEditor()
tool = ApplyPatchTool(editor=editor)
tool_call: dict[str, Any] = {
"type": "apply_patch_call",
"call_id": "call_mapping",
"operation": {
"type": "create_file",
"path": "notes.md",
"diff": "+hello\n",
},
}
agent, context_wrapper, tool_run = build_apply_patch_call(
tool,
"call_mapping",
tool_call["operation"],
context_wrapper=RunContextWrapper(context=None),
)
result = await ApplyPatchAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["call_id"] == "call_mapping"
assert editor.operations[0].path == "notes.md"
assert editor.operations[0].ctx_wrapper is context_wrapper
@pytest.mark.asyncio
async def test_apply_patch_tool_needs_approval_returns_approval_item() -> None:
"""Test that apply_patch tool with needs_approval=True returns ToolApprovalItem."""
editor = RecordingEditor()
tool = ApplyPatchTool(editor=editor, needs_approval=require_approval)
agent, context_wrapper, tool_run = build_apply_patch_call(
tool, "call_apply", {"type": "update_file", "path": "tasks.md", "diff": "-a\n+b\n"}
)
result = await ApplyPatchAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolApprovalItem)
assert result.tool_name == "apply_patch"
assert result.name == "apply_patch"
@pytest.mark.asyncio
async def test_apply_patch_tool_needs_approval_rejected_returns_rejection() -> None:
"""Test that apply_patch tool with needs_approval that is rejected returns rejection output."""
editor = RecordingEditor()
tool = ApplyPatchTool(editor=editor, needs_approval=require_approval)
tool_call = _call("call_apply", {"type": "update_file", "path": "tasks.md", "diff": "-a\n+b\n"})
agent, context_wrapper, tool_run = build_apply_patch_call(
tool, "call_apply", tool_call.operation, context_wrapper=make_context_wrapper()
)
# Pre-reject the tool call
reject_tool_call(context_wrapper, agent, cast(dict[str, Any], tool_call), "apply_patch")
result = await ApplyPatchAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
assert isinstance(result, ToolCallOutputItem)
assert HITL_REJECTION_MSG in result.output
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["type"] == "apply_patch_call_output"
assert raw_item["status"] == "failed"
assert raw_item["output"] == HITL_REJECTION_MSG
@pytest.mark.asyncio
async def test_apply_patch_rejection_uses_run_level_formatter() -> None:
"""Apply patch approval rejection should use the run-level formatter message."""
editor = RecordingEditor()
tool = ApplyPatchTool(
editor=editor,
needs_approval=require_approval,
)
tool_call = _call("call_apply", {"type": "update_file", "path": "tasks.md", "diff": "-a\n+b\n"})
agent, context_wrapper, tool_run = build_apply_patch_call(
tool, "call_apply", tool_call.operation, context_wrapper=make_context_wrapper()
)
reject_tool_call(context_wrapper, agent, cast(dict[str, Any], tool_call), "apply_patch")
result = await ApplyPatchAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(
tool_error_formatter=lambda args: f"{args.tool_name} denied ({args.call_id})"
),
)
assert isinstance(result, ToolCallOutputItem)
assert result.output == "apply_patch denied (call_apply)"
raw_item = cast(dict[str, Any], result.raw_item)
assert raw_item["output"] == "apply_patch denied (call_apply)"
@pytest.mark.asyncio
async def test_apply_patch_tool_on_approval_callback_auto_approves() -> None:
"""Test that apply_patch tool on_approval callback can auto-approve."""
editor = RecordingEditor()
tool = ApplyPatchTool(
editor=editor,
needs_approval=require_approval,
on_approval=make_on_approval_callback(approve=True),
)
agent, context_wrapper, tool_run = build_apply_patch_call(
tool, "call_apply", {"type": "update_file", "path": "tasks.md", "diff": "-a\n+b\n"}
)
result = await ApplyPatchAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
# Should execute normally since on_approval auto-approved
assert isinstance(result, ToolCallOutputItem)
assert "Updated tasks.md" in result.output
assert len(editor.operations) == 1
@pytest.mark.asyncio
async def test_apply_patch_tool_on_approval_callback_auto_rejects() -> None:
"""Test that apply_patch tool on_approval callback can auto-reject."""
editor = RecordingEditor()
tool = ApplyPatchTool(
editor=editor,
needs_approval=require_approval,
on_approval=make_on_approval_callback(approve=False, reason="Not allowed"),
)
agent, context_wrapper, tool_run = build_apply_patch_call(
tool, "call_apply", {"type": "update_file", "path": "tasks.md", "diff": "-a\n+b\n"}
)
result = await ApplyPatchAction.execute(
agent=agent,
call=tool_run,
hooks=RunHooks[Any](),
context_wrapper=context_wrapper,
config=RunConfig(),
)
# Should return rejection output
assert isinstance(result, ToolCallOutputItem)
assert HITL_REJECTION_MSG in result.output
assert len(editor.operations) == 0 # Should not have executed