run.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 requirement import requirement_search, requirement_list # noqa: F401
  37. # 导入项目配置
  38. from config import RUN_CONFIG, SKILLS_DIR, TRACE_STORE_PATH, DEBUG, LOG_LEVEL, LOG_FILE, BROWSER_TYPE, HEADLESS, INPUT_DIR, OUTPUT_DIR
  39. async def main():
  40. # 解析命令行参数
  41. parser = argparse.ArgumentParser(description="任务 (Agent 模式 + 交互增强)")
  42. parser.add_argument(
  43. "--trace", type=str, default=None,
  44. help="已有的 Trace ID,用于恢复继续执行(不指定则新建)",
  45. )
  46. args = parser.parse_args()
  47. # 路径配置
  48. base_dir = Path(__file__).parent
  49. project_root = base_dir.parent.parent
  50. prompt_path = base_dir / "requirement.prompt"
  51. output_dir = project_root / OUTPUT_DIR
  52. output_dir.mkdir(parents=True, exist_ok=True)
  53. # 1. 配置日志
  54. setup_logging(level=LOG_LEVEL, file=LOG_FILE)
  55. # 2. 加载 prompt
  56. print("2. 加载 prompt...")
  57. prompt = SimplePrompt(prompt_path)
  58. # 3. 构建任务消息
  59. print("3. 构建任务消息...")
  60. print(f" - 输入目录: {INPUT_DIR}")
  61. print(f" - 输出目录: {OUTPUT_DIR}")
  62. messages = prompt.build_messages(input_dir=INPUT_DIR, output_dir=OUTPUT_DIR)
  63. # 4. 初始化浏览器
  64. import platform
  65. actual_browser_type = BROWSER_TYPE
  66. if platform.system() == "Windows" and BROWSER_TYPE == "local":
  67. actual_browser_type = "cloud"
  68. print("⚠️ Windows 平台检测到本地浏览器配置,自动切换为云浏览器模式")
  69. browser_mode_names = {"cloud": "云浏览器", "local": "本地浏览器", "container": "容器浏览器"}
  70. browser_mode_name = browser_mode_names.get(actual_browser_type, actual_browser_type)
  71. print(f"4. 正在初始化{browser_mode_name}...")
  72. await init_browser_session(
  73. browser_type=actual_browser_type,
  74. headless=HEADLESS,
  75. url="https://www.google.com/",
  76. profile_name=""
  77. )
  78. print(f" ✅ {browser_mode_name}初始化完成\n")
  79. # 5. 创建 Agent Runner
  80. print("5. 创建 Agent Runner...")
  81. print(f" - Skills 目录: {SKILLS_DIR}")
  82. # 从 prompt 的 frontmatter 中提取模型配置(优先于 config.py)
  83. prompt_model = prompt.config.get("model", None)
  84. if prompt_model:
  85. model_for_llm = prompt_model
  86. print(f" - 模型 (from prompt): {model_for_llm}")
  87. else:
  88. model_for_llm = RUN_CONFIG.model
  89. print(f" - 模型 (from config): {model_for_llm}")
  90. store = FileSystemTraceStore(base_path=TRACE_STORE_PATH)
  91. runner = AgentRunner(
  92. trace_store=store,
  93. llm_call=create_qwen_llm_call(model=model_for_llm),
  94. skills_dir=SKILLS_DIR,
  95. debug=DEBUG
  96. )
  97. # 6. 创建交互控制器
  98. interactive = InteractiveController(
  99. runner=runner,
  100. store=store,
  101. enable_stdin_check=True
  102. )
  103. # 将 stdin 检查回调注入 runner,供子 agent 执行期间使用
  104. runner.stdin_check = interactive.check_stdin
  105. # 7. 任务信息
  106. task_name = RUN_CONFIG.name or base_dir.name
  107. print("=" * 60)
  108. print(f"{task_name}")
  109. print("=" * 60)
  110. print("💡 交互提示:")
  111. print(" - 执行过程中输入 'p' 或 'pause' 暂停并进入交互模式")
  112. print(" - 执行过程中输入 'q' 或 'quit' 停止执行")
  113. print("=" * 60)
  114. print()
  115. # 8. 判断是新建还是恢复
  116. resume_trace_id = args.trace
  117. if resume_trace_id:
  118. existing_trace = await store.get_trace(resume_trace_id)
  119. if not existing_trace:
  120. print(f"\n错误: Trace 不存在: {resume_trace_id}")
  121. sys.exit(1)
  122. print(f"恢复已有 Trace: {resume_trace_id[:8]}...")
  123. print(f" - 状态: {existing_trace.status}")
  124. print(f" - 消息数: {existing_trace.total_messages}")
  125. print(f"\n💡 提示:恢复 Trace 时会先进入交互菜单,您可以选择从指定消息续跑")
  126. else:
  127. print(f"启动新 Agent...")
  128. print()
  129. final_response = ""
  130. current_trace_id = resume_trace_id
  131. current_sequence = 0
  132. should_exit = False
  133. try:
  134. # 配置
  135. run_config = RUN_CONFIG
  136. if resume_trace_id:
  137. initial_messages = None
  138. run_config.trace_id = resume_trace_id
  139. else:
  140. initial_messages = messages
  141. run_config.name = f"{task_name}:调研任务"
  142. while not should_exit:
  143. if current_trace_id:
  144. run_config.trace_id = current_trace_id
  145. final_response = ""
  146. # 如果是恢复 trace 或 trace 已完成/失败且没有新消息,进入交互菜单
  147. if current_trace_id and initial_messages is None:
  148. check_trace = await store.get_trace(current_trace_id)
  149. if check_trace:
  150. # 显示 trace 状态
  151. if check_trace.status == "completed":
  152. print(f"\n[Trace] ✅ 已完成")
  153. print(f" - Total messages: {check_trace.total_messages}")
  154. print(f" - Total cost: ${check_trace.total_cost:.4f}")
  155. elif check_trace.status == "failed":
  156. print(f"\n[Trace] ❌ 已失败: {check_trace.error_message}")
  157. elif check_trace.status == "stopped":
  158. print(f"\n[Trace] ⏸️ 已停止")
  159. print(f" - Total messages: {check_trace.total_messages}")
  160. else:
  161. print(f"\n[Trace] 📊 状态: {check_trace.status}")
  162. print(f" - Total messages: {check_trace.total_messages}")
  163. current_sequence = check_trace.head_sequence
  164. menu_result = await interactive.show_menu(current_trace_id, current_sequence)
  165. if menu_result["action"] == "stop":
  166. break
  167. elif menu_result["action"] == "continue":
  168. new_messages = menu_result.get("messages", [])
  169. if new_messages:
  170. initial_messages = new_messages
  171. run_config.after_sequence = menu_result.get("after_sequence")
  172. else:
  173. initial_messages = []
  174. run_config.after_sequence = None
  175. continue
  176. break
  177. # 如果没有进入菜单(新建 trace),设置初始消息
  178. if initial_messages is None:
  179. initial_messages = []
  180. print(f"{'▶️ 开始执行...' if not current_trace_id else '▶️ 继续执行...'}")
  181. # 执行 Agent
  182. paused = False
  183. try:
  184. async for item in runner.run(messages=initial_messages, config=run_config):
  185. # 检查用户中断
  186. cmd = interactive.check_stdin()
  187. if cmd == 'pause':
  188. print("\n⏸️ 正在暂停执行...")
  189. if current_trace_id:
  190. await runner.stop(current_trace_id)
  191. await asyncio.sleep(0.5)
  192. menu_result = await interactive.show_menu(current_trace_id, current_sequence)
  193. if menu_result["action"] == "stop":
  194. should_exit = True
  195. paused = True
  196. break
  197. elif menu_result["action"] == "continue":
  198. new_messages = menu_result.get("messages", [])
  199. if new_messages:
  200. initial_messages = new_messages
  201. after_seq = menu_result.get("after_sequence")
  202. if after_seq is not None:
  203. run_config.after_sequence = after_seq
  204. paused = True
  205. break
  206. else:
  207. initial_messages = []
  208. run_config.after_sequence = None
  209. paused = True
  210. break
  211. elif cmd == 'quit':
  212. print("\n🛑 用户请求停止...")
  213. if current_trace_id:
  214. await runner.stop(current_trace_id)
  215. should_exit = True
  216. break
  217. # 处理 Trace 对象
  218. if isinstance(item, Trace):
  219. current_trace_id = item.trace_id
  220. if item.status == "running":
  221. print(f"[Trace] 开始: {item.trace_id[:8]}...")
  222. elif item.status == "completed":
  223. print(f"\n[Trace] ✅ 完成")
  224. print(f" - Total messages: {item.total_messages}")
  225. print(f" - Total cost: ${item.total_cost:.4f}")
  226. elif item.status == "failed":
  227. print(f"\n[Trace] ❌ 失败: {item.error_message}")
  228. elif item.status == "stopped":
  229. print(f"\n[Trace] ⏸️ 已停止")
  230. # 处理 Message 对象
  231. elif isinstance(item, Message):
  232. current_sequence = item.sequence
  233. if item.role == "assistant":
  234. content = item.content
  235. if isinstance(content, dict):
  236. text = content.get("text", "")
  237. tool_calls = content.get("tool_calls")
  238. if text and not tool_calls:
  239. final_response = text
  240. print(f"\n[Response] Agent 回复:")
  241. print(text)
  242. elif text:
  243. preview = text[:150] + "..." if len(text) > 150 else text
  244. print(f"[Assistant] {preview}")
  245. elif item.role == "tool":
  246. content = item.content
  247. tool_name = "unknown"
  248. if isinstance(content, dict):
  249. tool_name = content.get("tool_name", "unknown")
  250. if item.description and item.description != tool_name:
  251. desc = item.description[:80] if len(item.description) > 80 else item.description
  252. print(f"[Tool Result] ✅ {tool_name}: {desc}...")
  253. else:
  254. print(f"[Tool Result] ✅ {tool_name}")
  255. except Exception as e:
  256. print(f"\n执行出错: {e}")
  257. import traceback
  258. traceback.print_exc()
  259. if paused:
  260. if should_exit:
  261. break
  262. continue
  263. if should_exit:
  264. break
  265. # Runner 退出后显示交互菜单
  266. if current_trace_id:
  267. menu_result = await interactive.show_menu(current_trace_id, current_sequence)
  268. if menu_result["action"] == "stop":
  269. break
  270. elif menu_result["action"] == "continue":
  271. new_messages = menu_result.get("messages", [])
  272. if new_messages:
  273. initial_messages = new_messages
  274. run_config.after_sequence = menu_result.get("after_sequence")
  275. else:
  276. initial_messages = []
  277. run_config.after_sequence = None
  278. continue
  279. break
  280. except KeyboardInterrupt:
  281. print("\n\n用户中断 (Ctrl+C)")
  282. if current_trace_id:
  283. await runner.stop(current_trace_id)
  284. finally:
  285. # 清理浏览器会话
  286. try:
  287. await kill_browser_session()
  288. except Exception:
  289. pass
  290. # 7. 输出结果
  291. if final_response:
  292. print()
  293. print("=" * 60)
  294. print("Agent 响应:")
  295. print("=" * 60)
  296. print(final_response)
  297. print("=" * 60)
  298. print()
  299. output_file = output_dir / "result.txt"
  300. with open(output_file, 'w', encoding='utf-8') as f:
  301. f.write(final_response)
  302. print(f"✓ 结果已保存到: {output_file}")
  303. print()
  304. # 可视化提示
  305. if current_trace_id:
  306. print("=" * 60)
  307. print("可视化 Step Tree:")
  308. print("=" * 60)
  309. print("1. 启动 API Server:")
  310. print(" python3 api_server.py")
  311. print()
  312. print("2. 浏览器访问:")
  313. print(" http://localhost:8000/api/traces")
  314. print()
  315. print(f"3. Trace ID: {current_trace_id}")
  316. print("=" * 60)
  317. if __name__ == "__main__":
  318. asyncio.run(main())