Files
more_dots/services/ragflow_client.py
T
2026-02-26 13:43:44 +08:00

60 lines
1.8 KiB
Python

import json
from typing import Any, Dict, Optional
import httpx
from config import Config
class RagflowClient:
"""RAGFlow 客户端(仅检索)"""
def __init__(self):
cfg = Config.get_section("ragflow")
self._base_url = cfg.get("url", "")
self._api_key = cfg.get("api_key", "")
self._retrieval_path = cfg.get("retrieval", "/api/v1/retrieval")
self._dataset_ids = cfg.get("dataset_ids", "")
def _build_url(self) -> str:
return self._base_url.rstrip("/") + "/" + self._retrieval_path.lstrip("/")
def retrieve(self, query: str, top_k: int = 3) -> Dict[str, Any]:
"""检索匹配文档"""
if not self._base_url or not self._retrieval_path:
raise RuntimeError("未配置 ragflow.url 或 ragflow.retrieval")
url = self._build_url()
headers = {"Authorization": f"Bearer {self._api_key}"} if self._api_key else {}
payload = {
"dataset_ids": self._dataset_ids,
"query": query,
"top_k": top_k,
}
with httpx.Client(timeout=30) as client:
response = client.post(url, json=payload, headers=headers)
response.raise_for_status()
return response.json()
def extract_table_name(record: Dict[str, Any]) -> Optional[str]:
"""从检索结果中提取表名"""
if not record:
return None
metadata = record.get("metadata") or {}
for key in ("table", "table_name"):
if key in metadata:
return metadata.get(key)
for key in ("table", "table_name"):
if key in record:
return record.get(key)
content = record.get("content") or record.get("text") or ""
for line in str(content).splitlines():
if line.lower().startswith("table:"):
return line.split(":", 1)[1].strip()
return None