fix: устойчивый парсинг LLM-ответа — обработка markdown code blocks
- llm.py: возвращён (нужен для structured output) - Добавлен fallback-парсинг для ответов обёрнутых в ```json - Устранён undefined-variable баг в except-блоке
This commit is contained in:
@@ -83,9 +83,24 @@ async def analyze_finding(finding_data: dict) -> dict | None:
|
|||||||
content = body["choices"][0]["message"]["content"]
|
content = body["choices"][0]["message"]["content"]
|
||||||
return json.loads(content)
|
return json.loads(content)
|
||||||
except (KeyError, IndexError, json.JSONDecodeError) as e:
|
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(
|
log.warning(
|
||||||
"LLM response parse error for rule=%s: %s",
|
"LLM response parse error for rule=%s: %s — raw=%s",
|
||||||
finding_data.get("rule"),
|
finding_data.get("rule"),
|
||||||
e,
|
e,
|
||||||
|
raw[:200] if isinstance(raw, str) else str(raw)[:200],
|
||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
|||||||
Reference in New Issue
Block a user