run.py 26 KB

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