File size: 2,079 Bytes
6461f0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
"""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]}..."
    )