Files
vesti/web/llm.py
T

133 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Локальная модель (Ollama): запросы к qwen3 с JSON-ответом.
#
# Зачем отдельный модуль: `classifier/classify.py:call_ollama` ходит в OpenAI-совместимый
# /v1/chat/completions, который (замерено 2026-11-01) тратит 8.5 с и 303 токена на простую
# задачу, потому что рассуждения идут отдельным полем `reasoning`. Нативный /api/chat
# с think=false + format="json" даёт тот же ответ за 1.7 с и 61 токен.
import json
import re
import httpx
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)
if m:
t = t[m.end():].strip()
if t.startswith("```"):
t = re.sub(r"^```[a-zA-Z]*\s*", "", t)
t = re.sub(r"\s*```$", "", t).strip()
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 == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
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,
timeout: float = 120.0) -> dict:
"""Запрос к локальной модели с гарантией JSON-ответа (нативный API Ollama)."""
response = httpx.post(
f"{OLLAMA_URL}/api/chat",
timeout=timeout,
json={
"model": OLLAMA_MODEL,
"messages": [{"role": "user", "content": prompt}],
"stream": False,
"think": False,
"format": "json",
"options": {"temperature": temperature, "num_predict": num_predict},
},
)
response.raise_for_status()
content = ((response.json().get("message") or {}).get("content") or "")
return parse_json_response(content)