entities_enhance.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import json
  2. import asyncio
  3. from foundation.observability.monitoring.time_statistics import track_execution_time
  4. from foundation.ai.rag.retrieval.retrieval import retrieval_manager
  5. from foundation.observability.logger.loggering import server_logger
  6. class EntitiesEnhance():
  7. def __init__(self):
  8. self.save_path = "temp\entity_bfp_recall\entity_bfp_recall.json"
  9. self.bfp_result_lists = []
  10. @track_execution_time
  11. def entities_enhance_retrieval(self,query_pairs):
  12. def run_async(coro):
  13. """在合适的环境中运行异步函数"""
  14. try:
  15. loop = asyncio.get_running_loop()
  16. import concurrent.futures
  17. with concurrent.futures.ThreadPoolExecutor() as executor:
  18. future = executor.submit(asyncio.run, coro)
  19. return future.result()
  20. except RuntimeError:
  21. return asyncio.run(coro)
  22. for query_pair in query_pairs:
  23. entity = query_pair['entity']
  24. search_keywords = query_pair['search_keywords']
  25. background = query_pair['background']
  26. entity_list = run_async(retrieval_manager.entity_recall(
  27. entity,
  28. search_keywords,
  29. recall_top_k=5, # 主实体返回数量
  30. max_results=5 # 最终最多返回20个实体文本
  31. ))
  32. # top_k,二次重排最多返回数量
  33. bfp_result = run_async(retrieval_manager.async_bfp_recall(entity_list,background,top_k=3))
  34. server_logger.info(f"bfp_result:{bfp_result}")
  35. self.bfp_result_lists.append(bfp_result)
  36. server_logger.info("实体增强召回结束")
  37. #self.test_file(self.bfp_result_lists,seve=True)
  38. return self.bfp_result_lists
  39. def test_file(self,bfp_result,seve = False):
  40. if seve:
  41. with open(self.save_path, "w", encoding="utf-8") as f:
  42. json.dump(bfp_result, f, ensure_ascii=False, indent=4)
  43. entity_enhance = EntitiesEnhance()