llm_utils.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # -*- coding: utf-8 -*-
  2. """Small LLM output helpers."""
  3. import json
  4. import re
  5. from typing import Any, Dict
  6. _FENCED_JSON_RE = re.compile(r"```(?:json)?\s*([\s\S]*?)\s*```", re.IGNORECASE)
  7. def extract_json_object(text: str) -> Dict[str, Any]:
  8. """Extract a JSON object from a model response."""
  9. if not text:
  10. return {}
  11. stripped = text.strip()
  12. fenced_match = _FENCED_JSON_RE.search(stripped)
  13. if fenced_match:
  14. stripped = fenced_match.group(1).strip()
  15. try:
  16. value = json.loads(stripped)
  17. return value if isinstance(value, dict) else {}
  18. except json.JSONDecodeError:
  19. pass
  20. start = stripped.find("{")
  21. end = stripped.rfind("}")
  22. if start >= 0 and end > start:
  23. try:
  24. value = json.loads(stripped[start:end + 1])
  25. return value if isinstance(value, dict) else {}
  26. except json.JSONDecodeError:
  27. return {}
  28. return {}
  29. def compact_json(value: Any) -> str:
  30. return json.dumps(value, ensure_ascii=False, indent=2)