Files
more_dots/services/template_matcher.py
T

56 lines
1.9 KiB
Python
Raw Normal View History

2026-02-26 18:06:17 +08:00
from typing import Any, Dict
2026-02-26 13:43:44 +08:00
from config import Config
from services.ragflow_client import RagflowClient, extract_table_name
class TemplateMatcher:
2026-02-26 18:06:17 +08:00
"""模板匹配器:RAGFlow 检索"""
2026-02-26 13:43:44 +08:00
def __init__(self):
self._ragflow = RagflowClient()
cfg = Config.get_section("ragflow")
2026-02-26 18:06:17 +08:00
self._dataset_id = (cfg.get("table_retrieval_dataset_id") or "").strip()
2026-03-02 15:35:02 +08:00
self._top_k = int(cfg.get("retrieval_top_k", 3))
2026-02-26 13:43:44 +08:00
2026-02-26 18:06:17 +08:00
def _validate(self) -> None:
if not self._dataset_id:
raise RuntimeError("未配置 ragflow.table_retrieval_dataset_id,无法进行表名检索")
2026-02-26 13:43:44 +08:00
def match(self, normalized_text: str) -> Dict[str, Any]:
"""返回匹配的表名与原始响应"""
2026-02-26 18:06:17 +08:00
self._validate()
2026-02-26 13:43:44 +08:00
try:
2026-03-02 15:35:02 +08:00
response = self._ragflow.retrieve(normalized_text, top_k=self._top_k, dataset_id=self._dataset_id)
2026-02-26 13:43:44 +08:00
except Exception as e:
2026-02-26 18:06:17 +08:00
return {"table_name": None, "raw": {"error": str(e)}}
2026-02-26 13:43:44 +08:00
candidates = []
data = response.get("data") if isinstance(response, dict) else None
2026-03-02 15:35:02 +08:00
records = []
2026-02-26 13:43:44 +08:00
if isinstance(data, list):
2026-03-02 15:35:02 +08:00
records = data
elif isinstance(data, dict):
chunks = data.get("chunks")
if isinstance(chunks, list):
records = chunks
for item in records:
table_name = extract_table_name(item)
if table_name:
candidates.append(table_name)
2026-02-26 13:43:44 +08:00
matched = candidates[0] if candidates else None
2026-02-26 18:06:17 +08:00
return {"table_name": matched, "raw": response}
_GLOBAL_TEMPLATE_MATCHER: TemplateMatcher | None = None
2026-02-26 13:43:44 +08:00
2026-02-26 18:06:17 +08:00
def get_template_matcher() -> TemplateMatcher:
"""获取全局 TemplateMatcher(单例)"""
global _GLOBAL_TEMPLATE_MATCHER
if _GLOBAL_TEMPLATE_MATCHER is None:
_GLOBAL_TEMPLATE_MATCHER = TemplateMatcher()
return _GLOBAL_TEMPLATE_MATCHER