File size: 9,681 Bytes
d6bcdbc | 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 | """
robust_parser.py — Universal LLM output parser that never requires JSON.
The problem: LLMs are unreliable at producing valid JSON. Different models
format differently. Structured output (json_schema) isn't supported everywhere.
The solution: Parse whatever the LLM gives you. Extract fields by multiple
strategies, fall back gracefully, and always return something usable.
This replaces the fragile generate_structured → json.loads → crash pattern.
"""
from __future__ import annotations
import json
import re
import logging
from typing import Any
logger = logging.getLogger(__name__)
def extract_json(text: str) -> dict[str, Any] | None:
"""
Try to extract a JSON object from arbitrary LLM text.
Handles: pure JSON, JSON in code blocks, JSON embedded in prose.
Returns None if no valid JSON found.
"""
text = text.strip()
# Strategy 1: Entire text is JSON
try:
return json.loads(text)
except (json.JSONDecodeError, ValueError):
pass
# Strategy 2: JSON in markdown code block
m = re.search(r'```(?:json)?\s*(\{.*\})\s*```', text, re.DOTALL)
if m:
try:
return json.loads(m.group(1))
except (json.JSONDecodeError, ValueError):
pass
# Strategy 3: Find outermost { ... } by brace matching
start = text.find('{')
if start >= 0:
depth = 0
for i in range(start, len(text)):
if text[i] == '{':
depth += 1
elif text[i] == '}':
depth -= 1
if depth == 0:
try:
return json.loads(text[start:i + 1])
except (json.JSONDecodeError, ValueError):
break
return None
def extract_field(text: str, field_name: str, default: str = "") -> str:
"""
Extract a named field value from LLM text, regardless of format.
Handles:
- JSON: {"field": "value"}
- Markdown: **field:** value / field: value
- Labeled: FIELD: value
- Line-based: field\nvalue
"""
text_lower = text.lower()
name_lower = field_name.lower()
# Try JSON first
obj = extract_json(text)
if obj and field_name in obj:
return str(obj[field_name])
# Pattern: "field_name": "value" or field_name: value
patterns = [
rf'"{field_name}"\s*:\s*"((?:[^"\\]|\\.)*)"', # JSON string
rf'"{field_name}"\s*:\s*(\d+\.?\d*)', # JSON number
rf'\*?\*?{field_name}\*?\*?\s*:\s*(.+?)(?:\n|$)', # Markdown/label
rf'{field_name}\s*[=:]\s*(.+?)(?:\n|$)', # Assignment
]
for pattern in patterns:
m = re.search(pattern, text, re.IGNORECASE)
if m:
return m.group(1).strip().strip('"').strip("'")
return default
def extract_number(text: str, field_name: str, default: float = 0.0) -> float:
"""Extract a numeric field from LLM text."""
val = extract_field(text, field_name)
if val:
try:
return float(val.rstrip('.').rstrip(','))
except (ValueError, TypeError):
pass
# Try direct pattern: field_name = X.X or field_name: X.X
m = re.search(rf'{field_name}\s*[=:]\s*([\d.]+)', text, re.IGNORECASE)
if m:
try:
return float(m.group(1).rstrip('.'))
except ValueError:
pass
return default
def extract_code(text: str) -> str:
"""
Extract Python code from LLM text.
Handles:
- Code in ``` blocks
- Code in "code" JSON field
- Raw code with def/class keywords
"""
# Strategy 1: JSON with code field
obj = extract_json(text)
if obj:
# Nested: action.params.code
action = obj.get("action", {})
if isinstance(action, dict):
params = action.get("params", {})
if isinstance(params, dict) and "code" in params:
return params["code"]
if "code" in obj:
return obj["code"]
# Strategy 2: Python code block
m = re.search(r'```(?:python)?\s*\n(.*?)```', text, re.DOTALL)
if m:
return m.group(1).strip()
# Strategy 3: Find code starting with def/class
lines = text.split('\n')
code_lines = []
in_code = False
for line in lines:
if re.match(r'^(def |class |import |from )', line.strip()):
in_code = True
if in_code:
# Stop at empty line after code, or at non-code text
if line.strip() == '' and code_lines and not code_lines[-1].strip().endswith(':'):
# Could be blank line in code — keep going if next line is indented
code_lines.append(line)
elif in_code and (line.startswith(' ') or line.startswith('\t') or
re.match(r'^(def |class |import |from |#|$)', line.strip())):
code_lines.append(line)
elif re.match(r'^(def |class )', line.strip()):
code_lines.append(line)
else:
if code_lines:
break
if code_lines:
return '\n'.join(code_lines).strip()
return ""
def parse_actor_response(text: str) -> dict[str, Any]:
"""
Parse an actor's response into thought/action/expected_delta.
Works with any format the LLM produces.
"""
# Try JSON first (best case)
obj = extract_json(text)
if obj and ("action" in obj or "thought" in obj):
return obj
# Extract fields individually
thought = extract_field(text, "thought")
expected_delta = extract_field(text, "expected_delta")
# Extract action name
action_name = extract_field(text, "name", "")
if not action_name:
action_name = extract_field(text, "action", "")
if action_name and action_name.startswith("{"):
action_name = "" # It's a JSON object, not a name
# Extract code if this is a coding task
code = extract_code(text)
# Build action
action = {"name": action_name or "UNKNOWN", "params": {}}
if code:
action["name"] = action.get("name", "submit_code") if action["name"] == "UNKNOWN" else action["name"]
action["params"]["code"] = code
if not thought:
# Use the first sentence as thought
thought = text.split('\n')[0][:200] if text else ""
return {
"thought": thought,
"action": action,
"expected_delta": expected_delta or "",
}
def parse_critic_response(text: str) -> dict[str, Any]:
"""
Parse a critic's response into phi_before/phi_after/reasoning/evidence/confidence.
Works with any format.
"""
# Try JSON first
obj = extract_json(text)
if obj and ("phi_before" in obj or "phi_after" in obj):
return {
"phi_before": float(obj.get("phi_before", 0)),
"phi_after": float(obj.get("phi_after", 0)),
"reasoning": str(obj.get("reasoning", "")),
"evidence": str(obj.get("evidence", "")),
"confidence": float(obj.get("confidence", 0.5)),
}
# Extract scores from text
phi_before = extract_number(text, "phi_before", 0.0)
if phi_before == 0.0:
phi_before = extract_number(text, "Φ(state_before)", 0.0)
if phi_before == 0.0:
phi_before = extract_number(text, "state_before", 0.0)
phi_after = extract_number(text, "phi_after", 0.0)
if phi_after == 0.0:
phi_after = extract_number(text, "Φ(state_after)", 0.0)
if phi_after == 0.0:
phi_after = extract_number(text, "state_after", 0.0)
# Try SCORE: X pattern
if phi_before == 0.0 and phi_after == 0.0:
scores = re.findall(r'(?:score|SCORE|Score)\s*[=:]\s*([\d.]+)', text)
if len(scores) >= 2:
phi_before = float(scores[0].rstrip('.'))
phi_after = float(scores[1].rstrip('.'))
elif len(scores) == 1:
phi_after = float(scores[0].rstrip('.'))
reasoning = extract_field(text, "reasoning")
evidence = extract_field(text, "evidence")
confidence = extract_number(text, "confidence", 0.5)
if not reasoning:
reasoning = text[:300]
if not evidence:
evidence = text[300:500] if len(text) > 300 else ""
return {
"phi_before": min(10.0, max(0.0, phi_before)),
"phi_after": min(10.0, max(0.0, phi_after)),
"reasoning": reasoning,
"evidence": evidence,
"confidence": min(1.0, max(0.0, confidence)),
}
def parse_optimizer_response(text: str) -> dict[str, Any]:
"""
Parse optimizer output into heuristics list.
"""
obj = extract_json(text)
if obj and "heuristics" in obj:
return obj
# Try to find a JSON array
m = re.search(r'\[.*\]', text, re.DOTALL)
if m:
try:
arr = json.loads(m.group())
if isinstance(arr, list):
return {"heuristics": arr}
except (json.JSONDecodeError, ValueError):
pass
# Extract from text patterns
heuristics = []
patterns = re.findall(r'(?:pattern|when|if)\s*[:\-]\s*(.+?)(?:\n|$)', text, re.IGNORECASE)
strategies = re.findall(r'(?:strategy|do|then|action)\s*[:\-]\s*(.+?)(?:\n|$)', text, re.IGNORECASE)
for pat, strat in zip(patterns, strategies):
heuristics.append({"tier": "strategic", "pattern": pat.strip(), "strategy": strat.strip()})
# If nothing found, try numbered list items
if not heuristics:
items = re.findall(r'\d+\.\s*(.+?)(?:\n|$)', text)
for item in items[:5]:
heuristics.append({"tier": "strategic", "pattern": "General", "strategy": item.strip()})
return {"heuristics": heuristics}
|