Parse JSON from LLM response, handling fences, prose, and malformed JSON.
(text: str)
| 516 | |
| 517 | |
| 518 | def _parse_json(text: str) -> list | dict: |
| 519 | """Parse JSON from LLM response, handling fences, prose, and malformed JSON.""" |
| 520 | from json_repair import repair_json |
| 521 | |
| 522 | cleaned = text.strip() |
| 523 | if cleaned.startswith("```"): |
| 524 | first_nl = cleaned.find("\n") |
| 525 | cleaned = cleaned[first_nl + 1 :] if first_nl != -1 else cleaned[3:] |
| 526 | if cleaned.endswith("```"): |
| 527 | cleaned = cleaned[:-3] |
| 528 | result = json.loads(repair_json(cleaned.strip())) |
| 529 | if not isinstance(result, (dict, list)): |
| 530 | raise ValueError(f"Expected JSON object or array, got {type(result).__name__}") |
| 531 | return result |
| 532 | |
| 533 | |
| 534 | def _parse_page_json(text: str) -> dict | None: |
no outgoing calls