|
|
@@ -252,29 +252,33 @@ class FunctionKnowledge:
|
|
|
detail_info["fallback"] = "exception"
|
|
|
return default_params, detail_info
|
|
|
|
|
|
-
|
|
|
- def generate_and_save_new_tool(self, knowledge: str):
|
|
|
- """异步生成并保存新工具"""
|
|
|
+ def save_knowledge_to_file(self, knowledge: str, combined_question: str):
|
|
|
+ """保存获取到的知识到文件"""
|
|
|
try:
|
|
|
- logger.info("开始生成新工具...")
|
|
|
- prompt_template = self._load_prompt("function_knowledge_generate_new_tool_prompt.md")
|
|
|
- prompt = prompt_template.format(knowledge=knowledge)
|
|
|
-
|
|
|
- tool_code = generate_text(prompt=prompt)
|
|
|
-
|
|
|
- # 简单解析工具名(假设工具名在 def xxx( 中)
|
|
|
- # 这里做一个简单的提取,实际可能需要更复杂的解析
|
|
|
- import re
|
|
|
- match = re.search(r"def\s+([a-zA-Z_][a-zA-Z0-9_]*)", tool_code)
|
|
|
- if match:
|
|
|
- tool_name = match.group(1)
|
|
|
- save_path = save_tool_info(tool_name, tool_code)
|
|
|
- logger.info(f"新工具已保存: {save_path}")
|
|
|
+ logger.info("[保存知识] 开始保存知识到文件...")
|
|
|
+
|
|
|
+ # 获取问题hash
|
|
|
+ import hashlib
|
|
|
+ question_hash = hashlib.md5(combined_question.encode('utf-8')).hexdigest()[:12]
|
|
|
+
|
|
|
+ # 获取缓存目录(和execution_record.json同级)
|
|
|
+ if self.use_cache and self.cache:
|
|
|
+ cache_dir = os.path.join(self.cache.base_cache_dir, question_hash)
|
|
|
else:
|
|
|
- logger.warning("无法从生成的代码中提取工具名")
|
|
|
-
|
|
|
+ cache_dir = os.path.join(os.path.dirname(__file__), '.cache', question_hash)
|
|
|
+
|
|
|
+ os.makedirs(cache_dir, exist_ok=True)
|
|
|
+
|
|
|
+ # 保存到knowledge.txt
|
|
|
+ knowledge_file = os.path.join(cache_dir, 'knowledge.txt')
|
|
|
+ with open(knowledge_file, 'w', encoding='utf-8') as f:
|
|
|
+ f.write(knowledge)
|
|
|
+
|
|
|
+ logger.info(f"✓ 知识已保存到: {knowledge_file}")
|
|
|
+ logger.info(f" 知识长度: {len(knowledge)} 字符")
|
|
|
+
|
|
|
except Exception as e:
|
|
|
- logger.error(f"生成新工具失败: {e}")
|
|
|
+ logger.error(f"✗ 保存知识失败: {e}")
|
|
|
|
|
|
def get_knowledge(self, question: str, post_info: str, persona_info: str) -> dict:
|
|
|
"""
|
|
|
@@ -439,7 +443,7 @@ class FunctionKnowledge:
|
|
|
logger.info("[步骤4] 未找到合适工具,调用 MultiSearch...")
|
|
|
|
|
|
step4_start = time.time()
|
|
|
- knowledge = get_multi_search_knowledge(query)
|
|
|
+ knowledge = get_multi_search_knowledge(query, cache_key=combined_question)
|
|
|
|
|
|
execution_record["execution"]["steps"].append({
|
|
|
"step": 4,
|
|
|
@@ -461,8 +465,7 @@ class FunctionKnowledge:
|
|
|
|
|
|
# 异步生成新工具
|
|
|
logger.info("[后台任务] 启动新工具生成线程...")
|
|
|
- threading.Thread(target=self.generate_and_save_new_tool, args=(knowledge,)).start()
|
|
|
-
|
|
|
+ threading.Thread(target=self.save_knowledge_to_file, args=(knowledge, combined_question)).start()
|
|
|
# 计算总执行时间
|
|
|
execution_record["metadata"]["execution_time"] = time.time() - start_time
|
|
|
|