File size: 11,716 Bytes
cacd4d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Log Parser for Extracting Candidates and Feedback

Parses optimization logs to extract candidate prompts, feedback, and scores.
"""

import re
from typing import List, Dict, Optional, Tuple
from pathlib import Path


class OptimizationLogParser:
    """Parse optimization logs to extract candidates and feedback"""
    
    def __init__(self, log_file: str):
        """
        Initialize parser with log file path.
        
        Args:
            log_file: Path to log file
        """
        self.log_file = Path(log_file)
        self.content = ""
        if self.log_file.exists():
            with open(self.log_file, 'r', encoding='utf-8') as f:
                self.content = f.read()
    
    def extract_iterations(self) -> List[Dict]:
        """Extract iteration information from logs"""
        iterations = []
        
        # Pattern to find iteration markers
        iteration_pattern = r'Iteration\s+(\d+)|Starting GEPA optimization|πŸš€ Starting GEPA optimization'
        
        # Find all iteration starts
        for match in re.finditer(iteration_pattern, self.content):
            # Try to extract iteration number
            iter_num = 1
            if match.group(1):
                iter_num = int(match.group(1))
            
            # Find the section for this iteration
            start_pos = match.start()
            next_match = list(re.finditer(iteration_pattern, self.content))
            next_idx = next((i for i, m in enumerate(next_match) if m.start() > start_pos), None)
            
            if next_idx is not None:
                end_pos = next_match[next_idx].start()
                iter_content = self.content[start_pos:end_pos]
            else:
                iter_content = self.content[start_pos:]
            
            iterations.append({
                'iteration': iter_num,
                'content': iter_content,
                'start_pos': start_pos
            })
        
        return iterations
    
    def extract_candidates(self, iteration_content: str) -> List[Dict]:
        """
        Extract candidate prompts from iteration content.
        
        Args:
            iteration_content: Content for a single iteration
            
        Returns:
            List of candidate dictionaries
        """
        candidates = []
        
        # Pattern 1: GEPA Reflection candidates
        # Look for "PROPOSED PROMPT" or "πŸ“ PROPOSED PROMPT"
        gepa_patterns = [
            r'πŸ“ PROPOSED PROMPT.*?----------------------------------------\s*(.*?)(?=----------------------------------------|πŸ“Š|πŸš€|$)',
            r'PROPOSED PROMPT.*?----------------------------------------\s*(.*?)(?=----------------------------------------|πŸ“Š|πŸš€|$)',
            r'GEPA REFLECTION.*?----------------------------------------\s*(.*?)(?=----------------------------------------|πŸ“Š|πŸš€|$)',
        ]
        
        for pattern in gepa_patterns:
            for match in re.finditer(pattern, iteration_content, re.DOTALL):
                prompt = match.group(1).strip()
                if prompt and len(prompt) > 20:  # Valid prompt
                    candidates.append({
                        'source': 'GEPA_Reflection',
                        'prompt': prompt,
                        'position': match.start()
                    })
        
        # Pattern 2: LLEGO Crossover candidates
        crossover_patterns = [
            r'🧬 Crossover.*?----------------------------------------\s*(.*?)(?=----------------------------------------|πŸ“Š|πŸš€|$)',
            r'Crossover.*?----------------------------------------\s*(.*?)(?=----------------------------------------|πŸ“Š|πŸš€|$)',
        ]
        
        for pattern in crossover_patterns:
            for match in re.finditer(pattern, iteration_content, re.DOTALL):
                prompt = match.group(1).strip()
                if prompt and len(prompt) > 20:
                    candidates.append({
                        'source': 'LLEGO_Crossover',
                        'prompt': prompt,
                        'position': match.start()
                    })
        
        # Pattern 3: LLEGO Mutation candidates
        mutation_patterns = [
            r'🎲 Mutation.*?----------------------------------------\s*(.*?)(?=----------------------------------------|πŸ“Š|πŸš€|$)',
            r'Mutation.*?----------------------------------------\s*(.*?)(?=----------------------------------------|πŸ“Š|πŸš€|$)',
        ]
        
        for pattern in mutation_patterns:
            for match in re.finditer(pattern, iteration_content, re.DOTALL):
                prompt = match.group(1).strip()
                if prompt and len(prompt) > 20:
                    candidates.append({
                        'source': 'LLEGO_Mutation',
                        'prompt': prompt,
                        'position': match.start()
                    })
        
        # Pattern 4: Generic candidate markers
        # Look for prompts in quotes or code blocks
        generic_patterns = [
            r'"([^"]{50,})"',  # Quoted prompts
            r'```\s*(.*?)\s*```',  # Code blocks
        ]
        
        for pattern in generic_patterns:
            for match in re.finditer(pattern, iteration_content, re.DOTALL):
                prompt = match.group(1).strip()
                # Check if it looks like a prompt (contains task instructions)
                if (len(prompt) > 50 and 
                    any(keyword in prompt.lower() for keyword in 
                        ['you are', 'task', 'instruction', 'element', 'identify', 'select'])):
                    # Check if we haven't already captured this
                    if not any(c['prompt'] == prompt for c in candidates):
                        candidates.append({
                            'source': 'Unknown',
                            'prompt': prompt,
                            'position': match.start()
                        })
        
        # Sort by position
        candidates.sort(key=lambda x: x['position'])
        
        return candidates
    
    def extract_feedback(self, iteration_content: str) -> List[Dict]:
        """
        Extract feedback from iteration content.
        
        Args:
            iteration_content: Content for a single iteration
            
        Returns:
            List of feedback dictionaries
        """
        feedback_list = []
        
        # Pattern 1: Explicit feedback markers
        feedback_patterns = [
            r'πŸ’¬ FEEDBACK:\s*(.*?)(?=\n\n|\nπŸ“Š|\nπŸš€|\nπŸ’‘|$)',
            r'FEEDBACK:\s*(.*?)(?=\n\n|\nπŸ“Š|\nπŸš€|\nπŸ’‘|$)',
            r'Feedback:\s*(.*?)(?=\n\n|\nπŸ“Š|\nπŸš€|\nπŸ’‘|$)',
        ]
        
        for pattern in feedback_patterns:
            for match in re.finditer(pattern, iteration_content, re.DOTALL):
                feedback_text = match.group(1).strip()
                if feedback_text and len(feedback_text) > 10:
                    feedback_list.append({
                        'feedback': feedback_text,
                        'position': match.start()
                    })
        
        # Pattern 2: LLM-as-Judge feedback
        judge_patterns = [
            r'LLM-as-Judge.*?----------------------------------------\s*(.*?)(?=----------------------------------------|πŸ“Š|πŸš€|$)',
            r'Judge Feedback.*?----------------------------------------\s*(.*?)(?=----------------------------------------|πŸ“Š|πŸš€|$)',
        ]
        
        for pattern in judge_patterns:
            for match in re.finditer(pattern, iteration_content, re.DOTALL):
                feedback_text = match.group(1).strip()
                if feedback_text and len(feedback_text) > 10:
                    feedback_list.append({
                        'feedback': feedback_text,
                        'position': match.start(),
                        'source': 'LLM-as-Judge'
                    })
        
        # Sort by position
        feedback_list.sort(key=lambda x: x['position'])
        
        return feedback_list
    
    def extract_scores(self, iteration_content: str) -> List[Dict]:
        """
        Extract scores from iteration content.
        
        Args:
            iteration_content: Content for a single iteration
            
        Returns:
            List of score dictionaries
        """
        scores = []
        
        # Pattern for scores
        score_patterns = [
            r'Score:\s*([\d.]+)',
            r'Average score:\s*([\d.]+)',
            r'🎯 SCORE:\s*([\d.]+)',
            r'πŸ“Š Score:\s*([\d.]+)',
        ]
        
        for pattern in score_patterns:
            for match in re.finditer(pattern, iteration_content):
                score_value = float(match.group(1))
                scores.append({
                    'score': score_value,
                    'position': match.start()
                })
        
        # Sort by position
        scores.sort(key=lambda x: x['position'])
        
        return scores
    
    def parse_all(self) -> Dict:
        """
        Parse entire log file and extract all information.
        
        Returns:
            Dictionary with all extracted information
        """
        iterations = self.extract_iterations()
        
        result = {
            'iterations': [],
            'total_iterations': len(iterations),
            'all_candidates': [],
            'all_feedback': []
        }
        
        for iter_info in iterations:
            iter_num = iter_info['iteration']
            iter_content = iter_info['content']
            
            candidates = self.extract_candidates(iter_content)
            feedback = self.extract_feedback(iter_content)
            scores = self.extract_scores(iter_content)
            
            # Try to associate scores with candidates
            for i, candidate in enumerate(candidates):
                # Find nearest score after this candidate
                candidate_pos = candidate['position']
                nearest_score = None
                min_distance = float('inf')
                
                for score_info in scores:
                    if score_info['position'] > candidate_pos:
                        distance = score_info['position'] - candidate_pos
                        if distance < min_distance:
                            min_distance = distance
                            nearest_score = score_info['score']
                
                if nearest_score is not None:
                    candidate['score'] = nearest_score
                
                # Try to associate feedback
                nearest_feedback = None
                min_distance = float('inf')
                
                for feedback_info in feedback:
                    if feedback_info['position'] > candidate_pos:
                        distance = feedback_info['position'] - candidate_pos
                        if distance < min_distance and distance < 5000:  # Within reasonable distance
                            min_distance = distance
                            nearest_feedback = feedback_info['feedback']
                
                if nearest_feedback:
                    candidate['feedback'] = nearest_feedback
            
            result['iterations'].append({
                'iteration': iter_num,
                'candidates': candidates,
                'feedback': feedback,
                'scores': scores
            })
            
            result['all_candidates'].extend(candidates)
            result['all_feedback'].extend(feedback)
        
        return result