SolusOps/Study-with-ChampAI
0
1from __future__ import annotations2import json3import re4 5def extract_json(text: str) -> dict:6 """7 Robustly extract JSON from LLM response.8 Handles: raw JSON, markdown code fences, leading/trailing prose.9 """10 text = text.strip()11 text = re.sub(r"```(?:json)?\s*", "", text).replace("```", "")12 try:13 return json.loads(text)14 except json.JSONDecodeError:15 pass16 for pattern in (r"\{[\s\S]*\}", r"\[[\s\S]*\]"):17 match = re.search(pattern, text)18 if match:19 try:20 return json.loads(match.group())21 except json.JSONDecodeError:22 pass23 raise ValueError(f"No valid JSON found in response. First 200 chars: {text[:200]}")24 