fix(sources): batch llm ranking and salvage truncated json
This commit is contained in:
+37
-6
@@ -22,6 +22,9 @@ SCORE_MIN = 0.6
|
||||
UNRANKED_MAX = 5
|
||||
# Сколько кандидатов максимум показываем (остальное — шум)
|
||||
TOP_N = 6
|
||||
# Ранжирование батчами: 12 результатов в одном ответе модели не влезают в лимит токенов
|
||||
RANK_BATCH = 6
|
||||
RANK_NUM_PREDICT = 1400
|
||||
# Агрегаторы и перепечатки: не бывают первоисточником, даже если модель поставила оценку
|
||||
AGGREGATOR_DOMAINS = {
|
||||
"dzen.ru", "zen.yandex.ru", "turbopages.org", "news.rambler.ru", "smi2.ru",
|
||||
@@ -57,8 +60,9 @@ RANK_PROMPT = """Ты помогаешь найти ПЕРВОИСТОЧНИК
|
||||
{results}
|
||||
|
||||
Ответ строго в JSON:
|
||||
{{"items": [{{"url": "...", "kind": "telegram|rss|site|media", "score": 0.0, "reason": "коротко по-русски"}}]}}
|
||||
{{"items": [{{"url": "...", "kind": "telegram|rss|site|media", "score": 0.0, "reason": "до 6 слов"}}]}}
|
||||
Оцени КАЖДЫЙ результат из списка. Одинаковые оценки у всех — признак небрежного разбора, различай их.
|
||||
'url' копируй из списка дословно. 'reason' — не больше 6 слов по-русски.
|
||||
"""
|
||||
|
||||
|
||||
@@ -129,14 +133,16 @@ def _store_queries(conn, post_id: int, queries: list[str]) -> None:
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _llm_rank(text: str, results: list[dict]) -> dict[str, dict]:
|
||||
if not results:
|
||||
return {}
|
||||
def _rank_batch(text: str, batch: list[dict]) -> dict[str, dict]:
|
||||
"""Один запрос к модели на группу результатов (не больше RANK_BATCH)."""
|
||||
lines = [
|
||||
f"{i}. {r['title'][:120]} | {r['domain']} | {r['url']} | {r['snippet'][:80]}"
|
||||
for i, r in enumerate(results[:MAX_RANK_RESULTS], 1)
|
||||
for i, r in enumerate(batch, 1)
|
||||
]
|
||||
data = chat_json(RANK_PROMPT.format(text=text[:1200], results="\n".join(lines)), num_predict=900)
|
||||
data = chat_json(
|
||||
RANK_PROMPT.format(text=text[:1200], results="\n".join(lines)),
|
||||
num_predict=RANK_NUM_PREDICT,
|
||||
)
|
||||
ranked: dict[str, dict] = {}
|
||||
for item in data.get("items") or []:
|
||||
url = str(item.get("url") or "").strip()
|
||||
@@ -154,6 +160,31 @@ def _llm_rank(text: str, results: list[dict]) -> dict[str, dict]:
|
||||
return ranked
|
||||
|
||||
|
||||
def _llm_rank(text: str, results: list[dict]) -> dict[str, dict]:
|
||||
"""Ранжирует выдачу батчами: один длинный запрос упирается в num_predict и обрывается."""
|
||||
ranked: dict[str, dict] = {}
|
||||
first_error: Exception | None = None
|
||||
items = results[:MAX_RANK_RESULTS]
|
||||
for start in range(0, len(items), RANK_BATCH):
|
||||
batch = items[start:start + RANK_BATCH]
|
||||
try:
|
||||
ranked.update(_rank_batch(text, batch))
|
||||
continue
|
||||
except Exception as exc: # обрезанный/битый ответ — пробуем половинками
|
||||
first_error = first_error or exc
|
||||
half = max(1, len(batch) // 2)
|
||||
for sub in (batch[:half], batch[half:]):
|
||||
if not sub:
|
||||
continue
|
||||
try:
|
||||
ranked.update(_rank_batch(text, sub))
|
||||
except Exception as exc:
|
||||
first_error = first_error or exc
|
||||
if not ranked and first_error is not None:
|
||||
raise first_error
|
||||
return ranked
|
||||
|
||||
|
||||
def find_sources(conn, post: dict) -> dict:
|
||||
"""Ищет первоисточники поста. Возвращает {added, from_text, queries, errors}."""
|
||||
post_id = int(post["id"])
|
||||
|
||||
@@ -181,6 +181,48 @@
|
||||
priority: P1
|
||||
enabled: true
|
||||
own: false
|
||||
- slug: newsroom
|
||||
name: AMD Reports Third Quarter 2026 Financial Results - AMD Newsroom
|
||||
url: https://newsroom.amd.com/rss.xml
|
||||
channel: null
|
||||
crawler: rss
|
||||
feed_url: https://newsroom.amd.com/rss.xml
|
||||
base_url: null
|
||||
hashtag: null
|
||||
lookup_acct: null
|
||||
direction: null
|
||||
lang: ru
|
||||
priority: P1
|
||||
enabled: true
|
||||
own: false
|
||||
- slug: techpowerup
|
||||
name: AMD Guidance Points to Its First Quarter Ever With More Revenue...
|
||||
url: https://www.techpowerup.com/rss/news
|
||||
channel: null
|
||||
crawler: rss
|
||||
feed_url: https://www.techpowerup.com/rss/news
|
||||
base_url: null
|
||||
hashtag: null
|
||||
lookup_acct: null
|
||||
direction: null
|
||||
lang: ru
|
||||
priority: P1
|
||||
enabled: true
|
||||
own: false
|
||||
- slug: tomshardware
|
||||
name: AMD expects to outsell Intel in Q4 for the first time in... | Tom's Hardware
|
||||
url: https://www.tomshardware.com/feeds.xml
|
||||
channel: null
|
||||
crawler: rss
|
||||
feed_url: https://www.tomshardware.com/feeds.xml
|
||||
base_url: null
|
||||
hashtag: null
|
||||
lookup_acct: null
|
||||
direction: null
|
||||
lang: ru
|
||||
priority: P1
|
||||
enabled: true
|
||||
own: false
|
||||
- slug: fosstodon-selfhosting
|
||||
name: Fosstodon
|
||||
url: https://fosstodon.org/tags/selfhosting
|
||||
|
||||
Reference in New Issue
Block a user