Spaces:
Sleeping
Sleeping
File size: 3,404 Bytes
7ae37d5 2026abe 7ae37d5 358492d addbd2a 7ae37d5 addbd2a 358492d addbd2a 358492d addbd2a 358492d addbd2a 2026abe | 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 | import re
import json
import logging
from typing import Union, Any, Optional
logger = logging.getLogger(__name__)
def clean_json_text(text: str) -> str:
"""Clean JSON text by removing markdown wrappers, extracting JSON object/array,
handling control characters, and removing trailing commas.
"""
text = text.strip()
# Remove markdown code blocks if present
if text.startswith("```"):
match = re.search(r"```(?:json)?\s*(.*?)\s*```", text, re.DOTALL)
if match:
text = match.group(1).strip()
else:
lines = text.split("\n")
text = "\n".join(lines[1:]).strip()
if text.endswith("```"):
text = text[:-3].strip()
# Find the starting and ending boundaries of JSON
start_curly = text.find("{")
start_bracket = text.find("[")
start_idx = -1
if start_curly != -1 and start_bracket != -1:
start_idx = min(start_curly, start_bracket)
elif start_curly != -1:
start_idx = start_curly
elif start_bracket != -1:
start_idx = start_bracket
end_idx = -1
if start_idx == start_curly:
end_idx = text.rfind("}")
elif start_idx == start_bracket:
end_idx = text.rfind("]")
if start_idx != -1 and end_idx != -1 and end_idx >= start_idx:
text = text[start_idx:end_idx + 1]
# Tokenize strings vs non-strings to safely strip trailing commas
# without affecting commas inside string literals.
parts = []
pos = 0
for m in re.finditer(r'"(?:[^"\\]|\\.)*"', text, re.DOTALL):
non_string = text[pos:m.start()]
# Strip trailing commas in arrays/objects
non_string = re.sub(r',\s*([}\]])', r'\1', non_string)
parts.append(non_string)
parts.append(m.group(0))
pos = m.end()
non_string = text[pos:]
non_string = re.sub(r',\s*([}\]])', r'\1', non_string)
parts.append(non_string)
return "".join(parts)
def safe_load_json(text: str) -> Union[dict, list, None]:
"""Parse JSON from LLM output. Strips markdown fences. Returns None on failure."""
if not text:
return None
# Strip markdown code fences
cleaned = text.strip()
if cleaned.startswith("```"):
lines = cleaned.split("\n")
cleaned = "\n".join(lines[1:-1] if lines[-1].strip() == "```" else lines[1:])
try:
return json.loads(cleaned)
except json.JSONDecodeError as exc:
# Try to find JSON object/array inside the text
last_exc = exc
for start_char, end_char in [('{', '}'), ('[', ']')]:
start = cleaned.find(start_char)
end = cleaned.rfind(end_char)
if start != -1 and end > start:
try:
return json.loads(cleaned[start:end+1])
except json.JSONDecodeError as inner_exc:
last_exc = inner_exc
logger.warning("safe_load_json: could not parse LLM output. Error: %s. First 200 chars: %s", last_exc, cleaned[:200])
return None
def safe_parse_json(text: str, default: Any = None) -> Any:
"""Safely parse LLM text output into Python data structures with fallback."""
try:
cleaned = clean_json_text(text)
return json.loads(cleaned)
except Exception as e:
logger.warning(f"Failed to parse JSON: {e}")
return default if default is not None else {}
|