infinex commited on
Commit
449c371
Β·
verified Β·
1 Parent(s): b48b2f3

Uploading dataset files from the local data folder.

Browse files
Files changed (1) hide show
  1. regex_optmizer.py +371 -0
regex_optmizer.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import random
3
+ from typing import List, Dict, Tuple, Optional
4
+ from dataclasses import dataclass
5
+ from openai import OpenAI
6
+
7
+ @dataclass
8
+ class EvaluationResult:
9
+ """Structured result from regex evaluation."""
10
+ score: float
11
+ true_positives: List[Dict]
12
+ false_positives: List[Dict]
13
+ false_negatives: List[Dict]
14
+ error_message: Optional[str] = None
15
+
16
+ class RegexOptimizerAgent:
17
+ """
18
+ An AI agent that iteratively optimizes regex patterns using LLM feedback.
19
+
20
+ The agent uses a reflexion-based approach:
21
+ 1. Evaluates current regex on ground truth data
22
+ 2. Generates improvement suggestions via LLM
23
+ 3. Tests new regex and compares performance
24
+ 4. Learns from failures through critique
25
+ """
26
+
27
+ def __init__(self, ground_truth_data: List[Dict], openai_client: OpenAI,
28
+ model: str = "gpt-4", temperature: float = 0.7):
29
+ """
30
+ Initialize the optimizer agent.
31
+
32
+ Args:
33
+ ground_truth_data: List of dicts with 'text' and 'expected' keys
34
+ openai_client: OpenAI client instance
35
+ model: Model name (e.g., 'gpt-4', 'gpt-3.5-turbo')
36
+ temperature: Sampling temperature for generation
37
+ """
38
+ self.data = ground_truth_data
39
+ self.client = openai_client
40
+ self.model = model
41
+ self.temperature = temperature
42
+ self.best_regex = ""
43
+ self.best_score = -1.0
44
+ self.iteration_history = []
45
+
46
+ def _evaluate_and_sample(self, regex_str: str, k: int = 3) -> EvaluationResult:
47
+ """
48
+ Evaluate regex performance and sample results from each category.
49
+
50
+ Args:
51
+ regex_str: Regular expression pattern to test
52
+ k: Number of samples to return per category
53
+
54
+ Returns:
55
+ EvaluationResult with score and categorized samples
56
+ """
57
+ tp_samples, fp_samples, fn_samples = [], [], []
58
+ correct_count = 0
59
+ error_msg = None
60
+
61
+ # Validate regex syntax
62
+ try:
63
+ compiled = re.compile(regex_str)
64
+ except Exception as e:
65
+ return EvaluationResult(0.0, [], [], [], str(e))
66
+
67
+ # Test on all data points
68
+ for item in self.data:
69
+ raw_text = item['text']
70
+ expected = str(item['expected']) if item['expected'] is not None else None
71
+
72
+ match = compiled.search(raw_text)
73
+ actual = match.group(0) if match else None
74
+
75
+ is_correct = (actual == expected)
76
+
77
+ result_payload = {
78
+ "raw": raw_text,
79
+ "truth": expected if expected else "NO_MATCH",
80
+ "extracted": actual if actual else "NONE"
81
+ }
82
+
83
+ if is_correct:
84
+ correct_count += 1
85
+ tp_samples.append(result_payload)
86
+ else:
87
+ if actual is None and expected is not None:
88
+ fn_samples.append(result_payload) # Missed match
89
+ else:
90
+ fp_samples.append(result_payload) # Wrong match
91
+
92
+ score = correct_count / len(self.data) if self.data else 0
93
+
94
+ # Sample to keep prompt manageable
95
+ random.shuffle(tp_samples)
96
+ random.shuffle(fp_samples)
97
+ random.shuffle(fn_samples)
98
+
99
+ return EvaluationResult(
100
+ score=score,
101
+ true_positives=tp_samples[:k],
102
+ false_positives=fp_samples[:k],
103
+ false_negatives=fn_samples[:k],
104
+ error_message=error_msg
105
+ )
106
+
107
+ def _generate_failure_critique(self, attempted_regex: str, best_regex: str,
108
+ new_fp: List[Dict], new_fn: List[Dict],
109
+ error_msg: Optional[str]) -> str:
110
+ """Generate critique explaining why attempted regex failed."""
111
+ if error_msg:
112
+ return f"SYNTAX ERROR: {error_msg}"
113
+
114
+ prompt = f"""You are an expert regex analyst. Analyze why this regex attempt failed.
115
+
116
+ BEST PERFORMING REGEX (baseline): {best_regex}
117
+ FAILED ATTEMPT: {attempted_regex}
118
+
119
+ NEW ERRORS INTRODUCED:
120
+ False Positives (incorrectly matched): {new_fp[:2]}
121
+ False Negatives (failed to match): {new_fn[:2]}
122
+
123
+ Task: In 1-2 concise sentences, explain the core flaw in the attempted regex that caused it to perform worse than the baseline. Focus on what pattern logic was incorrect.
124
+
125
+ Critique:"""
126
+
127
+ try:
128
+ response = self.client.chat.completions.create(
129
+ model=self.model,
130
+ messages=[
131
+ {"role": "system", "content": "You are an expert regular expression analyst."},
132
+ {"role": "user", "content": prompt}
133
+ ],
134
+ temperature=self.temperature,
135
+ max_tokens=150
136
+ )
137
+ return response.choices[0].message.content.strip()
138
+ except Exception as e:
139
+ return f"Failed to generate critique: {str(e)}"
140
+
141
+ def _build_optimization_prompt(self, regex: str, score: float,
142
+ tp: List[Dict], fp: List[Dict], fn: List[Dict],
143
+ failure_context: Optional[str] = None) -> str:
144
+ """
145
+ Build comprehensive prompt for regex improvement.
146
+
147
+ Uses chain-of-thought reasoning and specific examples to guide the LLM.
148
+ """
149
+ def format_examples(examples: List[Dict], limit: int = 5) -> str:
150
+ if not examples:
151
+ return "None"
152
+ lines = []
153
+ for ex in examples[:limit]:
154
+ lines.append(f" β€’ Input: '{ex['raw']}'")
155
+ lines.append(f" Expected: {ex['truth']} | Got: {ex['extracted']}")
156
+ return "\n".join(lines)
157
+
158
+ prompt = f"""You are an expert Regular Expression engineer. Your task is to improve a regex pattern to achieve 100% accuracy on the test cases below.
159
+
160
+ CURRENT REGEX PATTERN: `{regex}`
161
+ CURRENT ACCURACY: {score:.1%} ({int(score * len(self.data))}/{len(self.data)} correct)
162
+
163
+ ═══════════════════════════════════════════════════════════════
164
+
165
+ [βœ“ CORRECT MATCHES - These MUST continue working]
166
+ {format_examples(tp)}
167
+
168
+ [βœ— FALSE POSITIVES - Incorrectly matched (should return NO_MATCH)]
169
+ {format_examples(fp)}
170
+
171
+ [βœ— FALSE NEGATIVES - Failed to extract (should have matched)]
172
+ {format_examples(fn)}
173
+
174
+ ═══════════════════════════════════════════════════════════════
175
+ """
176
+
177
+ if failure_context:
178
+ prompt += f"""
179
+ ⚠️ CRITICAL FEEDBACK FROM PREVIOUS ATTEMPT:
180
+ {failure_context}
181
+
182
+ Learn from this mistake and avoid repeating it.
183
+
184
+ ═══════════════════════════════════════════════════════════════
185
+ """
186
+
187
+ prompt += """
188
+ INSTRUCTIONS:
189
+ 1. Analyze the patterns in false positives and false negatives
190
+ 2. Identify what distinguishes valid matches from invalid ones
191
+ 3. Design a regex that captures ONLY the expected patterns
192
+ 4. Ensure all current correct matches continue working
193
+
194
+ Think step-by-step:
195
+ - What do all the expected matches have in common?
196
+ - What makes the false positives different from true matches?
197
+ - What patterns are the false negatives missing?
198
+
199
+ Return ONLY the improved regex pattern inside backticks, like: `your_regex_here`
200
+ Do not include explanations, just the regex pattern.
201
+
202
+ Improved regex:"""
203
+
204
+ return prompt
205
+
206
+ def _extract_regex_from_response(self, text: str) -> str:
207
+ """Extract regex pattern from LLM response."""
208
+ # Try to find pattern in backticks
209
+ match = re.search(r"`([^`]+)`", text)
210
+ if match:
211
+ return match.group(1)
212
+
213
+ # Fallback: take first line if no backticks found
214
+ lines = [line.strip() for line in text.split('\n') if line.strip()]
215
+ return lines[0] if lines else text.strip()
216
+
217
+ def run_optimization(self, initial_regex: str, max_iterations: int = 10,
218
+ patience: int = 3, sample_size: int = 3) -> str:
219
+ """
220
+ Run the iterative optimization loop.
221
+
222
+ Args:
223
+ initial_regex: Starting regex pattern
224
+ max_iterations: Maximum optimization iterations
225
+ patience: Stop after N iterations without improvement
226
+ sample_size: Number of examples to show LLM per category
227
+
228
+ Returns:
229
+ Best regex pattern found
230
+ """
231
+ current_regex = initial_regex
232
+ result = self._evaluate_and_sample(current_regex, k=sample_size)
233
+
234
+ self.best_regex = current_regex
235
+ self.best_score = result.score
236
+ no_improvement_counter = 0
237
+ last_failure_critique = None
238
+
239
+ print("=" * 60)
240
+ print("REGEX OPTIMIZATION AGENT STARTED")
241
+ print("=" * 60)
242
+ print(f"Initial Regex: {initial_regex}")
243
+ print(f"Baseline Accuracy: {result.score:.1%} ({int(result.score * len(self.data))}/{len(self.data)})")
244
+ print()
245
+
246
+ for iteration in range(max_iterations):
247
+ # Early stopping conditions
248
+ if self.best_score == 1.0:
249
+ print("βœ“ PERFECT SCORE ACHIEVED!")
250
+ break
251
+
252
+ if no_improvement_counter >= patience:
253
+ print(f"βŠ— Early stopping: No improvement for {patience} iterations")
254
+ break
255
+
256
+ print(f"{'─' * 60}")
257
+ print(f"Iteration {iteration + 1}/{max_iterations}")
258
+ print(f"{'─' * 60}")
259
+
260
+ # Generate candidate regex
261
+ prompt = self._build_optimization_prompt(
262
+ current_regex, self.best_score,
263
+ result.true_positives, result.false_positives, result.false_negatives,
264
+ last_failure_critique
265
+ )
266
+ print(f"Candidate: {candidate}")
267
+
268
+ # Evaluate candidate
269
+ new_result = self._evaluate_and_sample(candidate, k=sample_size)
270
+ new_score = new_result.score
271
+
272
+ # Compare performance
273
+ if new_score > self.best_score:
274
+ improvement = new_score - self.best_score
275
+ print(f"βœ“ IMPROVEMENT: {self.best_score:.1%} β†’ {new_score:.1%} (+{improvement:.1%})")
276
+
277
+ self.best_score = new_score
278
+ self.best_regex = candidate
279
+ current_regex = candidate
280
+ result = new_result
281
+ no_improvement_counter = 0
282
+ last_failure_critique = None
283
+
284
+ self.iteration_history.append({
285
+ "iteration": iteration + 1,
286
+ "regex": candidate,
287
+ "score": new_score,
288
+ "improved": True
289
+ })
290
+ else:
291
+ print(f"βœ— No improvement: {new_score:.1%} (best: {self.best_score:.1%})")
292
+ no_improvement_counter += 1
293
+
294
+ # Generate critique for next iteration
295
+ last_failure_critique = self._generate_failure_critique(
296
+ candidate, self.best_regex,
297
+ new_result.false_positives, new_result.false_negatives,
298
+ new_result.error_message
299
+ )
300
+ print(f"Critique: {last_failure_critique}")
301
+
302
+ # Revert to best regex
303
+ current_regex = self.best_regex
304
+
305
+ self.iteration_history.append({
306
+ "iteration": iteration + 1,
307
+ "regex": candidate,
308
+ "score": new_score,
309
+ "improved": False
310
+ })
311
+
312
+ print()
313
+
314
+ return self.best_regex
315
+
316
+ def get_final_report(self) -> str:
317
+ """Generate summary report of optimization process."""
318
+ report = f"""
319
+ {'=' * 60}
320
+ OPTIMIZATION COMPLETE
321
+ {'=' * 60}
322
+ Final Regex: {self.best_regex}
323
+ Final Accuracy: {self.best_score:.1%} ({int(self.best_score * len(self.data))}/{len(self.data)})
324
+ Total Iterations: {len(self.iteration_history)}
325
+ Improvements: {sum(1 for h in self.iteration_history if h['improved'])}
326
+ {'=' * 60}
327
+ """
328
+ return report
329
+
330
+
331
+ def main():
332
+ """Example usage with numerical ID extraction."""
333
+
334
+ # Example dataset: Extract order/reference IDs (numbers that aren't prices or emergency codes)
335
+ training_data = [
336
+ {"text": "Order 5521 was shipped", "expected": "5521"},
337
+ {"text": "Ref ID: 990", "expected": "990"},
338
+ {"text": "Customer 12", "expected": "12"},
339
+ {"text": "Invoice #7834 pending", "expected": "7834"},
340
+ {"text": "Total is $50.00", "expected": None}, # Should NOT match money
341
+ {"text": "Call 911 for help", "expected": None}, # Should NOT match emergency
342
+ {"text": "Price: $19.99", "expected": None},
343
+ {"text": "Tracking: 88234", "expected": "88234"}
344
+ ]
345
+
346
+ # Initialize OpenAI client
347
+ # Make sure to set your OPENAI_API_KEY environment variable
348
+ client = OpenAI() # Reads from OPENAI_API_KEY env variable
349
+
350
+ # Initialize agent
351
+ agent = RegexOptimizerAgent(
352
+ training_data,
353
+ client,
354
+ model="gpt-4", # or "gpt-3.5-turbo" for faster/cheaper runs
355
+ temperature=0.7
356
+ )
357
+
358
+ # Run optimization
359
+ final_regex = agent.run_optimization(
360
+ initial_regex=r"\d",
361
+ max_iterations=10,
362
+ patience=3,
363
+ sample_size=3
364
+ )
365
+
366
+ # Print results
367
+ print(agent.get_final_report())
368
+
369
+
370
+ if __name__ == "__main__":
371
+ main()