129 lines
4.7 KiB
Python
Executable File
129 lines
4.7 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Поиск по документации (RAG) с ответом локальной модели.
|
|
|
|
Использование:
|
|
rag_query.py "почему падал chronyd" # ответ + источники
|
|
rag_query.py --search "chronyd" # только фрагменты
|
|
rag_query.py --answer-only "вопрос" # только ответ
|
|
"""
|
|
import argparse
|
|
import json
|
|
import math
|
|
import os
|
|
import sqlite3
|
|
import struct
|
|
import sys
|
|
import urllib.request
|
|
|
|
LLM = "http://192.168.1.229:11434"
|
|
EMB_MODEL = "nomic-embed-text"
|
|
CHAT_MODEL = "qwen2.5:7b"
|
|
DB = "/root/buryan-infra/ops/rag/index.db"
|
|
|
|
|
|
def embed(text):
|
|
body = json.dumps({"model": EMB_MODEL, "prompt": text[:4000]}).encode()
|
|
req = urllib.request.Request(LLM + "/api/embeddings", data=body, method="POST")
|
|
req.add_header("Content-Type", "application/json")
|
|
with urllib.request.urlopen(req, timeout=120) as r:
|
|
return json.loads(r.read().decode()).get("embedding") or []
|
|
|
|
|
|
def cosine(a, b):
|
|
if not a or not b or len(a) != len(b):
|
|
return 0.0
|
|
dot = sum(x * y for x, y in zip(a, b))
|
|
na = math.sqrt(sum(x * x for x in a))
|
|
nb = math.sqrt(sum(y * y for y in b))
|
|
return dot / (na * nb) if na and nb else 0.0
|
|
|
|
|
|
def load_chunks():
|
|
con = sqlite3.connect(DB)
|
|
rows = con.execute("SELECT path, idx, text, vec FROM chunks").fetchall()
|
|
con.close()
|
|
out = []
|
|
for path, idx, text, blob in rows:
|
|
n = len(blob) // 4
|
|
out.append((path, idx, text, list(struct.unpack("%df" % n, blob))))
|
|
return out
|
|
|
|
|
|
def search(query, k=5):
|
|
"""Гибридный поиск. Если LLM-узел недоступен — работает по ключевым словам."""
|
|
import re
|
|
words = [w.lower() for w in re.findall(r"[\w\-]{4,}", query)]
|
|
qv = embed(query)
|
|
DEGRADED = not qv
|
|
scored = []
|
|
for path, idx, text, vec in load_chunks():
|
|
low = (text + " " + path).lower()
|
|
hits = sum(1 for w in words if w in low)
|
|
kw = hits / len(words) if words else 0.0
|
|
if DEGRADED:
|
|
score = kw # только ключевые слова, без векторов
|
|
else:
|
|
score = 0.7 * cosine(qv, vec) + 0.3 * kw
|
|
if score <= 0:
|
|
continue
|
|
scored.append((score, path, idx, text))
|
|
scored.sort(key=lambda x: -x[0])
|
|
if DEGRADED:
|
|
print("! LLM-узел недоступен: поиск только по ключевым словам", file=sys.stderr)
|
|
return scored[:k]
|
|
|
|
|
|
def ask(question, contexts, max_tokens=500):
|
|
ctx = "\n\n".join("--- %s (фрагмент %s) ---\n%s" % (p, i, t)
|
|
for _, p, i, t in contexts)
|
|
prompt = (
|
|
"Ты помощник по инфраструктуре Buryans Hub. Отвечай по-русски, кратко и по делу.\n"
|
|
"Используй ТОЛЬКО приведённые фрагменты документации. Если ответа в них нет — "
|
|
"так и скажи: «в документации этого нет».\n\n"
|
|
"ФРАГМЕНТЫ:\n%s\n\nВОПРОС: %s\n\nОТВЕТ:" % (ctx, question)
|
|
)
|
|
body = json.dumps({"model": CHAT_MODEL, "prompt": prompt, "stream": False,
|
|
"options": {"num_predict": max_tokens, "temperature": 0.1}}).encode()
|
|
req = urllib.request.Request(LLM + "/api/generate", data=body, method="POST")
|
|
req.add_header("Content-Type", "application/json")
|
|
with urllib.request.urlopen(req, timeout=600) as r:
|
|
return json.loads(r.read().decode()).get("response", "").strip()
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("query")
|
|
ap.add_argument("--k", type=int, default=5)
|
|
ap.add_argument("--search", action="store_true", help="только фрагменты")
|
|
ap.add_argument("--answer-only", action="store_true", dest="answer_only")
|
|
a = ap.parse_args()
|
|
|
|
if not os.path.exists(DB):
|
|
print("индекс не собран: запустите rag_index.py", file=sys.stderr)
|
|
return 2
|
|
|
|
hits = search(a.query, a.k)
|
|
if not hits:
|
|
print("ничего не найдено (узел LLM недоступен?)", file=sys.stderr)
|
|
return 1
|
|
|
|
if a.search:
|
|
for score, path, idx, text in hits:
|
|
print("\n=== %.3f %s [%d]" % (score, path, idx))
|
|
print(text[:400].strip())
|
|
return 0
|
|
|
|
answer = ask(a.query, hits)
|
|
if not a.answer_only:
|
|
print(answer)
|
|
print("\nИсточники:")
|
|
for score, path, idx, _ in hits:
|
|
print(" %.3f %s [%d]" % (score, path, idx))
|
|
else:
|
|
print(answer)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|