run.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. """
  2. 示例(增强版)
  3. 使用 Agent 模式 + Skills
  4. 新增功能:
  5. 1. 支持命令行随时打断(输入 'p' 暂停,'q' 退出)
  6. 2. 暂停后可插入干预消息
  7. 3. 支持触发经验总结
  8. 4. 查看当前 GoalTree
  9. 5. 框架层自动清理不完整的工具调用
  10. 6. 支持通过 --trace <ID> 恢复已有 Trace 继续执行
  11. """
  12. import argparse
  13. import os
  14. import sys
  15. import select
  16. import asyncio
  17. from pathlib import Path
  18. # Clash Verge TUN 模式兼容:禁止 httpx/urllib 自动检测系统 HTTP 代理
  19. # TUN 虚拟网卡已在网络层接管所有流量,不需要应用层再走 HTTP 代理,
  20. # 否则 httpx 检测到 macOS 系统代理 (127.0.0.1:7897) 会导致 ConnectError
  21. os.environ.setdefault("no_proxy", "*")
  22. # 添加项目根目录到 Python 路径
  23. sys.path.insert(0, str(Path(__file__).parent.parent.parent))
  24. from dotenv import load_dotenv
  25. load_dotenv()
  26. from agent.llm.prompts import SimplePrompt
  27. from agent.core.runner import AgentRunner, RunConfig
  28. from agent.core.presets import AgentPreset, register_preset
  29. from agent.trace import (
  30. FileSystemTraceStore,
  31. Trace,
  32. Message,
  33. )
  34. from agent.llm import create_openrouter_llm_call
  35. # ===== 非阻塞 stdin 检测 =====
  36. def check_stdin() -> str | None:
  37. """
  38. 非阻塞检查 stdin 是否有输入。
  39. 使用 select 轮询,不开后台线程,因此不会与交互菜单的 input() 抢 stdin。
  40. """
  41. ready, _, _ = select.select([sys.stdin], [], [], 0)
  42. if ready:
  43. line = sys.stdin.readline().strip().lower()
  44. if line in ('p', 'pause'):
  45. return 'pause'
  46. if line in ('q', 'quit'):
  47. return 'quit'
  48. return None
  49. # ===== 交互菜单 =====
  50. def _read_multiline() -> str:
  51. """
  52. 读取多行输入,以连续两次回车(空行)结束。
  53. 单次回车只是换行,不会提前终止输入。
  54. """
  55. print("\n请输入干预消息(连续输入两次回车结束):")
  56. lines: list[str] = []
  57. blank_count = 0
  58. while True:
  59. line = input()
  60. if line == "":
  61. blank_count += 1
  62. if blank_count >= 2:
  63. break
  64. lines.append("") # 保留单个空行
  65. else:
  66. blank_count = 0
  67. lines.append(line)
  68. # 去掉尾部多余空行
  69. while lines and lines[-1] == "":
  70. lines.pop()
  71. return "\n".join(lines)
  72. async def show_interactive_menu(
  73. runner: AgentRunner,
  74. trace_id: str,
  75. current_sequence: int,
  76. store: FileSystemTraceStore,
  77. ):
  78. """
  79. 显示交互式菜单,让用户选择操作。
  80. 进入本函数前不再有后台线程占用 stdin,所以 input() 能正常工作。
  81. """
  82. print("\n" + "=" * 60)
  83. print(" 执行已暂停")
  84. print("=" * 60)
  85. print("请选择操作:")
  86. print(" 1. 插入干预消息并继续")
  87. print(" 2. 触发经验总结(reflect)")
  88. print(" 3. 查看当前 GoalTree")
  89. print(" 4. 继续执行")
  90. print(" 5. 停止执行")
  91. print("=" * 60)
  92. while True:
  93. choice = input("请输入选项 (1-5): ").strip()
  94. if choice == "1":
  95. text = _read_multiline()
  96. if not text:
  97. print("未输入任何内容,取消操作")
  98. continue
  99. print(f"\n将插入干预消息并继续执行...")
  100. # 从 store 读取实际的 last_sequence,避免本地 current_sequence 过时
  101. live_trace = await store.get_trace(trace_id)
  102. actual_sequence = live_trace.last_sequence if live_trace and live_trace.last_sequence else current_sequence
  103. return {
  104. "action": "continue",
  105. "messages": [{"role": "user", "content": text}],
  106. "after_sequence": actual_sequence,
  107. }
  108. elif choice == "2":
  109. # 触发经验总结
  110. print("\n触发经验总结...")
  111. focus = input("请输入反思重点(可选,直接回车跳过): ").strip()
  112. from agent.trace.compaction import build_reflect_prompt
  113. # 保存当前 head_sequence
  114. trace = await store.get_trace(trace_id)
  115. saved_head = trace.head_sequence
  116. prompt = build_reflect_prompt()
  117. if focus:
  118. prompt += f"\n\n请特别关注:{focus}"
  119. print("正在生成反思...")
  120. reflect_cfg = RunConfig(trace_id=trace_id, max_iterations=1, tools=[])
  121. reflection_text = ""
  122. try:
  123. result = await runner.run_result(
  124. messages=[{"role": "user", "content": prompt}],
  125. config=reflect_cfg,
  126. )
  127. reflection_text = result.get("summary", "")
  128. finally:
  129. # 恢复 head_sequence(反思消息成为侧枝)
  130. await store.update_trace(trace_id, head_sequence=saved_head)
  131. # 追加到 experiences 文件
  132. if reflection_text:
  133. from datetime import datetime
  134. experiences_path = runner.experiences_path or "./.cache/experiences.md"
  135. os.makedirs(os.path.dirname(experiences_path), exist_ok=True)
  136. header = f"\n\n---\n\n## {trace_id} ({datetime.now().strftime('%Y-%m-%d %H:%M')})\n\n"
  137. with open(experiences_path, "a", encoding="utf-8") as f:
  138. f.write(header + reflection_text + "\n")
  139. print(f"\n反思已保存到: {experiences_path}")
  140. print("\n--- 反思内容 ---")
  141. print(reflection_text)
  142. print("--- 结束 ---\n")
  143. else:
  144. print("未生成反思内容")
  145. continue
  146. elif choice == "3":
  147. goal_tree = await store.get_goal_tree(trace_id)
  148. if goal_tree and goal_tree.goals:
  149. print("\n当前 GoalTree:")
  150. print(goal_tree.to_prompt())
  151. else:
  152. print("\n当前没有 Goal")
  153. continue
  154. elif choice == "4":
  155. print("\n继续执行...")
  156. return {"action": "continue"}
  157. elif choice == "5":
  158. print("\n停止执行...")
  159. return {"action": "stop"}
  160. else:
  161. print("无效选项,请重新输入")
  162. async def main():
  163. # 解析命令行参数
  164. parser = argparse.ArgumentParser(description="任务 (Agent 模式 + 交互增强)")
  165. parser.add_argument(
  166. "--trace", type=str, default=None,
  167. help="已有的 Trace ID,用于恢复继续执行(不指定则新建)",
  168. )
  169. args = parser.parse_args()
  170. # 路径配置
  171. base_dir = Path(__file__).parent
  172. project_root = base_dir.parent.parent
  173. prompt_path = base_dir / "production.prompt"
  174. output_dir = base_dir / "output_1"
  175. output_dir.mkdir(exist_ok=True)
  176. # 加载项目级 presets(examples/how/presets.json)
  177. presets_path = base_dir / "presets.json"
  178. if presets_path.exists():
  179. import json
  180. with open(presets_path, "r", encoding="utf-8") as f:
  181. project_presets = json.load(f)
  182. for name, cfg in project_presets.items():
  183. register_preset(name, AgentPreset(**cfg))
  184. print(f" - 已加载项目 presets: {list(project_presets.keys())}")
  185. # Skills 目录(可选:用户自定义 skills)
  186. # 注意:内置 skills(agent/memory/skills/)会自动加载
  187. skills_dir = str(base_dir / "skills")
  188. print("=" * 60)
  189. print("mcp/skills 发现、获取、评价 分析任务 (Agent 模式 + 交互增强)")
  190. print("=" * 60)
  191. print()
  192. print("💡 交互提示:")
  193. print(" - 执行过程中输入 'p' 或 'pause' 暂停并进入交互模式")
  194. print(" - 执行过程中输入 'q' 或 'quit' 停止执行")
  195. print("=" * 60)
  196. print()
  197. # 1. 加载 prompt
  198. print("1. 加载 prompt 配置...")
  199. prompt = SimplePrompt(prompt_path)
  200. # 2. 构建消息(仅新建时使用,恢复时消息已在 trace 中)
  201. print("2. 构建任务消息...")
  202. messages = prompt.build_messages()
  203. # 3. 创建 Agent Runner(配置 skills)
  204. print("3. 创建 Agent Runner...")
  205. print(f" - Skills 目录: {skills_dir}")
  206. print(f" - 模型: {prompt.config.get('model', 'sonnet-4.5')}")
  207. store = FileSystemTraceStore(base_path=".trace")
  208. runner = AgentRunner(
  209. trace_store=store,
  210. llm_call=create_openrouter_llm_call(model=f"anthropic/claude-{prompt.config.get('model', 'sonnet-4.5')}"),
  211. skills_dir=skills_dir,
  212. debug=True
  213. )
  214. # 4. 判断是新建还是恢复
  215. resume_trace_id = args.trace
  216. if resume_trace_id:
  217. # 验证 trace 存在
  218. existing_trace = await store.get_trace(resume_trace_id)
  219. if not existing_trace:
  220. print(f"\n错误: Trace 不存在: {resume_trace_id}")
  221. sys.exit(1)
  222. print(f"4. 恢复已有 Trace: {resume_trace_id[:8]}...")
  223. print(f" - 状态: {existing_trace.status}")
  224. print(f" - 消息数: {existing_trace.total_messages}")
  225. print(f" - 任务: {existing_trace.task}")
  226. else:
  227. print(f"4. 启动新 Agent 模式...")
  228. print()
  229. final_response = ""
  230. current_trace_id = resume_trace_id
  231. current_sequence = 0
  232. should_exit = False
  233. try:
  234. # 恢复模式:不发送初始消息,只指定 trace_id 续跑
  235. if resume_trace_id:
  236. initial_messages = None # None = 未设置,触发早期菜单检查
  237. config = RunConfig(
  238. model=f"claude-{prompt.config.get('model', 'sonnet-4.5')}",
  239. temperature=float(prompt.config.get('temperature', 0.3)),
  240. max_iterations=1000,
  241. trace_id=resume_trace_id,
  242. )
  243. else:
  244. initial_messages = messages
  245. config = RunConfig(
  246. model=f"claude-{prompt.config.get('model', 'sonnet-4.5')}",
  247. temperature=float(prompt.config.get('temperature', 0.3)),
  248. max_iterations=1000,
  249. name="mcp/skills 发现、获取、评价 分析任务",
  250. )
  251. while not should_exit:
  252. # 如果是续跑,需要指定 trace_id
  253. if current_trace_id:
  254. config.trace_id = current_trace_id
  255. # 清理上一轮的响应,避免失败后显示旧内容
  256. final_response = ""
  257. # 如果 trace 已完成/失败且没有新消息,直接进入交互菜单
  258. # 注意:initial_messages 为 None 表示未设置(首次加载),[] 表示有意为空(用户选择"继续")
  259. if current_trace_id and initial_messages is None:
  260. check_trace = await store.get_trace(current_trace_id)
  261. if check_trace and check_trace.status in ("completed", "failed"):
  262. if check_trace.status == "completed":
  263. print(f"\n[Trace] ✅ 已完成")
  264. print(f" - Total messages: {check_trace.total_messages}")
  265. print(f" - Total cost: ${check_trace.total_cost:.4f}")
  266. else:
  267. print(f"\n[Trace] ❌ 已失败: {check_trace.error_message}")
  268. current_sequence = check_trace.head_sequence
  269. menu_result = await show_interactive_menu(
  270. runner, current_trace_id, current_sequence, store
  271. )
  272. if menu_result["action"] == "stop":
  273. break
  274. elif menu_result["action"] == "continue":
  275. new_messages = menu_result.get("messages", [])
  276. if new_messages:
  277. initial_messages = new_messages
  278. config.after_sequence = menu_result.get("after_sequence")
  279. else:
  280. # 无新消息:对 failed trace 意味着重试,对 completed 意味着继续
  281. initial_messages = []
  282. config.after_sequence = None
  283. continue
  284. break
  285. # 对 stopped/running 等非终态的 trace,直接续跑
  286. initial_messages = []
  287. print(f"{'▶️ 开始执行...' if not current_trace_id else '▶️ 继续执行...'}")
  288. # 执行 Agent
  289. paused = False
  290. try:
  291. async for item in runner.run(messages=initial_messages, config=config):
  292. # 检查用户中断
  293. cmd = check_stdin()
  294. if cmd == 'pause':
  295. # 暂停执行
  296. print("\n⏸️ 正在暂停执行...")
  297. if current_trace_id:
  298. await runner.stop(current_trace_id)
  299. # 等待一小段时间让 runner 处理 stop 信号
  300. await asyncio.sleep(0.5)
  301. # 显示交互菜单
  302. menu_result = await show_interactive_menu(
  303. runner, current_trace_id, current_sequence, store
  304. )
  305. if menu_result["action"] == "stop":
  306. should_exit = True
  307. paused = True
  308. break
  309. elif menu_result["action"] == "continue":
  310. # 检查是否有新消息需要插入
  311. new_messages = menu_result.get("messages", [])
  312. if new_messages:
  313. # 有干预消息,需要重新启动循环
  314. initial_messages = new_messages
  315. after_seq = menu_result.get("after_sequence")
  316. if after_seq is not None:
  317. config.after_sequence = after_seq
  318. paused = True
  319. break
  320. else:
  321. # 没有新消息,需要重启执行
  322. initial_messages = []
  323. config.after_sequence = None
  324. paused = True
  325. break
  326. elif cmd == 'quit':
  327. print("\n🛑 用户请求停止...")
  328. if current_trace_id:
  329. await runner.stop(current_trace_id)
  330. should_exit = True
  331. break
  332. # 处理 Trace 对象(整体状态变化)
  333. if isinstance(item, Trace):
  334. current_trace_id = item.trace_id
  335. if item.status == "running":
  336. print(f"[Trace] 开始: {item.trace_id[:8]}...")
  337. elif item.status == "completed":
  338. print(f"\n[Trace] ✅ 完成")
  339. print(f" - Total messages: {item.total_messages}")
  340. print(f" - Total tokens: {item.total_tokens}")
  341. print(f" - Total cost: ${item.total_cost:.4f}")
  342. elif item.status == "failed":
  343. print(f"\n[Trace] ❌ 失败: {item.error_message}")
  344. elif item.status == "stopped":
  345. print(f"\n[Trace] ⏸️ 已停止")
  346. # 处理 Message 对象(执行过程)
  347. elif isinstance(item, Message):
  348. current_sequence = item.sequence
  349. if item.role == "assistant":
  350. content = item.content
  351. if isinstance(content, dict):
  352. text = content.get("text", "")
  353. tool_calls = content.get("tool_calls")
  354. if text and not tool_calls:
  355. # 纯文本回复(最终响应)
  356. final_response = text
  357. print(f"\n[Response] Agent 回复:")
  358. print(text)
  359. elif text:
  360. preview = text[:150] + "..." if len(text) > 150 else text
  361. print(f"[Assistant] {preview}")
  362. if tool_calls:
  363. for tc in tool_calls:
  364. tool_name = tc.get("function", {}).get("name", "unknown")
  365. print(f"[Tool Call] 🛠️ {tool_name}")
  366. elif item.role == "tool":
  367. content = item.content
  368. if isinstance(content, dict):
  369. tool_name = content.get("tool_name", "unknown")
  370. print(f"[Tool Result] ✅ {tool_name}")
  371. if item.description:
  372. desc = item.description[:80] if len(item.description) > 80 else item.description
  373. print(f" {desc}...")
  374. except Exception as e:
  375. print(f"\n执行出错: {e}")
  376. import traceback
  377. traceback.print_exc()
  378. # paused → 菜单已在暂停时内联显示过
  379. if paused:
  380. if should_exit:
  381. break
  382. continue
  383. # quit → 直接退出
  384. if should_exit:
  385. break
  386. # Runner 退出(完成/失败/停止/异常)→ 显示交互菜单
  387. if current_trace_id:
  388. menu_result = await show_interactive_menu(
  389. runner, current_trace_id, current_sequence, store
  390. )
  391. if menu_result["action"] == "stop":
  392. break
  393. elif menu_result["action"] == "continue":
  394. new_messages = menu_result.get("messages", [])
  395. if new_messages:
  396. initial_messages = new_messages
  397. config.after_sequence = menu_result.get("after_sequence")
  398. else:
  399. initial_messages = []
  400. config.after_sequence = None
  401. continue
  402. break
  403. except KeyboardInterrupt:
  404. print("\n\n用户中断 (Ctrl+C)")
  405. if current_trace_id:
  406. await runner.stop(current_trace_id)
  407. # 6. 输出结果
  408. if final_response:
  409. print()
  410. print("=" * 60)
  411. print("Agent 响应:")
  412. print("=" * 60)
  413. print(final_response)
  414. print("=" * 60)
  415. print()
  416. # 7. 保存结果
  417. output_file = output_dir / "result.txt"
  418. with open(output_file, 'w', encoding='utf-8') as f:
  419. f.write(final_response)
  420. print(f"✓ 结果已保存到: {output_file}")
  421. print()
  422. # 可视化提示
  423. if current_trace_id:
  424. print("=" * 60)
  425. print("可视化 Step Tree:")
  426. print("=" * 60)
  427. print("1. 启动 API Server:")
  428. print(" python3 api_server.py")
  429. print()
  430. print("2. 浏览器访问:")
  431. print(" http://localhost:8000/api/traces")
  432. print()
  433. print(f"3. Trace ID: {current_trace_id}")
  434. print("=" * 60)
  435. if __name__ == "__main__":
  436. asyncio.run(main())