run.py 23 KB

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