-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_utils.py
More file actions
52 lines (42 loc) · 1.49 KB
/
Copy pathjson_utils.py
File metadata and controls
52 lines (42 loc) · 1.49 KB
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
"""JSON extraction helpers for LLM text responses.
Ported from loom/src/loom/engine/semantic_compactor/parse.py.
"""
from __future__ import annotations
import json
import re
from typing import Any
def strip_markdown_fences(text: str) -> str:
if not text.startswith("```"):
return text
lines = text.split("\n")
content = "\n".join(lines[1:])
if content.endswith("```"):
content = content[:-3]
return content.strip()
def extract_first_json_object(text: str) -> dict[str, Any] | None:
decoder = json.JSONDecoder()
for match in re.finditer(r"\{", text):
start = match.start()
try:
candidate, _ = decoder.raw_decode(text[start:])
except json.JSONDecodeError:
continue
if isinstance(candidate, dict):
return candidate
return None
def parse_json_response(text: str) -> dict[str, Any]:
"""Parse a model response expected to contain a JSON object.
Tolerates markdown fences and junk before/after the object.
"""
stripped = strip_markdown_fences(str(text or "").strip())
if not stripped:
raise ValueError("empty response")
try:
parsed = json.loads(stripped)
except json.JSONDecodeError:
parsed = extract_first_json_object(stripped)
if parsed is None:
raise ValueError(f"could not extract JSON from response:\n{stripped[:500]}")
if not isinstance(parsed, dict):
raise ValueError("response JSON is not an object")
return parsed