-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsystem_improver.py
More file actions
2522 lines (2039 loc) · 102 KB
/
system_improver.py
File metadata and controls
2522 lines (2039 loc) · 102 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 python
"""
system_improver.py - Meta-improvement system that analyzes and enhances the Agentic Learning System
Usage:
python system_improver.py [--backup]
This script:
1. Inspects the current state of the Agentic Learning System
2. Analyzes performance history and identifies improvement opportunities
3. Makes targeted code changes to enhance performance
4. Tracks changes and validates improvements
USAGE INSTRUCTIONS:
------------------
1. STAGING WORKFLOW (Recommended):
a) Generate and stage changes for review:
python system_improver.py --stage-only
b) Review staged changes:
cat staged_changes.json
c) Apply staged changes if approved:
python system_improver.py --apply-staged
2. AUTOMATIC WORKFLOW:
a) Generate, apply and validate changes:
python system_improver.py
b) Generate and apply changes without validation:
python system_improver.py --skip-validation
"""
import os
import sys
import json
import time
import argparse
import datetime
import difflib
import re
import shutil
import subprocess
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple
# Import required dependencies for LLM calling
from google import genai
from google.genai import types
class SystemImprover:
"""
Autonomous improvement system for the Agentic Learning System.
Reviews performance and makes code changes to enhance the system.
"""
def __init__(self,
create_backup: bool = True):
"""
Initialize the system improver.
Args:
create_backup: Whether to create a backup before making changes
"""
# System paths
self.root_dir = Path(".")
self.archive_dir = self.root_dir / "archive"
self.scripts_dir = self.root_dir / "scripts"
self.diffs_dir = self.root_dir / "diffs"
self.backup_dir = self.root_dir / "backups"
# Create required directories
self.diffs_dir.mkdir(exist_ok=True)
self.backup_dir.mkdir(exist_ok=True)
# Core code files to analyze and potentially modify
self.code_files = [
"agent_system.py",
"dataset_loader.py",
"run_script.py",
"system_prompt.md"
]
# Settings
self.create_backup = create_backup
self.improvement_timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
# Initialize LLM client
try:
self.client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
print("Initialized Gemini API client successfully")
except Exception as e:
print(f"Error initializing Gemini API client: {e}")
print("Make sure to set the GEMINI_API_KEY environment variable")
sys.exit(1)
def generate_changes_only(self) -> Dict:
"""
Generate system improvement changes without applying them.
These changes can be reviewed and applied later.
Returns:
Dict containing proposed changes and system analysis
"""
print("\n" + "="*80)
print(f"System Improver - Generating Changes - {self.improvement_timestamp}")
print("="*80)
# 1. Inspect the current system state
system_data = self._inspect_system()
# 2. Analyze performance and identify improvement areas
improvement_plan = self._analyze_for_improvements(system_data)
# 3. Save the improvement plan
staged_changes = {
"timestamp": self.improvement_timestamp,
"system_state": {
"current_iteration": improvement_plan.get("current_iteration", 0)
},
"analysis_summary": improvement_plan.get("analysis", ""),
"improvement_history_analysis": improvement_plan.get("improvement_history_analysis", ""),
"proposed_changes": improvement_plan.get("changes", []),
"generated_by": "system_improver.py"
}
# 4. Create a human-readable report
report_path = self.diffs_dir / f"proposed_changes_{self.improvement_timestamp}.md"
report_content = f"""# Proposed System Changes - {self.improvement_timestamp}
## Summary
- **Timestamp:** {self.improvement_timestamp}
- **Current Iteration:** {improvement_plan.get("current_iteration", 0)}
- **Proposed Changes:** {len(improvement_plan.get("changes", []))}
## System Analysis
{improvement_plan.get("analysis", "")}
## Improvement History Analysis
{improvement_plan.get("improvement_history_analysis", "")}
## Proposed Changes
"""
for i, change in enumerate(improvement_plan.get("changes", [])):
report_content += f"""### Change {i+1}: {change['file']}
**Description:** {change['description']}
"""
if 'find' in change and 'replace' in change:
report_content += f"""**Find:**
```
{change['find']}
```
**Replace With:**
```
{change['replace']}
```
"""
elif 'diff' in change:
report_content += f"""```diff
{change['diff']}
```
"""
with open(report_path, 'w') as f:
f.write(report_content)
print(f"\nGenerated {len(improvement_plan.get('changes', []))} proposed changes.")
print(f"Changes staged for review in: staged_changes.json")
print(f"Report available at: {report_path}")
return staged_changes
def fix_nested_triple_quotes(self, code: str) -> str:
"""
Fix issues with nested triple quotes in f-strings.
Uses a pattern-specific approach that handles various types of nesting.
Args:
code: Python code that might contain problematic nested quotes
Returns:
Modified code with fixed nested quotes
"""
# Skip processing if there's no code or no potential problematic patterns
if not code or ('f"""' not in code and "f'''" not in code):
return code
# Track if we made changes
made_changes = False
# 1. Handle docstrings in code blocks
if '"""Analyzes' in code:
code = code.replace('"""Analyzes', "'''Analyzes")
code = code.replace('format."""', "format.'''")
made_changes = True
# 2. Other docstrings in code blocks
if '"""Applies the described' in code:
code = code.replace('"""Applies the described', "'''Applies the described")
code = code.replace('grid."""', "grid.'''")
made_changes = True
# 3. Nested f-strings with exact patterns from the example
if 'prompt = f"""' in code and 'Analyze the transformation' in code:
code = code.replace('prompt = f"""', "prompt = f'''")
code = code.replace('Describe the transformation concisely, including:',
'Describe the transformation concisely, including:')
code = code.replace('structured format."""', "structured format.'''")
made_changes = True
# 4. General nested f-strings with prompt patterns
patterns_to_fix = [
('prompt = f"""Apply the following', "prompt = f'''Apply the following"),
('JSON format: [[row1], [row2], ...]', 'JSON format: [[row1], [row2], ...]'),
('""" # Call LLM', "''' # Call LLM"),
('"""\n return', "'''\n return"),
('"""\ntransformed_grid_json', "'''\ntransformed_grid_json")
]
for old, new in patterns_to_fix:
if old in code:
code = code.replace(old, new)
made_changes = True
# 5. If we've made changes, do a final pass to ensure we haven't missed anything
if made_changes:
# Look for any remaining nested triple quotes in typical patterns
if 'f"""' in code and '"""' in code[code.find('f"""') + 5:]:
# Find all occurrences of f""" (the start of an f-string)
f_starts = []
pos = 0
while True:
pos = code.find('f"""', pos)
if pos == -1:
break
f_starts.append(pos)
pos += 5 # Move past the current f"""
# For each f-string start, find the matching end and convert any triple quotes between
for start in f_starts:
# Find the matching end """ for this f-string
# This is approximate - we assume the first """ after nested content is the end
content_start = start + 4 # Skip the f"""
# Look for the next """ that terminates this f-string
end = content_start
quote_depth = 1
while quote_depth > 0 and end < len(code):
# Find next triple quote
next_triple = code.find('"""', end)
if next_triple == -1:
break
# Check if this is the matching end quote
if quote_depth == 1:
# This is our matching end quote - extract content between
content = code[content_start:next_triple]
# Replace any triple quotes in the content
modified_content = content.replace('"""', "'''")
# Replace the content in the original code
code = code[:content_start] + modified_content + code[next_triple:]
quote_depth -= 1
else:
quote_depth -= 1
end = next_triple + 3
return code
def apply_changes(self, staged_changes: Dict) -> List[Dict]:
"""
Apply previously staged changes.
Args:
staged_changes: Dict containing the staged changes to apply
Returns:
List of changes that were successfully applied
"""
print("\n" + "="*80)
print(f"System Improver - Applying Staged Changes - {self.improvement_timestamp}")
print("="*80)
# Import here to ensure it's available in this method
import shutil
# Create a backup if requested
if self.create_backup:
self._create_system_backup()
# Extract the changes to apply
changes_to_apply = staged_changes.get("proposed_changes", [])
if not changes_to_apply:
print("No changes to apply - staged_changes.json has no proposed_changes")
return []
# Implement the changes
changes_made = []
# Sort changes by priority
sorted_changes = sorted(
changes_to_apply,
key=lambda x: 0 if x.get("priority", "medium") == "high" else 1
)
for change in sorted_changes:
file_path = change["file"]
full_path = self.root_dir / file_path
if not full_path.exists():
print(f"Warning: File not found: {file_path}, skipping change")
continue
# Use find-and-replace if those fields are present
if 'find' in change and 'replace' in change:
try:
# Read current file content
with open(full_path, 'r', encoding='utf-8') as f:
current_content = f.read()
# Backup the file
backup_dir = self.backup_dir / f"backup_file_{self.improvement_timestamp}"
backup_dir.mkdir(exist_ok=True, parents=True)
backup_path = backup_dir / file_path
backup_path.parent.mkdir(exist_ok=True, parents=True)
shutil.copy2(full_path, backup_path)
print(f"Backed up {file_path} to {backup_path}")
# Apply find-and-replace
new_content, success = self._apply_find_replace(full_path, change["find"], change["replace"])
if success:
# Generate diff for record
diff = self._generate_diff(current_content, new_content, file_path)
# Write changes to file
with open(full_path, 'w', encoding='utf-8') as f:
f.write(new_content)
print(f"✅ Successfully applied find-and-replace to {file_path}")
# Record the change
change_record = {
"file": file_path,
"description": change["description"],
"find": change["find"],
"replace": change["replace"],
"diff": diff,
"timestamp": datetime.datetime.now().isoformat()
}
changes_made.append(change_record)
else:
print(f"❌ Could not find text to replace in {file_path}")
except Exception as e:
print(f"❌ Error applying find-and-replace to {file_path}: {e}")
import traceback
traceback.print_exc()
# Standard approach for applying changes with diff
elif 'diff' in change:
try:
# Load current file content
with open(full_path, 'r', encoding='utf-8') as f:
current_content = f.read()
# Apply the diff
print(f"Applying diff to {file_path}")
new_content = self._apply_diff(current_content, change["diff"])
# Check if there was an actual change
if new_content == current_content:
print(f"Warning: No changes made to {file_path} - content identical after applying changes")
print("Trying alternative approach with direct LLM modification...")
new_content = self._generate_modified_file(file_path, current_content, change["description"])
# Only write if there's an actual change now
if new_content != current_content:
# Generate the real diff for record-keeping
diff = self._generate_diff(current_content, new_content, file_path)
# Print a summary of changes for debugging
diff_lines = diff.splitlines()
added = sum(1 for line in diff_lines if line.startswith('+'))
removed = sum(1 for line in diff_lines if line.startswith('-'))
print(f"Changes to write: {added} lines added, {removed} lines removed")
# Check if we have write permission
if not os.access(full_path, os.W_OK):
print(f"⚠️ WARNING: No write permission for {file_path}")
# Try to make the file writable
try:
os.chmod(full_path, os.stat(full_path).st_mode | 0o200) # Add write permission
print(f" Attempted to add write permission to {file_path}")
except Exception as perm_e:
print(f" Could not change permissions: {perm_e}")
# Create a backup of the specific file before modifying it
backup_dir = self.backup_dir / f"backup_file_{self.improvement_timestamp}"
backup_dir.mkdir(exist_ok=True, parents=True)
backup_path = backup_dir / file_path
backup_path.parent.mkdir(exist_ok=True, parents=True)
shutil.copy2(full_path, backup_path)
print(f"Backed up {file_path} to {backup_path}")
# Now write the changes
try:
with open(full_path, 'w', encoding='utf-8') as f:
f.write(new_content)
print(f"✅ Successfully wrote changes to {file_path}")
except Exception as write_e:
print(f"❌ ERROR WRITING FILE {file_path}: {write_e}")
# Try writing with different approach
try:
temp_path = self.root_dir / f"temp_{file_path}"
with open(temp_path, 'w', encoding='utf-8') as f:
f.write(new_content)
# If successful, rename the file
shutil.move(temp_path, full_path)
print(f"✅ Successfully wrote changes using alternative approach")
except Exception as alt_e:
print(f"❌ Alternative writing approach also failed: {alt_e}")
continue
change_record = {
"file": file_path,
"description": change["description"],
"diff": diff,
"timestamp": datetime.datetime.now().isoformat()
}
changes_made.append(change_record)
else:
print(f"❌ No changes could be made to {file_path} (content remains identical)")
except Exception as e:
print(f"❌ Error implementing change for {file_path}: {e}")
import traceback
traceback.print_exc()
else:
print(f"⚠️ Change for {file_path} has neither find/replace nor diff - skipping")
if not changes_made:
print("No changes were successfully implemented.")
else:
print(f"\nSuccessfully applied {len(changes_made)} of {len(changes_to_apply)} changes.")
# Optionally run validation
if os.environ.get("SKIP_VALIDATION") != "1":
self._validate_changes()
return changes_made
def run(self) -> bool:
"""
Run the system improvement process.
Returns:
bool: True if improvements were made, False otherwise
"""
print("\n" + "="*80)
print(f"System Improver - Running at {self.improvement_timestamp}")
print("="*80)
# Create a backup before making changes if requested
if self.create_backup:
self._create_system_backup()
# 1. Inspect the current system state
system_data = self._inspect_system()
# 2. Analyze performance and identify improvement areas
improvement_plan = self._analyze_for_improvements(system_data)
# 3. Generate and apply code modifications
changes_made = self._implement_improvements(improvement_plan)
# 4. Validate the changes
validation_results = self._validate_changes()
# 5. Record the changes and results
self._record_improvement_results(
improvement_plan,
changes_made,
validation_results
)
print("\nSystem improvement complete!")
print(f"Changes recorded in: {self.diffs_dir}/changes_{self.improvement_timestamp}.json")
print(f"Report available at: {self.diffs_dir}/report_{self.improvement_timestamp}.md")
return len(changes_made) > 0
def _inspect_system(self) -> Dict:
"""
Inspect the current state of the system, including:
- Current code files
- Performance history
- Learnings file
- Best script
- Common error patterns
- Previous system improvements and their effects
Returns:
Dict containing all system data
"""
print("\nInspecting system state...")
system_data = {
"code_files": {},
"performance_history": [],
"learnings": "",
"best_script": None,
"error_patterns": [],
"current_iteration": 0,
"timestamp": self.improvement_timestamp,
"improvement_history": [] # Will contain previous improvements
}
# Read all code files
for file_path in self.code_files:
path = self.root_dir / file_path
if path.exists():
try:
with open(path, 'r', encoding='utf-8') as f:
system_data["code_files"][file_path] = f.read()
print(f"Loaded {file_path}: {len(system_data['code_files'][file_path])} chars")
except Exception as e:
print(f"Error reading {file_path}: {e}")
# Get learnings file
learnings_path = self.root_dir / "learnings.txt"
if learnings_path.exists():
try:
with open(learnings_path, 'r', encoding='utf-8') as f:
system_data["learnings"] = f.read()
print(f"Loaded learnings.txt: {len(system_data['learnings'])} chars")
except Exception as e:
print(f"Error reading learnings.txt: {e}")
# Get performance history
summaries_path = self.archive_dir / "summaries.json"
if summaries_path.exists():
try:
with open(summaries_path, 'r') as f:
summaries = json.load(f)
system_data["performance_history"] = summaries
# Get the current iteration
if summaries:
sorted_summaries = sorted(summaries, key=lambda x: x.get("iteration", 0))
system_data["current_iteration"] = sorted_summaries[-1].get("iteration", 0)
print(f"Loaded {len(summaries)} iteration summaries")
except Exception as e:
print(f"Error reading summaries.json: {e}")
# Get recent iterations for detailed analysis
iterations = []
for i in range(max(0, system_data["current_iteration"] - 5), system_data["current_iteration"] + 1):
iteration_path = self.archive_dir / f"iteration_{i}.json"
if iteration_path.exists():
try:
with open(iteration_path, 'r') as f:
iteration_data = json.load(f)
iterations.append(iteration_data)
except Exception as e:
print(f"Error reading iteration_{i}.json: {e}")
system_data["recent_iterations"] = iterations
# Extract common error patterns
error_patterns = []
for summary in system_data["performance_history"]:
if "performance" in summary and "error_analysis" in summary["performance"]:
patterns = summary["performance"]["error_analysis"].get("error_patterns", [])
error_patterns.extend(patterns)
# Deduplicate error patterns
system_data["error_patterns"] = list(set(error_patterns))
# Get previous improvement history from diffs directory
self._load_improvement_history(system_data)
return system_data
def _load_improvement_history(self, system_data: Dict):
"""
Load and analyze previous improvement attempts from the diffs directory.
Args:
system_data: Current system data dictionary to update
"""
print("Analyzing previous system improvements...")
# Find all change records in chronological order
change_files = sorted(self.diffs_dir.glob("changes_*.json"))
improvement_history = []
performance_before_after = []
# Track iterations where improvements were made
improved_iterations = []
# Process each improvement record
for change_file in change_files:
try:
with open(change_file, 'r') as f:
change_record = json.load(f)
# Extract basic improvement data
timestamp = change_record.get("timestamp", "unknown")
iteration = change_record.get("system_state", {}).get("current_iteration", "unknown")
changes = change_record.get("changes_made", [])
# Skip if no actual changes were made
if not changes:
continue
improved_iterations.append(iteration)
# Find performance data from before and after this improvement
if iteration != "unknown":
# Find summaries before and after this improvement
before_perf = None
after_perf = None
for summary in system_data["performance_history"]:
if summary.get("iteration") == iteration:
before_perf = summary.get("performance", {}).get("accuracy", 0)
elif summary.get("iteration") == iteration + 1:
after_perf = summary.get("performance", {}).get("accuracy", 0)
if before_perf is not None and after_perf is not None:
perf_change = after_perf - before_perf
performance_before_after.append({
"improvement_timestamp": timestamp,
"iteration": iteration,
"before_accuracy": before_perf,
"after_accuracy": after_perf,
"change": perf_change,
"success": perf_change > 0
})
# Create a summary of this improvement
files_changed = [change.get("file") for change in changes]
change_descriptions = [change.get("description") for change in changes]
improvement_history.append({
"timestamp": timestamp,
"iteration": iteration,
"files_changed": files_changed,
"num_changes": len(changes),
"descriptions": change_descriptions,
"validation_success": change_record.get("validation_results", {}).get("success", False)
})
print(f"Found improvement at iteration {iteration} with {len(changes)} changes")
except Exception as e:
print(f"Error processing improvement record {change_file}: {e}")
# Add improvement history to system data
system_data["improvement_history"] = improvement_history
system_data["performance_impact"] = performance_before_after
system_data["improved_iterations"] = improved_iterations
print(f"Loaded {len(improvement_history)} previous improvement records")
# Analyze effectiveness of previous improvements
if performance_before_after:
successful = sum(1 for p in performance_before_after if p.get("success", False))
print(f"Previous improvements: {successful}/{len(performance_before_after)} led to performance gains")
def _analyze_for_improvements(self, system_data: Dict) -> Dict:
"""
Analyze the system data and identify improvement opportunities.
Uses LLM to generate a comprehensive improvement plan.
Args:
system_data: System inspection data
Returns:
Dict containing improvement plan
"""
print("\nAnalyzing system for improvement opportunities...")
# DEBUG: Let's see what files are loaded
print(f"Available files in system_data: {list(system_data.get('code_files', {}).keys())}")
# CRITICAL FIX: Ensure agent_system.py is loaded, even if not in the initial set
for key_file in ["agent_system.py", "dataset_loader.py", "system_prompt.md"]:
if key_file not in system_data.get("code_files", {}):
file_path = self.root_dir / key_file
if file_path.exists():
try:
with open(file_path, 'r', encoding='utf-8') as f:
if "code_files" not in system_data:
system_data["code_files"] = {}
system_data["code_files"][key_file] = f.read()
print(f"Added missing key file: {key_file}")
except Exception as e:
print(f"Error loading key file {key_file}: {e}")
# Prepare LLM prompt for system analysis
prompt = self._create_analysis_prompt(system_data)
# Call LLM for improvement analysis
system_instruction = """You are an Expert System Designer and Improvement Specialist.
Your task is to analyze a machine learning system's code and performance data,
identify limitations, and propose specific, actionable code changes to improve the system."""
print("Calling LLM for improvement analysis...")
improvement_analysis = self._call_llm(prompt, system_instruction)
# Save the raw response for debugging
debug_path = self.diffs_dir / f"raw_llm_response_{self.improvement_timestamp}.txt"
with open(debug_path, 'w', encoding='utf-8') as f:
f.write(improvement_analysis)
print(f"Raw LLM response saved to {debug_path}")
# Initialize the improvement plan with default values
improvement_plan = {
"analysis": "",
"improvement_history_analysis": "",
"changes": [],
"current_iteration": system_data.get("current_iteration", 0)
}
try:
# Extract the system analysis section
analysis_section = re.search(r"## SYSTEM ANALYSIS(.*?)(?:##|$)", improvement_analysis, re.DOTALL)
if analysis_section:
improvement_plan["analysis"] = analysis_section.group(1).strip()
print(f"Extracted system analysis: {len(improvement_plan['analysis'])} chars")
else:
print("WARNING: Could not extract system analysis section from LLM response")
# Extract the improvement history analysis section
history_analysis_section = re.search(r"## IMPROVEMENT HISTORY ANALYSIS(.*?)(?:##|$)", improvement_analysis, re.DOTALL)
if history_analysis_section:
improvement_plan["improvement_history_analysis"] = history_analysis_section.group(1).strip()
print(f"Extracted improvement history analysis: {len(improvement_plan['improvement_history_analysis'])} chars")
else:
print("WARNING: Could not extract improvement history analysis section from LLM response")
# Extract find-replace changes (primary approach)
find_replace_changes = self._extract_find_replace_changes(improvement_analysis)
if find_replace_changes:
# Process and use find-replace changes
print(f"Found {len(find_replace_changes)} find-replace changes")
improvement_plan["changes"] = find_replace_changes
else:
# Fall back to extracting regular changes
print("No find-replace changes found, trying to extract regular changes")
regular_changes = self._extract_changes_from_llm_response(improvement_analysis)
if regular_changes:
improvement_plan["changes"] = regular_changes
print(f"Extracted {len(regular_changes)} regular changes")
else:
print("WARNING: Could not extract any changes from LLM response")
# Try again with targeted prompt for changes only
if improvement_plan["analysis"]:
print("Trying to generate changes with targeted prompt...")
targeted_changes = self._generate_changes_from_analysis(
improvement_plan["analysis"],
system_data
)
if targeted_changes:
improvement_plan["changes"] = targeted_changes
print(f"Generated {len(targeted_changes)} targeted changes")
print(f"Identified {len(improvement_plan['changes'])} proposed code changes")
except Exception as e:
print(f"Error parsing improvement plan: {e}")
import traceback
traceback.print_exc()
# Return what we have, plus the raw analysis
improvement_plan["raw_analysis"] = improvement_analysis
return improvement_plan
def _extract_changes_from_llm_response(self, improvement_analysis: str) -> List[Dict]:
"""
Extract proposed changes from LLM response using a more robust approach.
Args:
improvement_analysis: Raw LLM response text
Returns:
List of extracted changes with file, description, and diff
"""
changes = []
# Check if the response contains a proposed changes section
if "## PROPOSED CODE CHANGES" not in improvement_analysis and "PROPOSED CODE CHANGES" not in improvement_analysis:
print("Warning: No 'PROPOSED CODE CHANGES' section found in the LLM response")
# Save the raw response for debugging
debug_path = self.diffs_dir / f"failed_analysis_{self.improvement_timestamp}.txt"
with open(debug_path, 'w', encoding='utf-8') as f:
f.write(improvement_analysis)
print(f"Saved raw LLM response to {debug_path}")
return changes
# Split the response into sections
sections = re.split(r'##\s+', improvement_analysis)
proposed_changes_section = None
# Find the changes section
for section in sections:
if section.strip().startswith("PROPOSED CODE CHANGES") or section.strip().upper().startswith("PROPOSED CODE CHANGES"):
proposed_changes_section = section
break
if not proposed_changes_section:
print("Warning: Could not extract proposed changes section")
return changes
# Extract individual changes
change_blocks = re.split(r'###\s+Change\s+\d+:', proposed_changes_section)
# The first block is usually just header text, not a change
if len(change_blocks) > 1:
change_blocks = change_blocks[1:] # Skip the header
print(f"Found {len(change_blocks)} change blocks to process")
for i, block in enumerate(change_blocks):
# Extract file path - try multiple patterns
file_path = None
file_patterns = [
r"""File:\s*[`\'"]?([\w./\-_]+\.\w+)[`\'"]?""", # Standard format
r"""File\s+`([\w./\-_]+\.\w+)`""", # With backticks
r'File\s+([\w./\-_]+\.\w+)', # Without any quotes
r"""in\s+[`\'"]?([\w./\-_]+\.\w+)[`\'"]?""" # Alternative "in file.py" format
]
for pattern in file_patterns:
file_match = re.search(pattern, block, re.IGNORECASE | re.MULTILINE)
if file_match:
file_path = file_match.group(1).strip()
break
if not file_path:
print(f" Warning: Could not extract file path from change block {i+1}")
continue
# Extract description - multiple patterns
description = ""
desc_patterns = [
r'Description:(.*?)(?:```|Diff:|FIND:|REPLACE WITH:|$)', # Standard format
r'Description\s*:(.*?)(?:```|Diff:|FIND:|REPLACE WITH:|$)' # With flexible whitespace
]
for pattern in desc_patterns:
desc_match = re.search(pattern, block, re.DOTALL | re.IGNORECASE)
if desc_match:
description = desc_match.group(1).strip()
break
# Extract diff - try multiple patterns
diff = ""
diff_patterns = [
r'```diff\s*(.*?)```', # Standard diff format
r'```\s*(.*?)```', # Any code block if diff not found
r'Diff:\s*(.*?)(?=###|$)' # Diff: marker without code block
]
for pattern in diff_patterns:
diff_match = re.search(pattern, block, re.DOTALL)
if diff_match:
diff = diff_match.group(1).strip()
break
# For debugging
if file_path:
print(f" Change {i+1}: File '{file_path}'")
print(f" Description: {len(description)} chars")
print(f" Diff: {len(diff)} chars")
# Add the change if we have at least a file path and either description or diff
if file_path and (description or diff):
# Determine priority based on description
priority = "high" if "high priority" in description.lower() else "medium"
changes.append({
"change_id": i+1,
"file": file_path,
"description": description,
"diff": diff,
"priority": priority
})
print(f" Added change for {file_path}")
else:
print(f" Warning: Incomplete change information for block {i+1}, skipping")
print(f"Successfully extracted {len(changes)} changes from LLM response")
return changes
def _extract_find_replace_changes(self, improvement_analysis: str) -> List[Dict]:
"""
Extract find and replace changes from the improvement analysis.
Enhanced version that handles nested code blocks and various formatting styles.
Args:
improvement_analysis: The full LLM analysis text
Returns:
List of changes with file, description, find, and replace fields
"""
changes = []
# Check if we have any actual analysis
if not improvement_analysis or len(improvement_analysis.strip()) == 0:
print("No improvement analysis to extract changes from")
return changes
# Check if there's a proposed changes section
if "## PROPOSED CODE CHANGES" not in improvement_analysis and "PROPOSED CODE CHANGES" not in improvement_analysis:
print("No PROPOSED CODE CHANGES section found in analysis")
return changes
# Split into change blocks - each change starts with "### Change X:"
change_blocks = re.split(r'###\s+Change\s+\d+\s*:', improvement_analysis)
# The first block is usually just header text
if len(change_blocks) > 1:
change_blocks = change_blocks[1:] # Skip the header
print(f"Found {len(change_blocks)} change blocks to process")
for i, block in enumerate(change_blocks):
print(f"\nProcessing Change Block {i+1}:")
print("-" * 40)
print(block[:200] + "..." if len(block) > 200 else block) # Print a preview
# Extract file path
file_match = re.search(r'File\s*:\s*[`\'"]*([^`\'"]+)[`\'"]*', block, re.IGNORECASE)
if not file_match:
print(f" Warning: Could not extract file path from change block {i+1}")
continue
file_path = file_match.group(1).strip()
print(f" File: {file_path}")
# Extract description
desc_match = re.search(r'Description\s*:(.*?)(?=FIND:|```|$)', block, re.DOTALL | re.IGNORECASE)
description = desc_match.group(1).strip() if desc_match else ""
print(f" Description: {len(description)} chars")
# Extract find content - looking for content between FIND: and REPLACE WITH:
find_section = None
replace_section = None
# First try to find the whole sections
find_section_match = re.search(r'FIND\s*:(.*?)(?=REPLACE WITH:|REPLACE:|$)', block, re.DOTALL | re.IGNORECASE)
if find_section_match:
find_section = find_section_match.group(1).strip()
replace_section_match = re.search(r'(?:REPLACE WITH|REPLACE)\s*:(.*?)(?=$|###)', block, re.DOTALL | re.IGNORECASE)
if replace_section_match:
replace_section = replace_section_match.group(1).strip()
print(f" Find section: {len(find_section) if find_section else 0} chars")
print(f" Replace section: {len(replace_section) if replace_section else 0} chars")
# Now extract the code blocks from within these sections
find_text = ""
replace_text = ""
if find_section:
# Extract code block from find section
code_block_match = re.search(r'```(?:python)?\s*\n(.*?)\n```', find_section, re.DOTALL)
if code_block_match:
find_text = code_block_match.group(1)
else:
# If no code block, use the whole section
find_text = find_section
if replace_section:
# Extract code block from replace section
code_block_match = re.search(r'```(?:python)?\s*\n(.*?)\n```', replace_section, re.DOTALL)
if code_block_match:
replace_text = code_block_match.group(1)
else: