"""parse.py: read a model reply into {decision, confidence, ...}; the last JSON object with a decision field wins.""" import json, math, re DONT, RUN = "don't run", "run" def norm_decision(s): s = str(s or "").strip().lower().replace("’", "'").replace("‘", "'") s = re.sub(r"[\s_\-]+", " ", s).strip(" .!\"'`*") if s in ("don't run", "dont run", "do not run", "don't", "no run", "not run", "hold", "hold it back"): return DONT, s in ("hold", "hold it back") if s in ("run", "run it", "send", "send it"): return RUN, s in ("send", "send it") return None, False def json_objects(text): """Every balanced {...} that parses as a JSON object, in order of appearance.""" out = [] for m in re.finditer(r"\{", text): depth, instr, esc = 0, False, False for j in range(m.start(), len(text)): c = text[j] if instr: esc = (c == "\\" and not esc) if c == '"' and not esc: instr = False continue if c == '"': instr = True elif c == "{": depth += 1 elif c == "}": depth -= 1 if depth == 0: try: o = json.loads(text[m.start():j + 1]) if isinstance(o, dict): out.append(o) except ValueError: pass break return out def parse_answer(text): """{"decision", "confidence", "key_condition", "reason", "decisive_records", "how", "legacy_label", "conf_rescaled"} or None.""" t = re.sub(r".*?", "", text or "", flags=re.S).strip() if not t: return None objs = [o for o in json_objects(t) if "decision" in o] how = "json" if objs and re.search(r"```", t): how = "fenced_json" if objs: o = objs[-1] d, legacy = norm_decision(o.get("decision")) if d: conf, resc = norm_conf(o.get("confidence")) recs = o.get("decisive_records") recs = [str(r).strip() for r in recs] if isinstance(recs, list) else ([str(recs)] if recs else []) return {"decision": d, "confidence": conf, "key_condition": str(o.get("key_condition") or ""), "reason": str(o.get("reason") or ""), "decisive_records": recs, "how": how, "legacy_label": legacy, "conf_rescaled": resc} m = re.findall(r'"decision"\s*:\s*"([^"]{1,20})"', t, re.I) how = "decision_field" if not m: m = re.findall(r"\bdecision\b[\s:*\-=]{0,6}(don['’]?t run|do not run|run)\b", t, re.I) how = "decision_word" if not m and norm_decision(t)[0]: m, how = [t], "bare_word" if m: d, legacy = norm_decision(m[-1]) if d: cm = re.findall(r'"?confidence"?\s*[:=]\s*"?([0-9.]+)', t, re.I) conf, resc = norm_conf(cm[-1] if cm else None) return {"decision": d, "confidence": conf, "key_condition": "", "reason": "", "decisive_records": [], "how": how, "legacy_label": legacy, "conf_rescaled": resc} return None def norm_conf(c): """Confidence in percent (0 to 100). A fraction below 1 written as a float is read as a probability and rescaled.""" if c is None or isinstance(c, bool): return None, False try: v = float(str(c).strip().rstrip("%")) except ValueError: return None, False if math.isnan(v): return None, False resc = False if 0 < v < 1 or (isinstance(c, float) and v == 1.0 and "." in str(c)): v, resc = v * 100, True return max(0.0, min(100.0, v)), resc # ---------- text helpers ----------