function_knowledge.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. '''
  2. 方法知识获取模块
  3. 1. 输入:问题 + 帖子信息 + 账号人设信息
  4. 2. 将输入的问题转化成query,调用大模型,prompt在 function_knowledge_generate_query_prompt.md 中
  5. 3. 从已有方法工具库中尝试选择合适的方法工具(调用大模型执行,prompt在 function_knowledge_select_tools_prompt.md 中),如果有,则返回选择的方法工具,否则:
  6. - 调用 multi_search_knowledge.py 获取知识
  7. - 返回新的方法工具知识
  8. - 异步从新方法知识中获取新工具(调用大模型执行,prompt在 function_knowledge_generate_new_tool_prompt.md 中),调用工具库系统,接入新的工具
  9. 4. 调用选择的方法工具执行验证,返回工具执行结果
  10. '''
  11. import os
  12. import sys
  13. import json
  14. import threading
  15. from loguru import logger
  16. # 设置路径以便导入工具类
  17. current_dir = os.path.dirname(os.path.abspath(__file__))
  18. root_dir = os.path.dirname(current_dir)
  19. sys.path.insert(0, root_dir)
  20. from utils.gemini_client import generate_text
  21. from knowledge_v2.tools_library import call_tool, save_tool_info, get_all_tool_infos, get_tool_info, get_tool_params
  22. from knowledge_v2.multi_search_knowledge import get_knowledge as get_multi_search_knowledge
  23. from knowledge_v2.cache_manager import CacheManager
  24. class FunctionKnowledge:
  25. """方法知识获取类"""
  26. def __init__(self, use_cache: bool = True):
  27. """
  28. 初始化
  29. Args:
  30. use_cache: 是否启用缓存,默认启用
  31. """
  32. logger.info("=" * 80)
  33. logger.info("初始化 FunctionKnowledge - 方法知识获取入口")
  34. self.prompt_dir = os.path.join(current_dir, "prompt")
  35. self.use_cache = use_cache
  36. self.cache = CacheManager() if use_cache else None
  37. # 执行详情收集
  38. self.execution_detail = {
  39. "generate_query": {},
  40. "select_tool": {},
  41. "extract_params": {},
  42. "execution_time": 0,
  43. "cache_hits": []
  44. }
  45. logger.info(f"缓存状态: {'启用' if use_cache else '禁用'}")
  46. logger.info("=" * 80)
  47. def _save_execution_detail(self, cache_key: str):
  48. """保存执行详情到缓存"""
  49. if not self.use_cache or not self.cache:
  50. return
  51. try:
  52. import hashlib
  53. question_hash = hashlib.md5(cache_key.encode('utf-8')).hexdigest()[:12]
  54. detail_dir = os.path.join(
  55. self.cache.base_cache_dir,
  56. question_hash,
  57. 'function_knowledge'
  58. )
  59. os.makedirs(detail_dir, exist_ok=True)
  60. detail_file = os.path.join(detail_dir, 'execution_detail.json')
  61. with open(detail_file, 'w', encoding='utf-8') as f:
  62. json.dump(self.execution_detail, f, ensure_ascii=False, indent=2)
  63. logger.info(f"✓ 执行详情已保存: {detail_file}")
  64. except Exception as e:
  65. logger.error(f"✗ 保存执行详情失败: {e}")
  66. def _load_prompt(self, filename: str) -> str:
  67. """加载prompt文件内容"""
  68. prompt_path = os.path.join(self.prompt_dir, filename)
  69. if not os.path.exists(prompt_path):
  70. raise FileNotFoundError(f"Prompt文件不存在: {prompt_path}")
  71. with open(prompt_path, 'r', encoding='utf-8') as f:
  72. return f.read().strip()
  73. def generate_query(self, question: str, post_info: str, persona_info: str) -> str:
  74. """
  75. 生成查询语句
  76. Returns:
  77. str: 生成的查询语句
  78. """
  79. logger.info(f"[步骤1] 生成Query...")
  80. # 组合问题的唯一标识
  81. combined_question = f"{question}||{post_info}||{persona_info}"
  82. # 尝试从缓存读取
  83. if self.use_cache:
  84. cached_query = self.cache.get(combined_question, 'function_knowledge', 'generated_query.txt')
  85. if cached_query:
  86. logger.info(f"✓ 使用缓存的Query: {cached_query}")
  87. # 记录缓存命中
  88. self.execution_detail["generate_query"].update({"cached": True, "query": cached_query})
  89. return cached_query
  90. try:
  91. prompt_template = self._load_prompt("function_generate_query_prompt.md")
  92. prompt = prompt_template.format(
  93. question=question,
  94. post_info=post_info,
  95. persona_info=persona_info
  96. )
  97. logger.info("→ 调用Gemini生成Query...")
  98. query = generate_text(prompt=prompt)
  99. query = query.strip()
  100. logger.info(f"✓ 生成Query: {query}")
  101. # 写入缓存
  102. if self.use_cache:
  103. self.cache.set(combined_question, 'function_knowledge', 'generated_query.txt', query)
  104. # 记录详情
  105. self.execution_detail["generate_query"] = {
  106. "cached": False,
  107. "prompt": prompt,
  108. "response": query,
  109. "query": query
  110. }
  111. return query
  112. except Exception as e:
  113. logger.error(f"✗ 生成Query失败: {e}")
  114. return question # 降级使用原问题
  115. def select_tool(self, combined_question: str, query: str) -> str:
  116. """
  117. 选择合适的工具
  118. Returns:
  119. str: 工具名称,如果没有合适的工具则返回"None"
  120. """
  121. logger.info(f"[步骤2] 选择工具...")
  122. try:
  123. all_tool_infos = get_all_tool_infos()
  124. if not all_tool_infos:
  125. logger.info(" 工具库为空,无可用工具")
  126. return "None"
  127. tool_count = len(all_tool_infos.split('--- Tool:')) - 1
  128. logger.info(f" 当前可用工具数: {tool_count}")
  129. prompt_template = self._load_prompt("function_knowledge_select_tools_prompt.md")
  130. prompt = prompt_template.format(
  131. query=query,
  132. tool_infos=all_tool_infos
  133. )
  134. # 尝试从缓存读取
  135. if self.use_cache:
  136. cached_tool = self.cache.get(combined_question, 'function_knowledge', 'selected_tool.txt')
  137. if cached_tool:
  138. logger.info(f"✓ 使用缓存的工具: {cached_tool}")
  139. # 记录缓存命中
  140. self.execution_detail["select_tool"].update({
  141. "cached": True,
  142. "response": json.loads(cached_tool),
  143. "prompt": prompt,
  144. })
  145. return json.loads(cached_tool)
  146. logger.info("→ 调用Gemini选择工具...")
  147. result = generate_text(prompt=prompt)
  148. result_json = result.loads(result)
  149. logger.info(f"✓ 选择结果: {result_json.get('工具名', 'None')}")
  150. # 写入缓存
  151. if self.use_cache:
  152. self.cache.set(combined_question, 'function_knowledge', 'selected_tool.txt', result)
  153. # 记录详情
  154. self.execution_detail["select_tool"] = {
  155. "cached": False,
  156. "prompt": prompt,
  157. "response": result_json,
  158. "available_tools_count": tool_count
  159. }
  160. return result_json
  161. except Exception as e:
  162. logger.error(f"✗ 选择工具失败: {e}")
  163. return "None"
  164. def extract_tool_params(self, combined_question: str, query: str, tool_id: str, tool_instructions: str) -> dict:
  165. """
  166. 根据工具信息和查询提取调用参数
  167. Args:
  168. combined_question: 组合问题(用于缓存)
  169. tool_name: 工具名称
  170. query: 查询内容
  171. Returns:
  172. dict: 提取的参数字典
  173. """
  174. logger.info(f"[步骤3] 提取工具参数...")
  175. # 尝试从缓存读取
  176. if self.use_cache:
  177. cached_params = self.cache.get(combined_question, 'function_knowledge', 'tool_params.json')
  178. if cached_params:
  179. logger.info(f"✓ 使用缓存的参数: {cached_params}")
  180. # 记录缓存命中
  181. self.execution_detail["extract_params"].update({
  182. "cached": True,
  183. "params": cached_params
  184. })
  185. return cached_params
  186. try:
  187. # 获取工具信息
  188. tool_params = get_tool_params(tool_id)
  189. if not tool_params:
  190. logger.warning(f" ⚠ 未找到工具 {tool_id} 的信息,使用默认参数")
  191. return {"keyword": query}
  192. # 加载prompt
  193. prompt_template = self._load_prompt("function_knowledge_extract_tool_params_prompt.md")
  194. prompt = prompt_template.format(
  195. query=query,
  196. # tool_info=tool_info
  197. )
  198. # 调用LLM提取参数
  199. logger.info(" → 调用Gemini提取参数...")
  200. response_text = generate_text(prompt=prompt)
  201. # 解析JSON
  202. logger.info(" → 解析参数JSON...")
  203. try:
  204. # 清理可能的markdown标记
  205. response_text = response_text.strip()
  206. if response_text.startswith("```json"):
  207. response_text = response_text[7:]
  208. if response_text.startswith("```"):
  209. response_text = response_text[3:]
  210. if response_text.endswith("```"):
  211. response_text = response_text[:-3]
  212. response_text = response_text.strip()
  213. params = json.loads(response_text)
  214. logger.info(f"✓ 提取参数成功: {params}")
  215. # 写入缓存
  216. if self.use_cache:
  217. self.cache.set(combined_question, 'function_knowledge', 'tool_params.json', params)
  218. # 记录详情
  219. self.execution_detail["extract_params"].update({
  220. "cached": False,
  221. "prompt": prompt,
  222. "response": response_text,
  223. "params": params
  224. })
  225. return params
  226. except json.JSONDecodeError as e:
  227. logger.error(f" ✗ 解析JSON失败: {e}")
  228. logger.error(f" 响应内容: {response_text}")
  229. # 降级:使用query作为keyword
  230. default_params = {"keyword": query}
  231. logger.warning(f" 使用默认参数: {default_params}")
  232. return default_params
  233. except Exception as e:
  234. logger.error(f"✗ 提取工具参数失败: {e}")
  235. # 降级:使用query作为keyword
  236. return {"keyword": query}
  237. def save_knowledge_to_file(self, knowledge: str, combined_question: str):
  238. """保存获取到的知识到文件"""
  239. try:
  240. logger.info("[保存知识] 开始保存知识到文件...")
  241. # 获取问题hash
  242. import hashlib
  243. question_hash = hashlib.md5(combined_question.encode('utf-8')).hexdigest()[:12]
  244. # 获取缓存目录(和execution_record.json同级)
  245. if self.use_cache and self.cache:
  246. cache_dir = os.path.join(self.cache.base_cache_dir, question_hash)
  247. else:
  248. cache_dir = os.path.join(os.path.dirname(__file__), '.cache', question_hash)
  249. os.makedirs(cache_dir, exist_ok=True)
  250. # 保存到knowledge.txt
  251. knowledge_file = os.path.join(cache_dir, 'knowledge.txt')
  252. with open(knowledge_file, 'w', encoding='utf-8') as f:
  253. f.write(knowledge)
  254. logger.info(f"✓ 知识已保存到: {knowledge_file}")
  255. logger.info(f" 知识长度: {len(knowledge)} 字符")
  256. except Exception as e:
  257. logger.error(f"✗ 保存知识失败: {e}")
  258. def get_knowledge(self, question: str, post_info: str, persona_info: str) -> dict:
  259. """
  260. 获取方法知识的主流程(重构后)
  261. Returns:
  262. dict: 完整的执行记录
  263. """
  264. import time
  265. timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
  266. start_time = time.time()
  267. logger.info("=" * 80)
  268. logger.info(f"Function Knowledge - 开始处理")
  269. logger.info(f"问题: {question}")
  270. logger.info(f"帖子信息: {post_info}")
  271. logger.info(f"人设信息: {persona_info}")
  272. logger.info("=" * 80)
  273. # 组合问题的唯一标识
  274. combined_question = f"{question}||{post_info}||{persona_info}"
  275. try:
  276. # 步骤1: 生成Query
  277. query = self.generate_query(question, post_info, persona_info)
  278. # 步骤2: 选择工具
  279. tool_info = self.select_tool(combined_question, query)
  280. # tool_name = tool_info.get("工具名")
  281. tool_id = tool_info.get("工具调用ID")
  282. tool_instructions = tool_info.get("使用方法")
  283. if tool_id and tool_instructions:
  284. # 路径A: 使用工具
  285. # 步骤3: 提取参数
  286. arguments = self.extract_tool_params(combined_question, query, tool_id, tool_instructions)
  287. # 步骤4: 调用工具
  288. logger.info(f"[步骤4] 调用工具: {tool_id}")
  289. # 检查工具调用缓存
  290. if self.use_cache:
  291. cached_tool_result = self.cache.get(combined_question, 'function_knowledge', 'tool_result.json')
  292. if cached_tool_result:
  293. logger.info(f"✓ 使用缓存的工具调用结果")
  294. tool_result = cached_tool_result
  295. else:
  296. logger.info(f" → 调用工具,参数: {arguments}")
  297. tool_result = call_tool(tool_id, arguments)
  298. # 缓存工具调用结果
  299. self.cache.set(combined_question, 'function_knowledge', 'tool_result.json', tool_result)
  300. else:
  301. logger.info(f" → 调用工具,参数: {arguments}")
  302. tool_result = call_tool(tool_id, arguments)
  303. # 缓存工具调用结果
  304. self.cache.set(combined_question, 'function_knowledge', 'tool_result.json', tool_result)
  305. logger.info(f"✓ 工具调用完成")
  306. else:
  307. # 路径B: 知识搜索
  308. logger.info("[步骤4] 未找到合适工具,调用 MultiSearch...")
  309. knowledge = get_multi_search_knowledge(query, cache_key=combined_question)
  310. # 异步保存知识到文件
  311. logger.info("[后台任务] 保存知识到文件...")
  312. threading.Thread(target=self.save_knowledge_to_file, args=(knowledge, combined_question)).start()
  313. # 计算执行时间并保存详情
  314. self.execution_detail["execution_time"] = time.time() - start_time
  315. self._save_execution_detail(combined_question)
  316. # 收集所有执行记录
  317. logger.info("=" * 80)
  318. logger.info("收集执行记录...")
  319. logger.info("=" * 80)
  320. from knowledge_v2.execution_collector import collect_and_save_execution_record
  321. execution_record = collect_and_save_execution_record(
  322. combined_question,
  323. {
  324. "question": question,
  325. "post_info": post_info,
  326. "persona_info": persona_info,
  327. "timestamp": timestamp
  328. }
  329. )
  330. logger.info("=" * 80)
  331. logger.info(f"✓ Function Knowledge 完成")
  332. logger.info(f" 执行时间: {execution_record.get('metadata', {}).get('execution_time', 0):.2f}秒")
  333. logger.info("=" * 80 + "\n")
  334. return execution_record
  335. except Exception as e:
  336. logger.error(f"✗ 执行失败: {e}")
  337. import traceback
  338. logger.error(traceback.format_exc())
  339. # 即使失败也尝试保存详情和收集记录
  340. try:
  341. self.execution_detail["execution_time"] = time.time() - start_time
  342. self._save_execution_detail(combined_question)
  343. from knowledge_v2.execution_collector import collect_and_save_execution_record
  344. execution_record = collect_and_save_execution_record(
  345. combined_question,
  346. {
  347. "question": question,
  348. "post_info": post_info,
  349. "persona_info": persona_info,
  350. "timestamp": timestamp
  351. }
  352. )
  353. return execution_record
  354. except Exception as collect_error:
  355. logger.error(f"收集执行记录也失败: {collect_error}")
  356. # 返回基本错误信息
  357. return {
  358. "input": {
  359. "question": question,
  360. "post_info": post_info,
  361. "persona_info": persona_info,
  362. "timestamp": timestamp
  363. },
  364. "result": {
  365. "type": "error",
  366. "content": f"执行失败: {str(e)}"
  367. },
  368. "metadata": {
  369. "errors": [str(e)]
  370. }
  371. }
  372. if __name__ == "__main__":
  373. # 测试代码
  374. question = "教资查分这个信息怎么来的"
  375. post_info = "发帖时间:2025.11.07"
  376. persona_info = ""
  377. try:
  378. agent = FunctionKnowledge()
  379. execution_result = agent.get_knowledge(question, post_info, persona_info)
  380. print("=" * 50)
  381. print("执行结果:")
  382. print("=" * 50)
  383. print(json.dumps(execution_result, ensure_ascii=False, indent=2))
  384. print(f"\n完整JSON已保存到缓存目录")
  385. except Exception as e:
  386. logger.error(f"测试失败: {e}")