run.py 21 KB

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