feat(sources): primary-source discovery via searxng and local llm

This commit is contained in:
kpa39l
2026-11-01 18:03:20 +00:00
parent fba0e395b6
commit 13a6d0647e
25 changed files with 1339 additions and 4 deletions
+65
View File
@@ -0,0 +1,65 @@
# Локальная модель (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 parse_json_response(text: str) -> dict:
"""Достаёт JSON из ответа модели.
Qwen3 может примешивать блок рассуждений в текст ответа даже с think=false
(зависит от сборки модели): срезаем всё до закрывающего тега, убираем ```-обёртки,
и если json.loads всё равно падает — берём первый сбалансированный {...}.
"""
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()
try:
return json.loads(t)
except json.JSONDecodeError:
start = t.find("{")
if start < 0:
raise
depth = 0
for i, ch in enumerate(t[start:], start):
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return json.loads(t[start:i + 1])
raise
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)