feat: нормативный RAG — поиск по TG постам и PDF в контексте GLM
При каждом вопросе в чат — semantic search в normative_index.faiss (260 vectors: 146 TG постов + 114 PDF чанков). Top-3 результата добавляются в user message как контекст. Источники: приказы/письма Минстроя, ГОСТы, путеводители НПА. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -62,6 +62,50 @@ def _build_system_prompt() -> str:
|
||||
Если вопрос про конкретную расценку ГЭСН — скажи что проверишь по базе."""
|
||||
|
||||
|
||||
# --- Normative RAG (TG posts + PDF from smeta-monitor) ---
|
||||
_norm_index = None
|
||||
_norm_metadata = None
|
||||
_NORM_INDEX_PATH = Path(__file__).parent.parent / "smeta-monitor" / "data" / "normative_index.faiss"
|
||||
_NORM_META_PATH = Path(__file__).parent.parent / "smeta-monitor" / "data" / "normative_metadata.json"
|
||||
|
||||
|
||||
def _search_normative(query: str, top_k: int = 3) -> str:
|
||||
"""Semantic search in normative TG posts + PDF index."""
|
||||
global _norm_index, _norm_metadata
|
||||
if _norm_index is None:
|
||||
if not _NORM_INDEX_PATH.exists():
|
||||
return ""
|
||||
try:
|
||||
import faiss
|
||||
_norm_index = faiss.read_index(str(_NORM_INDEX_PATH))
|
||||
import json as _json
|
||||
_norm_metadata = _json.load(open(_NORM_META_PATH, encoding="utf-8"))
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
try:
|
||||
import sys
|
||||
smeta_src = Path(__file__).parent.parent / "smeta-railway" / "src"
|
||||
if str(smeta_src) not in sys.path:
|
||||
sys.path.insert(0, str(smeta_src))
|
||||
from smeta_railway.ai.embeddings import embed_query
|
||||
emb = embed_query(query)
|
||||
D, I = _norm_index.search(emb, top_k)
|
||||
|
||||
results = []
|
||||
for dist, idx in zip(D[0], I[0]):
|
||||
if dist < 0.5: # skip low relevance
|
||||
continue
|
||||
m = _norm_metadata[idx]
|
||||
results.append(f"[{m['source']}] {m['full_text'][:500]}")
|
||||
|
||||
if not results:
|
||||
return ""
|
||||
return "Актуальная нормативная информация:\n" + "\n---\n".join(results)
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _search_resources(query: str, top_k: int = 5) -> str:
|
||||
"""Simple text search in resources.json."""
|
||||
_load_smeta_data()
|
||||
@@ -210,12 +254,17 @@ async def stream_claude(
|
||||
# Read files from work directory if they exist
|
||||
file_context = _read_work_dir_files(work_dir)
|
||||
|
||||
# Search normative RAG (TG posts + PDF)
|
||||
normative_context = _search_normative(message)
|
||||
|
||||
# Build user message with context
|
||||
user_content = message
|
||||
if file_context:
|
||||
user_content = f"{message}\n\n[Файлы в рабочей директории]{file_context}"
|
||||
if resource_context:
|
||||
user_content += f"\n\n[Данные из базы ФСНБ-2022]\n{resource_context}"
|
||||
if normative_context:
|
||||
user_content += f"\n\n[{normative_context}]"
|
||||
|
||||
history.append({"role": "user", "content": user_content})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user