hybrid_search_tool.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """混合搜索工具:向量 + BM25 混合检索"""
  2. from __future__ import annotations
  3. from backend.tools.base import Tool
  4. async def hybrid_search(query: str, top_k: int = 5) -> dict:
  5. """混合检索向量库,返回相关段落。
  6. 复用 build_vector_index 模块的 HybridSearcher 单例,
  7. 保证索引写入与检索读取共享同一实例。
  8. Returns:
  9. {"query": query, "results": [{text, paper_path, title, section, score}]}
  10. """
  11. # 复用 build_vector_index 的单例,确保索引数据可被检索
  12. from backend.tools.build_vector_index import _get_searcher
  13. searcher = _get_searcher()
  14. results = await searcher.async_search(query, top_k=top_k)
  15. return {"query": query, "results": results}
  16. # ---------- Tool 定义 ----------
  17. _PARAMETERS = {
  18. "type": "object",
  19. "properties": {
  20. "query": {
  21. "type": "string",
  22. "description": "检索查询文本",
  23. },
  24. "top_k": {
  25. "type": "integer",
  26. "description": "返回结果数量,默认 5",
  27. "default": 5,
  28. },
  29. },
  30. "required": ["query"],
  31. }
  32. hybrid_search_tool = Tool(
  33. name="hybrid_search",
  34. description=(
  35. "混合搜索(向量相似度 + BM25 关键词)论文向量库,返回相关段落。"
  36. "用于回溯原文细节。返回 {query, results: [{text, paper_path, title, section, score}]}。"
  37. ),
  38. parameters=_PARAMETERS,
  39. func=hybrid_search,
  40. )