Repair malformed LLM JSON responses
All checks were successful
Deploy Dzen assistant / deploy (push) Successful in 1m57s
All checks were successful
Deploy Dzen assistant / deploy (push) Successful in 1m57s
This commit is contained in:
parent
bd32e28a91
commit
ca6d953785
2 changed files with 14 additions and 7 deletions
|
|
@ -10,6 +10,7 @@ from pathlib import Path
|
|||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from json_repair import repair_json as repair_json_text
|
||||
from celery import Celery
|
||||
from sqlalchemy import select
|
||||
|
||||
|
|
@ -1232,13 +1233,18 @@ def parse_llm_json(text: str) -> dict[str, Any]:
|
|||
try:
|
||||
return json.loads(candidate)
|
||||
except json.JSONDecodeError:
|
||||
repaired = repair_llm_json(candidate)
|
||||
try:
|
||||
return json.loads(repaired)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise RuntimeError(
|
||||
f"LLM вернул невалидный JSON: {exc.msg} в строке {exc.lineno}, колонке {exc.colno}."
|
||||
) from exc
|
||||
repairs = (repair_json_text(candidate), repair_llm_json(candidate))
|
||||
for repaired in repairs:
|
||||
try:
|
||||
parsed = json.loads(repaired)
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
continue
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
raise RuntimeError(
|
||||
f"LLM вернул невалидный JSON: {original_error.msg} в строке {original_error.lineno}, "
|
||||
f"колонке {original_error.colno}."
|
||||
) from original_error
|
||||
|
||||
|
||||
def repair_llm_json(value: str) -> str:
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ fastapi==0.115.12
|
|||
faster-whisper==1.1.1
|
||||
feedgen==1.0.0
|
||||
httpx==0.28.1
|
||||
json-repair==0.63.4
|
||||
Jinja2==3.1.6
|
||||
Pillow==11.2.1
|
||||
pydantic-settings==2.9.1
|
||||
|
|
|
|||
Loading…
Reference in a new issue