forked from ace-agent/ace
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplaybook_utils.py
More file actions
371 lines (305 loc) · 13.4 KB
/
playbook_utils.py
File metadata and controls
371 lines (305 loc) · 13.4 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
"""
==============================================================================
playbook.py
==============================================================================
This file contains functions for parsing and manipulating the playbook.
"""
import json
import re
from utils import get_section_slug
def parse_playbook_line(line):
"""Parse a single playbook line to extract components"""
# Pattern: [id] helpful=X harmful=Y :: content
pattern = r'\[([^\]]+)\]\s*helpful=(\d+)\s*harmful=(\d+)\s*::\s*(.*)'
match = re.match(pattern, line.strip())
if match:
return {
'id': match.group(1),
'helpful': int(match.group(2)),
'harmful': int(match.group(3)),
'content': match.group(4),
'raw_line': line
}
return None
def get_next_global_id(playbook_text):
"""Extract highest global ID and return next one"""
max_id = 0
lines = playbook_text.strip().split('\n')
for line in lines:
parsed = parse_playbook_line(line)
if parsed:
# Extract numeric part from ID
id_match = re.search(r'-(\d+)$', parsed['id'])
if id_match:
num = int(id_match.group(1))
max_id = max(max_id, num)
return max_id + 1
def format_playbook_line(bullet_id, helpful, harmful, content):
"""Format a bullet into playbook line format"""
return f"[{bullet_id}] helpful={helpful} harmful={harmful} :: {content}"
def update_bullet_counts(playbook_text, bullet_tags):
"""Update helpful/harmful counts based on tags (Counter layer)"""
lines = playbook_text.strip().split('\n')
updated_lines = []
# Create tag lookup - handle both old and new formats
tag_map = {}
if isinstance(bullet_tags, list) and len(bullet_tags) > 0:
for tag in bullet_tags:
if isinstance(tag, dict):
# Handle both 'id' and 'bullet' keys for backwards compatibility
bullet_id = tag.get('id') or tag.get('bullet', '')
tag_value = tag.get('tag', 'neutral')
if bullet_id:
tag_map[bullet_id] = tag_value
if not tag_map:
print("Warning: No valid bullet tags found to update counts")
return playbook_text
for line in lines:
if line.strip().startswith('#') or not line.strip():
# Preserve section headers and empty lines
updated_lines.append(line)
continue
parsed = parse_playbook_line(line)
if parsed and parsed['id'] in tag_map:
tag = tag_map[parsed['id']]
if tag == 'helpful':
parsed['helpful'] += 1
elif tag == 'harmful':
parsed['harmful'] += 1
# neutral: no change
# Reconstruct line with updated counts
new_line = format_playbook_line(
parsed['id'], parsed['helpful'], parsed['harmful'], parsed['content']
)
updated_lines.append(new_line)
else:
updated_lines.append(line)
return '\n'.join(updated_lines)
def apply_curator_operations(playbook_text, operations, next_id):
"""
Apply curator operations to playbook
TODO: Future Operations (not implemented yet)
- UPDATE: Rewrite existing bullets to be more accurate or comprehensive
- MERGE: Combine related bullets into stronger ones
- CREATE_META: Add high-level strategy sections
- DELETE: Remove outdated or incorrect bullets (if needed)
"""
lines = playbook_text.strip().split('\n')
# Build section map
sections = {}
current_section = "general"
section_line_map = {} # Track which line each section header is on
for i, line in enumerate(lines):
if line.strip().startswith('##'):
# Extract section name and normalize it
section_header = line.strip()[2:].strip()
current_section = section_header.lower().replace(' ', '_').replace('&', 'and')
section_line_map[current_section] = i
if current_section not in sections:
sections[current_section] = []
elif line.strip():
sections[current_section].append((i, line))
# Process operations
bullets_to_add = []
for op in operations:
op_type = op['type']
# TODO: Future operation types (not implemented yet)
# elif op_type == 'UPDATE':
# bullet_id = op.get('bullet_id', '')
# new_content = op.get('content', '')
# bullets_to_update[bullet_id] = new_content
# elif op_type == 'MERGE':
# source_ids = op.get('source_ids', [])
# bullets_to_delete.update(source_ids)
# # Add merged bullet logic here
# elif op_type == 'CREATE_META':
# section_name = op.get('section_name', 'META_STRATEGIES')
# # Add meta section creation logic here
if op_type == 'ADD':
# Normalize section name from operation
section_raw = op.get('section', 'general')
section = section_raw.lower().replace(' ', '_').replace('&', 'and')
# Check if section exists, if not use 'others'
if section not in sections and section != 'general':
print(f"Warning: Section '{section_raw}' not found, adding to OTHERS")
section = 'others'
slug = get_section_slug(section)
new_id = f"{slug}-{next_id:05d}"
next_id += 1
content = op.get('content', '')
new_line = format_playbook_line(new_id, 0, 0, content)
bullets_to_add.append((section, new_line))
print(f" Added bullet {new_id} to section {section}")
# Rebuild playbook
new_lines = []
for line in lines:
parsed = parse_playbook_line(line)
if parsed:
new_lines.append(line)
else:
new_lines.append(line)
# Add new bullets to appropriate sections
final_lines = []
current_section = None
for line in new_lines:
if line.strip().startswith('##'):
# Before moving to new section, add any bullets for current section
if current_section:
section_adds = [b for s, b in bullets_to_add if s == current_section]
final_lines.extend(section_adds)
# Clear added bullets
bullets_to_add = [(s, b) for s, b in bullets_to_add if s != current_section]
section_header = line.strip()[2:].strip()
current_section = section_header.lower().replace(' ', '_').replace('&', 'and')
final_lines.append(line)
# Add remaining bullets to current section
if current_section:
section_adds = [b for s, b in bullets_to_add if s == current_section]
final_lines.extend(section_adds)
bullets_to_add = [(s, b) for s, b in bullets_to_add if s != current_section]
# If there are still bullets to add (for sections that don't exist), add them to OTHERS
if bullets_to_add:
print(f"Warning: {len(bullets_to_add)} bullets have no matching section, adding to OTHERS")
others_bullets = [b for s, b in bullets_to_add]
# Find OTHERS section
others_idx = -1
for i, line in enumerate(final_lines):
if line.strip() == "## OTHERS":
others_idx = i
break
if others_idx >= 0:
# Insert after OTHERS header
for i, bullet in enumerate(others_bullets):
final_lines.insert(others_idx + 1 + i, bullet)
else:
# Append to end
final_lines.extend(others_bullets)
return '\n'.join(final_lines), next_id
def get_playbook_stats(playbook_text):
"""Generate statistics about the playbook"""
lines = playbook_text.strip().split('\n')
stats = {
'total_bullets': 0,
'high_performing': 0, # helpful > 5, harmful < 2
'problematic': 0, # harmful >= helpful
'unused': 0, # helpful + harmful = 0
'by_section': {}
}
current_section = 'general'
for line in lines:
if line.strip().startswith('##'):
current_section = line.strip()[2:].strip()
continue
parsed = parse_playbook_line(line)
if parsed:
stats['total_bullets'] += 1
if parsed['helpful'] > 5 and parsed['harmful'] < 2:
stats['high_performing'] += 1
elif parsed['harmful'] >= parsed['helpful'] and parsed['harmful'] > 0:
stats['problematic'] += 1
elif parsed['helpful'] + parsed['harmful'] == 0:
stats['unused'] += 1
if current_section not in stats['by_section']:
stats['by_section'][current_section] = {'count': 0, 'helpful': 0, 'harmful': 0}
stats['by_section'][current_section]['count'] += 1
stats['by_section'][current_section]['helpful'] += parsed['helpful']
stats['by_section'][current_section]['harmful'] += parsed['harmful']
return stats
def extract_json_from_text(text, json_key=None):
"""Extract JSON object from text, handling various formats"""
try:
# First, try to parse the entire response as JSON (JSON mode)
try:
result = json.loads(text.strip())
return result
except json.JSONDecodeError:
pass
# Fallback: Look for ```json blocks
json_pattern = r'```json\s*(.*?)\s*```'
matches = re.findall(json_pattern, text, re.DOTALL | re.IGNORECASE)
if matches:
# Try each match until we find valid JSON
for match in matches:
try:
json_str = match.strip()
result = json.loads(json_str)
return result
except json.JSONDecodeError:
continue
# Improved JSON extraction using balanced brace counting
# This handles deeply nested structures better
def find_json_objects(text):
"""Find JSON objects using balanced brace counting"""
json_objects = []
i = 0
while i < len(text):
if text[i] == '{':
# Found start of potential JSON object
brace_count = 1
start = i
i += 1
while i < len(text) and brace_count > 0:
if text[i] == '{':
brace_count += 1
elif text[i] == '}':
brace_count -= 1
elif text[i] == '"':
# Handle quoted strings to avoid counting braces inside strings
i += 1
while i < len(text) and text[i] != '"':
if text[i] == '\\':
i += 1 # Skip escaped character
i += 1
i += 1
if brace_count == 0:
# Found complete JSON object
json_candidate = text[start:i]
json_objects.append(json_candidate)
else:
i += 1
return json_objects
# Find all potential JSON objects
json_objects = find_json_objects(text)
for json_str in json_objects:
try:
result = json.loads(json_str)
return result
except json.JSONDecodeError:
continue
except Exception as e:
print(f"Failed to extract JSON: {e}")
if len(text) > 500:
print(f"Raw content preview:\n{text[:500]}...")
else:
print(f"Raw content:\n{text}")
return None
def extract_playbook_bullets(playbook_text, bullet_ids):
"""
Extract specific bullet points from playbook based on bullet_ids.
Args:
playbook_text (str): The full playbook text
bullet_ids (list): List of bullet IDs to extract
Returns:
str: Formatted playbook content containing only the specified bullets
"""
if not bullet_ids:
return "(No bullets used by generator)"
lines = playbook_text.strip().split('\n')
found_bullets = []
for line in lines:
if line.strip(): # Skip empty lines
parsed = parse_playbook_line(line)
if parsed and parsed['id'] in bullet_ids:
found_bullets.append({
'id': parsed['id'],
'content': parsed['content'],
'helpful': parsed['helpful'],
'harmful': parsed['harmful']
})
if not found_bullets:
return "(Generator referenced bullet IDs but none were found in playbook)"
# Format the bullets for reflector input
formatted_bullets = []
for bullet in found_bullets:
formatted_bullets.append(f"[{bullet['id']}] helpful={bullet['helpful']} harmful={bullet['harmful']} :: {bullet['content']}")
return '\n'.join(formatted_bullets)