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 {}