-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathtest_astr_agent_tool_exec.py
More file actions
561 lines (466 loc) · 16.9 KB
/
test_astr_agent_tool_exec.py
File metadata and controls
561 lines (466 loc) · 16.9 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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
from types import SimpleNamespace
import mcp
import pytest
from astrbot.core.agent.run_context import ContextWrapper
from astrbot.core.astr_agent_tool_exec import FunctionToolExecutor
from astrbot.core.message.components import Image
class _DummyEvent:
def __init__(self, message_components: list[object] | None = None) -> None:
self.unified_msg_origin = "webchat:FriendMessage:webchat!user!session"
self.message_obj = SimpleNamespace(message=message_components or [])
def get_extra(self, _key: str):
return None
class _DummyTool:
def __init__(self) -> None:
self.name = "transfer_to_subagent"
self.agent = SimpleNamespace(name="subagent")
def _build_run_context(message_components: list[object] | None = None):
event = _DummyEvent(message_components=message_components)
ctx = SimpleNamespace(event=event, context=SimpleNamespace())
return ContextWrapper(context=ctx)
@pytest.mark.asyncio
async def test_collect_handoff_image_urls_normalizes_filters_and_appends_event_image(
monkeypatch: pytest.MonkeyPatch,
):
async def _fake_convert_to_file_path(self):
return "/tmp/event_image.png"
monkeypatch.setattr(Image, "convert_to_file_path", _fake_convert_to_file_path)
run_context = _build_run_context([Image(file="file:///tmp/original.png")])
image_urls_input = (
" https://example.com/a.png ",
"/tmp/not_an_image.txt",
"/tmp/local.webp",
123,
)
image_urls = await FunctionToolExecutor._collect_handoff_image_urls(
run_context,
image_urls_input,
)
assert image_urls == [
"https://example.com/a.png",
"/tmp/local.webp",
"/tmp/event_image.png",
]
@pytest.mark.asyncio
async def test_collect_handoff_image_urls_skips_failed_event_image_conversion(
monkeypatch: pytest.MonkeyPatch,
):
async def _fake_convert_to_file_path(self):
raise RuntimeError("boom")
monkeypatch.setattr(Image, "convert_to_file_path", _fake_convert_to_file_path)
run_context = _build_run_context([Image(file="file:///tmp/original.png")])
image_urls = await FunctionToolExecutor._collect_handoff_image_urls(
run_context,
["https://example.com/a.png"],
)
assert image_urls == ["https://example.com/a.png"]
@pytest.mark.asyncio
@pytest.mark.parametrize(
("image_refs", "expected_supported_refs"),
[
pytest.param(
(
"https://example.com/valid.png",
"base64://iVBORw0KGgoAAAANSUhEUgAAAAUA",
"file:///tmp/photo.heic",
"file://localhost/tmp/vector.svg",
"file://fileserver/share/image.webp",
"file:///tmp/not-image.txt",
"mailto:user@example.com",
"random-string-without-scheme-or-extension",
),
{
"https://example.com/valid.png",
"base64://iVBORw0KGgoAAAANSUhEUgAAAAUA",
"file:///tmp/photo.heic",
"file://localhost/tmp/vector.svg",
"file://fileserver/share/image.webp",
},
id="mixed_supported_and_unsupported_refs",
),
],
)
async def test_collect_handoff_image_urls_filters_supported_schemes_and_extensions(
image_refs: tuple[str, ...],
expected_supported_refs: set[str],
):
run_context = _build_run_context([])
result = await FunctionToolExecutor._collect_handoff_image_urls(
run_context, image_refs
)
assert set(result) == expected_supported_refs
@pytest.mark.asyncio
async def test_collect_handoff_image_urls_collects_event_image_when_args_is_none(
monkeypatch: pytest.MonkeyPatch,
):
async def _fake_convert_to_file_path(self):
return "/tmp/event_only.png"
monkeypatch.setattr(Image, "convert_to_file_path", _fake_convert_to_file_path)
run_context = _build_run_context([Image(file="file:///tmp/original.png")])
image_urls = await FunctionToolExecutor._collect_handoff_image_urls(
run_context,
None,
)
assert image_urls == ["/tmp/event_only.png"]
@pytest.mark.asyncio
async def test_do_handoff_background_reports_prepared_image_urls(
monkeypatch: pytest.MonkeyPatch,
):
captured: dict = {}
async def _fake_execute_handoff(
cls, tool, run_context, image_urls_prepared=False, **tool_args
):
assert image_urls_prepared is True
yield mcp.types.CallToolResult(
content=[mcp.types.TextContent(type="text", text="ok")]
)
async def _fake_wake(cls, run_context, **kwargs):
captured.update(kwargs)
monkeypatch.setattr(
FunctionToolExecutor,
"_execute_handoff",
classmethod(_fake_execute_handoff),
)
monkeypatch.setattr(
FunctionToolExecutor,
"_wake_main_agent_for_background_result",
classmethod(_fake_wake),
)
run_context = _build_run_context()
await FunctionToolExecutor._do_handoff_background(
tool=_DummyTool(),
run_context=run_context,
task_id="task-id",
input="hello",
image_urls="https://example.com/raw.png",
)
assert captured["tool_args"]["image_urls"] == ["https://example.com/raw.png"]
@pytest.mark.asyncio
async def test_execute_handoff_skips_renormalize_when_image_urls_prepared(
monkeypatch: pytest.MonkeyPatch,
):
captured: dict = {}
def _boom(_items):
raise RuntimeError("normalize should not be called")
async def _fake_get_current_chat_provider_id(_umo):
return "provider-id"
async def _fake_tool_loop_agent(**kwargs):
captured.update(kwargs)
return SimpleNamespace(completion_text="ok")
context = SimpleNamespace(
get_current_chat_provider_id=_fake_get_current_chat_provider_id,
tool_loop_agent=_fake_tool_loop_agent,
get_config=lambda **_kwargs: {"provider_settings": {}},
)
event = _DummyEvent([])
run_context = ContextWrapper(context=SimpleNamespace(event=event, context=context))
tool = SimpleNamespace(
name="transfer_to_subagent",
provider_id=None,
agent=SimpleNamespace(
name="subagent",
tools=[],
instructions="subagent-instructions",
begin_dialogs=[],
run_hooks=None,
),
)
monkeypatch.setattr(
"astrbot.core.astr_agent_tool_exec.normalize_and_dedupe_strings", _boom
)
results = []
async for result in FunctionToolExecutor._execute_handoff(
tool,
run_context,
image_urls_prepared=True,
input="hello",
image_urls=["https://example.com/raw.png"],
):
results.append(result)
assert len(results) == 1
assert captured["image_urls"] == ["https://example.com/raw.png"]
@pytest.mark.asyncio
async def test_collect_handoff_image_urls_keeps_extensionless_existing_event_file(
monkeypatch: pytest.MonkeyPatch,
):
async def _fake_convert_to_file_path(self):
return "/tmp/astrbot-handoff-image"
monkeypatch.setattr(Image, "convert_to_file_path", _fake_convert_to_file_path)
monkeypatch.setattr(
"astrbot.core.astr_agent_tool_exec.get_astrbot_temp_path", lambda: "/tmp"
)
monkeypatch.setattr(
"astrbot.core.utils.image_ref_utils.os.path.exists", lambda _: True
)
run_context = _build_run_context([Image(file="file:///tmp/original.png")])
image_urls = await FunctionToolExecutor._collect_handoff_image_urls(
run_context,
[],
)
assert image_urls == ["/tmp/astrbot-handoff-image"]
@pytest.mark.asyncio
async def test_collect_handoff_image_urls_filters_extensionless_missing_event_file(
monkeypatch: pytest.MonkeyPatch,
):
async def _fake_convert_to_file_path(self):
return "/tmp/astrbot-handoff-missing-image"
monkeypatch.setattr(Image, "convert_to_file_path", _fake_convert_to_file_path)
monkeypatch.setattr(
"astrbot.core.astr_agent_tool_exec.get_astrbot_temp_path", lambda: "/tmp"
)
monkeypatch.setattr(
"astrbot.core.utils.image_ref_utils.os.path.exists", lambda _: False
)
run_context = _build_run_context([Image(file="file:///tmp/original.png")])
image_urls = await FunctionToolExecutor._collect_handoff_image_urls(
run_context,
[],
)
assert image_urls == []
@pytest.mark.asyncio
async def test_execute_handoff_passes_tool_call_timeout_to_tool_loop_agent(
monkeypatch: pytest.MonkeyPatch,
):
captured: dict = {}
async def _fake_get_current_chat_provider_id(_umo):
return "provider-id"
async def _fake_tool_loop_agent(**kwargs):
captured.update(kwargs)
return SimpleNamespace(completion_text="ok")
context = SimpleNamespace(
get_current_chat_provider_id=_fake_get_current_chat_provider_id,
tool_loop_agent=_fake_tool_loop_agent,
get_config=lambda **_kwargs: {"provider_settings": {}},
)
event = _DummyEvent([])
run_context = ContextWrapper(
context=SimpleNamespace(event=event, context=context),
tool_call_timeout=120,
)
tool = SimpleNamespace(
name="transfer_to_subagent",
provider_id=None,
agent=SimpleNamespace(
name="subagent",
tools=[],
instructions="subagent-instructions",
begin_dialogs=[],
run_hooks=None,
),
)
results = []
async for result in FunctionToolExecutor._execute_handoff(
tool,
run_context,
image_urls_prepared=True,
input="hello",
image_urls=[],
):
results.append(result)
assert len(results) == 1
assert captured["tool_call_timeout"] == 120
@pytest.mark.asyncio
async def test_collect_handoff_image_urls_filters_extensionless_file_outside_temp_root(
monkeypatch: pytest.MonkeyPatch,
):
async def _fake_convert_to_file_path(self):
return "/var/tmp/astrbot-handoff-image"
monkeypatch.setattr(Image, "convert_to_file_path", _fake_convert_to_file_path)
monkeypatch.setattr(
"astrbot.core.astr_agent_tool_exec.get_astrbot_temp_path", lambda: "/tmp"
)
monkeypatch.setattr(
"astrbot.core.utils.image_ref_utils.os.path.exists", lambda _: True
)
run_context = _build_run_context([Image(file="file:///tmp/original.png")])
image_urls = await FunctionToolExecutor._collect_handoff_image_urls(
run_context,
[],
)
assert image_urls == []
@pytest.mark.asyncio
async def test_execute_handoff_rejects_when_call_limit_reached():
captured: dict = {}
class _EventWithExtras:
def __init__(self) -> None:
self.unified_msg_origin = "webchat:FriendMessage:webchat!user!session"
self.message_obj = SimpleNamespace(message=[])
self._extras = {
FunctionToolExecutor._HANDOFF_CALL_COUNT_EXTRA_KEY: 1,
}
def get_extra(self, key: str, default=None):
return self._extras.get(key, default)
def set_extra(self, key: str, value):
self._extras[key] = value
async def _fake_get_current_chat_provider_id(_umo):
return "provider-id"
async def _fake_tool_loop_agent(**kwargs):
captured.update(kwargs)
return SimpleNamespace(completion_text="ok")
context = SimpleNamespace(
get_current_chat_provider_id=_fake_get_current_chat_provider_id,
tool_loop_agent=_fake_tool_loop_agent,
get_config=lambda **_kwargs: {
"provider_settings": {},
"subagent_orchestrator": {"max_handoff_calls_per_run": 1},
},
)
event = _EventWithExtras()
run_context = ContextWrapper(context=SimpleNamespace(event=event, context=context))
tool = SimpleNamespace(
name="transfer_to_subagent",
provider_id=None,
agent=SimpleNamespace(
name="subagent",
tools=[],
instructions="subagent-instructions",
begin_dialogs=[],
run_hooks=None,
),
)
results = []
async for result in FunctionToolExecutor._execute_handoff(
tool,
run_context,
image_urls_prepared=True,
input="hello",
image_urls=[],
):
results.append(result)
assert len(results) == 1
assert "handoff_call_limit_reached" in results[0].content[0].text
assert captured == {}
@pytest.mark.asyncio
async def test_execute_handoff_increments_call_count_on_success():
class _EventWithExtras:
def __init__(self) -> None:
self.unified_msg_origin = "webchat:FriendMessage:webchat!user!session"
self.message_obj = SimpleNamespace(message=[])
self._extras: dict[str, int] = {}
def get_extra(self, key: str, default=None):
return self._extras.get(key, default)
def set_extra(self, key: str, value):
self._extras[key] = value
async def _fake_get_current_chat_provider_id(_umo):
return "provider-id"
async def _fake_tool_loop_agent(**_kwargs):
return SimpleNamespace(completion_text="ok")
context = SimpleNamespace(
get_current_chat_provider_id=_fake_get_current_chat_provider_id,
tool_loop_agent=_fake_tool_loop_agent,
get_config=lambda **_kwargs: {
"provider_settings": {},
"subagent_orchestrator": {"max_handoff_calls_per_run": 2},
},
)
event = _EventWithExtras()
run_context = ContextWrapper(context=SimpleNamespace(event=event, context=context))
tool = SimpleNamespace(
name="transfer_to_subagent",
provider_id=None,
agent=SimpleNamespace(
name="subagent",
tools=[],
instructions="subagent-instructions",
begin_dialogs=[],
run_hooks=None,
),
)
results = []
async for result in FunctionToolExecutor._execute_handoff(
tool,
run_context,
image_urls_prepared=True,
input="hello",
image_urls=[],
):
results.append(result)
assert len(results) == 1
assert (
event._extras[FunctionToolExecutor._HANDOFF_CALL_COUNT_EXTRA_KEY]
== 1
)
@pytest.mark.asyncio
async def test_execute_handoff_enforces_call_limit_across_multiple_calls():
call_count = {"tool_loop": 0}
class _EventWithExtras:
def __init__(self) -> None:
self.unified_msg_origin = "webchat:FriendMessage:webchat!user!session"
self.message_obj = SimpleNamespace(message=[])
self._extras: dict[str, int] = {}
def get_extra(self, key: str, default=None):
return self._extras.get(key, default)
def set_extra(self, key: str, value):
self._extras[key] = value
async def _fake_get_current_chat_provider_id(_umo):
return "provider-id"
async def _fake_tool_loop_agent(**_kwargs):
call_count["tool_loop"] += 1
return SimpleNamespace(completion_text="ok")
context = SimpleNamespace(
get_current_chat_provider_id=_fake_get_current_chat_provider_id,
tool_loop_agent=_fake_tool_loop_agent,
get_config=lambda **_kwargs: {
"provider_settings": {},
"subagent_orchestrator": {"max_handoff_calls_per_run": 2},
},
)
event = _EventWithExtras()
run_context = ContextWrapper(context=SimpleNamespace(event=event, context=context))
tool = SimpleNamespace(
name="transfer_to_subagent",
provider_id=None,
agent=SimpleNamespace(
name="subagent",
tools=[],
instructions="subagent-instructions",
begin_dialogs=[],
run_hooks=None,
),
)
first_results = []
async for result in FunctionToolExecutor._execute_handoff(
tool,
run_context,
image_urls_prepared=True,
input="first",
image_urls=[],
):
first_results.append(result)
assert len(first_results) == 1
assert "handoff_call_limit_reached" not in first_results[0].content[0].text
assert (
event._extras[FunctionToolExecutor._HANDOFF_CALL_COUNT_EXTRA_KEY]
== 1
)
second_results = []
async for result in FunctionToolExecutor._execute_handoff(
tool,
run_context,
image_urls_prepared=True,
input="second",
image_urls=[],
):
second_results.append(result)
assert len(second_results) == 1
assert "handoff_call_limit_reached" not in second_results[0].content[0].text
assert (
event._extras[FunctionToolExecutor._HANDOFF_CALL_COUNT_EXTRA_KEY]
== 2
)
third_results = []
async for result in FunctionToolExecutor._execute_handoff(
tool,
run_context,
image_urls_prepared=True,
input="third",
image_urls=[],
):
third_results.append(result)
assert len(third_results) == 1
assert "handoff_call_limit_reached" in third_results[0].content[0].text
assert (
event._extras[FunctionToolExecutor._HANDOFF_CALL_COUNT_EXTRA_KEY]
== 2
)
assert call_count["tool_loop"] == 2