-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathagent_cli.py
More file actions
1900 lines (1615 loc) · 67.6 KB
/
Copy pathagent_cli.py
File metadata and controls
1900 lines (1615 loc) · 67.6 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
#!/usr/bin/env python3
import argparse
import json
import os
import subprocess
import sys
import threading
import time
from datetime import datetime
import questionary
from rich.columns import Columns
from rich.console import Console
from rich.live import Live
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.prompt import Confirm, Prompt
from rich.table import Table
# Import Interceptor and Map
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from agent_reasoning.interceptor import AGENT_MAP, ReasoningInterceptor
from agent_reasoning.visualization import get_visualizer
console = Console()
client = ReasoningInterceptor()
MODEL_NAME = "gemma3:latest"
# Agent descriptions for display
AGENT_DESCRIPTIONS = {
"standard": ("Standard", "Direct generation", "N/A", "Baseline responses"),
"cot": (
"Chain of Thought",
"Step-by-step reasoning",
"Wei et al. 2022",
"Math, logic, analysis",
),
"tot": (
"Tree of Thoughts",
"Branching exploration with pruning",
"Yao et al. 2023",
"Complex puzzles, riddles",
),
"react": (
"ReAct",
"Reasoning + tool actions",
"Yao et al. 2022",
"Fact-checking, calculations",
),
"recursive": (
"Recursive LM",
"Code REPL with sub_llm()",
"Author et al. 2025",
"Data processing, long-context",
),
"reflection": (
"Self-Reflection",
"Draft → critique → refine loop",
"Shinn et al. 2023",
"Creative writing, code",
),
"decomposed": (
"Decomposed",
"Break into sub-tasks, solve each",
"Khot et al. 2022",
"Planning, complex queries",
),
"least_to_most": (
"Least-to-Most",
"Easiest to hardest sub-questions",
"Zhou et al. 2022",
"Multi-step reasoning",
),
"consistency": (
"Self-Consistency",
"k samples + majority vote",
"Wang et al. 2022",
"Diverse problems",
),
"refinement": (
"Refinement Loop",
"Score-based iterative improvement",
"Iterative Refinement",
"Technical writing",
),
"complex_refinement": (
"Complex Pipeline",
"5-stage optimization pipeline",
"Multi-Stage Refinement",
"High-quality content",
),
"debate": (
"Adversarial Debate",
"Pro/con debate with judge evaluation",
"Irving et al. 2018",
"Controversial topics, analysis",
),
"mcts": (
"MCTS",
"Monte Carlo Tree Search reasoning",
"Browne et al. 2012",
"Complex strategy, planning",
),
"analogical": (
"Analogical",
"Solve by structural analogy",
"Gentner 1983",
"Novel problems, cross-domain",
),
"socratic": (
"Socratic",
"Progressive questioning method",
"Paul & Elder 2007",
"Deep understanding, philosophy",
),
"meta": (
"Meta-Reasoning",
"Auto-classifies query and routes to optimal strategy",
"Novel",
"Any query type",
),
}
# Session directory
SESSION_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "sessions")
os.makedirs(SESSION_DIR, exist_ok=True)
def get_ollama_models():
try:
result = subprocess.run(["ollama", "list"], capture_output=True, text=True)
lines = result.stdout.strip().split("\n")[1:] # Skip header
models = [line.split()[0] for line in lines if line.strip()]
return models
except Exception:
return ["gemma3:latest", "gemma3:270m", "llama3"]
def select_model_panel():
global MODEL_NAME
models = get_ollama_models()
selected = questionary.select("Select AI Model:", choices=models, default=MODEL_NAME).ask()
if selected:
MODEL_NAME = selected
console.print(f"[green]Model set to: {MODEL_NAME}[/green]")
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def print_header():
clear_screen()
console.print(
Panel.fit(
"[bold cyan]AGENT REASONING CLI[/bold cyan]\n"
"[dim]Advanced Cognitive Architectures (Gemma 3)[/dim]",
border_style="cyan",
)
)
console.print(f"[dim]Working Directory: {os.getcwd()}[/dim]\n")
from rich.markdown import Markdown # noqa: E402
def save_session(strategy, query, response, metrics):
"""Save a chat interaction to session history."""
session = {
"timestamp": datetime.now().isoformat(),
"model": MODEL_NAME,
"strategy": strategy,
"query": query,
"response": response,
"metrics": metrics,
}
filename = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{strategy}.json"
filepath = os.path.join(SESSION_DIR, filename)
with open(filepath, "w") as f:
json.dump(session, f, indent=2)
return filepath
def print_metrics(metrics):
"""Print timing metrics after a response."""
parts = []
if metrics.get("total_time"):
parts.append(f"Total: {metrics['total_time']:.1f}s")
if metrics.get("ttft"):
parts.append(f"TTFT: {metrics['ttft']:.2f}s")
if metrics.get("tps"):
parts.append(f"~{metrics['tps']:.0f} tok/s")
if metrics.get("chunks"):
parts.append(f"{metrics['chunks']} chunks")
if parts:
console.print(f"\n[dim] [{' | '.join(parts)}][/dim]")
def run_agent_chat(strategy):
print_header()
desc = AGENT_DESCRIPTIONS.get(strategy, ("Unknown", "", "", ""))
console.print(f"[bold yellow]Chat Mode: {desc[0]} ({strategy.upper()})[/bold yellow]")
console.print(f"[dim]{desc[1]} | Ref: {desc[2]} | Best for: {desc[3]}[/dim]")
console.print("Type 'exit' or '0' to return.\n")
while True:
query = Prompt.ask("\n[bold green]Query[/bold green]")
if query.lower() in ["exit", "quit", "0"]:
break
full_model_name = f"{MODEL_NAME}+{strategy}"
console.print(f"[dim]Using model: {full_model_name}[/dim]")
console.print(f"[bold cyan]--- {strategy.upper()} Thinking ---[/bold cyan]")
# Check if visualizer exists for this strategy
visualizer = get_visualizer(strategy)
if visualizer:
response, metrics = run_with_visualizer(strategy, query, visualizer)
else:
response, metrics = run_with_markdown(strategy, query)
print_metrics(metrics)
# Auto-save session
if response:
save_session(strategy, query, response, metrics)
def run_with_visualizer(strategy, query, visualizer):
"""Run agent with rich visualization using structured events."""
agent_class = AGENT_MAP.get(strategy)
if not agent_class:
console.print(f"[red]Unknown strategy: {strategy}[/red]")
return "", {}
agent = agent_class(model=MODEL_NAME)
if not hasattr(agent, "stream_structured"):
console.print(
"[dim]Agent does not support structured streaming, falling back to text mode.[/dim]"
)
return run_with_markdown(strategy, query)
start_time = time.time()
first_chunk_time = None
chunk_count = 0
full_response = ""
last_render_time = 0
render_interval = 0.15 # ~6-7 fps max — smooth without jitter
try:
with Live(
visualizer.render(), console=console, refresh_per_second=4, vertical_overflow="visible"
) as live:
for event in agent.stream_structured(query):
if first_chunk_time is None:
first_chunk_time = time.time()
chunk_count += 1
if event.event_type == "text":
full_response += event.data
visualizer.update(event)
# Only re-render when visualizer state actually changed
if not getattr(visualizer, "_dirty", True):
continue
now = time.time()
is_structural = event.event_type in (
"refinement",
"pipeline",
"iteration",
"phase",
"final",
)
if is_structural or (now - last_render_time) >= render_interval:
live.update(visualizer.render())
last_render_time = now
# Final render to ensure everything is shown
if getattr(visualizer, "_dirty", False):
live.update(visualizer.render())
except Exception as e:
console.print(f"[bold red]Error:[/bold red] {e}")
elapsed = time.time() - start_time
ttft = (first_chunk_time - start_time) if first_chunk_time else 0
tps = chunk_count / elapsed if elapsed > 0 else 0
return full_response, {"total_time": elapsed, "ttft": ttft, "tps": tps, "chunks": chunk_count}
def run_with_markdown(strategy, query):
"""Fallback: Run agent with simple markdown rendering."""
full_model_name = f"{MODEL_NAME}+{strategy}"
full_response = ""
start_time = time.time()
first_chunk_time = None
chunk_count = 0
last_render_time = 0
render_interval = 0.15 # ~6-7 fps max — smooth without jitter
with Live("", console=console, refresh_per_second=4, vertical_overflow="visible") as live:
try:
for chunk_dict in client.generate(model=full_model_name, prompt=query, stream=True):
if first_chunk_time is None:
first_chunk_time = time.time()
chunk = chunk_dict.get("response", "")
chunk_count += 1
full_response += chunk
now = time.time()
if (now - last_render_time) >= render_interval:
live.update(Markdown(full_response))
last_render_time = now
except Exception as e:
console.print(f"[bold red]Error:[/bold red] {e}")
# Final render to show complete output
live.update(Markdown(full_response))
elapsed = time.time() - start_time
ttft = (first_chunk_time - start_time) if first_chunk_time else 0
tps = chunk_count / elapsed if elapsed > 0 else 0
return full_response, {"total_time": elapsed, "ttft": ttft, "tps": tps, "chunks": chunk_count}
def run_arena_mode():
print_header()
console.print("[bold yellow]⚔️ ARENA MODE ⚔️[/bold yellow]")
console.print("Run the same query across ALL agents to compare reasoning styles.")
query = Prompt.ask("\n[bold green]Enter Test Query[/bold green]")
if not query:
return
# Filter unique strategies roughly
strategies = [
"standard",
"cot",
"tot",
"react",
"recursive",
"reflection",
"refinement",
"complex_refinement",
"decomposed",
"least_to_most",
"consistency",
]
results = {}
for strategy in strategies:
console.print(f"\n[bold magenta]Running {strategy.upper()}...[/bold magenta]")
full_model_name = f"{MODEL_NAME}+{strategy}"
start_time = time.time()
response_text = ""
console.rule(f"[bold]{strategy}[/bold]")
try:
last_render = 0
render_interval = 0.15
with Live("", console=console, refresh_per_second=4) as live:
for chunk_dict in client.generate(model=full_model_name, prompt=query, stream=True):
chunk = chunk_dict.get("response", "")
response_text += chunk
now = time.time()
if (now - last_render) >= render_interval:
live.update(Markdown(response_text))
last_render = now
live.update(Markdown(response_text))
except Exception as e:
response_text = f"Error: {e}"
console.print(f"[red]{e}[/red]")
duration = time.time() - start_time
# For the table, we might want just the final answer if parsing is possible,
# but for now, raw text is fine.
results[strategy] = (response_text, duration)
console.print(f"\n[green]Done in {duration:.2f}s[/green]")
# Summary Table
console.print("\n\n")
console.rule("[bold red]Comparison Results[/bold red]")
table = Table(title="Arena Results")
table.add_column("Strategy", style="cyan")
table.add_column("Time", style="green")
table.add_column("Response Length", style="magenta")
for strat, (resp, dur) in results.items():
table.add_row(strat, f"{dur:.2f}s", str(len(resp)))
console.print(table)
# Save Report Option
if Confirm.ask("Save Arena Report?"):
with open("arena_report.md", "w") as f:
f.write(f"# Arena Report\n**Model**: {MODEL_NAME}\n**Query**: {query}\n\n")
for strat, (resp, dur) in results.items():
f.write(f"## {strat.upper()} ({dur:.2f}s)\n{resp}\n\n")
console.print("[green]Saved to arena_report.md[/green]")
def run_refinement_demo(interactive=False):
"""
Demo showcasing the Refinement Loop agent.
Writes an article and iteratively improves it to be more technical.
Runs for 5 iterations to demonstrate score-based refinement.
Args:
interactive: If True, asks user for a query. If False, uses the default demo query.
"""
print_header()
console.print("[bold yellow]🔄 REFINEMENT LOOP AGENT[/bold yellow]")
console.print("This agent iteratively improves content using score-based feedback.")
console.print("Generator → Critic (score 0.0-1.0) → Refiner → Loop until threshold met\n")
# Import the agent directly for custom configuration
from agent_reasoning.agents.refinement_loop import RefinementLoopAgent
if interactive:
# Ask user for query
query = Prompt.ask("\n[bold green]Query (or press Enter for demo)[/bold green]")
if not query.strip():
interactive = False # Fall back to demo
if not interactive:
# Use default demo query
query = (
"Write a brief technical article (2-3 paragraphs) explaining "
"how neural networks learn.\n"
"The article should be suitable for a technical blog and "
"include specific details about:\n"
"- Backpropagation algorithm\n"
"- Gradient descent optimization\n"
"- Loss functions\n\n"
"Make it technically accurate and precise."
)
console.print(
Panel(
query,
title="[bold cyan]Demo Query: Technical Article on Neural Networks[/bold cyan]",
border_style="cyan",
)
)
console.print()
# Create agent with 5 iterations for demo, high threshold to ensure multiple refinements
agent = RefinementLoopAgent(model=MODEL_NAME, score_threshold=0.99, max_iterations=5)
console.print(
f"[dim]Using model: {MODEL_NAME}+refinement (max 5 iterations, threshold=0.99)[/dim]"
)
console.print("[bold cyan]--- REFINEMENT LOOP Running ---[/bold cyan]\n")
# Check if visualizer is available
visualizer = get_visualizer("refinement")
if visualizer and hasattr(agent, "stream_structured"):
try:
last_render = 0
render_interval = 0.15
with Live(
visualizer.render(),
console=console,
refresh_per_second=4,
vertical_overflow="visible",
) as live:
for event in agent.stream_structured(query):
visualizer.update(event)
if not getattr(visualizer, "_dirty", True):
continue
now = time.time()
is_structural = event.event_type in (
"refinement",
"pipeline",
"iteration",
"phase",
"final",
)
if is_structural or (now - last_render) >= render_interval:
live.update(visualizer.render())
last_render = now
if getattr(visualizer, "_dirty", False):
live.update(visualizer.render())
except Exception as e:
console.print(f"[bold red]Error:[/bold red] {e}")
else:
# Fallback to text streaming
full_response = ""
last_render = 0
render_interval = 0.15
with Live("", console=console, refresh_per_second=4, vertical_overflow="visible") as live:
try:
for chunk in agent.stream(query):
full_response += chunk
now = time.time()
if (now - last_render) >= render_interval:
live.update(Markdown(full_response))
last_render = now
except Exception as e:
console.print(f"[bold red]Error:[/bold red] {e}")
live.update(Markdown(full_response))
console.print("\n[bold green]Demo Complete![/bold green]")
console.print(
"[dim]This demonstrates how iterative refinement improves "
"content quality through score-based feedback.[/dim]"
)
input("\nPress Enter to return...")
def run_complex_refinement_demo():
"""
Demo showcasing the Complex Refinement Pipeline agent.
Runs an article through a 5-stage optimization pipeline:
1. Technical Accuracy
2. Structure & Clarity
3. Technical Depth
4. Examples & Analogies
5. Professional Polish
"""
print_header()
console.print("[bold magenta]🔄 COMPLEX REFINEMENT PIPELINE[/bold magenta]")
console.print("This agent runs content through a 5-stage optimization pipeline.")
console.print(
"Each stage has its own critic that evaluates and refines until threshold is met.\n"
)
console.print("[bold]Pipeline Stages:[/bold]")
console.print(" 1. [cyan]Technical Accuracy[/cyan] - Ensure all facts are correct")
console.print(" 2. [cyan]Structure & Clarity[/cyan] - Improve organization and flow")
console.print(" 3. [cyan]Technical Depth[/cyan] - Add more details and formulas")
console.print(" 4. [cyan]Examples & Analogies[/cyan] - Add concrete illustrations")
console.print(" 5. [cyan]Professional Polish[/cyan] - Final editing pass\n")
# Import the agent directly for custom configuration
from agent_reasoning.agents.complex_refinement import ComplexRefinementLoopAgent
# Use default demo query
query = (
"Write a brief technical article (2-3 paragraphs) explaining "
"how neural networks learn.\n"
"The article should be suitable for a technical blog and "
"include specific details about:\n"
"- Backpropagation algorithm\n"
"- Gradient descent optimization\n"
"- Loss functions\n\n"
"Make it technically accurate and precise."
)
console.print(
Panel(
query,
title="[bold cyan]Demo Query: Technical Article on Neural Networks[/bold cyan]",
border_style="cyan",
)
)
console.print()
# Create agent with threshold 0.9, max 3 iterations per stage
agent = ComplexRefinementLoopAgent(
model=MODEL_NAME, score_threshold=0.9, max_iterations_per_stage=3
)
console.print(
f"[dim]Using model: {MODEL_NAME}+complex_refinement "
f"(5 stages, threshold=0.9, max 3 iter/stage)[/dim]"
)
console.print("[bold magenta]--- COMPLEX REFINEMENT PIPELINE Running ---[/bold magenta]\n")
# Use PipelineVisualizer for structured rendering
visualizer = get_visualizer("complex_refinement")
if visualizer and hasattr(agent, "stream_structured"):
try:
last_render = 0
render_interval = 0.15
with Live(
visualizer.render(),
console=console,
refresh_per_second=4,
vertical_overflow="visible",
) as live:
for event in agent.stream_structured(query):
visualizer.update(event)
if not getattr(visualizer, "_dirty", True):
continue
now = time.time()
is_structural = event.event_type in (
"refinement",
"pipeline",
"iteration",
"phase",
"final",
)
if is_structural or (now - last_render) >= render_interval:
live.update(visualizer.render())
last_render = now
if getattr(visualizer, "_dirty", False):
live.update(visualizer.render())
except Exception as e:
console.print(f"[bold red]Error:[/bold red] {e}")
else:
# Fallback to text streaming
full_response = ""
last_render = 0
render_interval = 0.15
with Live("", console=console, refresh_per_second=4, vertical_overflow="visible") as live:
try:
for chunk in agent.stream(query):
full_response += chunk
now = time.time()
if (now - last_render) >= render_interval:
live.update(Markdown(full_response))
last_render = now
except Exception as e:
console.print(f"[bold red]Error:[/bold red] {e}")
live.update(Markdown(full_response))
console.print("\n[bold green]Pipeline Complete![/bold green]")
console.print(
"[dim]This demonstrates how multi-stage refinement "
"progressively improves content through specialized critics.[/dim]"
)
input("\nPress Enter to return...")
def run_benchmark_menu():
"""Benchmark submenu for running various benchmarks."""
while True:
print_header()
console.print("[bold cyan]📊 BENCHMARK SUITE[/bold cyan]")
console.print("Run performance benchmarks and generate reports.\n")
choices = [
questionary.Choice("🧠 Agent Reasoning Benchmark (All Strategies)", value="agent_all"),
questionary.Choice("🧠 Agent Reasoning Benchmark (Select Tasks)", value="agent_select"),
questionary.Choice(
"🎯 Accuracy Benchmark (GSM8K, MMLU, ARC, HellaSwag)", value="accuracy"
),
questionary.Choice("⚡ Inference Speed Benchmark (Ollama)", value="inference"),
questionary.Choice("☁️ OCI vs Ollama Comparison", value="oci_comparison"),
questionary.Choice("📈 View Last Report", value="view_report"),
questionary.Choice("💾 Export Results to JSON", value="export"),
questionary.Separator(),
questionary.Choice("← Back to Main Menu", value="back"),
]
choice = questionary.select("Select Benchmark:", choices=choices, use_arrow_keys=True).ask()
if not choice or choice == "back":
return
elif choice == "agent_all":
run_agent_benchmark(select_tasks=False)
elif choice == "agent_select":
run_agent_benchmark(select_tasks=True)
elif choice == "accuracy":
run_accuracy_benchmark()
elif choice == "inference":
run_inference_benchmark()
elif choice == "oci_comparison":
run_oci_comparison_benchmark()
elif choice == "view_report":
view_benchmark_report()
elif choice == "export":
export_benchmark_results()
def run_agent_benchmark(select_tasks=False):
"""Run agent reasoning benchmarks with real-time output."""
from src.benchmarks.runner import AGENT_BENCHMARK_TASKS, BenchmarkRunner
print_header()
console.print("[bold cyan]🧠 AGENT REASONING BENCHMARK[/bold cyan]\n")
# Task selection
if select_tasks:
task_choices = [
questionary.Choice(f"{t.name} ({t.category}) - {t.recommended_strategy}", value=t.id)
for t in AGENT_BENCHMARK_TASKS
]
selected_ids = questionary.checkbox(
"Select tasks to run:",
choices=task_choices,
).ask()
if not selected_ids:
console.print("[yellow]No tasks selected.[/yellow]")
input("\nPress Enter to return...")
return
tasks = [t for t in AGENT_BENCHMARK_TASKS if t.id in selected_ids]
else:
tasks = AGENT_BENCHMARK_TASKS
console.print(f"[dim]Running {len(tasks)} benchmark tasks with model: {MODEL_NAME}[/dim]\n")
# Show task list
task_table = Table(title="Benchmark Tasks", show_lines=True)
task_table.add_column("Task", style="cyan")
task_table.add_column("Category", style="green")
task_table.add_column("Strategy", style="yellow")
task_table.add_column("Status", style="white")
task_status = {t.id: "⏳ Pending" for t in tasks}
def render_task_table():
table = Table(title="Benchmark Progress", show_lines=True)
table.add_column("Task", style="cyan", width=25)
table.add_column("Category", style="green", width=12)
table.add_column("Strategy", style="yellow", width=15)
table.add_column("Time (ms)", style="magenta", width=10)
table.add_column("Status", style="white", width=15)
for t in tasks:
status = task_status.get(t.id, "⏳ Pending")
time_str = "-"
if isinstance(status, tuple):
time_str = f"{status[1]:.0f}"
status = status[0]
table.add_row(t.name[:24], t.category, t.recommended_strategy, time_str, status)
return table
# Initialize runner
runner = BenchmarkRunner(model=MODEL_NAME)
# Run benchmarks with live updates
with Live(render_task_table(), console=console, refresh_per_second=4) as live:
def on_task_start(task, strategy):
task_status[task.id] = "🔄 Running..."
live.update(render_task_table())
def on_task_complete(result):
if result.success:
task_status[result.task_id] = ("✅ Done", result.total_ms)
else:
task_status[result.task_id] = ("❌ Failed", 0)
live.update(render_task_table())
results = list(
runner.run_agent_benchmark(
tasks=tasks, on_task_start=on_task_start, on_task_complete=on_task_complete
)
)
# Generate and display report
report = runner.generate_report()
console.print("\n" + "=" * 60)
console.print("[bold green]BENCHMARK COMPLETE[/bold green]\n")
summary_table = Table(title="Summary")
summary_table.add_column("Metric", style="cyan")
summary_table.add_column("Value", style="green")
summary_table.add_row("Total Tasks", str(report.total_tasks))
summary_table.add_row("Successful", str(report.successful_tasks))
summary_table.add_row("Failed", str(report.failed_tasks))
summary_table.add_row("Avg Latency", f"{report.avg_latency_ms:.2f} ms")
summary_table.add_row("Avg TTFT", f"{report.avg_ttft_ms:.2f} ms")
summary_table.add_row("Avg TPS", f"{report.avg_tps:.2f}")
console.print(summary_table)
# Save report
if Confirm.ask("\nSave report to file?"):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
os.makedirs("benchmarks", exist_ok=True)
filepath = f"benchmarks/agent_benchmark_{timestamp}.md"
runner.save_report(filepath, format="markdown")
console.print(f"[green]Report saved to {filepath}[/green]")
# Auto-generate charts
console.print("\n[dim]Generating benchmark charts...[/dim]")
from src.benchmarks.charts import generate_agent_benchmark_charts
chart_data = []
for r in results:
chart_data.append(
{
"task_name": r.task_name,
"strategy": r.strategy,
"total_ms": r.total_ms,
"ttft_ms": r.ttft_ms,
"tps": r.tps,
"token_count": r.token_count,
"success": r.success,
}
)
chart_paths = generate_agent_benchmark_charts(chart_data, model=MODEL_NAME)
if chart_paths:
console.print(f"[green]Generated {len(chart_paths)} charts:[/green]")
for cp in chart_paths:
console.print(f" [dim]{cp}[/dim]")
else:
console.print("[yellow]No charts generated (need matplotlib).[/yellow]")
input("\nPress Enter to return...")
def run_accuracy_benchmark():
"""Run accuracy benchmarks against standard datasets."""
from src.benchmarks.accuracy import (
DATASET_REGISTRY,
AccuracyBenchmarkRunner,
generate_accuracy_charts,
)
print_header()
console.print("[bold cyan]🎯 ACCURACY BENCHMARK[/bold cyan]")
console.print("Evaluate reasoning strategies against standard NLP datasets.\n")
# Dataset selection
ds_choices = [
questionary.Choice(
f"{info['name']} - {info['description']} ({len(info['loader']())} questions)",
value=ds_id,
checked=True,
)
for ds_id, info in DATASET_REGISTRY.items()
]
selected_datasets = questionary.checkbox(
"Select datasets:",
choices=ds_choices,
).ask()
if not selected_datasets:
console.print("[yellow]No datasets selected.[/yellow]")
input("\nPress Enter to return...")
return
# Strategy selection
all_strategies = [
"standard",
"cot",
"tot",
"react",
"reflection",
"decomposed",
"least_to_most",
"consistency",
"refinement",
"complex_refinement",
"recursive",
]
strat_choices = [
questionary.Choice(
f"{AGENT_DESCRIPTIONS.get(s, (s,))[0]} ({s})",
value=s,
checked=(s in ["standard", "cot", "tot", "decomposed", "consistency"]),
)
for s in all_strategies
]
selected_strategies = questionary.checkbox(
"Select strategies to evaluate:",
choices=strat_choices,
).ask()
if not selected_strategies:
console.print("[yellow]No strategies selected.[/yellow]")
input("\nPress Enter to return...")
return
# Count total questions
total_questions = sum(len(DATASET_REGISTRY[ds]["loader"]()) for ds in selected_datasets)
total_evals = total_questions * len(selected_strategies)
console.print(f"\n[dim]Model: {MODEL_NAME}[/dim]")
console.print(
f"[dim]Datasets: {len(selected_datasets)} | "
f"Strategies: {len(selected_strategies)} | "
f"Total evaluations: {total_evals}[/dim]\n"
)
runner = AccuracyBenchmarkRunner(model=MODEL_NAME)
completed = 0
current_results = []
# Live progress table
def render_progress():
table = Table(title="Accuracy Benchmark Progress", show_lines=True)
table.add_column("Dataset", style="cyan", width=15)
table.add_column("Strategy", style="yellow", width=18)
table.add_column("Progress", style="white", width=12)
table.add_column("Correct", style="green", width=10)
table.add_column("Accuracy", style="bold", width=10)
# Group by dataset+strategy
groups = {}
for r in current_results:
key = f"{r.dataset}|{r.strategy}"
groups.setdefault(key, []).append(r)
for key, results in sorted(groups.items()):
ds, strat = key.split("|")
total = len(DATASET_REGISTRY[ds]["loader"]())
done = len(results)
correct = sum(1 for r in results if r.correct)
pct = correct / done * 100 if done else 0
ds_name = DATASET_REGISTRY.get(ds, {}).get("name", ds)
strat_name = AGENT_DESCRIPTIONS.get(strat, (strat,))[0]
color = "[green]" if pct >= 60 else "[yellow]" if pct >= 40 else "[red]"
table.add_row(
ds_name,
strat_name,
f"{done}/{total}",
str(correct),
f"{color}{pct:.0f}%[/]",
)
return table
with Live(render_progress(), refresh_per_second=2, console=console) as live:
for ds_id in selected_datasets:
for result in runner.run_dataset(
ds_id,
selected_strategies,
on_question_done=lambda r: None,
):
current_results.append(result)
completed += 1
live.update(render_progress())
# Final reports
reports = runner.generate_reports()
console.print("\n" + "=" * 60)
console.print("[bold green]ACCURACY BENCHMARK COMPLETE[/bold green]\n")
# Summary table
summary = Table(title="Accuracy Results", show_lines=True)
summary.add_column("Dataset", style="cyan")
summary.add_column("Strategy", style="yellow")
summary.add_column("Correct", style="green")
summary.add_column("Total", style="white")
summary.add_column("Accuracy", style="bold")
summary.add_column("Avg Latency", style="dim")
for r in sorted(reports, key=lambda x: (x.dataset, -x.accuracy_pct)):
ds_name = DATASET_REGISTRY.get(r.dataset, {}).get("name", r.dataset)
strat_name = AGENT_DESCRIPTIONS.get(r.strategy, (r.strategy,))[0]
color = (
"[green]" if r.accuracy_pct >= 60 else "[yellow]" if r.accuracy_pct >= 40 else "[red]"
)
summary.add_row(
ds_name,
strat_name,
str(r.correct),
str(r.total),
f"{color}{r.accuracy_pct:.1f}%[/]",
f"{r.avg_latency_ms:.0f}ms",
)
console.print(summary)
# Auto-generate charts
console.print("\n[dim]Generating accuracy charts...[/dim]")
chart_paths = generate_accuracy_charts(reports, model=MODEL_NAME)
if chart_paths:
console.print(f"[green]Generated {len(chart_paths)} charts:[/green]")
for cp in chart_paths:
console.print(f" [dim]{cp}[/dim]")
# Save results
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
os.makedirs("benchmarks", exist_ok=True)
json_path = f"benchmarks/accuracy_results_{timestamp}.json"
runner.save_results(json_path)
console.print(f"[green]Results saved to {json_path}[/green]")
input("\nPress Enter to return...")
def run_inference_benchmark():
"""Run raw inference speed benchmarks."""
from src.benchmarks.runner import INFERENCE_BENCHMARK_PROMPTS, BenchmarkRunner
print_header()
console.print("[bold cyan]⚡ INFERENCE SPEED BENCHMARK[/bold cyan]\n")
iterations = int(Prompt.ask("Iterations per prompt", default="3"))
console.print(
f"\n[dim]Running {len(INFERENCE_BENCHMARK_PROMPTS)} prompts "
f"x {iterations} iterations with model: {MODEL_NAME}[/dim]\n"
)