fix(sources): batch llm ranking and salvage truncated json

This commit is contained in:
kpa39l
2026-11-05 09:13:53 +00:00
parent b719dc00b4
commit fe4298b8a8
11 changed files with 373 additions and 15 deletions
+75 -8
View File
@@ -14,12 +14,63 @@ from config import OLLAMA_MODEL, OLLAMA_URL
THINK_RE = re.compile(r"</think(?:ing)?>", re.I)
def _complete_objects(text: str, key: str = "items") -> list[str]:
"""Собирает синтаксически полные объекты {...} внутри массива `"key": [...]`.
Нужно для обрезанного ответа: модель упирается в лимит токенов и обрывается
посреди строки, но предыдущие элементы массива уже целые — их можно спасти.
Сканер учитывает строки и экранирование, поэтому фигурные скобки внутри значений
не сбивают счётчик глубины.
"""
at = text.find(f'"{key}"')
if at < 0:
return []
start = text.find("[", at)
if start < 0:
return []
objs: list[str] = []
depth = 0
obj_start = -1
in_str = False
esc = False
for pos in range(start + 1, len(text)):
ch = text[pos]
if in_str:
if esc:
esc = False
elif ch == "\\":
esc = True
elif ch == '"':
in_str = False
continue
if ch == '"':
in_str = True
elif ch == "{":
if depth == 0:
obj_start = pos
depth += 1
elif ch == "}":
if depth > 0:
depth -= 1
if depth == 0 and obj_start >= 0:
objs.append(text[obj_start:pos + 1])
obj_start = -1
elif ch == "]" and depth == 0:
break
return objs
def parse_json_response(text: str) -> dict:
"""Достаёт JSON из ответа модели.
Qwen3 может примешивать блок рассуждений в текст ответа даже с think=false
(зависит от сборки модели): срезаем всё до закрывающего тега, убираем ```-обёртки,
и если json.loads всё равно падает — берём первый сбалансированный {...}.
Если ответ оборван по лимиту токенов (обычное дело на длинных списках), собираем
из него все **полные** элементы массива items и возвращаем частичный результат:
половина оценок полезнее, чем никаких.
"""
t = (text or "").strip()
m = THINK_RE.search(t)
@@ -28,12 +79,14 @@ def parse_json_response(text: str) -> dict:
if t.startswith("```"):
t = re.sub(r"^```[a-zA-Z]*\s*", "", t)
t = re.sub(r"\s*```$", "", t).strip()
try:
return json.loads(t)
except json.JSONDecodeError:
start = t.find("{")
if start < 0:
raise
candidates = [t, re.sub(r",\s*([}\]])", r"\1", t)]
for src in candidates:
try:
return json.loads(src)
except json.JSONDecodeError:
pass
start = t.find("{")
if start >= 0:
depth = 0
for i, ch in enumerate(t[start:], start):
if ch == "{":
@@ -41,8 +94,22 @@ def parse_json_response(text: str) -> dict:
elif ch == "}":
depth -= 1
if depth == 0:
return json.loads(t[start:i + 1])
raise
try:
return json.loads(t[start:i + 1])
except json.JSONDecodeError:
break
# обрыв посреди ответа: спасаем полные элементы списка
salvaged = []
for obj in _complete_objects(t):
cleaned = re.sub(r",\s*([}\]])", r"\1", obj)
try:
json.loads(cleaned)
salvaged.append(cleaned)
except json.JSONDecodeError:
continue
if salvaged:
return json.loads('{"items": [' + ",".join(salvaged) + "]}")
raise json.JSONDecodeError("не удалось разобрать ответ модели", t, len(t))
def chat_json(prompt: str, *, num_predict: int = 700, temperature: float = 0.2,