import re def extract_json(text: str) -> str: """ Extracts JSON from LLM output, removing markdown triple backticks. Falls back to grabbing first {...} block if no fenced block detected. """ # Try triple backticks with optional 'json' match = re.search(r"``````", text, re.DOTALL) if match: return match.group(1).strip() # Fallback: Try to find first JSON object in text without triple backticks match = re.search(r"(\{.*\})", text, re.DOTALL) if match: return match.group(1).strip() return text.strip()