fix: устойчивый парсинг LLM-ответа — обработка markdown code blocks

- llm.py:  возвращён (нужен для structured output)
- Добавлен fallback-парсинг для ответов обёрнутых в ```json
- Устранён undefined-variable баг в except-блоке
This commit is contained in:
Marker689
2026-05-10 05:14:38 +03:00
parent 0a22c2cce8
commit a754f91abf

View File

@@ -83,9 +83,24 @@ async def analyze_finding(finding_data: dict) -> dict | None:
content = body["choices"][0]["message"]["content"]
return json.loads(content)
except (KeyError, IndexError, json.JSONDecodeError) as e:
raw = ""
try:
raw = body["choices"][0]["message"]["content"]
except (KeyError, IndexError):
raw = str(body)[:300]
# Some models wrap JSON in markdown code blocks
if isinstance(raw, str) and raw.strip().startswith("```"):
try:
stripped = raw.strip().strip("`").strip()
if stripped.startswith("json\n"):
stripped = stripped[5:]
return json.loads(stripped)
except json.JSONDecodeError:
pass
log.warning(
"LLM response parse error for rule=%s: %s",
"LLM response parse error for rule=%s: %s — raw=%s",
finding_data.get("rule"),
e,
raw[:200] if isinstance(raw, str) else str(raw)[:200],
)
return None