| """I/O utilities: safe JSON read/write and lenient JSON parsing |
| of LLM outputs (handles ```json fences, trailing prose, etc.).""" |
| from __future__ import annotations |
|
|
| import json |
| import os |
| import re |
| from typing import Any |
|
|
|
|
| def load_json_safe(path: str, default: Any) -> Any: |
| """Load JSON if file exists; otherwise return ``default``.""" |
| if os.path.exists(path): |
| with open(path, "r", encoding="utf-8") as f: |
| return json.load(f) |
| return default |
|
|
|
|
| def save_json_atomic(data: Any, path: str) -> None: |
| """Atomic JSON save (write to .tmp then rename), creates parent dir.""" |
| parent = os.path.dirname(path) or "." |
| os.makedirs(parent, exist_ok=True) |
| tmp_path = f"{path}.tmp" |
| with open(tmp_path, "w", encoding="utf-8") as f: |
| json.dump(data, f, indent=2, ensure_ascii=False) |
| os.replace(tmp_path, path) |
|
|
|
|
| def parse_json_from_model_output(output_text: str) -> dict[str, Any]: |
| """Best-effort extraction of a JSON object from a model response. |
| |
| Order of attempts: |
| 1. ```json ... ``` fenced block. |
| 2. ``` ... ``` fenced block whose content starts with '{'. |
| 3. Substring between the first '{' and the last '}'. |
| """ |
| text = (output_text or "").strip() |
|
|
| match = re.search(r"```json\s*(.*?)\s*```", text, re.DOTALL) |
| if match: |
| try: |
| return json.loads(match.group(1)) |
| except json.JSONDecodeError: |
| pass |
|
|
| match = re.search(r"```\s*(.*?)\s*```", text, re.DOTALL) |
| if match: |
| candidate = match.group(1).strip() |
| if candidate.startswith("{"): |
| try: |
| return json.loads(candidate) |
| except json.JSONDecodeError: |
| pass |
|
|
| first_brace = text.find("{") |
| last_brace = text.rfind("}") |
| if first_brace != -1 and last_brace > first_brace: |
| try: |
| return json.loads(text[first_brace : last_brace + 1]) |
| except json.JSONDecodeError: |
| pass |
|
|
| raise ValueError( |
| f"Failed to extract valid JSON from model output. Preview: {text[:300]}..." |
| ) |
|
|