"""Extract the final JSON answer from a model response.""" from __future__ import annotations import json import re FENCE = re.compile(r"```(?:json)?\s*(\{.*?\})\s*```", re.S) def _candidates(text: str): for m in reversed(FENCE.findall(text)): yield m # fallback: the last balanced {...} in the text depth, end = 0, None for i in range(len(text) - 1, -1, -1): c = text[i] if c == "}": if depth == 0: end = i depth += 1 elif c == "{" and depth: depth -= 1 if depth == 0 and end is not None: yield text[i:end + 1] end = None def parse(text: str, people: list[str]) -> dict: """Return {"answer": {...}, "p_dies": {...}, "deciding_factors": str, "ok": bool, "error": str|None}.""" for cand in _candidates(text or ""): try: obj = json.loads(cand) except json.JSONDecodeError: continue ans = obj.get("answer") if not isinstance(ans, dict): continue norm = {} for k, v in ans.items(): k2 = str(k).strip().upper()[:1] v2 = str(v).strip().lower() norm[k2] = "dies" if v2.startswith(("die", "dead", "kill")) else "survives" if v2.startswith(("surv", "live", "alive", "safe")) else v2 missing = [p for p in people if p not in norm] p = obj.get("p_dies") or {} pd = {} for k, v in p.items(): try: pd[str(k).strip().upper()[:1]] = min(1.0, max(0.0, float(v))) except (TypeError, ValueError): pass return {"answer": norm, "p_dies": pd, "deciding_factors": str(obj.get("deciding_factors", "")), "ok": not missing and all(norm[q] in ("dies", "survives") for q in people), "error": f"missing {missing}" if missing else None} return {"answer": {}, "p_dies": {}, "deciding_factors": "", "ok": False, "error": "no JSON answer found"}