-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllm_tournament.py
1646 lines (1305 loc) · 60.6 KB
/
llm_tournament.py
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
"""
LLM Multi-Round Coding Tournament Automation
This script automates the process of running a multi-round coding tournament between
different LLMs, where models analyze and improve each other's solutions across
multiple rounds of refinement and integration.
Features:
- Supports multiple LLM providers through the aisuite API
- Creates a structured directory hierarchy for organizing tournament artifacts
- Manages the full lifecycle of prompt creation, response collection, and analysis
- Generates test scripts to evaluate the performance of each solution
- Tracks and reports detailed metrics about each solution
- Supports configurable tournament parameters (rounds, models, etc.)
- Handles error recovery and rate limiting
"""
import os
import re
import time
import json
import logging
import argparse
import traceback
import statistics
import subprocess
import textwrap
import threading
from typing import List, Dict, Tuple, Any, Optional, Union, Set
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
from dotenv import load_dotenv
import aisuite as ai
load_dotenv() # This will load variables from your .env file
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("tournament.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger("llm_tournament")
# Model configurations with appropriate parameters
MODELS = {
"o3_mini": {
"id": "openai:o3-mini",
"thinking": True,
"provider": "openai"
},
"gpt4o": {
"id": "openai:gpt-4o",
"thinking": False,
"provider": "openai"
},
"claude37": {
"id": "anthropic:claude-3-7-sonnet-20250219",
"thinking": True,
"provider": "anthropic"
},
"mistral_large": {
"id": "mistral:mistral-large-latest",
"thinking": True,
"provider": "mistral"
}
}
# Maximum retry attempts for API calls
MAX_RETRIES = 3
# Backoff times (in seconds) for retrying API calls
BACKOFF_TIMES = [5, 15, 30]
@dataclass
class ModelResponse:
"""Class for storing and processing a single model's response"""
model_name: str
round_num: int
prompt: str
response: str
file_path: Optional[Path] = None
code: Optional[str] = None
thinking: Optional[str] = None
error: Optional[str] = None
metrics: Dict[str, Any] = field(default_factory=dict)
timestamp: datetime = field(default_factory=datetime.now)
def extract_code(self, output_dir: Optional[Path] = None) -> str:
"""
Extract code from the model's response using the AI suite to process and structure it.
If the code has already been extracted and saved to a file, load it from there instead.
Args:
output_dir: Base directory for tournament artifacts (optional)
Returns:
Extracted and cleaned code as a string
"""
if not self.response:
return ""
# If code has already been extracted, return it
if self.code:
return self.code
# If output_dir is provided, check if the extracted code file exists
if output_dir:
extracted_code_dir = output_dir / "extracted_code"
extracted_code_dir.mkdir(exist_ok=True, parents=True)
# Create filename from model name and round number
code_filename = f"extracted_code__round_{self.round_num}__{self.model_name}.py"
code_file_path = extracted_code_dir / code_filename
# Check if the file already exists
if code_file_path.exists():
try:
logger.info(f"Loading previously extracted code for {self.model_name} Round {self.round_num} from file")
with open(code_file_path, "r", encoding="utf-8") as f:
self.code = f.read()
return self.code
except Exception as e:
logger.warning(f"Error loading extracted code from file: {str(e)}. Re-extracting from response.")
try:
# Create a prompt for the AI to extract and transform the code
prompt = f"""
Extract all code from the text below and format it as a complete, self-contained class
with the name {self.model_name}Round{self.round_num}Solution.
The class should:
1. Include all necessary imports at the top
2. Have a static 'solve' method that takes 'input_text' as its parameter
3. Contain all functions from the original code
4. Ensure the solve method correctly calls the main function with the input_text parameter
5. Be properly indented and formatted for execution
Important: Provide ONLY the complete code WITHOUT ANY explanations, comments about the task,
or markdown formatting. Do not include any text before or after the code.
Here is the text to extract code from:
{self.response}
"""
# Call the AI service
client = ai.Client()
print(f"Submitting model response to Claude3.7 to extract the code from {self.model_name} Round {self.round_num} and turn it into a self-contained class...")
response = client.chat.completions.create(
model="anthropic:claude-3-7-sonnet-20250219",
messages=[{"role": "user", "content": prompt}],
max_tokens=25000
)
# Get the extracted code
extracted_code = response.choices[0].message.content
# Remove any markdown formatting
extracted_code = re.sub(r'^```(?:\w+)?\n', '', extracted_code)
extracted_code = re.sub(r'\n```$', '', extracted_code)
# Store the extracted code
self.code = extracted_code.strip()
# Save to file if output_dir is provided
if output_dir:
try:
with open(code_file_path, "w", encoding="utf-8") as f:
f.write(self.code)
logger.info(f"Saved extracted code to {code_file_path}")
except Exception as e:
logger.error(f"Error saving extracted code to file: {str(e)}")
return self.code
except Exception as e:
logger.error(f"Error using AI to extract code: {str(e)}")
logger.debug(traceback.format_exc())
# Fallback to a minimal implementation
fallback_code = f"""
class {self.model_name}Round{self.round_num}Solution:
\"\"\"Solution from {self.model_name} at round {self.round_num}\"\"\"
@staticmethod
def solve(input_text):
\"\"\"Apply the solution to the input text\"\"\"
# Simple fallback implementation that returns the input
return input_text
"""
self.code = fallback_code.strip()
# Save the fallback code to file if output_dir is provided
if output_dir:
try:
with open(code_file_path, "w", encoding="utf-8") as f:
f.write(self.code)
logger.info(f"Saved fallback code to {code_file_path}")
except Exception as e:
logger.error(f"Error saving fallback code to file: {str(e)}")
return self.code
def extract_thinking(self) -> Optional[str]:
"""
Extract the thought process or reasoning from the model's response.
Returns:
Extracted thinking content if found, None otherwise
"""
# Look for chain-of-thought sections marked with common patterns
patterns = [
r'<thinking>(.*?)</thinking>',
r'### Thinking\s*\n(.*?)(?:\n###|\Z)',
r'## Thought Process\s*\n(.*?)(?:\n##|\Z)',
r'Step-by-step reasoning:\s*\n(.*?)(?:\n#|\Z)',
r'Let me think through this:\s*\n(.*?)(?:\nFinal answer:|\Z)'
]
for pattern in patterns:
matches = re.findall(pattern, self.response, re.DOTALL)
if matches:
self.thinking = matches[0].strip()
return self.thinking
return None
def calculate_metrics(self) -> Dict[str, Any]:
"""
Calculate various metrics about the response and code.
Returns:
Dictionary of calculated metrics
"""
# Extract code if not already done
if not self.code:
self.extract_code()
# Calculate basic metrics
response_size = len(self.response)
response_lines = self.response.count('\n') + 1
code_size = len(self.code) if self.code else 0
code_lines = self.code.count('\n') + 1 if self.code else 0
# Compute code complexity metrics using the class-structured code
complexity_metrics = self._compute_code_complexity()
# Combine metrics
metrics = {
"response_size_kb": round(response_size / 1024, 2),
"response_lines": response_lines,
"code_size_kb": round(code_size / 1024, 2),
"code_lines": code_lines,
"timestamp": self.timestamp.isoformat(),
**complexity_metrics
}
self.metrics = metrics
return metrics
def _compute_code_complexity(self) -> Dict[str, Any]:
"""
Compute code complexity metrics like function count, class count, etc.
from the class-structured code.
Returns:
Dictionary of complexity metrics
"""
if not self.code:
return {}
# Count functions - now looking for methods and static methods in class structure
function_count = len(re.findall(r'(?:^|\s)def\s+([a-zA-Z0-9_]+)\s*\(', self.code))
# Count classes (should be at least 1 - the solution class)
class_count = len(re.findall(r'(?:^|\s)class\s+([a-zA-Z0-9_]+)', self.code))
# Count import statements
import_count = len(re.findall(r'(?:^|\s)import\s+([a-zA-Z0-9_., ]+)', self.code))
from_import_count = len(re.findall(r'(?:^|\s)from\s+([a-zA-Z0-9_.]+)\s+import', self.code))
total_imports = import_count + from_import_count
# Estimate cyclomatic complexity by counting decision points
decision_patterns = [
r'\bif\s+', r'\belif\s+', r'\belse\s*:',
r'\bfor\s+', r'\bwhile\s+', r'\bexcept\s*',
r'\btry\s*:'
]
decision_count = sum(len(re.findall(pattern, self.code)) for pattern in decision_patterns)
return {
"function_count": function_count,
"class_count": class_count,
"import_count": total_imports,
"decision_points": decision_count,
"complexity_estimate": decision_count / (function_count if function_count else 1)
}
def save_to_file(self, output_dir: Path) -> Path:
"""
Save the response to a file.
Args:
output_dir: Directory where the file should be saved
Returns:
Path to the saved file
"""
# Create the output directory if it doesn't exist
output_dir.mkdir(exist_ok=True, parents=True)
# Create a filename from the model name and round number
filename = f"tournament_response__round_{self.round_num}__{self.model_name}.md"
file_path = output_dir / filename
# Write the response to the file
with open(file_path, "w", encoding="utf-8") as f:
f.write(self.response)
self.file_path = file_path
return file_path
class LLMTournament:
"""
Main class for managing the multi-round LLM tournament.
This class handles the full lifecycle of the tournament, including:
- Creating and managing the directory structure
- Querying LLMs for responses
- Creating prompts for each round
- Tracking metrics and generating reports
- Testing solutions
"""
def __init__(
self,
prompt: str,
rounds: int = 5,
output_dir: str = "tournament_results",
models: Dict[str, Dict[str, Any]] = None,
temperature: float = 0.7,
concurrent_requests: int = 2,
test_file: Optional[str] = None,
verbose: bool = False
):
"""
Initialize the tournament with the given parameters.
Args:
prompt: The initial coding challenge prompt
rounds: Number of rounds to run (not including round 0)
output_dir: Base directory for tournament artifacts
models: Dictionary of model configurations (defaults to MODELS)
temperature: Temperature setting for generation
concurrent_requests: Maximum number of concurrent API requests
test_file: Optional path to a file for testing solutions
verbose: Whether to enable verbose logging
"""
self.prompt = prompt
self.rounds = rounds
self.output_dir = Path(output_dir)
self.models = models or MODELS
self.temperature = temperature
self.concurrent_requests = concurrent_requests
self.test_file = test_file
self.verbose = verbose
# Set logging level based on verbosity
if verbose:
logger.setLevel(logging.DEBUG)
# Initialize the AI client
self.client = ai.Client()
# Store responses for each round and model
self.responses: Dict[int, Dict[str, ModelResponse]] = {i: {} for i in range(rounds + 1)}
# Initialize metrics tracking
self.metrics: Dict[str, Any] = {}
# Create directory structure
self.setup_directories()
# Log initialization
logger.info(f"Initialized LLM Tournament with {len(self.models)} models for {rounds} rounds")
logger.info(f"Output directory: {self.output_dir}")
logger.debug(f"Models: {list(self.models.keys())}")
def setup_directories(self) -> None:
"""
Create the necessary directory structure for the tournament.
Directory structure:
- output_dir/
- round_0_responses/
- round_1_responses/
- ...
- round_N_responses/
- output_results_for_each_round_and_model/
- extracted_code/ # New directory for extracted code
- metrics/
"""
# Create main output directory
self.output_dir.mkdir(exist_ok=True, parents=True)
# Create round-specific directories
for i in range(self.rounds + 1):
round_dir = self.output_dir / f"round_{i}_responses"
round_dir.mkdir(exist_ok=True)
# Create output results directory
results_dir = self.output_dir / "output_results_for_each_round_and_model"
results_dir.mkdir(exist_ok=True)
# Create extracted code directory (new)
extracted_code_dir = self.output_dir / "extracted_code"
extracted_code_dir.mkdir(exist_ok=True)
# Create metrics directory
metrics_dir = self.output_dir / "metrics"
metrics_dir.mkdir(exist_ok=True)
logger.debug(f"Created directory structure in {self.output_dir}")
def query_model(
self,
model_name: str,
round_num: int,
prompt_text: str
) -> ModelResponse:
"""
Query an LLM with the given prompt and handle retries and errors.
Args:
model_name: Name of the model to query
round_num: Current tournament round number
prompt_text: The prompt to send to the model
Returns:
ModelResponse object containing the model's response and metadata
"""
# Check if we already have a valid response file for this model and round
response_dir = self.output_dir / f"round_{round_num}_responses"
response_filename = f"tournament_response__round_{round_num}__{model_name}.md"
response_file_path = response_dir / response_filename
if response_file_path.exists():
logger.info(f"Found existing response file for {model_name} (round {round_num}). Loading...")
try:
# Read the existing response
with open(response_file_path, "r", encoding="utf-8") as f:
response_text = f.read()
# Create a ModelResponse object
response_obj = ModelResponse(
model_name=model_name,
round_num=round_num,
prompt=prompt_text,
response=response_text,
file_path=response_file_path
)
# Extract code (will use cached file if available) and thinking components
response_obj.extract_code(self.output_dir)
response_obj.extract_thinking()
# Calculate metrics
response_obj.calculate_metrics()
# Log success
logger.info(f"Successfully loaded existing response for {model_name} (round {round_num})")
# Store in the responses dictionary
self.responses[round_num][model_name] = response_obj
return response_obj
except Exception as e:
logger.warning(f"Error loading existing response for {model_name} (round {round_num}): {str(e)}. Requesting a new one.")
model_config = self.models[model_name]
model_id = model_config["id"]
thinking_enabled = model_config.get("thinking", False)
max_tokens = model_config.get("max_tokens", 4096)
provider = model_config.get("provider", "")
# Create system message based on model capabilities
system_message = "You are an expert programmer specializing in writing clean, efficient, and robust code."
if thinking_enabled:
system_message += (
" Please think through the problem carefully before providing your solution. "
"Show your reasoning process and explain key design decisions."
)
logger.info(f"Querying {model_name} (round {round_num})...")
# Create a ModelResponse object to store the result
response_obj = ModelResponse(
model_name=model_name,
round_num=round_num,
prompt=prompt_text,
response=""
)
# Try the API call with retries
for attempt in range(MAX_RETRIES):
try:
start_time = time.time()
# Prepare API parameters based on provider and model
api_params = {
"model": model_id,
"messages": [
{"role": "system", "content": system_message},
{"role": "user", "content": prompt_text}
]
}
# Handle provider-specific parameters
if provider.lower() == "openai":
# Check if this is o3-mini model which has parameter limitations
if "o3-mini" in model_id.lower():
# For o3-mini models, don't add temperature or max_tokens parameters
pass
else:
# For other OpenAI models, use these parameters
api_params["max_completion_tokens"] = max_tokens
api_params["temperature"] = self.temperature
else:
# Other providers use standard parameters
api_params["max_tokens"] = max_tokens
api_params["temperature"] = self.temperature
# Make the API call
api_response = self.client.chat.completions.create(**api_params)
# Calculate response time
response_time = time.time() - start_time
# Extract and store the response text
response_text = api_response.choices[0].message.content
response_obj.response = response_text
response_obj.metrics["response_time"] = round(response_time, 2)
# Extract code (and save to file) and thinking components
response_obj.extract_code(self.output_dir)
response_obj.extract_thinking()
# Calculate metrics
response_obj.calculate_metrics()
# Log success
logger.info(f"Received response from {model_name} ({round(response_time, 2)}s)")
logger.debug(f"Response metrics: {response_obj.metrics}")
# Store in the responses dictionary
self.responses[round_num][model_name] = response_obj
return response_obj
except Exception as e:
# Log the error
error_msg = f"Error querying {model_name} (attempt {attempt+1}/{MAX_RETRIES}): {str(e)}"
logger.error(error_msg)
logger.debug(traceback.format_exc())
# If we're seeing an unsupported parameter error, try to adapt
if "Unsupported parameter" in str(e):
error_details = str(e)
logger.info(f"Detected unsupported parameter error. Adapting request for next attempt.")
# Extract unsupported parameter name if possible
param_match = re.search(r"'([^']+)' is not supported", error_details)
if param_match and param_match.group(1) in api_params:
unsupported_param = param_match.group(1)
logger.info(f"Removing unsupported parameter: {unsupported_param}")
api_params.pop(unsupported_param, None)
# Store error information
response_obj.error = error_msg
# Retry with backoff if not the last attempt
if attempt < MAX_RETRIES - 1:
backoff_time = BACKOFF_TIMES[min(attempt, len(BACKOFF_TIMES) - 1)]
logger.info(f"Retrying in {backoff_time} seconds...")
time.sleep(backoff_time)
else:
# If all retries failed, return the error response
response_obj.response = f"ERROR: Failed to get response after {MAX_RETRIES} attempts.\n\n{error_msg}"
return response_obj
# This should never be reached, but just in case
return response_obj
def create_round_prompt(self, round_num: int) -> str:
"""
Create the prompt for a specific round by combining responses from the previous round.
Args:
round_num: The round number to create a prompt for
Returns:
The combined prompt text for the next round
"""
# For round 0, just use the original prompt
if round_num == 0:
return self.prompt
# For subsequent rounds, combine the responses from the previous round
prev_round = round_num - 1
# Start with the standard combination prompt
combined_prompt = f"""
I have the following problem which I posed to 4 different LLMs. I want you to carefully read the problem and then each solution. Choose the best ideas and elements from ALL solutions to the extent they are complementary rather than conflicting/inconsistent, and then weave together a true hybrid "best of all worlds" implementation which you are highly confident will not only work, but will outperform any of the individual solutions individually.
Original prompt:
{self.prompt}
Responses from different LLMs:
"""
# Add each model's response
for model_name, model_response in self.responses[prev_round].items():
# For round 1, include the full response; for later rounds, just include the code
if round_num == 1:
content = model_response.response
else:
content = model_response.code or model_response.response
combined_prompt += f"\n\n{model_name}:\n\n```python\n{content}\n```\n"
# Add specific instructions for synthesis
combined_prompt += """
Analyze each solution carefully, identifying strengths and weaknesses. Consider:
1. Correctness - Does the code handle all cases properly?
2. Efficiency - Is the code optimized for performance?
3. Readability - Is the code clear and maintainable?
4. Robustness - Does the code handle errors gracefully?
Then create a new implementation that combines the best aspects of all solutions.
Your implementation should be complete and ready to use without modification.
"""
return combined_prompt
def _all_responses_exist(self, round_num: int) -> bool:
"""
Check if all response files for a specific round already exist.
"""
response_dir = self.output_dir / f"round_{round_num}_responses"
for model_name in self.models.keys():
response_filename = f"tournament_response__round_{round_num}__{model_name}.md"
response_file_path = response_dir / response_filename
if not response_file_path.exists():
return False
return True
def _load_existing_responses(self, round_num: int) -> Dict[str, ModelResponse]:
"""
Load existing response files for a specific round.
"""
round_responses = {}
response_dir = self.output_dir / f"round_{round_num}_responses"
# Try to load the prompt for this round
prompt_text = ""
prompt_file = self.output_dir / f"prompt_round_{round_num}.md"
if prompt_file.exists():
try:
with open(prompt_file, "r", encoding="utf-8") as f:
prompt_text = f.read()
except Exception as e:
logger.warning(f"Error loading prompt for round {round_num}: {str(e)}")
for model_name in self.models.keys():
response_filename = f"tournament_response__round_{round_num}__{model_name}.md"
response_file_path = response_dir / response_filename
if response_file_path.exists():
try:
# Read the existing response
with open(response_file_path, "r", encoding="utf-8") as f:
response_text = f.read()
# Create a ModelResponse object
response_obj = ModelResponse(
model_name=model_name,
round_num=round_num,
prompt=prompt_text,
response=response_text,
file_path=response_file_path
)
# Extract code (will use cached file if available) and thinking components
response_obj.extract_code(self.output_dir)
response_obj.extract_thinking()
# Calculate metrics
response_obj.calculate_metrics()
# Store in responses dictionaries
round_responses[model_name] = response_obj
self.responses[round_num][model_name] = response_obj
logger.info(f"Loaded existing response for {model_name} (round {round_num})")
except Exception as e:
logger.error(f"Error loading existing response for {model_name} (round {round_num}): {str(e)}")
# Create comparison file and update metrics
self.create_round_comparison_file(round_num)
self.update_metrics(round_num, round_responses)
return round_responses
def run_round(self, round_num: int) -> Dict[str, ModelResponse]:
"""
Run a single round of the tournament, querying all models in parallel.
"""
logger.info(f"Starting Round {round_num}")
# Check if all response files for this round already exist
if self._all_responses_exist(round_num):
logger.info(f"All responses for round {round_num} already exist. Loading...")
return self._load_existing_responses(round_num)
# Check if the next round is already complete, which means we can skip prompt creation
# for this round and just load whatever responses exist
if round_num < self.rounds and self._all_responses_exist(round_num + 1):
logger.info(f"Next round {round_num + 1} is already complete. Loading existing responses for round {round_num}...")
return self._load_existing_responses(round_num)
# Create the prompt for this round
round_prompt = self.create_round_prompt(round_num)
# Save the prompt for reference
prompt_file = self.output_dir / f"prompt_round_{round_num}.md"
with open(prompt_file, "w", encoding="utf-8") as f:
f.write(round_prompt)
# Query all models in parallel
round_responses = {}
with ThreadPoolExecutor(max_workers=self.concurrent_requests) as executor:
# Submit all model queries
future_to_model = {
executor.submit(self.query_model, model_name, round_num, round_prompt): model_name
for model_name in self.models.keys()
}
# Process results as they complete
for future in as_completed(future_to_model):
model_name = future_to_model[future]
try:
response = future.result()
round_responses[model_name] = response
# Save the response to a file
response_dir = self.output_dir / f"round_{round_num}_responses"
response.save_to_file(response_dir)
logger.info(f"Saved response from {model_name} for round {round_num}")
except Exception as e:
logger.error(f"Error processing response from {model_name}: {str(e)}")
logger.debug(traceback.format_exc())
# Create comparison file for all responses in this round
self.create_round_comparison_file(round_num)
# Update metrics
self.update_metrics(round_num, round_responses)
# Return the responses
return round_responses
def create_round_comparison_file(self, round_num: int) -> Path:
"""
Create a markdown file comparing all responses for a specific round.
Args:
round_num: The round number to create a comparison for
Returns:
Path to the created comparison file
"""
if round_num == 0:
return None
# Create the comparison content
comparison_content = f"""# Round {round_num} Response Comparison
## Original Prompt
```
{self.prompt}
```
## Model Responses
"""
# Add each model's response
for model_name, response in self.responses[round_num].items():
# Extract metrics
metrics = response.metrics
code_lines = metrics.get("code_lines", 0)
code_size = metrics.get("code_size_kb", 0)
comparison_content += f"### {model_name}\n\n"
comparison_content += f"**Metrics:** {code_lines} lines, {code_size} KB\n\n"
comparison_content += "```python\n"
comparison_content += response.code or "# No code extracted"
comparison_content += "\n```\n\n"
# Save the comparison file
comparison_file = self.output_dir / f"markdown_table_prompt_response_comparison__round_{round_num}.md"
with open(comparison_file, "w", encoding="utf-8") as f:
f.write(comparison_content)
logger.info(f"Created comparison file for round {round_num}: {comparison_file}")
return comparison_file
def update_metrics(self, round_num: int, round_responses: Dict[str, ModelResponse]) -> None:
"""
Update the tournament metrics with the results from a round.
Args:
round_num: The round number
round_responses: Dictionary of model responses from the round
"""
# Create metrics structure if it doesn't exist
if "rounds" not in self.metrics:
self.metrics["rounds"] = {}
# Create metrics for this round
round_metrics = {
"timestamp": datetime.now().isoformat(),
"models": {}
}
# Add metrics for each model
for model_name, response in round_responses.items():
round_metrics["models"][model_name] = response.metrics
# Calculate aggregate metrics
code_sizes = [r.metrics.get("code_size_kb", 0) for r in round_responses.values()]
code_lines = [r.metrics.get("code_lines", 0) for r in round_responses.values()]
round_metrics["aggregate"] = {
"avg_code_size_kb": round(statistics.mean(code_sizes), 2) if code_sizes else 0,
"avg_code_lines": round(statistics.mean(code_lines), 2) if code_lines else 0,
"max_code_size_kb": round(max(code_sizes), 2) if code_sizes else 0,
"max_code_lines": max(code_lines) if code_lines else 0,
"min_code_size_kb": round(min(code_sizes), 2) if code_sizes else 0,
"min_code_lines": min(code_lines) if code_lines else 0
}
# Store the metrics
self.metrics["rounds"][round_num] = round_metrics
# Save metrics to file
self.save_metrics()
def save_metrics(self) -> Path:
"""
Save the tournament metrics to a JSON file.
Returns:
Path to the saved metrics file
"""
metrics_file = self.output_dir / "metrics" / "tournament_metrics.json"
with open(metrics_file, "w", encoding="utf-8") as f:
json.dump(self.metrics, f, indent=2)
logger.debug(f"Saved metrics to {metrics_file}")
return metrics_file
def generate_metrics_report(self) -> Path:
"""
Generate a detailed metrics report in markdown format.
Returns:
Path to the generated report
"""
# Create report content
report_content = f"""# LLM Tournament Metrics Report
## Tournament Overview
- **Start Time:** {self.metrics.get("start_time", "Unknown")}
- **End Time:** {self.metrics.get("end_time", "Unknown")}
- **Total Rounds:** {self.rounds + 1} (including round 0)
- **Models:** {", ".join(self.models.keys())}
## Round Summaries
"""
# Add metrics for each round
for round_num in range(self.rounds + 1):
round_metrics = self.metrics.get("rounds", {}).get(str(round_num), {})
if not round_metrics:
continue
report_content += f"### Round {round_num}\n\n"
# Create a table of metrics
report_content += "| Model | Code Size (KB) | Code Lines | Functions | Complexity |\n"
report_content += "|-------|---------------|------------|-----------|------------|\n"
for model_name, model_metrics in round_metrics.get("models", {}).items():
code_size = model_metrics.get("code_size_kb", "N/A")
code_lines = model_metrics.get("code_lines", "N/A")
function_count = model_metrics.get("function_count", "N/A")
complexity = model_metrics.get("complexity_estimate", "N/A")
report_content += f"| {model_name} | {code_size} | {code_lines} | {function_count} | {complexity} |\n"
report_content += "\n"
# Add convergence analysis
report_content += "## Convergence Analysis\n\n"
# Plot code size and lines over rounds
report_content += "### Code Size Over Rounds\n\n"
report_content += "| Round | " + " | ".join(self.models.keys()) + " |\n"
report_content += "|-------| " + " | ".join(["-" * len(name) for name in self.models.keys()]) + " |\n"
for round_num in range(self.rounds + 1):
round_metrics = self.metrics.get("rounds", {}).get(str(round_num), {})
if not round_metrics:
continue
row = [str(round_num)]
for model_name in self.models.keys():
model_metrics = round_metrics.get("models", {}).get(model_name, {})
code_size = model_metrics.get("code_size_kb", "N/A")
row.append(str(code_size))
report_content += "| " + " | ".join(row) + " |\n"
# Save the report
report_file = self.output_dir / "metrics" / "tournament_report.md"
with open(report_file, "w", encoding="utf-8") as f:
f.write(report_content)
logger.info(f"Generated metrics report: {report_file}")
return report_file
def create_test_suite(self) -> Tuple[Path, Path]:
"""
Create a comprehensive test suite for evaluating all solutions.
Returns:
Tuple containing paths to the test script and test runner
"""
# Collect all solution classes
solution_classes = []
for round_num in range(self.rounds + 1):
for model_name, response in self.responses.get(round_num, {}).items():
if not response.code:
continue
# Clean model name for use as a class name
clean_model_name = re.sub(r'[^a-zA-Z0-9]', '_', model_name)
class_name = f"{clean_model_name.title()}Round{round_num}Solution"
# With the new LLM-powered extract_code, we should already have a properly formatted class
# Just add the class directly to our solution_classes list
solution_classes.append(response.code)
# Create the test script
test_script = f"""#!/usr/bin/env python3
\"\"\"
LLM Tournament Test Suite
This script tests solutions from all rounds and models on a given input file,
and collects metrics on the results.
\"\"\"
import os
import time
import json