File size: 2,024 Bytes
572a861
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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"}