| 12345678910111213141516171819202122232425262728293031323334353637383940 |
- # -*- coding: utf-8 -*-
- """Small LLM output helpers."""
- import json
- import re
- from typing import Any, Dict
- _FENCED_JSON_RE = re.compile(r"```(?:json)?\s*([\s\S]*?)\s*```", re.IGNORECASE)
- def extract_json_object(text: str) -> Dict[str, Any]:
- """Extract a JSON object from a model response."""
- if not text:
- return {}
- stripped = text.strip()
- fenced_match = _FENCED_JSON_RE.search(stripped)
- if fenced_match:
- stripped = fenced_match.group(1).strip()
- try:
- value = json.loads(stripped)
- return value if isinstance(value, dict) else {}
- except json.JSONDecodeError:
- pass
- start = stripped.find("{")
- end = stripped.rfind("}")
- if start >= 0 and end > start:
- try:
- value = json.loads(stripped[start:end + 1])
- return value if isinstance(value, dict) else {}
- except json.JSONDecodeError:
- return {}
- return {}
- def compact_json(value: Any) -> str:
- return json.dumps(value, ensure_ascii=False, indent=2)
|