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
|
from typing import Any
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
from json_repair import repair_json as repair_json_text
|
||||||
from celery import Celery
|
from celery import Celery
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
|
@ -1232,13 +1233,18 @@ def parse_llm_json(text: str) -> dict[str, Any]:
|
||||||
try:
|
try:
|
||||||
return json.loads(candidate)
|
return json.loads(candidate)
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
repaired = repair_llm_json(candidate)
|
repairs = (repair_json_text(candidate), repair_llm_json(candidate))
|
||||||
try:
|
for repaired in repairs:
|
||||||
return json.loads(repaired)
|
try:
|
||||||
except json.JSONDecodeError as exc:
|
parsed = json.loads(repaired)
|
||||||
raise RuntimeError(
|
except (TypeError, json.JSONDecodeError):
|
||||||
f"LLM вернул невалидный JSON: {exc.msg} в строке {exc.lineno}, колонке {exc.colno}."
|
continue
|
||||||
) from exc
|
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:
|
def repair_llm_json(value: str) -> str:
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ fastapi==0.115.12
|
||||||
faster-whisper==1.1.1
|
faster-whisper==1.1.1
|
||||||
feedgen==1.0.0
|
feedgen==1.0.0
|
||||||
httpx==0.28.1
|
httpx==0.28.1
|
||||||
|
json-repair==0.63.4
|
||||||
Jinja2==3.1.6
|
Jinja2==3.1.6
|
||||||
Pillow==11.2.1
|
Pillow==11.2.1
|
||||||
pydantic-settings==2.9.1
|
pydantic-settings==2.9.1
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue