-
-
Notifications
You must be signed in to change notification settings - Fork 413
Expand file tree
/
Copy pathtest_batch.py
More file actions
691 lines (582 loc) · 22.1 KB
/
Copy pathtest_batch.py
File metadata and controls
691 lines (582 loc) · 22.1 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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
import asyncio
import threading
import time
from typing import Any, List, Optional, Tuple
import pytest
from langroid import ChatDocument
from langroid.agent.batch import (
ExceptionHandling,
_convert_exception_handling,
_process_batch_async,
llm_response_batch,
run_batch_agent_method,
run_batch_function,
run_batch_task_gen,
run_batch_tasks,
)
from langroid.agent.chat_agent import ChatAgent, ChatAgentConfig
from langroid.agent.task import Task
from langroid.agent.tool_message import ToolMessage
from langroid.agent.tools.orchestration import DoneTool
from langroid.language_models.mock_lm import MockLMConfig
from langroid.language_models.openai_gpt import OpenAIGPTConfig
from langroid.mytypes import Entity
from langroid.utils.configuration import Settings, set_global, settings
from langroid.utils.constants import DONE
from langroid.vector_store.base import VectorStoreConfig
def process_int(x: str) -> str:
if int(x) == 0:
return str(int(x) + 1)
else:
time.sleep(2)
return str(int(x) + 1)
class _TestChatAgentConfig(ChatAgentConfig):
vecdb: Optional[VectorStoreConfig] = None
llm: MockLMConfig = MockLMConfig(response_fn=lambda x: process_int(x))
@pytest.mark.parametrize("batch_size", [1, 2, 3, None])
@pytest.mark.parametrize("sequential", [True, False])
@pytest.mark.parametrize("stop_on_first", [True, False])
@pytest.mark.parametrize("return_type", [True, False])
def test_task_batch(
test_settings: Settings,
sequential: bool,
batch_size: Optional[int],
stop_on_first: bool,
return_type: bool,
):
set_global(test_settings)
cfg = _TestChatAgentConfig()
agent = ChatAgent(cfg)
task = Task(
agent,
name="Test",
interactive=False,
done_if_response=[Entity.LLM],
done_if_no_response=[Entity.LLM],
)
if return_type:
# specialized to return str
task = task[str]
# run clones of this task on these inputs
N = 3
questions = list(range(N))
expected_answers = [(i + 1) for i in range(N)]
orig_quiet = settings.quiet
# batch run
answers = run_batch_tasks(
task,
questions,
input_map=lambda x: str(x), # what to feed to each task
output_map=lambda x: x, # how to process the result of each task
sequential=sequential,
batch_size=batch_size,
stop_on_first_result=stop_on_first,
)
assert settings.quiet == orig_quiet
if stop_on_first:
# only the task with input 0 succeeds since it's fastest
non_null_answer = [a for a in answers if a is not None][0]
assert non_null_answer is not None
answer = non_null_answer if return_type else non_null_answer.content
assert answer == str(expected_answers[0])
else:
for e in expected_answers:
if return_type:
assert any(str(e) in a.lower() for a in answers)
else:
assert any(str(e) in a.content.lower() for a in answers)
@pytest.mark.parametrize("batch_size", [1, 2, 3, None])
@pytest.mark.parametrize("sequential", [True, False])
@pytest.mark.parametrize("use_done_tool", [True, False])
def test_task_batch_turns(
test_settings: Settings,
sequential: bool,
batch_size: Optional[int],
use_done_tool: bool,
):
"""Test if `turns`, `max_cost`, `max_tokens` params work as expected.
The latter two are not really tested (since we need to turn off caching etc)
we just make sure they don't break anything.
"""
set_global(test_settings)
cfg = _TestChatAgentConfig()
class _TestChatAgent(ChatAgent):
def handle_message_fallback(
self, msg: str | ChatDocument
) -> str | DoneTool | None:
if isinstance(msg, ChatDocument) and msg.metadata.sender == Entity.LLM:
return (
DoneTool(content=str(msg.content))
if use_done_tool
else DONE + " " + str(msg.content)
)
agent = _TestChatAgent(cfg)
agent.llm.reset_usage_cost()
task = Task(
agent,
name="Test",
interactive=False,
)
# run clones of this task on these inputs
N = 3
questions = list(range(N))
expected_answers = [(i + 1) for i in range(N)]
# batch run
answers = run_batch_tasks(
task,
questions,
input_map=lambda x: str(x), # what to feed to each task
output_map=lambda x: x, # how to process the result of each task
sequential=sequential,
batch_size=batch_size,
turns=2,
max_cost=0.005,
max_tokens=100,
)
# expected_answers are simple numbers, but
# actual answers may be more wordy like "sum of 1 and 3 is 4",
# so we just check if the expected answer is contained in the actual answer
for e in expected_answers:
assert any(str(e) in a.content.lower() for a in answers)
@pytest.mark.parametrize("batch_size", [1, 2, 3, None])
@pytest.mark.parametrize("sequential", [True, False])
@pytest.mark.parametrize("stop_on_first", [True, False])
def test_agent_llm_response_batch(
test_settings: Settings,
sequential: bool,
stop_on_first: bool,
batch_size: Optional[int],
):
set_global(test_settings)
cfg = _TestChatAgentConfig()
agent = ChatAgent(cfg)
# get llm_response_async result on clones of this agent, on these inputs:
N = 3
questions = list(range(N))
expected_answers = [(i + 1) for i in range(N)]
# batch run
answers = run_batch_agent_method(
agent,
agent.llm_response_async,
questions,
input_map=lambda x: str(x), # what to feed to each task
output_map=lambda x: x, # how to process the result of each task
sequential=sequential,
stop_on_first_result=stop_on_first,
batch_size=batch_size,
)
if stop_on_first:
# only the task with input 0 succeeds since it's fastest
non_null_answer = [a for a in answers if a is not None][0]
assert non_null_answer is not None
assert non_null_answer.content == str(expected_answers[0])
else:
for e in expected_answers:
assert any(str(e) in a.content.lower() for a in answers)
# Test the helper function as well
answers = llm_response_batch(
agent,
questions,
input_map=lambda x: str(x), # what to feed to each task
output_map=lambda x: x, # how to process the result of each task
sequential=sequential,
stop_on_first_result=stop_on_first,
)
if stop_on_first:
# only the task with input 0 succeeds since it's fastest
non_null_answer = [a for a in answers if a is not None][0]
assert non_null_answer is not None
assert non_null_answer.content == str(expected_answers[0])
else:
for e in expected_answers:
assert any(str(e) in a.content.lower() for a in answers)
@pytest.mark.parametrize("stop_on_first", [True, False])
@pytest.mark.parametrize("batch_size", [1, 2, 3, None])
@pytest.mark.parametrize("sequential", [True, False])
def test_task_gen_batch(
test_settings: Settings,
sequential: bool,
stop_on_first: bool,
batch_size: Optional[int],
):
set_global(test_settings)
def task_gen(i: int) -> Task:
async def response_fn_async(x):
match i:
case 0:
await asyncio.sleep(0.1)
return str(x)
case 1:
return "hmm"
case _:
await asyncio.sleep(0.2)
return str(2 * int(x))
class _TestChatAgentConfig(ChatAgentConfig):
vecdb: Optional[VectorStoreConfig] = None
llm: MockLMConfig = MockLMConfig(response_fn_async=response_fn_async)
cfg = _TestChatAgentConfig()
return Task(
ChatAgent(cfg),
name=f"Test-{i}",
single_round=True,
)
# run the generated tasks on these inputs
questions = list(range(3))
expected_answers = ["0", "hmm", "4"]
# batch run
answers = run_batch_task_gen(
task_gen,
questions,
sequential=sequential,
stop_on_first_result=stop_on_first,
batch_size=batch_size,
)
if stop_on_first:
non_null_answer = [a for a in answers if a is not None][0].content
# Unless the first task is scheduled alone,
# the second task should always finish first
if batch_size == 1:
assert "0" in non_null_answer
else:
assert "hmm" in non_null_answer
else:
for answer, expected in zip(answers, expected_answers):
assert answer is not None
assert expected in answer.content.lower()
@pytest.mark.parametrize("batch_size", [None, 1, 2, 3])
@pytest.mark.parametrize(
"handle_exceptions", [ExceptionHandling.RETURN_EXCEPTION, True, False]
)
@pytest.mark.parametrize("sequential", [False, True])
@pytest.mark.parametrize("fn_api", [False, True])
@pytest.mark.parametrize("use_done_tool", [True, False])
def test_task_gen_batch_exceptions(
test_settings: Settings,
fn_api: bool,
use_done_tool: bool,
sequential: bool,
handle_exceptions: bool | ExceptionHandling,
batch_size: Optional[int],
):
set_global(test_settings)
kill_called = [] # Track Task.kill() calls
class ComputeTool(ToolMessage):
request: str = "compute"
purpose: str = "To compute an unknown function of the input"
input: int
system_message = """
You will make a call with the `compute` tool/function with
`input` the value I provide.
"""
class MockTask(Task):
"""Mock Task that raises exceptions for testing"""
def kill(self):
kill_called.append(self.name)
super().kill()
def task_gen(i: int) -> Task:
cfg = ChatAgentConfig(
vecdb=None,
llm=OpenAIGPTConfig(async_stream_quiet=False),
use_functions_api=fn_api,
use_tools=not fn_api,
use_tools_api=True,
)
agent = ChatAgent(cfg)
agent.enable_message(ComputeTool)
if use_done_tool:
agent.enable_message(DoneTool)
task = MockTask(
agent,
name=f"Test-{i}",
system_message=system_message,
interactive=False,
)
def handle(m: ComputeTool) -> str | DoneTool:
if i == 1:
raise RuntimeError("disaster")
elif i == 2:
raise asyncio.CancelledError()
return DoneTool(content="success") if use_done_tool else f"{DONE} success"
setattr(agent, "compute", handle)
return task
questions = list(range(3))
try:
answers = run_batch_task_gen(
task_gen,
questions,
sequential=sequential,
handle_exceptions=handle_exceptions,
batch_size=batch_size,
)
error_encountered = False
# Test successful case
assert answers[0] is not None
assert "success" in answers[0].content.lower()
# the task that raised CancelledError
assert kill_called == ["Test-2"]
# Test RuntimeError case
if (
_convert_exception_handling(handle_exceptions)
== ExceptionHandling.RETURN_EXCEPTION
):
assert isinstance(answers[1], RuntimeError)
assert "disaster" in str(answers[1])
assert isinstance(answers[2], asyncio.CancelledError)
elif (
_convert_exception_handling(handle_exceptions)
== ExceptionHandling.RETURN_NONE
):
assert answers[1] is None
assert answers[2] is None
else:
assert False, "Invalid handle_exceptions value"
except RuntimeError as e:
error_encountered = True
assert "disaster" in str(e)
except asyncio.CancelledError:
error_encountered = True
assert error_encountered == (
_convert_exception_handling(handle_exceptions) == ExceptionHandling.RAISE
)
@pytest.mark.parametrize(
"func, input_list, batch_size, expected",
[
(lambda x: x * 2, [1, 2, 3], None, [2, 4, 6]),
(lambda x: x + 1, [1, 2, 3, 4], 2, [2, 3, 4, 5]),
(lambda x: x * x, [], None, []),
(lambda x: x * 3, [1, 2], 1, [3, 6]),
],
)
def test_run_batch_function(func, input_list, batch_size, expected):
result = run_batch_function(func, input_list, batch_size=batch_size)
assert result == expected
def test_batch_size_processing(test_settings: Settings):
"""Test that batch_size parameter correctly processes items in batches"""
set_global(test_settings)
cfg = _TestChatAgentConfig()
agent = ChatAgent(cfg)
N = 5
questions = list(range(N))
batch_size = 2
answers = run_batch_agent_method(
agent,
agent.llm_response_async,
questions,
input_map=lambda x: str(x),
output_map=lambda x: x,
sequential=True,
batch_size=batch_size,
)
# Verify we got all expected answers
assert len(answers) == N
for i, answer in enumerate(answers):
assert answer is not None
assert str(i + 1) in answer.content
@pytest.mark.parametrize("sequential", [True, False])
@pytest.mark.parametrize(
"handle_exceptions", [True, False, ExceptionHandling.RETURN_EXCEPTION]
)
def test_process_batch_async_basic(sequential, handle_exceptions):
"""Test the core async batch processing function"""
async def mock_task(input: str, i: int) -> str:
if i == 1: # Make second task fail
raise ValueError("Task failed")
await asyncio.sleep(0.1)
return f"Processed {input}"
inputs = ["a", "b", "c"]
coroutine = _process_batch_async(
inputs,
mock_task,
sequential=sequential,
handle_exceptions=handle_exceptions,
output_map=lambda x: x,
)
# If handle_exceptions is True, the function should return
# the results of the successful tasks
orig_quiet = settings.quiet
if _convert_exception_handling(handle_exceptions) == ExceptionHandling.RETURN_NONE:
results = asyncio.run(coroutine)
assert results[1] is None
assert "Processed" in results[0]
assert "Processed" in results[2]
assert settings.quiet == orig_quiet
# If handle_exceptions is False, the function should raise an error
elif _convert_exception_handling(handle_exceptions) == ExceptionHandling.RAISE:
with pytest.raises(ValueError):
results = asyncio.run(coroutine)
# If handle_exceptions is RETURN_EXCEPTION, the function should return
# the results of the successful tasks and the exception of the failed task
else:
assert (
_convert_exception_handling(handle_exceptions)
== ExceptionHandling.RETURN_EXCEPTION
)
results = asyncio.run(coroutine)
assert settings.quiet == orig_quiet
assert "Processed" in results[0]
assert "Processed" in results[2]
assert isinstance(results[1], ValueError)
@pytest.mark.parametrize("stop_on_first_result", [True, False])
def test_process_batch_async_stop_on_first(stop_on_first_result):
"""Test stop_on_first_result behavior"""
async def mock_task(input: str, i: int) -> str:
await asyncio.sleep(0.1 * i) # Make later tasks slower
return f"Processed {input}"
inputs = ["a", "b", "c"]
results = asyncio.run(
_process_batch_async(
inputs,
mock_task,
stop_on_first_result=stop_on_first_result,
sequential=False,
handle_exceptions=ExceptionHandling.RAISE,
output_map=lambda x: x,
)
)
# When stop_on_first_result is True, only the first task should complete
if stop_on_first_result:
assert any(r is not None for r in results)
assert any(r is None for r in results)
# First task should complete first due to sleep timing
assert results[0] is not None
assert "Processed a" in results[0]
# When stop_on_first_result is False, all tasks should complete
else:
assert all(r is not None for r in results)
assert all("Processed" in r for r in results)
def test_process_batch_async_stop_on_first_skips_none_result() -> None:
"""Keep waiting when the first completed task has no valid result."""
async def run_batch() -> list[Any]:
release_valid = asyncio.Event()
def output_map(result: Any) -> Any:
if result is None:
release_valid.set()
return result
async def mock_task(input: str, i: int) -> str | None:
if input == "invalid":
return None
if input == "valid":
await release_valid.wait()
return "Processed valid"
await asyncio.Event().wait()
raise AssertionError("Unreachable")
return await _process_batch_async(
["invalid", "valid", "slow"],
mock_task,
stop_on_first_result=True,
handle_exceptions=ExceptionHandling.RAISE,
output_map=output_map,
)
results = asyncio.run(run_batch())
assert results == [None, "Processed valid", None]
def test_process_batch_async_stop_on_first_all_none() -> None:
"""Return after all tasks complete when every mapped result is None."""
async def mock_task(input: str, i: int) -> None:
return None
results = asyncio.run(
_process_batch_async(
["invalid-1", "invalid-2"],
mock_task,
stop_on_first_result=True,
handle_exceptions=ExceptionHandling.RAISE,
)
)
assert results == [None, None]
def test_process_batch_async_stop_on_first_skips_exception_result() -> None:
"""Keep waiting when an exception is converted to no valid result."""
async def run_batch() -> list[Any]:
release_valid = asyncio.Event()
never_release = asyncio.Event()
invalid_result = object()
def output_map(result: Any) -> Any:
if result is invalid_result:
release_valid.set()
return None
return result
async def mock_task(input: str, i: int) -> Any:
if input == "error":
raise ValueError("test error")
if input == "invalid":
return invalid_result
if input == "valid":
await release_valid.wait()
return "Processed valid"
await never_release.wait()
raise AssertionError("Unreachable")
return await _process_batch_async(
["error", "invalid", "valid", "slow"],
mock_task,
stop_on_first_result=True,
handle_exceptions=ExceptionHandling.RETURN_NONE,
output_map=output_map,
)
results = asyncio.run(run_batch())
assert results == [None, None, "Processed valid", None]
_PROBE_ITEMS = 4
def _overlap_probe(
sequential: bool,
batch_size: Optional[int] = None,
wait_timeout: float = 0.5,
) -> Tuple[List[int], int]:
"""Run `run_batch_function` over `_PROBE_ITEMS` items, recording the peak
number of callbacks in flight at once.
Each callback waits until *every* item is running at once, or until a
short bounded timeout expires -- never unbounded, so the probe cannot
hang when execution turns out to be more serial than expected.
Releasing only at full width is what makes the measurement meaningful:
a probe that released as soon as it saw a second peer would report a peak
of 2 no matter how much concurrency was actually available, and so could
not tell `batch_size=2` apart from `batch_size` being ignored.
Args:
sequential: Passed through to `run_batch_function`.
batch_size: Passed through to `run_batch_function`.
wait_timeout: Per-callback upper bound on the blocking wait.
Returns:
The results list, and the peak number of concurrently active calls.
"""
lock = threading.Lock()
all_running = threading.Event()
state = {"active": 0, "peak": 0}
def work(i: int) -> int:
with lock:
state["active"] += 1
state["peak"] = max(state["peak"], state["active"])
if state["active"] >= _PROBE_ITEMS:
all_running.set()
all_running.wait(timeout=wait_timeout)
with lock:
state["active"] -= 1
return i * i
results = run_batch_function(
work,
list(range(_PROBE_ITEMS)),
sequential=sequential,
batch_size=batch_size,
)
return results, state["peak"]
def test_run_batch_function_sequential_does_not_overlap() -> None:
"""`sequential=True` must keep exactly one callback in flight."""
# the event can never fire here, so every call pays `wait_timeout`;
# keep it small since the assertion does not depend on its size.
results, peak = _overlap_probe(sequential=True, wait_timeout=0.05)
assert results == [0, 1, 4, 9]
assert peak == 1
def test_run_batch_function_concurrent_overlaps() -> None:
"""`sequential=False` must actually overlap blocking sync callbacks.
Regression guard for issue #1157: the concurrent path wrapped `function`
in a coroutine that called it directly, giving `asyncio.gather` no
suspension point, so blocking callbacks ran back to back and
`sequential=False` was indistinguishable from `sequential=True`.
"""
results, peak = _overlap_probe(sequential=False)
assert results == [0, 1, 4, 9], "results must stay in input order"
assert peak == _PROBE_ITEMS, f"expected all calls to overlap, saw peak {peak}"
def test_run_batch_function_concurrent_respects_batch_size() -> None:
"""Concurrency is confined to one batch at a time, and order is kept.
With `batch_size=2` only two of the four calls may be in flight at once,
so the probe's full-width event never fires and the peak must stay at the
batch size -- which is what distinguishes this from the unbatched case.
"""
results, peak = _overlap_probe(sequential=False, batch_size=2)
assert results == [0, 1, 4, 9]
assert peak == 2