feat: Structured RAG — фильтрация по категории вопроса
Чанки типизированы: index_letter, nr_sp, winter_temp, nds_tax, expertise, gost_sp, method, gesn_norm, prikaz, general. _detect_categories() определяет тип вопроса по regex. FAISS search ищет top_k*5, потом фильтрует по категории. Высокий score (>0.85) проходит без фильтра. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
+40
-4
@@ -69,8 +69,36 @@ _NORM_INDEX_PATH = Path(__file__).parent.parent / "smeta-monitor" / "data" / "no
|
||||
_NORM_META_PATH = Path(__file__).parent.parent / "smeta-monitor" / "data" / "normative_metadata.json"
|
||||
|
||||
|
||||
import re as _re
|
||||
|
||||
# Category detection for filtered RAG search
|
||||
_CATEGORY_PATTERNS = {
|
||||
"index_letter": [r"(?i)(индекс|пересч[её]т|текущ\w+\s+цен|базисн)"],
|
||||
"nr_sp": [r"(?i)(накладн\w+\s+расход|\bНР\b|сметн\w+\s+прибыл|\bСП\b.{0,10}процент|приказ.{0,10}(812|774))"],
|
||||
"winter_temp": [r"(?i)(зимн|времен\w+\s+здан|приказ.{0,10}(325|332)|температурн)"],
|
||||
"nds_tax": [r"(?i)(\bНДС\b|налог|УСН|упрощ[её]н)"],
|
||||
"expertise": [r"(?i)(экспертиз|ГГЭ|главгосэкспертиз|формат.{0,5}GGE)"],
|
||||
"gost_sp": [r"(?i)(ГОСТ|СНиП|\bСП\s+\d)"],
|
||||
"gesn_norm": [r"(?i)(расценк|ГЭСН|\d{2}-\d{2}-\d{3})"],
|
||||
"method": [r"(?i)(методик|МДС|порядок\s+определен|правил\w+\s+определен)"],
|
||||
}
|
||||
|
||||
|
||||
def _detect_categories(query: str) -> list[str]:
|
||||
"""Detect which RAG categories are relevant for the query."""
|
||||
cats = []
|
||||
for cat, patterns in _CATEGORY_PATTERNS.items():
|
||||
for p in patterns:
|
||||
if _re.search(p, query):
|
||||
cats.append(cat)
|
||||
break
|
||||
if not cats:
|
||||
cats = ["prikaz", "general"] # default: search in general normative
|
||||
return cats
|
||||
|
||||
|
||||
def _search_normative(query: str, top_k: int = 3) -> str:
|
||||
"""Semantic search in normative TG posts + PDF index."""
|
||||
"""Category-filtered semantic search in normative index."""
|
||||
global _norm_index, _norm_metadata
|
||||
if _norm_index is None:
|
||||
if not _NORM_INDEX_PATH.exists():
|
||||
@@ -90,14 +118,22 @@ def _search_normative(query: str, top_k: int = 3) -> str:
|
||||
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)
|
||||
|
||||
# Search more candidates, then filter by category
|
||||
cats = _detect_categories(query)
|
||||
D, I = _norm_index.search(emb, top_k * 5)
|
||||
|
||||
results = []
|
||||
for dist, idx in zip(D[0], I[0]):
|
||||
if dist < 0.815: # e5-base scores cluster 0.79-0.89; 0.815 after 3443 vectors
|
||||
if dist < 0.81:
|
||||
continue
|
||||
m = _norm_metadata[idx]
|
||||
results.append(f"[{m['source']}] {m['full_text'][:500]}")
|
||||
chunk_cat = m.get("category", "general")
|
||||
# Accept if category matches OR score is very high (>0.85)
|
||||
if chunk_cat in cats or dist > 0.85:
|
||||
results.append(f"[{m['source']}] {m['full_text'][:500]}")
|
||||
if len(results) >= top_k:
|
||||
break
|
||||
|
||||
if not results:
|
||||
return ""
|
||||
|
||||
Reference in New Issue
Block a user