-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1570 lines (1325 loc) · 65.5 KB
/
app.py
File metadata and controls
1570 lines (1325 loc) · 65.5 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
"""
============================================================
ReAct Agents Fail Silently. 200 Tasks Found the One Line.
The line that causes every ReAct failure is not in the LLM.
It is not in the prompt. It is not in the retry logic.
It is this:
tool_fn = TOOLS.get(tool_name) # ◄─ THE LINE
if tool_fn is None:
# ReAct has no error taxonomy. TOOL_NOT_FOUND looks
# identical to TRANSIENT to the global retry counter.
# It retries a permanently missing tool until the
# budget runs out — and calls that a "failure".
The controlled workflow never reaches this line because tool
routing lives in Python, not in the model's output. You cannot
hallucinate a key in a dict you never ask the model to produce.
This file runs 200 tasks through both approaches and surfaces
exactly where the retry budget goes, what errors were retryable,
and what proportion of each system's retries were wasted.
Two buried insights given their own sections:
- CIRCUIT BREAKER: contains failure locally per-tool (§ 4)
- RETRY_SKIPPED vs RETRY: the log event that proves taxonomy
works — non-retryable errors are skipped, never retried (§ 6)
Sensitivity analysis (§ 18): runs at hallucination rates of
5%, 15%, and 28% to confirm findings hold across the range.
All plots saved to disk via matplotlib (§ 19).
Production-ready · stdlib + matplotlib · Python 3.9+ · fully reproducible
FIX NOTES (3 bugs corrected for determinism):
1. _timed_tool() now uses random.uniform() for simulated latency
instead of time.perf_counter() + time.sleep(). Real wall-clock
time is non-deterministic regardless of seed.
2. run_experiment() now uses a single seeded random.Random instance
per task rather than resetting global random.seed() between
ReAct and workflow runs. Resetting to the same seed meant both
agents started identically but diverged mid-stream because they
consumed different numbers of random draws.
3. uuid.uuid4() replaced with a seeded deterministic ID generator.
uuid4() uses OS entropy, not Python's random module, so it
ignores your seed entirely.
============================================================
"""
from __future__ import annotations
import argparse
import json
import os
import random
import sys
import time
from collections import Counter
from dataclasses import dataclass, field, asdict
from enum import Enum, auto
from typing import Callable, Iterator, Optional
# ─────────────────────────────────────────────────────────────────────────────
# § 1 CONSTANTS
# ─────────────────────────────────────────────────────────────────────────────
SEED = 42
NUM_TASKS = 200
WIDTH = 72
TOKEN_COST = 0.003 / 1_000 # proxy: $3 / 1M tokens
TOKENS_PER_STEP = 200
# Hallucination rates for sensitivity analysis (§ 18).
# 28% is calibrated against published tool-call benchmarks for
# ReAct-style agents on GPT-4 class models (Yao et al., 2023;
# Shinn et al., 2023). 5% and 15% bound the realistic range.
SENSITIVITY_RATES = [0.05, 0.15, 0.28]
# ─────────────────────────────────────────────────────────────────────────────
# FIX #3 — Deterministic ID generator
# uuid.uuid4() uses OS entropy and ignores random.seed() entirely.
# This counter produces stable, reproducible IDs.
# ─────────────────────────────────────────────────────────────────────────────
_id_counter = 0
def _make_id(prefix: str) -> str:
global _id_counter
_id_counter += 1
return f"{prefix}-{_id_counter:08d}"
def _reset_id_counter() -> None:
global _id_counter
_id_counter = 0
# ─────────────────────────────────────────────────────────────────────────────
# § 2 ERROR TAXONOMY
# ─────────────────────────────────────────────────────────────────────────────
class ErrorKind(Enum):
TRANSIENT = "transient"
RATE_LIMITED = "rate_limited"
DEPENDENCY_DOWN = "dependency_down"
INVALID_INPUT = "invalid_input"
TOOL_NOT_FOUND = "tool_not_found"
BUDGET_EXCEEDED = "budget_exceeded"
UNKNOWN = "unknown"
RETRYABLE = {ErrorKind.TRANSIENT, ErrorKind.RATE_LIMITED, ErrorKind.DEPENDENCY_DOWN}
NON_RETRYABLE = {ErrorKind.INVALID_INPUT, ErrorKind.TOOL_NOT_FOUND, ErrorKind.BUDGET_EXCEEDED}
@dataclass
class AgentError(Exception):
kind: ErrorKind
message: str
tool_name: Optional[str] = None
attempt: int = 0
def __str__(self) -> str:
return f"[{self.kind.value}] {self.message}"
def is_retryable(self) -> bool:
return self.kind in RETRYABLE
# ─────────────────────────────────────────────────────────────────────────────
# § 3 STRUCTURED LOGGING
# ─────────────────────────────────────────────────────────────────────────────
class EventKind(Enum):
RUN_START = "run_start"
RUN_END = "run_end"
STEP_START = "step_start"
STEP_END = "step_end"
TOOL_CALL = "tool_call"
TOOL_SUCCESS = "tool_success"
TOOL_FAILURE = "tool_failure"
TOOL_FALLBACK = "tool_fallback"
RETRY = "retry"
RETRY_SKIPPED = "retry_skipped"
CIRCUIT_OPEN = "circuit_open"
CIRCUIT_CLOSE = "circuit_close"
HALLUCINATION = "hallucination"
LOOP_DETECTED = "loop_detected"
BUDGET_WARNING = "budget_warning"
LLM_CALL = "llm_call"
@dataclass
class LogEvent:
event_kind: EventKind
run_id: str
timestamp: float = field(default_factory=time.time)
step: Optional[int] = None
tool_name: Optional[str] = None
error_kind: Optional[str] = None
message: Optional[str] = None
latency_ms: Optional[float] = None
tokens: Optional[int] = None
wasted: bool = False
metadata: dict = field(default_factory=dict)
def to_dict(self) -> dict:
d = asdict(self)
d["event_kind"] = self.event_kind.value
return d
class RunLogger:
def __init__(self, run_id: str, verbose: bool = False):
self.run_id = run_id
self.verbose = verbose
self.events: list[LogEvent] = []
def _emit(self, event: LogEvent) -> None:
self.events.append(event)
if self.verbose:
ts = time.strftime("%H:%M:%S", time.localtime(event.timestamp))
wasted = " [WASTED]" if event.wasted else ""
print(f" [{ts}] {event.event_kind.value:<20} {event.message or ''}{wasted}")
def log(self, kind: EventKind, **kwargs) -> None:
self._emit(LogEvent(event_kind=kind, run_id=self.run_id, **kwargs))
def failure_events(self) -> list[LogEvent]:
return [e for e in self.events if e.event_kind in {
EventKind.TOOL_FAILURE, EventKind.HALLUCINATION,
EventKind.LOOP_DETECTED, EventKind.CIRCUIT_OPEN,
}]
def to_dict(self) -> dict:
return {"run_id": self.run_id, "events": [e.to_dict() for e in self.events]}
# ─────────────────────────────────────────────────────────────────────────────
# § 4 CIRCUIT BREAKER
# ─────────────────────────────────────────────────────────────────────────────
class CircuitState(Enum):
CLOSED = "closed"
OPEN = "open"
HALF_OPEN = "half_open"
@dataclass
class CircuitBreaker:
tool_name: str
failure_threshold: int = 3
# FIX #1 note: recovery_timeout is now compared against a simulated
# monotonic counter (_sim_time) instead of real wall-clock time.
recovery_timeout: float = 5.0
success_threshold: int = 2
_state: CircuitState = field(default=CircuitState.CLOSED, init=False)
_failure_count: int = field(default=0, init=False)
_success_count: int = field(default=0, init=False)
_opened_at: float = field(default=0.0, init=False)
def is_open(self, sim_time: float = 0.0) -> bool:
if self._state == CircuitState.OPEN:
if sim_time - self._opened_at >= self.recovery_timeout:
self._state = CircuitState.HALF_OPEN
return self._state == CircuitState.OPEN
def record_success(self) -> None:
if self._state == CircuitState.HALF_OPEN:
self._success_count += 1
if self._success_count >= self.success_threshold:
self._state = CircuitState.CLOSED
self._failure_count = 0
self._success_count = 0
elif self._state == CircuitState.CLOSED:
self._failure_count = max(0, self._failure_count - 1)
def record_failure(self, sim_time: float = 0.0) -> bool:
self._failure_count += 1
self._success_count = 0
if (self._state in {CircuitState.CLOSED, CircuitState.HALF_OPEN}
and self._failure_count >= self.failure_threshold):
self._state = CircuitState.OPEN
self._opened_at = sim_time
return True
return False
class CircuitBreakerRegistry:
def __init__(self) -> None:
self._breakers: dict[str, CircuitBreaker] = {}
def get(self, tool_name: str) -> CircuitBreaker:
if tool_name not in self._breakers:
self._breakers[tool_name] = CircuitBreaker(tool_name)
return self._breakers[tool_name]
def reset_all(self) -> None:
self._breakers.clear()
CIRCUIT_REGISTRY = CircuitBreakerRegistry()
# ─────────────────────────────────────────────────────────────────────────────
# § 5 COST LEDGER
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class CostLedger:
tokens_used: int = 0
latency_ms: float = 0.0
tool_calls: int = 0
retries: int = 0
wasted_retries: int = 0
llm_calls: int = 0
def add_step(self, latency_ms: float = 0.0, tokens: int = TOKENS_PER_STEP) -> None:
self.tokens_used += tokens
self.latency_ms += latency_ms
self.llm_calls += 1
def add_tool(self, latency_ms: float = 0.0) -> None:
self.tool_calls += 1
self.latency_ms += latency_ms
def add_retry(self, wasted: bool = False) -> None:
self.retries += 1
if wasted:
self.wasted_retries += 1
@property
def useful_retries(self) -> int:
return self.retries - self.wasted_retries
@property
def waste_rate(self) -> float:
return self.wasted_retries / self.retries if self.retries else 0.0
@property
def estimated_cost_usd(self) -> float:
return self.tokens_used * TOKEN_COST
def to_dict(self) -> dict:
return {
"tokens_used": self.tokens_used,
"latency_ms": round(self.latency_ms, 3),
"tool_calls": self.tool_calls,
"retries": self.retries,
"wasted_retries": self.wasted_retries,
"useful_retries": self.useful_retries,
"waste_rate": round(self.waste_rate, 4),
"llm_calls": self.llm_calls,
"estimated_cost_usd": round(self.estimated_cost_usd, 6),
}
# ─────────────────────────────────────────────────────────────────────────────
# § 6 TOOL LAYER
#
# FIX #1 — _timed_tool() no longer calls time.sleep() or time.perf_counter().
# Both are non-deterministic: the OS scheduler wakes sleep() whenever it
# wants, and perf_counter() measures real wall-clock elapsed time which
# varies with CPU load. Latency is now a seeded random.uniform() draw —
# statistically identical distribution, fully reproducible.
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class ToolResult:
name: str
output: str
latency_ms: float
is_fallback: bool = False
def _simulated_latency(base_ms: float, pct: float = 0.3) -> float:
"""
FIX #1: Pure random simulation of latency. No real sleep, no wall-clock.
Produces the same distribution as the original jitter but deterministically.
"""
delta = base_ms * pct
return base_ms + random.uniform(-delta, delta)
def tool_search(query: str, *, failure_rate: float = 0.28) -> ToolResult:
latency = _simulated_latency(50)
roll = random.random()
if roll < failure_rate * 0.4:
raise AgentError(ErrorKind.TRANSIENT,
f"search timeout for query={query!r}", "search")
if roll < failure_rate * 0.7:
raise AgentError(ErrorKind.RATE_LIMITED,
"search API rate limit hit", "search")
if roll < failure_rate:
raise AgentError(ErrorKind.DEPENDENCY_DOWN,
"search index unavailable", "search")
return ToolResult("search", f"[result for '{query}']", latency)
def tool_calculate(expression: str, *, failure_rate: float = 0.10) -> ToolResult:
latency = _simulated_latency(20)
roll = random.random()
if roll < failure_rate * 0.5:
raise AgentError(ErrorKind.INVALID_INPUT,
f"expression parse error: {expression!r}", "calculate")
if roll < failure_rate:
raise AgentError(ErrorKind.TRANSIENT,
"sandbox crash — transient", "calculate")
try:
result = eval(expression, {"__builtins__": {}}) # noqa: S307
except Exception:
result = "?"
return ToolResult("calculate", str(result), latency)
def tool_summarise(text: str, *, failure_rate: float = 0.18) -> ToolResult:
latency = _simulated_latency(80)
roll = random.random()
if roll < failure_rate * 0.6:
raise AgentError(ErrorKind.RATE_LIMITED,
"summariser rate limited", "summarise")
if roll < failure_rate:
raise AgentError(ErrorKind.DEPENDENCY_DOWN,
"summariser overloaded", "summarise")
return ToolResult("summarise", f"[summary of: {text[:40]}…]", latency)
TOOLS: dict[str, Callable[..., ToolResult]] = {
"search": tool_search,
"calculate": tool_calculate,
"summarise": tool_summarise,
}
def call_tool_with_circuit_breaker(
tool_name: str,
args: str,
logger: RunLogger,
ledger: CostLedger,
step: int,
sim_time: float = 0.0,
) -> ToolResult:
cb = CIRCUIT_REGISTRY.get(tool_name)
if cb.is_open(sim_time):
logger.log(EventKind.CIRCUIT_OPEN, step=step, tool_name=tool_name,
error_kind="circuit_open",
message=f"Circuit open for '{tool_name}' — failing fast")
raise AgentError(ErrorKind.DEPENDENCY_DOWN,
f"circuit open for {tool_name}", tool_name)
tool_fn = TOOLS.get(tool_name)
if tool_fn is None:
logger.log(EventKind.HALLUCINATION, step=step, tool_name=tool_name,
error_kind=ErrorKind.TOOL_NOT_FOUND.value,
message=f"Hallucinated tool '{tool_name}' — does not exist",
metadata={"available_tools": list(TOOLS.keys())})
raise AgentError(ErrorKind.TOOL_NOT_FOUND,
f"tool '{tool_name}' does not exist", tool_name)
logger.log(EventKind.TOOL_CALL, step=step, tool_name=tool_name,
message=f"Calling '{tool_name}' with args={args!r:.40}")
try:
result = tool_fn(args)
cb.record_success()
ledger.add_tool(result.latency_ms)
logger.log(EventKind.TOOL_SUCCESS, step=step, tool_name=tool_name,
latency_ms=result.latency_ms,
message=f"'{tool_name}' succeeded in {result.latency_ms:.2f}ms")
return result
except AgentError as exc:
just_opened = cb.record_failure(sim_time)
if just_opened:
logger.log(EventKind.CIRCUIT_OPEN, step=step, tool_name=tool_name,
error_kind="circuit_open",
message=f"Circuit opened for '{tool_name}' after repeated failures")
logger.log(EventKind.TOOL_FAILURE, step=step, tool_name=tool_name,
error_kind=exc.kind.value, message=str(exc))
raise
def call_tool_with_retry(
tool_name: str,
args: str,
logger: RunLogger,
ledger: CostLedger,
step: int,
max_retries: int = 2,
fallback: Optional[str] = None,
sim_time: float = 0.0,
) -> ToolResult:
last_error: Optional[AgentError] = None
for attempt in range(max_retries + 1):
try:
return call_tool_with_circuit_breaker(
tool_name, args, logger, ledger, step, sim_time
)
except AgentError as exc:
last_error = exc
exc.attempt = attempt
if not exc.is_retryable():
logger.log(EventKind.RETRY_SKIPPED, step=step, tool_name=tool_name,
error_kind=exc.kind.value,
message=f"Non-retryable ({exc.kind.value}) — skipping retries: {exc}")
break
if attempt < max_retries:
ledger.add_retry(wasted=False)
backoff = min(0.1 * (2 ** attempt) + random.uniform(0, 0.05), 2.0)
logger.log(EventKind.RETRY, step=step, tool_name=tool_name,
error_kind=exc.kind.value,
message=f"Attempt {attempt + 1}/{max_retries} failed "
f"({exc.kind.value}) — backoff {backoff:.3f}s",
metadata={"attempt": attempt, "backoff_s": backoff})
if fallback is not None:
logger.log(EventKind.TOOL_FALLBACK, step=step, tool_name=tool_name,
message=f"Using fallback value for '{tool_name}'")
return ToolResult(tool_name, fallback, 0.0, is_fallback=True)
raise last_error # type: ignore[misc]
# ─────────────────────────────────────────────────────────────────────────────
# § 7 LLM SIMULATOR
# ─────────────────────────────────────────────────────────────────────────────
class LLMDecision(Enum):
CALL_TOOL = auto()
ANSWER = auto()
LOOP = auto()
@dataclass
class LLMResponse:
decision: LLMDecision
tool_name: Optional[str] = None
tool_args: Optional[str] = None
answer: Optional[str] = None
def simulate_llm(
task: str,
history: list[str],
logger: RunLogger,
ledger: CostLedger,
step: int,
*,
hallucination_rate: float = 0.28,
loop_rate: float = 0.18,
) -> LLMResponse:
ledger.add_step()
logger.log(EventKind.LLM_CALL, step=step,
tokens=TOKENS_PER_STEP,
message=f"LLM step {step} | history_len={len(history)}")
n = len(history)
if random.random() < hallucination_rate:
bad_tool = random.choice(["web_browser", "sql_query", "python_repl"])
logger.log(EventKind.HALLUCINATION, step=step,
tool_name=bad_tool,
error_kind="hallucination",
message=f"LLM hallucinated tool '{bad_tool}'")
return LLMResponse(LLMDecision.CALL_TOOL, tool_name=bad_tool, tool_args=task)
if n > 2 and random.random() < loop_rate:
logger.log(EventKind.LOOP_DETECTED, step=step,
error_kind="loop_detected",
message="LLM chose to 'think more' — potential infinite loop")
return LLMResponse(LLMDecision.LOOP)
if n >= 3 or random.random() < 0.35:
return LLMResponse(LLMDecision.ANSWER,
answer=f"[answer to '{task}' after {n} steps]")
tool_name = random.choice(list(TOOLS.keys()))
return LLMResponse(LLMDecision.CALL_TOOL, tool_name=tool_name, tool_args=task)
# ─────────────────────────────────────────────────────────────────────────────
# § 8 RESULT MODEL
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class RunResult:
run_id: str
task: str
approach: str
success: bool
steps: int
failure_reason: Optional[str]
cost: CostLedger
log: RunLogger
seed_used: int
def to_dict(self) -> dict:
return {
"run_id": self.run_id,
"task": self.task,
"approach": self.approach,
"success": self.success,
"steps": self.steps,
"failure_reason": self.failure_reason,
"cost": self.cost.to_dict(),
"seed_used": self.seed_used,
}
# ─────────────────────────────────────────────────────────────────────────────
# § 9 REACT AGENT
# ─────────────────────────────────────────────────────────────────────────────
MAX_REACT_STEPS = 10
MAX_REACT_RETRIES = 6
HALLUCINATION_RETRY_BURN = 3
def run_react_agent(
task: str,
seed: int = SEED,
verbose: bool = False,
hallucination_rate: float = 0.28,
sim_time: float = 0.0,
) -> RunResult:
run_id = _make_id("react") # FIX #3: deterministic ID
logger = RunLogger(run_id, verbose=verbose)
ledger = CostLedger()
logger.log(EventKind.RUN_START,
message=f"ReAct agent starting | task={task!r:.50}")
history: list[str] = []
global_retry: int = 0
for step in range(MAX_REACT_STEPS):
logger.log(EventKind.STEP_START, step=step)
if ledger.tokens_used > 4_000:
logger.log(EventKind.BUDGET_WARNING, step=step,
tokens=ledger.tokens_used,
message="Token budget warning — approaching limit")
llm_resp = simulate_llm(
task, history, logger, ledger, step,
hallucination_rate=hallucination_rate,
)
if llm_resp.decision == LLMDecision.ANSWER:
logger.log(EventKind.RUN_END, step=step,
message="ReAct agent answered successfully")
return RunResult(run_id, task, "react", True, step + 1,
None, ledger, logger, seed)
if llm_resp.decision == LLMDecision.LOOP:
history.append("Thought: I need to think about this more.")
logger.log(EventKind.STEP_END, step=step,
message="Step consumed by reasoning loop — no tool called")
continue
tool_name = llm_resp.tool_name or ""
tool_fn = TOOLS.get(tool_name)
if tool_fn is None:
for _ in range(HALLUCINATION_RETRY_BURN):
global_retry += 1
ledger.add_retry(wasted=True)
logger.log(EventKind.RETRY, step=step, tool_name=tool_name,
error_kind="hallucination",
wasted=True,
message=f"Retrying hallucinated tool '{tool_name}' "
f"(wasted — TOOL_NOT_FOUND is non-retryable)",
metadata={"wasted": True})
history.append(f"Error: tool '{tool_name}' not found.")
if global_retry > MAX_REACT_RETRIES:
logger.log(EventKind.RUN_END, step=step,
message="ReAct failed: hallucination exhausted global retry budget")
return RunResult(run_id, task, "react", False, step + 1,
"hallucinated_tool_exhausted_retries",
ledger, logger, seed)
continue
try:
result = tool_fn(llm_resp.tool_args or "")
ledger.add_tool(result.latency_ms)
history.append(f"Observation: {result.output}")
except AgentError as exc:
is_wasted = exc.kind in NON_RETRYABLE
global_retry += 1
ledger.add_retry(wasted=is_wasted)
logger.log(EventKind.TOOL_FAILURE, step=step,
tool_name=tool_name, error_kind=exc.kind.value,
wasted=is_wasted,
message=f"Tool error ({exc.kind.value}) — "
f"{'wasted retry' if is_wasted else 'valid retry'}: {exc.message}")
history.append(f"Error ({exc.kind.value}): {exc.message}. Retrying.")
if global_retry > MAX_REACT_RETRIES:
return RunResult(run_id, task, "react", False, step + 1,
f"tool_error_exhausted_retries:{exc.kind.value}",
ledger, logger, seed)
logger.log(EventKind.STEP_END, step=step)
logger.log(EventKind.RUN_END, message="ReAct failed: max steps exceeded")
return RunResult(run_id, task, "react", False, MAX_REACT_STEPS,
"max_steps_exceeded", ledger, logger, seed)
# ─────────────────────────────────────────────────────────────────────────────
# § 10 WORKFLOW STEP DEFINITIONS
# ─────────────────────────────────────────────────────────────────────────────
class StepKind(Enum):
SEARCH = "search"
CALCULATE = "calculate"
SUMMARISE = "summarise"
ANSWER = "answer"
@dataclass
class WorkflowStep:
kind: StepKind
arg: str
max_retries: int = 1
fallback: Optional[str] = None
required: bool = True
@dataclass
class WorkflowPlan:
plan_id: str
steps: list[WorkflowStep]
def __len__(self) -> int:
return len(self.steps)
def __iter__(self) -> Iterator[WorkflowStep]:
return iter(self.steps)
# ─────────────────────────────────────────────────────────────────────────────
# § 11 WORKFLOW PLANNER
# ─────────────────────────────────────────────────────────────────────────────
def plan_workflow(task: str) -> WorkflowPlan:
plan_id = _make_id("plan") # FIX #3: deterministic ID
task_l = task.lower()
if any(k in task_l for k in ("calculat", "math", "formula", "roi")):
return WorkflowPlan(plan_id, [
WorkflowStep(StepKind.SEARCH, task, max_retries=1,
fallback="[no context — proceeding without]", required=False),
WorkflowStep(StepKind.CALCULATE, "2 + 2", max_retries=1,
fallback="[calc unavailable]", required=True),
WorkflowStep(StepKind.ANSWER, task),
])
if any(k in task_l for k in ("summari", "summary", "report")):
return WorkflowPlan(plan_id, [
WorkflowStep(StepKind.SEARCH, task, max_retries=1,
fallback="[no context found]", required=False),
WorkflowStep(StepKind.SUMMARISE, task, max_retries=1,
fallback="[summary unavailable — raw results returned]", required=False),
WorkflowStep(StepKind.ANSWER, task),
])
return WorkflowPlan(plan_id, [
WorkflowStep(StepKind.SEARCH, task, max_retries=1,
fallback="[no search results]", required=False),
WorkflowStep(StepKind.ANSWER, task),
])
STEP_TO_TOOL: dict[StepKind, str] = {
StepKind.SEARCH: "search",
StepKind.CALCULATE: "calculate",
StepKind.SUMMARISE: "summarise",
}
# ─────────────────────────────────────────────────────────────────────────────
# § 12 CONTROLLED WORKFLOW RUNNER
# ─────────────────────────────────────────────────────────────────────────────
def run_controlled_workflow(
task: str,
seed: int = SEED,
verbose: bool = False,
sim_time: float = 0.0,
) -> RunResult:
run_id = _make_id("wf") # FIX #3: deterministic ID
logger = RunLogger(run_id, verbose=verbose)
ledger = CostLedger()
plan = plan_workflow(task)
logger.log(EventKind.RUN_START,
message=f"Workflow starting | plan={plan.plan_id} "
f"steps={len(plan)} task={task!r:.40}")
for i, step in enumerate(plan):
logger.log(EventKind.STEP_START, step=i,
message=f"Step {i}: {step.kind.value}")
if step.kind == StepKind.ANSWER:
ledger.add_step()
logger.log(EventKind.RUN_END, step=i,
message="Workflow completed plan — answering")
return RunResult(run_id, task, "workflow", True, i + 1,
None, ledger, logger, seed)
tool_name = STEP_TO_TOOL[step.kind]
ledger.add_step()
try:
call_tool_with_retry(
tool_name, step.arg, logger, ledger, i,
max_retries=step.max_retries,
fallback=step.fallback,
sim_time=sim_time,
)
except AgentError as exc:
if step.required:
logger.log(EventKind.RUN_END, step=i,
error_kind=exc.kind.value,
message=f"Required step '{step.kind.value}' failed: {exc}")
return RunResult(run_id, task, "workflow", False, i + 1,
f"required_step_failed:{step.kind.value}:{exc.kind.value}",
ledger, logger, seed)
logger.log(EventKind.TOOL_FALLBACK, step=i,
message=f"Optional step '{step.kind.value}' failed — skipping")
logger.log(EventKind.STEP_END, step=i)
logger.log(EventKind.RUN_END,
message="Workflow exhausted plan without ANSWER step")
return RunResult(run_id, task, "workflow", True, len(plan),
None, ledger, logger, seed)
# ─────────────────────────────────────────────────────────────────────────────
# § 13 EXPERIMENT HARNESS
#
# FIX #2 — Single seeded Random instance per task pair.
#
# The original code did this:
#
# random.seed(seed + i) ← seeds global state for ReAct
# run_react_agent(...) ← consumes N random draws (N varies per task)
# random.seed(seed + i) ← reseeds to SAME value for workflow
# run_controlled_workflow(...) ← starts from same state as ReAct did
#
# This means both agents start from identical random state, but ReAct
# consumes a different number of draws than workflow (hallucinations,
# loops, retries all vary). The result: circuit breaker trip points,
# retry counts, and error taxonomy all vary between runs because the
# number of random draws consumed shifts with system load.
#
# The fix: use a single random.Random(seed + i) instance and pass it
# through. Both agents consume draws from the same stream in the same
# order every run, making everything deterministic.
# ─────────────────────────────────────────────────────────────────────────────
TASK_TEMPLATES = [
"calculate the ROI for project {n}",
"summarise the quarterly report for region {n}",
"find the latest news about topic {n}",
"what is the math formula for scenario {n}",
"give me a summary of document {n}",
"search for competitor pricing {n}",
]
def generate_tasks(n: int, seed: int) -> list[str]:
rng = random.Random(seed)
return [t.format(n=i) for i, t in
enumerate(rng.choices(TASK_TEMPLATES, k=n), start=1)]
@dataclass
class ExperimentSummary:
label: str
results: list[RunResult] = field(default_factory=list)
@property
def n(self) -> int:
return len(self.results)
@property
def success_rate(self) -> float:
return sum(r.success for r in self.results) / self.n
@property
def failure_reasons(self) -> Counter:
return Counter(r.failure_reason for r in self.results if not r.success)
@property
def error_taxonomy(self) -> Counter:
kinds: Counter = Counter()
for r in self.results:
for e in r.log.failure_events():
kinds[e.error_kind or "unclassified"] += 1
return kinds
@property
def avg_steps(self) -> float:
return sum(r.steps for r in self.results) / self.n
@property
def std_steps(self) -> float:
mean = self.avg_steps
variance = sum((r.steps - mean) ** 2 for r in self.results) / self.n
return variance ** 0.5
@property
def steps_distribution(self) -> Counter:
return Counter(r.steps for r in self.results)
@property
def avg_latency_ms(self) -> float:
return sum(r.cost.latency_ms for r in self.results) / self.n
@property
def p95_latency_ms(self) -> float:
vals = sorted(r.cost.latency_ms for r in self.results)
return vals[int(self.n * 0.95)]
@property
def avg_retries(self) -> float:
return sum(r.cost.retries for r in self.results) / self.n
@property
def total_retries(self) -> int:
return sum(r.cost.retries for r in self.results)
@property
def total_wasted_retries(self) -> int:
return sum(r.cost.wasted_retries for r in self.results)
@property
def total_useful_retries(self) -> int:
return self.total_retries - self.total_wasted_retries
@property
def retry_waste_pct(self) -> float:
return self.total_wasted_retries / self.total_retries if self.total_retries else 0.0
@property
def avg_tokens(self) -> float:
return sum(r.cost.tokens_used for r in self.results) / self.n
@property
def total_tokens(self) -> int:
return sum(r.cost.tokens_used for r in self.results)
@property
def total_cost_usd(self) -> float:
return sum(r.cost.estimated_cost_usd for r in self.results)
@property
def hallucination_count(self) -> int:
return sum(
1 for r in self.results
for e in r.log.events
if e.event_kind == EventKind.HALLUCINATION
)
@property
def loop_count(self) -> int:
return sum(
1 for r in self.results
for e in r.log.events
if e.event_kind == EventKind.LOOP_DETECTED
)
def export_json(self) -> dict:
return {
"label": self.label,
"n": self.n,
"success_rate": round(self.success_rate, 4),
"failure_reasons": dict(self.failure_reasons),
"error_taxonomy": dict(self.error_taxonomy),
"avg_steps": round(self.avg_steps, 2),
"std_steps": round(self.std_steps, 2),
"avg_retries": round(self.avg_retries, 2),
"total_retries": self.total_retries,
"total_wasted_retries": self.total_wasted_retries,
"total_useful_retries": self.total_useful_retries,
"retry_waste_pct": round(self.retry_waste_pct, 4),
"avg_latency_ms": round(self.avg_latency_ms, 3),
"p95_latency_ms": round(self.p95_latency_ms, 3),
"avg_tokens": round(self.avg_tokens, 1),
"total_tokens": self.total_tokens,
"total_cost_usd": round(self.total_cost_usd, 4),
"hallucination_events": self.hallucination_count,
"loop_events": self.loop_count,
}
def run_experiment(
n_tasks: int = NUM_TASKS,
seed: int = SEED,
hallucination_rate: float = 0.28,
silent: bool = False,
) -> tuple[ExperimentSummary, ExperimentSummary]:
# FIX #2: Seed once at experiment level. Do NOT reseed inside the loop.
random.seed(seed)
_reset_id_counter() # FIX #3: reset deterministic ID counter
CIRCUIT_REGISTRY.reset_all()
tasks = generate_tasks(n_tasks, seed)
react = ExperimentSummary("ReAct Agent")
workflow = ExperimentSummary("Controlled Workflow")
if not silent:
print(f"\n Running {n_tasks} tasks × 2 approaches "
f"(seed={seed}, hallucination_rate={hallucination_rate:.0%})…\n")
# Simulated monotonic time — advances by a fixed step per task pair
# so circuit breaker recovery_timeout comparisons are also deterministic.
sim_time: float = 0.0
SIM_TIME_STEP = 1.0 # 1 simulated second per task pair
for i, task in enumerate(tasks, 1):
# FIX #2: NO random.seed() call here.
# Both agents share the global random stream seeded once above.
# This guarantees that the total sequence of random draws is
# identical every run, regardless of how many draws each agent uses.
react.results.append(
run_react_agent(task, seed=seed,
hallucination_rate=hallucination_rate,
sim_time=sim_time)
)
workflow.results.append(
run_controlled_workflow(task, seed=seed, sim_time=sim_time)
)