-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtest_tool_calling_loop.py
More file actions
1963 lines (1719 loc) · 71.1 KB
/
Copy pathtest_tool_calling_loop.py
File metadata and controls
1963 lines (1719 loc) · 71.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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Characterization tests for the generic ToolCallingLoop engine.
These pin the engine seams the agent does NOT exercise but a future read-only
judge will rely on:
* running with NO user simulator (``user_turn=None``) — the loop must never
reference user-simulator concepts, and a no-tool-call turn just re-prompts;
* terminating on a *specific tool call* via the termination callback (how the
judge will stop when ``submit_report`` is called);
* metrics accumulation through an arbitrary ``MetricsSink``;
* error classification through the shared ``classify_loop_error``.
We use the project's real ``ToolExecutor``-shaped fakes minimally — only a
generate seam and a tool executor are faked, no over-mocking of the loop.
"""
import time
import pytest
from litellm.exceptions import RateLimitError
from tolokaforge.core.llm.client import GenerationResult, LLMApiTimeoutError, ParserError
from tolokaforge.core.llm.usage import Usage
from tolokaforge.core.logging import get_logger
from tolokaforge.core.loop import (
LoopConfig,
MetricsSink,
TerminationDecision,
ToolCallingLoop,
classify_loop_error,
)
from tolokaforge.core.models import Message, MessageRole, TerminationReason, ToolCall, TrialStatus
from tolokaforge.tools.registry import ToolResult
pytestmark = pytest.mark.unit
class _ScriptedClient:
"""Yields a fixed sequence of GenerationResults, one per generate call.
An entry that is an ``Exception`` instance is raised on that call instead —
the retry-loop tests script provider failures this way.
``messages_history`` snapshots the wire ``messages`` argument on each call
so a test can pin what actually reached the provider on the second call
(a copy is taken because the loop mutates the underlying list in place).
"""
def __init__(self, results: list[GenerationResult | Exception]) -> None:
self._results = list(results)
self.calls = 0
self.messages_history: list[list[Message]] = []
def generate(self, system, messages, tools, tool_choice="auto", observation=None):
self.calls += 1
self.messages_history.append(list(messages))
item = self._results.pop(0)
if isinstance(item, Exception):
raise item
return item
class _RecordingExecutor:
"""Minimal ToolExecutor-shaped fake."""
def __init__(self) -> None:
self.executed: list[tuple[str, dict, str]] = []
def execute(self, tool_name, arguments, *, call_id, validation_schema=None):
self.executed.append((tool_name, arguments, call_id))
return ToolResult(success=True, output=f"ran {tool_name}")
class _CountingSink(MetricsSink):
def __init__(self) -> None:
self.generations = 0
self.tool_calls = 0
self.prompt_tokens = 0
def record_generation(self, result: GenerationResult) -> None:
self.generations += 1
self.prompt_tokens += result.usage.prompt_tokens
def record_tool_call(self) -> None:
self.tool_calls += 1
def _logger():
return get_logger("loop-test", strict=False)
def _never_terminate(result, turn, messages):
return None
def _classify_no_patterns(exc: Exception) -> TerminationDecision:
return classify_loop_error(exc, ())
def _loop(
client,
*,
should_terminate,
user_turn=None,
max_turns=5,
executor=None,
sink=None,
config=None,
retry_sleep=None,
):
return ToolCallingLoop(
llm_client=client,
tool_executor=executor or _RecordingExecutor(),
tool_schemas=[],
config=config or LoopConfig(max_turns=max_turns, episode_timeout_s=10_000),
metrics=sink or _CountingSink(),
should_terminate=should_terminate,
user_turn=user_turn,
classify_error=_classify_no_patterns,
logger=_logger(),
retry_sleep=retry_sleep or (lambda _s: None),
)
def test_no_user_simulator_no_tool_calls_re_prompts_until_max_turns():
"""Judge-shaped: with no user_turn, a no-tool-call turn advances to the next
turn (re-prompt) rather than terminating, until max_turns is hit."""
client = _ScriptedClient(
[GenerationResult(text=f"thinking {i}", usage=Usage(prompt_tokens=1)) for i in range(3)]
)
messages: list[Message] = []
outcome = _loop(client, should_terminate=_never_terminate, max_turns=3).run(
"sys", messages, time.time()
)
assert client.calls == 3
assert outcome.termination_reason == TerminationReason.MAX_TURNS
assert outcome.status == TrialStatus.COMPLETED
# No USER-role message ever appears without a user simulator.
assert all(m.role != MessageRole.USER for m in messages)
def test_terminates_on_specific_tool_call():
"""Judge-shaped: terminate when a named tool is called (submit_report)."""
def stop_on_submit(result, turn, messages):
if any(tc.name == "submit_report" for tc in result.tool_calls):
return TerminationDecision(
reason=TerminationReason.AGENT_DONE,
system_message="report submitted",
)
return None
client = _ScriptedClient(
[
GenerationResult(
text="look first",
tool_calls=[ToolCall(id="t1", name="get_state", arguments={})],
usage=Usage(prompt_tokens=2),
),
GenerationResult(
text="now report",
tool_calls=[ToolCall(id="t2", name="submit_report", arguments={"score": 1})],
usage=Usage(prompt_tokens=2),
),
]
)
executor = _RecordingExecutor()
messages: list[Message] = []
outcome = _loop(client, should_terminate=stop_on_submit, executor=executor, max_turns=10).run(
"sys", messages, time.time()
)
assert outcome.termination_reason == TerminationReason.AGENT_DONE
# submit_report terminates BEFORE its own tool execution; only get_state ran.
assert executor.executed == [("get_state", {}, "t1")]
assert messages[-1].role == MessageRole.SYSTEM
assert messages[-1].content == "report submitted"
def test_tool_calls_executed_and_counted_then_loop_continues():
executor = _RecordingExecutor()
sink = _CountingSink()
client = _ScriptedClient(
[
GenerationResult(
text="call two",
tool_calls=[
ToolCall(id="a", name="query", arguments={"q": 1}),
ToolCall(id="b", name="query", arguments={"q": 2}),
],
usage=Usage(prompt_tokens=5),
),
GenerationResult(text="done", usage=Usage(prompt_tokens=5)),
]
)
messages: list[Message] = []
_loop(client, should_terminate=_never_terminate, executor=executor, sink=sink, max_turns=2).run(
"sys", messages, time.time()
)
assert len(executor.executed) == 2
assert sink.tool_calls == 2
assert sink.generations == 2
# Each tool call produced a TOOL message after the assistant message.
tool_msgs = [m for m in messages if m.role == MessageRole.TOOL]
assert len(tool_msgs) == 2
def test_each_executed_call_carries_its_own_provider_call_id():
"""The executor is handed ``ToolCall.id``, and the result message keys on the
same id — so a call and its result join on the id, never on position. The two
calls here differ only in that id and their arguments."""
executor = _RecordingExecutor()
client = _ScriptedClient(
[
GenerationResult(
text="refund twice",
tool_calls=[
ToolCall(id="toolu_A", name="refund", arguments={"payment_id": "PAY-1"}),
ToolCall(id="toolu_B", name="refund", arguments={"payment_id": "PAY-1"}),
],
usage=Usage(prompt_tokens=5),
),
GenerationResult(text="done", usage=Usage(prompt_tokens=5)),
]
)
messages: list[Message] = []
_loop(client, should_terminate=_never_terminate, executor=executor, max_turns=2).run(
"sys", messages, time.time()
)
assert [call_id for _, _, call_id in executor.executed] == ["toolu_A", "toolu_B"]
assert [m.tool_call_id for m in messages if m.role == MessageRole.TOOL] == [
"toolu_A",
"toolu_B",
]
class _FailingTransportExecutor:
"""A ToolExecutor-shaped seam whose transport fails on one named call.
In a Docker run the executor is the gRPC client, so a transport failure
raises out of ``execute`` rather than coming back as a failed ``ToolResult``.
A tool that fails *in band* is recorded and the loop carries on, which is why
that case cannot stand in for this one.
"""
def __init__(self, raise_on: str) -> None:
self._raise_on = raise_on
self.attempted: list[str] = []
def execute(self, tool_name, arguments, *, call_id, validation_schema=None):
self.attempted.append(call_id)
if call_id == self._raise_on:
raise RuntimeError("runner unreachable")
return ToolResult(success=True, output=f"ran {tool_name}")
def test_a_failed_call_leaves_its_turns_remaining_calls_unexecuted_and_ends_the_episode():
"""The suffix invariant, asserted rather than assumed.
The timeline joins a call to its result by occurrence order, which is sound
only if the k-th declared occurrence of an id is the k-th executed one — that
is, if the declarations that never executed are a trailing *suffix* of the
trial rather than a gap in the middle. Two things make it one: a turn's calls
run in declaration order and stop at the first failure, and the episode stops
with them, so no later turn declares anything either.
"""
executor = _FailingTransportExecutor(raise_on="b1")
client = _ScriptedClient(
[
GenerationResult(
text="",
tool_calls=[ToolCall(id="a1", name="query", arguments={"q": 1})],
usage=Usage(prompt_tokens=5),
),
GenerationResult(
text="",
tool_calls=[
ToolCall(id="b1", name="query", arguments={"q": 2}),
ToolCall(id="b2", name="query", arguments={"q": 3}),
ToolCall(id="b3", name="query", arguments={"q": 4}),
],
usage=Usage(prompt_tokens=5),
),
GenerationResult(text="never reached", usage=Usage(prompt_tokens=5)),
]
)
messages: list[Message] = []
outcome = _loop(client, should_terminate=_never_terminate, executor=executor, max_turns=3).run(
"sys", messages, time.time()
)
assert executor.attempted == ["a1", "b1"]
assert outcome.status == TrialStatus.ERROR
assert outcome.termination_reason == TerminationReason.ERROR
assert client.calls == 2, "the episode continued past the failure and declared more calls"
declared = [call.id for message in messages for call in (message.tool_calls or [])]
assert declared == ["a1", "b1", "b2", "b3"], (
"the unexecuted calls must still reach the message view — they are the suffix "
"the join relies on being a suffix"
)
def test_episode_timeout_terminates_before_first_generation():
client = _ScriptedClient([GenerationResult(text="never", usage=Usage())])
loop = ToolCallingLoop(
llm_client=client,
tool_executor=_RecordingExecutor(),
tool_schemas=[],
config=LoopConfig(max_turns=5, episode_timeout_s=0),
metrics=_CountingSink(),
should_terminate=_never_terminate,
classify_error=_classify_no_patterns,
logger=_logger(),
)
messages: list[Message] = []
# start_time in the past so elapsed > 0 immediately.
outcome = loop.run("sys", messages, time.time() - 100)
assert outcome.status == TrialStatus.TIMEOUT
assert outcome.termination_reason == TerminationReason.TIMEOUT
assert client.calls == 0
def test_generation_error_is_classified_via_shared_classifier():
class _Boom:
def generate(self, system, messages, tools, tool_choice="auto", observation=None):
raise LLMApiTimeoutError("LLM API call timed out")
messages: list[Message] = []
outcome = _loop(_Boom(), should_terminate=_never_terminate).run("sys", messages, time.time())
assert outcome.status == TrialStatus.ERROR
assert outcome.termination_reason == TerminationReason.API_TIMEOUT
assert messages[-1].role == MessageRole.SYSTEM
def test_empty_completion_terminates_before_appending():
"""A generation with no text and no tool calls terminates the loop with
``EMPTY_COMPLETION``, without ever appending the empty assistant message
that a subsequent request would send to the provider."""
client = _ScriptedClient(
[
GenerationResult(text="", tool_calls=[], usage=Usage(prompt_tokens=1)),
GenerationResult(text="unreached", usage=Usage(prompt_tokens=1)),
]
)
messages: list[Message] = []
outcome = _loop(client, should_terminate=_never_terminate, max_turns=5).run(
"sys", messages, time.time()
)
assert client.calls == 1
assert outcome.termination_reason == TerminationReason.EMPTY_COMPLETION
assert outcome.status == TrialStatus.FAILED
assert not any(
m.role == MessageRole.ASSISTANT and m.content == "" and not m.tool_calls for m in messages
)
assert messages[-1].role == MessageRole.SYSTEM
assert "empty completion" in messages[-1].content
def test_empty_completion_still_records_generation_usage():
"""The trial paid for the empty completion, so metrics record it — only the
assistant message is skipped."""
client = _ScriptedClient(
[GenerationResult(text="", tool_calls=[], usage=Usage(prompt_tokens=7))]
)
sink = _CountingSink()
messages: list[Message] = []
_loop(client, should_terminate=_never_terminate, sink=sink, max_turns=5).run(
"sys", messages, time.time()
)
assert sink.generations == 1
assert sink.prompt_tokens == 7
def test_api_error_retry_recovers_on_second_attempt():
"""Bounded retry: a transient API-error on turn 0 recovers on the retry,
the tool call executes, the trial completes without a SYSTEM error."""
sleeps: list[float] = []
executor = _RecordingExecutor()
client = _ScriptedClient(
[
RuntimeError("LLM API call failed: gemini rejected empty tail"),
GenerationResult(
text="ok",
tool_calls=[ToolCall(id="a", name="query", arguments={"q": 1})],
usage=Usage(prompt_tokens=5),
),
]
)
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
executor=executor,
config=LoopConfig(
max_turns=1, episode_timeout_s=10_000, api_error_retries=1, api_error_backoff_s=0.0
),
retry_sleep=lambda s: sleeps.append(s),
).run("sys", messages, time.time())
assert client.calls == 2
assert outcome.status == TrialStatus.COMPLETED
assert executor.executed == [("query", {"q": 1}, "a")]
assert not any(m.role == MessageRole.SYSTEM and "API error" in m.content for m in messages)
assert sleeps == [0.0]
def test_api_error_retry_exhausts_and_fails_loud():
"""Retry budget spent: after ``api_error_retries + 1`` attempts, the trial
terminates with the classified system message intact."""
client = _ScriptedClient(
[
RuntimeError("LLM API call failed: gemini rejected empty tail"),
RuntimeError("LLM API call failed: gemini rejected empty tail"),
]
)
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
config=LoopConfig(
max_turns=5, episode_timeout_s=10_000, api_error_retries=1, api_error_backoff_s=0.0
),
).run("sys", messages, time.time())
assert client.calls == 2
assert outcome.status == TrialStatus.ERROR
assert outcome.termination_reason == TerminationReason.API_ERROR
assert messages[-1].role == MessageRole.SYSTEM
assert messages[-1].content == (
"API error: LLM API call failed: gemini rejected empty tail. Dialogue terminated."
)
def test_api_error_retry_does_not_mutate_messages_before_success():
"""Invariant lock: a raised attempt leaves ``messages`` unchanged, so the
successful attempt's assistant message stands alone with no ghost entry
from the failed attempt above it."""
client = _ScriptedClient(
[
RuntimeError("LLM API call failed: gemini rejected empty tail"),
GenerationResult(text="recovered", usage=Usage(prompt_tokens=5)),
]
)
messages: list[Message] = []
_loop(
client,
should_terminate=_never_terminate,
config=LoopConfig(
max_turns=1, episode_timeout_s=10_000, api_error_retries=1, api_error_backoff_s=0.0
),
).run("sys", messages, time.time())
assistant_messages = [m for m in messages if m.role == MessageRole.ASSISTANT]
assert len(assistant_messages) == 1
assert assistant_messages[0].content == "recovered"
def test_rate_limit_stays_one_shot():
"""Rate limits are not retried at the loop level — the client's own probe
controller owns 429 recovery, and retrying them here would double-count
the exclusion."""
def _classify_with_rate_limit(exc: Exception) -> TerminationDecision:
return classify_loop_error(exc, ())
wrapped_rate_limit = RuntimeError(
f"LLM API call failed: {RateLimitError(message='quota', llm_provider='openrouter', model='anthropic/claude')}"
)
wrapped_rate_limit.__cause__ = RateLimitError(
message="quota", llm_provider="openrouter", model="anthropic/claude"
)
client = _ScriptedClient([wrapped_rate_limit])
messages: list[Message] = []
outcome = ToolCallingLoop(
llm_client=client,
tool_executor=_RecordingExecutor(),
tool_schemas=[],
config=LoopConfig(
max_turns=5, episode_timeout_s=10_000, api_error_retries=5, api_error_backoff_s=0.0
),
metrics=_CountingSink(),
should_terminate=_never_terminate,
classify_error=_classify_with_rate_limit,
logger=_logger(),
retry_sleep=lambda _s: None,
).run("sys", messages, time.time())
assert client.calls == 1
assert outcome.termination_reason == TerminationReason.RATE_LIMIT
def test_empty_completion_not_retried_by_api_error_budget():
"""The API-error retry budget does not cover empty completions: even with a
generous ``api_error_retries``, an empty completion terminates on the first
turn when ``empty_retry_count == 0``. The two retry classes are orthogonal —
the empty-completion budget lives in a dedicated ``LoopConfig`` field."""
client = _ScriptedClient(
[GenerationResult(text="", tool_calls=[], usage=Usage(prompt_tokens=1))]
)
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
config=LoopConfig(
max_turns=5,
episode_timeout_s=10_000,
api_error_retries=5,
api_error_backoff_s=0.0,
empty_retry_count=0,
),
).run("sys", messages, time.time())
assert client.calls == 1
assert outcome.termination_reason == TerminationReason.EMPTY_COMPLETION
assert outcome.status == TrialStatus.FAILED
def test_empty_completion_retries_up_to_configured_count_then_succeeds():
"""With ``empty_retry_count=1``, the first empty resamples once and the
second sample's text lands as the assistant message. No ghost empty
assistant entry is appended. Both generations bill the metrics sink because
the trial paid for both calls."""
client = _ScriptedClient(
[
GenerationResult(text="", tool_calls=[], usage=Usage(prompt_tokens=3)),
GenerationResult(text="recovered", usage=Usage(prompt_tokens=5)),
]
)
sink = _CountingSink()
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
sink=sink,
config=LoopConfig(
max_turns=1,
episode_timeout_s=10_000,
empty_retry_count=1,
),
).run("sys", messages, time.time())
assert client.calls == 2
assert sink.generations == 2
assert sink.prompt_tokens == 8
assert outcome.termination_reason != TerminationReason.EMPTY_COMPLETION
assert outcome.status == TrialStatus.COMPLETED
assistant_messages = [m for m in messages if m.role == MessageRole.ASSISTANT]
assert len(assistant_messages) == 1
assert assistant_messages[0].content == "recovered"
assert not any(
m.role == MessageRole.ASSISTANT and m.content == "" and not m.tool_calls for m in messages
)
def test_empty_completion_retry_exhausts_and_terminates():
"""With ``empty_retry_count=N``, ``N + 1`` consecutive empty completions
exhaust the budget and terminate with ``EMPTY_COMPLETION``. Every resampled
empty still bills the metrics sink; exactly one SYSTEM message closes out
the loop with the empty-completion phrasing."""
retry_count = 2
client = _ScriptedClient(
[
GenerationResult(text="", tool_calls=[], usage=Usage(prompt_tokens=1))
for _ in range(retry_count + 1)
]
)
sink = _CountingSink()
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
sink=sink,
config=LoopConfig(
max_turns=5,
episode_timeout_s=10_000,
empty_retry_count=retry_count,
),
).run("sys", messages, time.time())
assert client.calls == retry_count + 1
assert sink.generations == retry_count + 1
assert outcome.termination_reason == TerminationReason.EMPTY_COMPLETION
assert outcome.status == TrialStatus.FAILED
assert messages[-1].role == MessageRole.SYSTEM
assert "empty completion" in messages[-1].content
system_messages = [m for m in messages if m.role == MessageRole.SYSTEM]
assert len(system_messages) == 1
def test_empty_completion_retry_does_not_advance_turn_counter():
"""Resamples happen within the same outer turn. With ``max_turns=1`` and
``empty_retry_count=2`` the loop absorbs two empties on turn 0 and executes
the recovered tool call also on turn 0, so a single outer iteration consumes
three generations. A subsequent generation would live in turn 1, which does
not fit under ``max_turns=1`` — this test locks that resamples do not
themselves count against the outer turn budget."""
executor = _RecordingExecutor()
client = _ScriptedClient(
[
GenerationResult(text="", tool_calls=[], usage=Usage(prompt_tokens=1)),
GenerationResult(text="", tool_calls=[], usage=Usage(prompt_tokens=1)),
GenerationResult(
text="ok",
tool_calls=[ToolCall(id="a", name="query", arguments={"q": 1})],
usage=Usage(prompt_tokens=5),
),
]
)
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
executor=executor,
config=LoopConfig(
max_turns=1,
episode_timeout_s=10_000,
empty_retry_count=2,
),
).run("sys", messages, time.time())
assert client.calls == 3
assert executor.executed == [("query", {"q": 1}, "a")]
assert outcome.termination_reason == TerminationReason.MAX_TURNS
def test_length_truncated_completion_not_retried_when_opt_out():
"""With ``output_length_retry_count=0`` (the default) a content-carrying
result with ``finish_reason="length"`` lands as the assistant turn
unchanged and the loop advances. No feedback marker is inserted — this
locks the default-off invariant against silent drift into a global
retry-with-feedback default (which would double reasoning spend on every
truncation across every preset)."""
client = _ScriptedClient(
[
GenerationResult(
text="partial",
usage=Usage(prompt_tokens=3),
finish_reason="length",
),
]
)
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
max_turns=1,
config=LoopConfig(
max_turns=1,
episode_timeout_s=10_000,
output_length_retry_count=0,
),
).run("sys", messages, time.time())
assert client.calls == 1
assistant_messages = [m for m in messages if m.role == MessageRole.ASSISTANT]
assert len(assistant_messages) == 1
assert assistant_messages[0].content == "partial"
assert not any(
m.role == MessageRole.USER and "truncated at max_tokens" in (m.content or "")
for m in messages
)
assert outcome.termination_reason == TerminationReason.MAX_TURNS
def test_length_truncated_completion_resamples_and_recovers():
"""With ``output_length_retry_count=1`` the first truncated response is
discarded, a ``role=user`` truncation-feedback turn is appended to both
the recorded history and the wire history, and the second (untruncated)
sample lands as the assistant turn. Locks the recovery shape and pins
that the feedback actually reaches the wire on the retry call."""
client = _ScriptedClient(
[
GenerationResult(
text="partial",
usage=Usage(prompt_tokens=3),
finish_reason="length",
),
GenerationResult(
text="recovered",
usage=Usage(prompt_tokens=5),
finish_reason="stop",
),
]
)
sink = _CountingSink()
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
sink=sink,
config=LoopConfig(
max_turns=1,
episode_timeout_s=10_000,
output_length_retry_count=1,
),
).run("sys", messages, time.time())
assert client.calls == 2
# (c) both generations bill the metrics sink because the trial paid.
assert sink.generations == 2
# (a) exactly one user-feedback turn with the truncation phrasing.
feedback_turns = [
m
for m in messages
if m.role == MessageRole.USER and "truncated at max_tokens" in (m.content or "")
]
assert len(feedback_turns) == 1
# (b) the truncated assistant message was NOT appended.
assert not any(m.role == MessageRole.ASSISTANT and m.content == "partial" for m in messages)
assistant_messages = [m for m in messages if m.role == MessageRole.ASSISTANT]
assert len(assistant_messages) == 1
assert assistant_messages[0].content == "recovered"
# (d) wire-level lock: the SECOND generate call's messages list ends with
# the truncation-feedback user turn — the retry with feedback actually
# reaches the provider, not just the recorded trajectory.
second_call_messages = client.messages_history[1]
tail = second_call_messages[-1]
assert tail.role == MessageRole.USER
assert "truncated at max_tokens" in (tail.content or "")
assert outcome.termination_reason == TerminationReason.MAX_TURNS
def test_length_truncated_completion_exhausts_and_accepts_last_response():
"""With ``output_length_retry_count=1``, two consecutive truncated
responses exhaust the budget: exactly one feedback turn was inserted
(before the second attempt) and the second truncated response lands as
the assistant turn with its partial content preserved. The loop
continues normally — no new terminal, no ``EMPTY_COMPLETION`` — the
exhaustion path is strictly recoverable."""
client = _ScriptedClient(
[
GenerationResult(
text="partial-1",
usage=Usage(prompt_tokens=3),
finish_reason="length",
),
GenerationResult(
text="partial-2",
usage=Usage(prompt_tokens=3),
finish_reason="length",
),
]
)
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
config=LoopConfig(
max_turns=1,
episode_timeout_s=10_000,
output_length_retry_count=1,
),
).run("sys", messages, time.time())
assert client.calls == 2
assert outcome.termination_reason == TerminationReason.MAX_TURNS
assert outcome.status == TrialStatus.COMPLETED
assistant_messages = [m for m in messages if m.role == MessageRole.ASSISTANT]
assert len(assistant_messages) == 1
assert assistant_messages[0].content == "partial-2"
feedback_turns = [
m
for m in messages
if m.role == MessageRole.USER and "truncated at max_tokens" in (m.content or "")
]
assert len(feedback_turns) == 1
def test_length_retry_does_not_advance_turn_counter():
"""Resamples happen within the same outer turn. With ``max_turns=1`` and
``output_length_retry_count=2`` the loop absorbs two truncated resamples
on turn 0 and executes the recovered tool call also on turn 0, so a
single outer iteration consumes three generations. Mirrors the shape of
``test_empty_completion_retry_does_not_advance_turn_counter``."""
executor = _RecordingExecutor()
client = _ScriptedClient(
[
GenerationResult(
text="partial-1",
usage=Usage(prompt_tokens=1),
finish_reason="length",
),
GenerationResult(
text="partial-2",
usage=Usage(prompt_tokens=1),
finish_reason="length",
),
GenerationResult(
text="ok",
tool_calls=[ToolCall(id="a", name="query", arguments={"q": 1})],
usage=Usage(prompt_tokens=5),
finish_reason="tool_calls",
),
]
)
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
executor=executor,
config=LoopConfig(
max_turns=1,
episode_timeout_s=10_000,
output_length_retry_count=2,
),
).run("sys", messages, time.time())
assert client.calls == 3
assert executor.executed == [("query", {"q": 1}, "a")]
assert outcome.termination_reason == TerminationReason.MAX_TURNS
def test_length_finish_reason_with_empty_content_uses_empty_path():
"""A ``finish_reason=='length'`` result with no text / no tool_calls
routes through the empty-completion branch, not the length-retry branch.
Locks the disjoint-path invariant against a future refactor that flattens
the current nesting under ``if result.text or result.tool_calls:``."""
client = _ScriptedClient(
[
GenerationResult(
text="",
usage=Usage(prompt_tokens=1),
finish_reason="length",
),
]
)
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
config=LoopConfig(
max_turns=1,
episode_timeout_s=10_000,
empty_retry_count=0,
output_length_retry_count=1,
),
).run("sys", messages, time.time())
assert client.calls == 1
assert outcome.termination_reason == TerminationReason.EMPTY_COMPLETION
# Length-retry did NOT fire — no user feedback marker was inserted.
assert not any(
m.role == MessageRole.USER and "truncated at max_tokens" in (m.content or "")
for m in messages
)
def _result_with_parser_errors(
*,
text: str = "call",
tool_calls: list[ToolCall],
parser_errors: tuple[ParserError, ...],
prompt_tokens: int = 3,
) -> GenerationResult:
"""Build a scripted ``GenerationResult`` with a ``parser_errors`` sidecar
populated the way ``LLMClient._assemble_result`` populates it."""
result = GenerationResult(
text=text,
tool_calls=tool_calls,
usage=Usage(prompt_tokens=prompt_tokens),
)
result.parser_errors = parser_errors
return result
def test_parser_error_not_retried_when_opt_out():
"""With ``parser_error_retry_count=0`` (the default) a response carrying
``parser_errors`` lands as the assistant turn unchanged and the loop
advances normally — the ``{}``-coerced tool_call is handed to the
executor. No user-feedback marker is inserted. Locks the default-off
invariant against silent drift."""
executor = _RecordingExecutor()
client = _ScriptedClient(
[
_result_with_parser_errors(
text="broken",
tool_calls=[ToolCall(id="a", name="query", arguments={})],
parser_errors=(
ParserError(
tool_name="query",
raw_arguments='{"broken',
reason="Unable to parse with JSON/YAML fallbacks",
),
),
),
]
)
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
executor=executor,
config=LoopConfig(
max_turns=1,
episode_timeout_s=10_000,
parser_error_retry_count=0,
),
).run("sys", messages, time.time())
assert client.calls == 1
assistant_messages = [m for m in messages if m.role == MessageRole.ASSISTANT]
assert len(assistant_messages) == 1
assert executor.executed == [("query", {}, "a")]
assert not any(
m.role == MessageRole.USER and "tool_call argument parse errors" in (m.content or "")
for m in messages
)
assert outcome.termination_reason == TerminationReason.MAX_TURNS
def test_parser_error_resamples_and_recovers():
"""With ``parser_error_retry_count=1``, the first response has non-empty
``parser_errors`` and is discarded; a ``role=user`` parse-error feedback
turn is appended to both the recorded history and the wire history; the
second (parser-clean) sample is executed. Locks the recovery shape and
pins that the feedback actually reaches the wire on the retry call."""
executor = _RecordingExecutor()
sink = _CountingSink()
client = _ScriptedClient(
[
_result_with_parser_errors(
text="broken",
tool_calls=[ToolCall(id="a", name="query", arguments={})],
parser_errors=(
ParserError(
tool_name="query",
raw_arguments='{"broken',
reason="Unable to parse with JSON/YAML fallbacks",
),
),
),
GenerationResult(
text="ok",
tool_calls=[ToolCall(id="b", name="query", arguments={"q": 1})],
usage=Usage(prompt_tokens=5),
),
]
)
messages: list[Message] = []
outcome = _loop(
client,
should_terminate=_never_terminate,
executor=executor,
sink=sink,
config=LoopConfig(
max_turns=1,
episode_timeout_s=10_000,
parser_error_retry_count=1,
),
).run("sys", messages, time.time())
assert client.calls == 2
assert sink.generations == 2 # (c) both generations bill the metrics sink.
# (a) exactly one user-feedback turn carrying the parser-error phrasing,
# the failing tool name, the raw args snippet, and the reason.
feedback_turns = [
m
for m in messages
if m.role == MessageRole.USER and "tool_call argument parse errors" in (m.content or "")
]
assert len(feedback_turns) == 1
feedback_content = feedback_turns[0].content or ""
assert "'query'" in feedback_content
assert '{"broken' in feedback_content
assert "Unable to parse with JSON/YAML fallbacks" in feedback_content
# (b) the discarded assistant message (with the failed tool_call) is NOT
# in the recorded history.
assert not any(m.role == MessageRole.ASSISTANT and m.content == "broken" for m in messages)
assistant_messages = [m for m in messages if m.role == MessageRole.ASSISTANT]
assert len(assistant_messages) == 1
assert assistant_messages[0].content == "ok"
# (d) wire-level lock: the SECOND generate call's messages list ends with
# the parser-error feedback user turn — the retry with feedback actually
# reaches the provider, not just the recorded trajectory.
second_call_messages = client.messages_history[1]
tail = second_call_messages[-1]
assert tail.role == MessageRole.USER
assert "tool_call argument parse errors" in (tail.content or "")
# (e) the recovered tool_call was executed with the recovered args.
assert executor.executed == [("query", {"q": 1}, "b")]
assert outcome.termination_reason == TerminationReason.MAX_TURNS