run.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. """
  2. 示例(简化版 - 使用框架交互功能)
  3. 使用 Agent 模式 + Skills + 框架交互控制器
  4. 新功能:
  5. 1. 使用框架提供的 InteractiveController
  6. 2. 使用配置文件管理运行参数
  7. 3. 支持命令行随时打断(输入 'p' 暂停,'q' 退出)
  8. 4. 暂停后可插入干预消息
  9. 5. 支持触发经验总结
  10. 6. 查看当前 GoalTree
  11. 7. 支持通过 --trace <ID> 恢复已有 Trace 继续执行
  12. """
  13. import argparse
  14. import os
  15. import sys
  16. import asyncio
  17. from pathlib import Path
  18. # Clash Verge TUN 模式兼容:禁止 httpx/urllib 自动检测系统 HTTP 代理
  19. os.environ.setdefault("no_proxy", "*")
  20. # 添加项目根目录到 Python 路径
  21. sys.path.insert(0, str(Path(__file__).parent.parent.parent))
  22. from dotenv import load_dotenv
  23. load_dotenv()
  24. from agent.llm.prompts import SimplePrompt
  25. from agent.core.runner import AgentRunner, RunConfig
  26. from agent.trace import (
  27. FileSystemTraceStore,
  28. Trace,
  29. Message,
  30. )
  31. from agent.llm import create_qwen_llm_call
  32. from agent.cli import InteractiveController
  33. from agent.utils import setup_logging
  34. from agent.tools.builtin.browser.baseClass import init_browser_session, kill_browser_session
  35. # 导入自定义工具(触发 @tool 注册)
  36. # from .tools.reflect import reflect
  37. # 导入项目配置
  38. from config import RUN_CONFIG, SKILLS_DIR, TRACE_STORE_PATH, DEBUG, LOG_LEVEL, LOG_FILE, BROWSER_TYPE, HEADLESS, OUTPUT_DIR
  39. from config import IM_ENABLED, IM_CONTACT_ID, IM_SERVER_URL, IM_WINDOW_MODE, IM_NOTIFY_INTERVAL
  40. from config import KNOWLEDGE_MANAGER_ENABLED, KNOWLEDGE_MANAGER_CONTACT_ID, KNOWLEDGE_MANAGER_ENABLE_DB_COMMIT
  41. async def main():
  42. # 解析命令行参数
  43. parser = argparse.ArgumentParser(description="任务 (Agent 模式 + 交互增强)")
  44. parser.add_argument(
  45. "--trace", type=str, default=None,
  46. help="已有的 Trace ID,用于恢复继续执行(不指定则新建)",
  47. )
  48. args = parser.parse_args()
  49. # 路径配置
  50. base_dir = Path(__file__).parent
  51. project_root = base_dir.parent.parent
  52. prompt_path = base_dir / "tool_research.prompt"
  53. output_dir = project_root / OUTPUT_DIR
  54. output_dir.mkdir(parents=True, exist_ok=True)
  55. # 1. 配置日志
  56. setup_logging(level=LOG_LEVEL, file=LOG_FILE)
  57. # 2. 加载项目级 presets
  58. print("2. 加载 presets...")
  59. presets_path = base_dir / "presets.json"
  60. if presets_path.exists():
  61. from agent.core.presets import load_presets_from_json
  62. load_presets_from_json(str(presets_path))
  63. print(f" - 已加载项目 presets")
  64. else:
  65. print(f" - 未找到 presets.json,跳过")
  66. # 3. 加载 prompt
  67. print("3. 加载 prompt...")
  68. prompt = SimplePrompt(prompt_path)
  69. # 4. 构建任务消息
  70. print("4. 构建任务消息...")
  71. print(f" - 输出目录: {output_dir}")
  72. messages = prompt.build_messages(output_dir=str(output_dir))
  73. # 5. 初始化浏览器
  74. browser_mode_names = {"cloud": "云浏览器", "local": "本地浏览器", "container": "容器浏览器"}
  75. browser_mode_name = browser_mode_names.get(BROWSER_TYPE, BROWSER_TYPE)
  76. print(f"5. 正在初始化{browser_mode_name}...")
  77. await init_browser_session(
  78. browser_type=BROWSER_TYPE,
  79. headless=HEADLESS,
  80. url="https://www.google.com/",
  81. profile_name=""
  82. )
  83. print(f" ✅ {browser_mode_name}初始化完成\n")
  84. # 5.5 初始化 IM Client(可选)
  85. km_task = None
  86. if IM_ENABLED:
  87. from agent.tools.builtin.im.chat import im_setup, im_open_window
  88. print("5.5 初始化 IM Client...")
  89. print(f" - 身份: {IM_CONTACT_ID}, 服务器: {IM_SERVER_URL}")
  90. result = await im_setup(
  91. contact_id=IM_CONTACT_ID,
  92. server_url=IM_SERVER_URL,
  93. notify_interval=IM_NOTIFY_INTERVAL,
  94. )
  95. print(f" ✅ {result.output}")
  96. # 如果启用窗口模式,打开一个窗口
  97. if IM_WINDOW_MODE:
  98. window_result = await im_open_window(contact_id=IM_CONTACT_ID)
  99. print(f" ✅ {window_result.output}\n")
  100. else:
  101. print()
  102. # 启动 Knowledge Manager(如果启用)
  103. if KNOWLEDGE_MANAGER_ENABLED:
  104. print("5.6 启动 Knowledge Manager...")
  105. print(f" - Contact ID: {KNOWLEDGE_MANAGER_CONTACT_ID}")
  106. try:
  107. sys.path.insert(0, str(Path(__file__).parent.parent.parent / "knowhub"))
  108. from agents.knowledge_manager import start_knowledge_manager
  109. km_task = asyncio.create_task(start_knowledge_manager(
  110. contact_id=KNOWLEDGE_MANAGER_CONTACT_ID,
  111. server_url=IM_SERVER_URL,
  112. chat_id="main",
  113. enable_db_commit=KNOWLEDGE_MANAGER_ENABLE_DB_COMMIT
  114. ))
  115. print(f" ✅ Knowledge Manager 已启动(后台运行)\n")
  116. except Exception as e:
  117. print(f" ⚠️ 启动失败: {e}\n")
  118. # 6. 创建 Agent Runner
  119. print("6. 创建 Agent Runner...")
  120. print(f" - Skills 目录: {SKILLS_DIR}")
  121. # 从 prompt 的 frontmatter 中提取模型配置(优先于 config.py)
  122. prompt_model = prompt.config.get("model", None)
  123. if prompt_model:
  124. model_for_llm = prompt_model
  125. print(f" - 模型 (from prompt): {model_for_llm}")
  126. else:
  127. model_for_llm = RUN_CONFIG.model
  128. print(f" - 模型 (from config): {model_for_llm}")
  129. store = FileSystemTraceStore(base_path=TRACE_STORE_PATH)
  130. runner = AgentRunner(
  131. trace_store=store,
  132. llm_call=create_qwen_llm_call(model=model_for_llm),
  133. skills_dir=SKILLS_DIR,
  134. debug=DEBUG
  135. )
  136. # 7. 创建交互控制器
  137. interactive = InteractiveController(
  138. runner=runner,
  139. store=store,
  140. enable_stdin_check=True
  141. )
  142. # 将 stdin 检查回调注入 runner,供子 agent 执行期间使用
  143. runner.stdin_check = interactive.check_stdin
  144. # 8. 任务信息
  145. task_name = RUN_CONFIG.name or base_dir.name
  146. print("=" * 60)
  147. print(f"{task_name}")
  148. print("=" * 60)
  149. print("💡 交互提示:")
  150. print(" - 执行过程中输入 'p' 或 'pause' 暂停并进入交互模式")
  151. print(" - 执行过程中输入 'q' 或 'quit' 停止执行")
  152. print("=" * 60)
  153. print()
  154. # 9. 判断是新建还是恢复
  155. resume_trace_id = args.trace
  156. if resume_trace_id:
  157. existing_trace = await store.get_trace(resume_trace_id)
  158. if not existing_trace:
  159. print(f"\n错误: Trace 不存在: {resume_trace_id}")
  160. sys.exit(1)
  161. print(f"恢复已有 Trace: {resume_trace_id[:8]}...")
  162. print(f" - 状态: {existing_trace.status}")
  163. print(f" - 消息数: {existing_trace.total_messages}")
  164. print(f"\n💡 提示:恢复 Trace 时会先进入交互菜单,您可以选择从指定消息续跑")
  165. else:
  166. print(f"启动新 Agent...")
  167. print()
  168. final_response = ""
  169. current_trace_id = resume_trace_id
  170. current_sequence = 0
  171. should_exit = False
  172. try:
  173. # 配置
  174. run_config = RUN_CONFIG
  175. if resume_trace_id:
  176. initial_messages = None
  177. run_config.trace_id = resume_trace_id
  178. else:
  179. initial_messages = messages
  180. run_config.name = f"{task_name}:工具调研"
  181. while not should_exit:
  182. if current_trace_id:
  183. run_config.trace_id = current_trace_id
  184. final_response = ""
  185. # 如果是恢复 trace 或 trace 已完成/失败且没有新消息,进入交互菜单
  186. if current_trace_id and initial_messages is None:
  187. check_trace = await store.get_trace(current_trace_id)
  188. if check_trace:
  189. # 显示 trace 状态
  190. if check_trace.status == "completed":
  191. print(f"\n[Trace] ✅ 已完成")
  192. print(f" - Total messages: {check_trace.total_messages}")
  193. print(f" - Total cost: ${check_trace.total_cost:.4f}")
  194. elif check_trace.status == "failed":
  195. print(f"\n[Trace] ❌ 已失败: {check_trace.error_message}")
  196. elif check_trace.status == "stopped":
  197. print(f"\n[Trace] ⏸️ 已停止")
  198. print(f" - Total messages: {check_trace.total_messages}")
  199. else:
  200. print(f"\n[Trace] 📊 状态: {check_trace.status}")
  201. print(f" - Total messages: {check_trace.total_messages}")
  202. current_sequence = check_trace.head_sequence
  203. menu_result = await interactive.show_menu(current_trace_id, current_sequence)
  204. if menu_result["action"] == "stop":
  205. break
  206. elif menu_result["action"] == "continue":
  207. new_messages = menu_result.get("messages", [])
  208. if new_messages:
  209. initial_messages = new_messages
  210. run_config.after_sequence = menu_result.get("after_sequence")
  211. else:
  212. initial_messages = []
  213. run_config.after_sequence = None
  214. continue
  215. break
  216. # 如果没有进入菜单(新建 trace),设置初始消息
  217. if initial_messages is None:
  218. initial_messages = []
  219. print(f"{'▶️ 开始执行...' if not current_trace_id else '▶️ 继续执行...'}")
  220. # 执行 Agent
  221. paused = False
  222. try:
  223. async for item in runner.run(messages=initial_messages, config=run_config):
  224. # 检查用户中断
  225. cmd = interactive.check_stdin()
  226. if cmd == 'pause':
  227. print("\n⏸️ 正在暂停执行...")
  228. if current_trace_id:
  229. await runner.stop(current_trace_id)
  230. await asyncio.sleep(0.5)
  231. menu_result = await interactive.show_menu(current_trace_id, current_sequence)
  232. if menu_result["action"] == "stop":
  233. should_exit = True
  234. paused = True
  235. break
  236. elif menu_result["action"] == "continue":
  237. new_messages = menu_result.get("messages", [])
  238. if new_messages:
  239. initial_messages = new_messages
  240. after_seq = menu_result.get("after_sequence")
  241. if after_seq is not None:
  242. run_config.after_sequence = after_seq
  243. paused = True
  244. break
  245. else:
  246. initial_messages = []
  247. run_config.after_sequence = None
  248. paused = True
  249. break
  250. elif cmd == 'quit':
  251. print("\n🛑 用户请求停止...")
  252. if current_trace_id:
  253. await runner.stop(current_trace_id)
  254. should_exit = True
  255. break
  256. # 处理 Trace 对象
  257. if isinstance(item, Trace):
  258. current_trace_id = item.trace_id
  259. if item.status == "running":
  260. print(f"[Trace] 开始: {item.trace_id[:8]}...")
  261. elif item.status == "completed":
  262. print(f"\n[Trace] ✅ 完成")
  263. print(f" - Total messages: {item.total_messages}")
  264. print(f" - Total cost: ${item.total_cost:.4f}")
  265. elif item.status == "failed":
  266. print(f"\n[Trace] ❌ 失败: {item.error_message}")
  267. elif item.status == "stopped":
  268. print(f"\n[Trace] ⏸️ 已停止")
  269. # 处理 Message 对象
  270. elif isinstance(item, Message):
  271. current_sequence = item.sequence
  272. if item.role == "assistant":
  273. content = item.content
  274. if isinstance(content, dict):
  275. text = content.get("text", "")
  276. tool_calls = content.get("tool_calls")
  277. if text and not tool_calls:
  278. final_response = text
  279. print(f"\n[Response] Agent 回复:")
  280. print(text)
  281. elif text:
  282. preview = text[:150] + "..." if len(text) > 150 else text
  283. print(f"[Assistant] {preview}")
  284. elif item.role == "tool":
  285. content = item.content
  286. tool_name = "unknown"
  287. if isinstance(content, dict):
  288. tool_name = content.get("tool_name", "unknown")
  289. if item.description and item.description != tool_name:
  290. desc = item.description[:80] if len(item.description) > 80 else item.description
  291. print(f"[Tool Result] ✅ {tool_name}: {desc}...")
  292. else:
  293. print(f"[Tool Result] ✅ {tool_name}")
  294. except Exception as e:
  295. print(f"\n执行出错: {e}")
  296. import traceback
  297. traceback.print_exc()
  298. if paused:
  299. if should_exit:
  300. break
  301. continue
  302. if should_exit:
  303. break
  304. # Runner 退出后显示交互菜单
  305. if current_trace_id:
  306. menu_result = await interactive.show_menu(current_trace_id, current_sequence)
  307. if menu_result["action"] == "stop":
  308. break
  309. elif menu_result["action"] == "continue":
  310. new_messages = menu_result.get("messages", [])
  311. if new_messages:
  312. initial_messages = new_messages
  313. run_config.after_sequence = menu_result.get("after_sequence")
  314. else:
  315. initial_messages = []
  316. run_config.after_sequence = None
  317. continue
  318. break
  319. except KeyboardInterrupt:
  320. print("\n\n用户中断 (Ctrl+C)")
  321. if current_trace_id:
  322. await runner.stop(current_trace_id)
  323. finally:
  324. # 清理 Knowledge Manager
  325. if km_task and not km_task.done():
  326. print("正在关闭 Knowledge Manager...")
  327. km_task.cancel()
  328. try:
  329. await km_task
  330. except asyncio.CancelledError:
  331. pass
  332. # 清理浏览器会话
  333. try:
  334. await kill_browser_session()
  335. except Exception:
  336. pass
  337. # 7. 输出结果
  338. if final_response:
  339. print()
  340. print("=" * 60)
  341. print("Agent 响应:")
  342. print("=" * 60)
  343. print(final_response)
  344. print("=" * 60)
  345. print()
  346. output_file = output_dir / "result.txt"
  347. with open(output_file, 'w', encoding='utf-8') as f:
  348. f.write(final_response)
  349. print(f"✓ 结果已保存到: {output_file}")
  350. print()
  351. # 可视化提示
  352. if current_trace_id:
  353. print("=" * 60)
  354. print("可视化 Step Tree:")
  355. print("=" * 60)
  356. print("1. 启动 API Server:")
  357. print(" python3 api_server.py")
  358. print()
  359. print("2. 浏览器访问:")
  360. print(" http://localhost:8000/api/traces")
  361. print()
  362. print(f"3. Trace ID: {current_trace_id}")
  363. print("=" * 60)
  364. if __name__ == "__main__":
  365. asyncio.run(main())