|
@@ -1,366 +1,332 @@
|
|
|
"""
|
|
"""
|
|
|
-示例(流程对齐版)
|
|
|
|
|
|
|
+示例(增强版)
|
|
|
|
|
|
|
|
-参考 examples/research/run.py:
|
|
|
|
|
-1. 使用框架 InteractiveController 统一交互流程
|
|
|
|
|
-2. 使用 config.py 管理运行参数
|
|
|
|
|
-3. 保留 create 场景特有的 prompt 注入与详细消息打印
|
|
|
|
|
|
|
+使用 Agent 模式 + Skills
|
|
|
|
|
+
|
|
|
|
|
+新增功能:
|
|
|
|
|
+1. 支持命令行随时打断(输入 'p' 暂停,'q' 退出)
|
|
|
|
|
+2. 暂停后可插入干预消息
|
|
|
|
|
+3. 支持触发经验总结
|
|
|
|
|
+4. 查看当前 GoalTree
|
|
|
|
|
+5. 框架层自动清理不完整的工具调用
|
|
|
|
|
+6. 支持通过 --trace <ID> 恢复已有 Trace 继续执行
|
|
|
"""
|
|
"""
|
|
|
|
|
|
|
|
import argparse
|
|
import argparse
|
|
|
-import asyncio
|
|
|
|
|
-import copy
|
|
|
|
|
-import json
|
|
|
|
|
import os
|
|
import os
|
|
|
import sys
|
|
import sys
|
|
|
|
|
+import select
|
|
|
|
|
+import asyncio
|
|
|
from pathlib import Path
|
|
from pathlib import Path
|
|
|
-from typing import Any
|
|
|
|
|
-import logging
|
|
|
|
|
|
|
|
|
|
# Clash Verge TUN 模式兼容:禁止 httpx/urllib 自动检测系统 HTTP 代理
|
|
# Clash Verge TUN 模式兼容:禁止 httpx/urllib 自动检测系统 HTTP 代理
|
|
|
|
|
+# TUN 虚拟网卡已在网络层接管所有流量,不需要应用层再走 HTTP 代理,
|
|
|
|
|
+# 否则 httpx 检测到 macOS 系统代理 (127.0.0.1:7897) 会导致 ConnectError
|
|
|
os.environ.setdefault("no_proxy", "*")
|
|
os.environ.setdefault("no_proxy", "*")
|
|
|
|
|
|
|
|
-logger = logging.getLogger(__name__)
|
|
|
|
|
-
|
|
|
|
|
# 添加项目根目录到 Python 路径
|
|
# 添加项目根目录到 Python 路径
|
|
|
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
|
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
|
|
|
|
|
|
|
from dotenv import load_dotenv
|
|
from dotenv import load_dotenv
|
|
|
-
|
|
|
|
|
load_dotenv()
|
|
load_dotenv()
|
|
|
|
|
|
|
|
-from agent.cli import InteractiveController
|
|
|
|
|
|
|
+from agent.llm.prompts import SimplePrompt
|
|
|
|
|
+from agent.core.runner import AgentRunner, RunConfig
|
|
|
from agent.core.presets import AgentPreset, register_preset
|
|
from agent.core.presets import AgentPreset, register_preset
|
|
|
-from agent.core.runner import AgentRunner
|
|
|
|
|
|
|
+from agent.trace import (
|
|
|
|
|
+ FileSystemTraceStore,
|
|
|
|
|
+ Trace,
|
|
|
|
|
+ Message,
|
|
|
|
|
+)
|
|
|
from agent.llm import create_openrouter_llm_call
|
|
from agent.llm import create_openrouter_llm_call
|
|
|
-from agent.llm.prompts import SimplePrompt
|
|
|
|
|
-from agent.trace import FileSystemTraceStore, Message, Trace
|
|
|
|
|
-from agent.utils import setup_logging
|
|
|
|
|
-from examples.create.html import trace_to_html
|
|
|
|
|
|
|
+from agent.tools import get_tool_registry
|
|
|
|
|
|
|
|
-# 导入项目配置
|
|
|
|
|
-from config import DEBUG, LOG_FILE, LOG_LEVEL, RUN_CONFIG, SKILLS_DIR, TRACE_STORE_PATH
|
|
|
|
|
|
|
+DEFAULT_MODEL = "google/gemini-3-flash-preview"
|
|
|
|
|
|
|
|
|
|
|
|
|
-def _format_json(obj: Any, indent: int = 2) -> str:
|
|
|
|
|
- """格式化 JSON 对象为字符串"""
|
|
|
|
|
- try:
|
|
|
|
|
- return json.dumps(obj, indent=indent, ensure_ascii=False)
|
|
|
|
|
- except (TypeError, ValueError):
|
|
|
|
|
- return str(obj)
|
|
|
|
|
-
|
|
|
|
|
-
|
|
|
|
|
-def _print_message_details(message: Message):
|
|
|
|
|
- """完整打印消息的详细信息"""
|
|
|
|
|
- logger.info("\n" + "=" * 80)
|
|
|
|
|
- logger.info(f"[Message #{message.sequence}] {message.role.upper()}")
|
|
|
|
|
- logger.info("=" * 80)
|
|
|
|
|
-
|
|
|
|
|
- if message.goal_id:
|
|
|
|
|
- logger.info(f"Goal ID: {message.goal_id}")
|
|
|
|
|
- if message.parent_sequence is not None:
|
|
|
|
|
- logger.info(f"Parent Sequence: {message.parent_sequence}")
|
|
|
|
|
- if message.tool_call_id:
|
|
|
|
|
- logger.info(f"Tool Call ID: {message.tool_call_id}")
|
|
|
|
|
-
|
|
|
|
|
- if message.role == "user":
|
|
|
|
|
- logger.info("\n[输入内容]")
|
|
|
|
|
- logger.info("-" * 80)
|
|
|
|
|
- if isinstance(message.content, str):
|
|
|
|
|
- logger.info(message.content)
|
|
|
|
|
- else:
|
|
|
|
|
- logger.info(_format_json(message.content))
|
|
|
|
|
- elif message.role == "assistant":
|
|
|
|
|
- content = message.content
|
|
|
|
|
- if isinstance(content, dict):
|
|
|
|
|
- text = content.get("text", "")
|
|
|
|
|
- tool_calls = content.get("tool_calls")
|
|
|
|
|
-
|
|
|
|
|
- if text:
|
|
|
|
|
- logger.info("\n[LLM 文本回复]")
|
|
|
|
|
- logger.info("-" * 80)
|
|
|
|
|
- logger.info(text)
|
|
|
|
|
-
|
|
|
|
|
- if tool_calls:
|
|
|
|
|
- logger.info(f"\n[工具调用] (共 {len(tool_calls)} 个)")
|
|
|
|
|
- logger.info("-" * 80)
|
|
|
|
|
- for idx, tc in enumerate(tool_calls, 1):
|
|
|
|
|
- func = tc.get("function", {})
|
|
|
|
|
- tool_name = func.get("name", "unknown")
|
|
|
|
|
- tool_id = tc.get("id", "unknown")
|
|
|
|
|
- arguments = func.get("arguments", {})
|
|
|
|
|
-
|
|
|
|
|
- logger.info(f"\n工具 #{idx}: {tool_name}")
|
|
|
|
|
- logger.info(f" Call ID: {tool_id}")
|
|
|
|
|
- logger.info(" 参数:")
|
|
|
|
|
- if isinstance(arguments, str):
|
|
|
|
|
- try:
|
|
|
|
|
- parsed_args = json.loads(arguments)
|
|
|
|
|
- logger.info(_format_json(parsed_args, indent=4))
|
|
|
|
|
- except json.JSONDecodeError:
|
|
|
|
|
- logger.info(f" {arguments}")
|
|
|
|
|
- else:
|
|
|
|
|
- logger.info(_format_json(arguments, indent=4))
|
|
|
|
|
- elif isinstance(content, str):
|
|
|
|
|
- logger.info("\n[LLM 文本回复]")
|
|
|
|
|
- logger.info("-" * 80)
|
|
|
|
|
- logger.info(content)
|
|
|
|
|
- else:
|
|
|
|
|
- logger.info("\n[内容]")
|
|
|
|
|
- logger.info("-" * 80)
|
|
|
|
|
- logger.info(_format_json(content))
|
|
|
|
|
-
|
|
|
|
|
- if message.finish_reason:
|
|
|
|
|
- logger.info(f"\n完成原因: {message.finish_reason}")
|
|
|
|
|
- elif message.role == "tool":
|
|
|
|
|
- content = message.content
|
|
|
|
|
- logger.info("\n[工具执行结果]")
|
|
|
|
|
- logger.info("-" * 80)
|
|
|
|
|
- if isinstance(content, dict):
|
|
|
|
|
- tool_name = content.get("tool_name", "unknown")
|
|
|
|
|
- result = content.get("result", content)
|
|
|
|
|
- logger.info(f"工具名称: {tool_name}")
|
|
|
|
|
- logger.info("\n返回结果:")
|
|
|
|
|
- if isinstance(result, str):
|
|
|
|
|
- logger.info(result)
|
|
|
|
|
- elif isinstance(result, list):
|
|
|
|
|
- for idx, item in enumerate(result, 1):
|
|
|
|
|
- if isinstance(item, dict) and item.get("type") == "image_url":
|
|
|
|
|
- logger.info(f" [{idx}] 图片 (base64, 已省略显示)")
|
|
|
|
|
- else:
|
|
|
|
|
- logger.info(f" [{idx}] {item}")
|
|
|
|
|
- else:
|
|
|
|
|
- logger.info(_format_json(result))
|
|
|
|
|
- else:
|
|
|
|
|
- logger.info(str(content) if content is not None else "(无内容)")
|
|
|
|
|
- elif message.role == "system":
|
|
|
|
|
- logger.info("\n[系统提示]")
|
|
|
|
|
- logger.info("-" * 80)
|
|
|
|
|
- if isinstance(message.content, str):
|
|
|
|
|
- logger.info(message.content)
|
|
|
|
|
- else:
|
|
|
|
|
- logger.info(_format_json(message.content))
|
|
|
|
|
-
|
|
|
|
|
- if message.prompt_tokens is not None or message.completion_tokens is not None:
|
|
|
|
|
- logger.info("\n[Token 使用]")
|
|
|
|
|
- logger.info("-" * 80)
|
|
|
|
|
- if message.prompt_tokens is not None:
|
|
|
|
|
- logger.info(f" 输入 Tokens: {message.prompt_tokens:,}")
|
|
|
|
|
- if message.completion_tokens is not None:
|
|
|
|
|
- logger.info(f" 输出 Tokens: {message.completion_tokens:,}")
|
|
|
|
|
- if message.reasoning_tokens is not None:
|
|
|
|
|
- logger.info(f" 推理 Tokens: {message.reasoning_tokens:,}")
|
|
|
|
|
- if message.cache_creation_tokens is not None:
|
|
|
|
|
- logger.info(f" 缓存创建 Tokens: {message.cache_creation_tokens:,}")
|
|
|
|
|
- if message.cache_read_tokens is not None:
|
|
|
|
|
- logger.info(f" 缓存读取 Tokens: {message.cache_read_tokens:,}")
|
|
|
|
|
- if message.tokens:
|
|
|
|
|
- logger.info(f" 总计 Tokens: {message.tokens:,}")
|
|
|
|
|
-
|
|
|
|
|
- if message.cost is not None:
|
|
|
|
|
- logger.info(f"\n[成本] ${message.cost:.6f}")
|
|
|
|
|
-
|
|
|
|
|
- if message.duration_ms is not None:
|
|
|
|
|
- logger.info(f"[执行时间] {message.duration_ms}ms")
|
|
|
|
|
-
|
|
|
|
|
- logger.info("=" * 80 + "\n")
|
|
|
|
|
-
|
|
|
|
|
-
|
|
|
|
|
-def _apply_prompt_placeholders(base_dir: Path, prompt: SimplePrompt, persona_dir: str = None):
|
|
|
|
|
- """把 PRD 文件内容和人设树数据注入 prompt 占位符。
|
|
|
|
|
-
|
|
|
|
|
- Args:
|
|
|
|
|
- base_dir: 基础目录
|
|
|
|
|
- prompt: SimplePrompt 对象
|
|
|
|
|
- persona_dir: 人设数据目录名,如 "家有大志"。如果为 None,则不替换树数据
|
|
|
|
|
|
|
+
|
|
|
|
|
+# ===== 非阻塞 stdin 检测 =====
|
|
|
|
|
+if sys.platform == 'win32':
|
|
|
|
|
+ import msvcrt
|
|
|
|
|
+
|
|
|
|
|
+def check_stdin() -> str | None:
|
|
|
|
|
+ """
|
|
|
|
|
+ 跨平台非阻塞检查 stdin 输入。
|
|
|
|
|
+ Windows: 使用 msvcrt.kbhit()
|
|
|
|
|
+ macOS/Linux: 使用 select.select()
|
|
|
"""
|
|
"""
|
|
|
- # 替换 {{person_name}} 占位符
|
|
|
|
|
- if persona_dir:
|
|
|
|
|
- person_name_placeholder = "{{person_name}}"
|
|
|
|
|
- if "system" in prompt._messages and person_name_placeholder in prompt._messages["system"]:
|
|
|
|
|
- prompt._messages["system"] = prompt._messages["system"].replace(person_name_placeholder, persona_dir)
|
|
|
|
|
- logger.info(f" - 已替换 {{{{person_name}}}} 为: {persona_dir}")
|
|
|
|
|
- if "user" in prompt._messages and person_name_placeholder in prompt._messages["user"]:
|
|
|
|
|
- prompt._messages["user"] = prompt._messages["user"].replace(person_name_placeholder, persona_dir)
|
|
|
|
|
- logger.info(f" - 已替换 {{{{person_name}}}} 为: {persona_dir} (user)")
|
|
|
|
|
-
|
|
|
|
|
- system_md_path = base_dir / "PRD" / "system.md"
|
|
|
|
|
- if system_md_path.exists():
|
|
|
|
|
- system_content = system_md_path.read_text(encoding="utf-8")
|
|
|
|
|
- if "system" in prompt._messages and "{system}" in prompt._messages["system"]:
|
|
|
|
|
- prompt._messages["system"] = prompt._messages["system"].replace("{system}", system_content)
|
|
|
|
|
|
|
+ if sys.platform == 'win32':
|
|
|
|
|
+ # 检查是否有按键按下
|
|
|
|
|
+ if msvcrt.kbhit():
|
|
|
|
|
+ # 读取按下的字符(msvcrt.getwch 是非阻塞读取宽字符)
|
|
|
|
|
+ ch = msvcrt.getwch().lower()
|
|
|
|
|
+ if ch == 'p':
|
|
|
|
|
+ return 'pause'
|
|
|
|
|
+ if ch == 'q':
|
|
|
|
|
+ return 'quit'
|
|
|
|
|
+ # 如果是其他按键,可以选择消耗掉或者忽略
|
|
|
|
|
+ return None
|
|
|
else:
|
|
else:
|
|
|
- logger.warning(f" - 警告: system.md 文件不存在: {system_md_path}")
|
|
|
|
|
-
|
|
|
|
|
- # 优先使用 v2 版本,如果不存在则使用原版本
|
|
|
|
|
- create_process_md_path = base_dir / "PRD" / "create_process_v2.md"
|
|
|
|
|
- if not create_process_md_path.exists():
|
|
|
|
|
- create_process_md_path = base_dir / "PRD" / "create_process.md"
|
|
|
|
|
-
|
|
|
|
|
- if create_process_md_path.exists():
|
|
|
|
|
- create_process_content = create_process_md_path.read_text(encoding="utf-8")
|
|
|
|
|
- if "system" in prompt._messages and "{create_process}" in prompt._messages["system"]:
|
|
|
|
|
- prompt._messages["system"] = prompt._messages["system"].replace("{create_process}", create_process_content)
|
|
|
|
|
- logger.info(f" - 已替换 {create_process_md_path.name} 内容到 prompt")
|
|
|
|
|
|
|
+ # Unix/Mac 逻辑
|
|
|
|
|
+ ready, _, _ = select.select([sys.stdin], [], [], 0)
|
|
|
|
|
+ if ready:
|
|
|
|
|
+ line = sys.stdin.readline().strip().lower()
|
|
|
|
|
+ if line in ('p', 'pause'):
|
|
|
|
|
+ return 'pause'
|
|
|
|
|
+ if line in ('q', 'quit'):
|
|
|
|
|
+ return 'quit'
|
|
|
|
|
+ return None
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+# ===== 交互菜单 =====
|
|
|
|
|
+
|
|
|
|
|
+def _read_multiline() -> str:
|
|
|
|
|
+ """
|
|
|
|
|
+ 读取多行输入,以连续两次回车(空行)结束。
|
|
|
|
|
+
|
|
|
|
|
+ 单次回车只是换行,不会提前终止输入。
|
|
|
|
|
+ """
|
|
|
|
|
+ print("\n请输入干预消息(连续输入两次回车结束):")
|
|
|
|
|
+ lines: list[str] = []
|
|
|
|
|
+ blank_count = 0
|
|
|
|
|
+ while True:
|
|
|
|
|
+ line = input()
|
|
|
|
|
+ if line == "":
|
|
|
|
|
+ blank_count += 1
|
|
|
|
|
+ if blank_count >= 2:
|
|
|
|
|
+ break
|
|
|
|
|
+ lines.append("") # 保留单个空行
|
|
|
else:
|
|
else:
|
|
|
- logger.warning(" - 警告: prompt 中未找到 {create_process} 占位符")
|
|
|
|
|
- else:
|
|
|
|
|
- logger.warning(f" - 警告: create_process.md 文件不存在: {create_process_md_path}")
|
|
|
|
|
-
|
|
|
|
|
- # 替换人设树数据
|
|
|
|
|
- if persona_dir:
|
|
|
|
|
- tree_dir = base_dir / "data" / persona_dir / "tree"
|
|
|
|
|
- if tree_dir.exists():
|
|
|
|
|
- # 读取三个树文件
|
|
|
|
|
- tree_files = {
|
|
|
|
|
- "形式_point_tree_how": tree_dir / "形式_point_tree_how.json",
|
|
|
|
|
- "实质_point_tree_how": tree_dir / "实质_point_tree_how.json",
|
|
|
|
|
- "意图_point_tree_how": tree_dir / "意图_point_tree_how.json"
|
|
|
|
|
|
|
+ blank_count = 0
|
|
|
|
|
+ lines.append(line)
|
|
|
|
|
+
|
|
|
|
|
+ # 去掉尾部多余空行
|
|
|
|
|
+ while lines and lines[-1] == "":
|
|
|
|
|
+ lines.pop()
|
|
|
|
|
+ return "\n".join(lines)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+async def show_interactive_menu(
|
|
|
|
|
+ runner: AgentRunner,
|
|
|
|
|
+ trace_id: str,
|
|
|
|
|
+ current_sequence: int,
|
|
|
|
|
+ store: FileSystemTraceStore,
|
|
|
|
|
+):
|
|
|
|
|
+ """
|
|
|
|
|
+ 显示交互式菜单,让用户选择操作。
|
|
|
|
|
+
|
|
|
|
|
+ 进入本函数前不再有后台线程占用 stdin,所以 input() 能正常工作。
|
|
|
|
|
+ """
|
|
|
|
|
+ print("\n" + "=" * 60)
|
|
|
|
|
+ print(" 执行已暂停")
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+ print("请选择操作:")
|
|
|
|
|
+ print(" 1. 插入干预消息并继续")
|
|
|
|
|
+ print(" 2. 触发经验总结(reflect)")
|
|
|
|
|
+ print(" 3. 查看当前 GoalTree")
|
|
|
|
|
+ print(" 4. 手动压缩上下文(compact)")
|
|
|
|
|
+ print(" 5. 继续执行")
|
|
|
|
|
+ print(" 6. 停止执行")
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+
|
|
|
|
|
+ while True:
|
|
|
|
|
+ choice = input("请输入选项 (1-6): ").strip()
|
|
|
|
|
+
|
|
|
|
|
+ if choice == "1":
|
|
|
|
|
+ text = _read_multiline()
|
|
|
|
|
+ if not text:
|
|
|
|
|
+ print("未输入任何内容,取消操作")
|
|
|
|
|
+ continue
|
|
|
|
|
+
|
|
|
|
|
+ print(f"\n将插入干预消息并继续执行...")
|
|
|
|
|
+ # 从 store 读取实际的 last_sequence,避免本地 current_sequence 过时
|
|
|
|
|
+ live_trace = await store.get_trace(trace_id)
|
|
|
|
|
+ actual_sequence = live_trace.last_sequence if live_trace and live_trace.last_sequence else current_sequence
|
|
|
|
|
+ return {
|
|
|
|
|
+ "action": "continue",
|
|
|
|
|
+ "messages": [{"role": "user", "content": text}],
|
|
|
|
|
+ "after_sequence": actual_sequence,
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- for var_name, tree_path in tree_files.items():
|
|
|
|
|
- if tree_path.exists():
|
|
|
|
|
- tree_content = tree_path.read_text(encoding="utf-8")
|
|
|
|
|
- placeholder = "{{" + var_name + "}}"
|
|
|
|
|
-
|
|
|
|
|
- # 在 system 消息中替换
|
|
|
|
|
- if "system" in prompt._messages and placeholder in prompt._messages["system"]:
|
|
|
|
|
- prompt._messages["system"] = prompt._messages["system"].replace(placeholder, tree_content)
|
|
|
|
|
- logger.info(f" - 已替换 {var_name} 数据到 prompt")
|
|
|
|
|
-
|
|
|
|
|
- # 在 user 消息中替换
|
|
|
|
|
- if "user" in prompt._messages and placeholder in prompt._messages["user"]:
|
|
|
|
|
- prompt._messages["user"] = prompt._messages["user"].replace(placeholder, tree_content)
|
|
|
|
|
- logger.info(f" - 已替换 {var_name} 数据到 prompt (user)")
|
|
|
|
|
- else:
|
|
|
|
|
- logger.warning(f" - 警告: 树文件不存在: {tree_path}")
|
|
|
|
|
- else:
|
|
|
|
|
- logger.warning(f" - 警告: 人设树目录不存在: {tree_dir}")
|
|
|
|
|
-
|
|
|
|
|
- input_md_path = base_dir / "PRD" / "input.md"
|
|
|
|
|
- if input_md_path.exists():
|
|
|
|
|
- user_content = input_md_path.read_text(encoding="utf-8")
|
|
|
|
|
- if "user" in prompt._messages and "{input}" in prompt._messages["user"]:
|
|
|
|
|
- prompt._messages["user"] = prompt._messages["user"].replace("{input}", user_content)
|
|
|
|
|
- logger.info(" - 已替换 input.md 内容到 prompt")
|
|
|
|
|
- else:
|
|
|
|
|
- logger.warning(" - 警告: prompt 中未找到 {input} 占位符")
|
|
|
|
|
- else:
|
|
|
|
|
- logger.warning(f" - 警告: input.md 文件不存在: {input_md_path}")
|
|
|
|
|
-
|
|
|
|
|
- output_md_path = base_dir / "PRD" / "output.md"
|
|
|
|
|
- if output_md_path.exists():
|
|
|
|
|
- output_content = output_md_path.read_text(encoding="utf-8")
|
|
|
|
|
- if "user" in prompt._messages and "{output}" in prompt._messages["user"]:
|
|
|
|
|
- prompt._messages["user"] = prompt._messages["user"].replace("{output}", output_content)
|
|
|
|
|
- logger.info(" - 已替换 output.md 内容到 prompt")
|
|
|
|
|
|
|
+ elif choice == "2":
|
|
|
|
|
+ # 触发经验总结
|
|
|
|
|
+ print("\n触发经验总结...")
|
|
|
|
|
+ focus = input("请输入反思重点(可选,直接回车跳过): ").strip()
|
|
|
|
|
+
|
|
|
|
|
+ from agent.trace.compaction import build_reflect_prompt
|
|
|
|
|
+
|
|
|
|
|
+ # 保存当前 head_sequence
|
|
|
|
|
+ trace = await store.get_trace(trace_id)
|
|
|
|
|
+ saved_head = trace.head_sequence
|
|
|
|
|
+
|
|
|
|
|
+ prompt = build_reflect_prompt()
|
|
|
|
|
+ if focus:
|
|
|
|
|
+ prompt += f"\n\n请特别关注:{focus}"
|
|
|
|
|
+
|
|
|
|
|
+ print("正在生成反思...")
|
|
|
|
|
+ reflect_cfg = RunConfig(trace_id=trace_id, max_iterations=1, tools=[])
|
|
|
|
|
+
|
|
|
|
|
+ reflection_text = ""
|
|
|
|
|
+ try:
|
|
|
|
|
+ result = await runner.run_result(
|
|
|
|
|
+ messages=[{"role": "user", "content": prompt}],
|
|
|
|
|
+ config=reflect_cfg,
|
|
|
|
|
+ )
|
|
|
|
|
+ reflection_text = result.get("summary", "")
|
|
|
|
|
+ finally:
|
|
|
|
|
+ # 恢复 head_sequence(反思消息成为侧枝)
|
|
|
|
|
+ await store.update_trace(trace_id, head_sequence=saved_head)
|
|
|
|
|
+
|
|
|
|
|
+ # 追加到 experiences 文件
|
|
|
|
|
+ if reflection_text:
|
|
|
|
|
+ from datetime import datetime
|
|
|
|
|
+ experiences_path = runner.experiences_path or "./.cache/experiences.md"
|
|
|
|
|
+ os.makedirs(os.path.dirname(experiences_path), exist_ok=True)
|
|
|
|
|
+ header = f"\n\n---\n\n## {trace_id} ({datetime.now().strftime('%Y-%m-%d %H:%M')})\n\n"
|
|
|
|
|
+ with open(experiences_path, "a", encoding="utf-8") as f:
|
|
|
|
|
+ f.write(header + reflection_text + "\n")
|
|
|
|
|
+ print(f"\n反思已保存到: {experiences_path}")
|
|
|
|
|
+ print("\n--- 反思内容 ---")
|
|
|
|
|
+ print(reflection_text)
|
|
|
|
|
+ print("--- 结束 ---\n")
|
|
|
|
|
+ else:
|
|
|
|
|
+ print("未生成反思内容")
|
|
|
|
|
+
|
|
|
|
|
+ continue
|
|
|
|
|
+
|
|
|
|
|
+ elif choice == "3":
|
|
|
|
|
+ goal_tree = await store.get_goal_tree(trace_id)
|
|
|
|
|
+ if goal_tree and goal_tree.goals:
|
|
|
|
|
+ print("\n当前 GoalTree:")
|
|
|
|
|
+ print(goal_tree.to_prompt())
|
|
|
|
|
+ else:
|
|
|
|
|
+ print("\n当前没有 Goal")
|
|
|
|
|
+ continue
|
|
|
|
|
+
|
|
|
|
|
+ elif choice == "4":
|
|
|
|
|
+ # 手动压缩上下文
|
|
|
|
|
+ print("\n正在执行上下文压缩(compact)...")
|
|
|
|
|
+ try:
|
|
|
|
|
+ goal_tree = await store.get_goal_tree(trace_id)
|
|
|
|
|
+ trace = await store.get_trace(trace_id)
|
|
|
|
|
+ if not trace:
|
|
|
|
|
+ print("未找到 Trace,无法压缩")
|
|
|
|
|
+ continue
|
|
|
|
|
+
|
|
|
|
|
+ # 重建当前 history
|
|
|
|
|
+ main_path = await store.get_main_path_messages(trace_id, trace.head_sequence)
|
|
|
|
|
+ history = [msg.to_llm_dict() for msg in main_path]
|
|
|
|
|
+ head_seq = main_path[-1].sequence if main_path else 0
|
|
|
|
|
+ next_seq = head_seq + 1
|
|
|
|
|
+
|
|
|
|
|
+ compact_config = RunConfig(trace_id=trace_id)
|
|
|
|
|
+ new_history, new_head, new_seq = await runner._compress_history(
|
|
|
|
|
+ trace_id=trace_id,
|
|
|
|
|
+ history=history,
|
|
|
|
|
+ goal_tree=goal_tree,
|
|
|
|
|
+ config=compact_config,
|
|
|
|
|
+ sequence=next_seq,
|
|
|
|
|
+ head_seq=head_seq,
|
|
|
|
|
+ )
|
|
|
|
|
+ print(f"\n✅ 压缩完成: {len(history)} 条消息 → {len(new_history)} 条")
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ print(f"\n❌ 压缩失败: {e}")
|
|
|
|
|
+ continue
|
|
|
|
|
+
|
|
|
|
|
+ elif choice == "5":
|
|
|
|
|
+ print("\n继续执行...")
|
|
|
|
|
+ return {"action": "continue"}
|
|
|
|
|
+
|
|
|
|
|
+ elif choice == "6":
|
|
|
|
|
+ print("\n停止执行...")
|
|
|
|
|
+ return {"action": "stop"}
|
|
|
|
|
+
|
|
|
else:
|
|
else:
|
|
|
- logger.warning(" - 警告: prompt 中未找到 {output} 占位符")
|
|
|
|
|
- else:
|
|
|
|
|
- logger.warning(f" - 警告: output.md 文件不存在: {output_md_path}")
|
|
|
|
|
|
|
+ print("无效选项,请重新输入")
|
|
|
|
|
|
|
|
|
|
|
|
|
async def main():
|
|
async def main():
|
|
|
|
|
+ # 解析命令行参数
|
|
|
parser = argparse.ArgumentParser(description="任务 (Agent 模式 + 交互增强)")
|
|
parser = argparse.ArgumentParser(description="任务 (Agent 模式 + 交互增强)")
|
|
|
parser.add_argument(
|
|
parser.add_argument(
|
|
|
- "--trace",
|
|
|
|
|
- type=str,
|
|
|
|
|
- default=None,
|
|
|
|
|
|
|
+ "--trace", type=str, default=None,
|
|
|
help="已有的 Trace ID,用于恢复继续执行(不指定则新建)",
|
|
help="已有的 Trace ID,用于恢复继续执行(不指定则新建)",
|
|
|
)
|
|
)
|
|
|
- parser.add_argument(
|
|
|
|
|
- "--persona",
|
|
|
|
|
- type=str,
|
|
|
|
|
- default=None,
|
|
|
|
|
- help="人设数据目录名,如 '家有大志'。用于读取 data/{目录名}/tree 下的树数据",
|
|
|
|
|
- )
|
|
|
|
|
args = parser.parse_args()
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
|
|
+ # 路径配置
|
|
|
base_dir = Path(__file__).parent
|
|
base_dir = Path(__file__).parent
|
|
|
- prompt_path = base_dir / "create.prompt"
|
|
|
|
|
|
|
+ project_root = base_dir.parent.parent
|
|
|
|
|
+ prompt_path = base_dir / "production.prompt"
|
|
|
output_dir = base_dir / "output_1"
|
|
output_dir = base_dir / "output_1"
|
|
|
output_dir.mkdir(exist_ok=True)
|
|
output_dir.mkdir(exist_ok=True)
|
|
|
|
|
|
|
|
- setup_logging(level=LOG_LEVEL, file=LOG_FILE)
|
|
|
|
|
-
|
|
|
|
|
- logger.info("2. 加载 presets...")
|
|
|
|
|
|
|
+ # 加载项目级 presets(examples/how/presets.json)
|
|
|
presets_path = base_dir / "presets.json"
|
|
presets_path = base_dir / "presets.json"
|
|
|
if presets_path.exists():
|
|
if presets_path.exists():
|
|
|
|
|
+ import json
|
|
|
with open(presets_path, "r", encoding="utf-8") as f:
|
|
with open(presets_path, "r", encoding="utf-8") as f:
|
|
|
project_presets = json.load(f)
|
|
project_presets = json.load(f)
|
|
|
for name, cfg in project_presets.items():
|
|
for name, cfg in project_presets.items():
|
|
|
register_preset(name, AgentPreset(**cfg))
|
|
register_preset(name, AgentPreset(**cfg))
|
|
|
- logger.info(f" - 已加载项目 presets: {list(project_presets.keys())}")
|
|
|
|
|
-
|
|
|
|
|
- logger.info("3. 加载 prompt...")
|
|
|
|
|
|
|
+ print(f" - 已加载项目 presets: {list(project_presets.keys())}")
|
|
|
|
|
+
|
|
|
|
|
+ # Skills 目录(可选:用户自定义 skills)
|
|
|
|
|
+ # 注意:内置 skills(agent/memory/skills/)会自动加载
|
|
|
|
|
+ skills_dir = str(base_dir / "skills")
|
|
|
|
|
+
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+ print("mcp/skills 发现、获取、评价 分析任务 (Agent 模式 + 交互增强)")
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+ print()
|
|
|
|
|
+ print("💡 交互提示:")
|
|
|
|
|
+ print(" - 执行过程中输入 'p' 或 'pause' 暂停并进入交互模式")
|
|
|
|
|
+ print(" - 执行过程中输入 'q' 或 'quit' 停止执行")
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+ print()
|
|
|
|
|
+
|
|
|
|
|
+ # 1. 加载 prompt
|
|
|
|
|
+ print("1. 加载 prompt 配置...")
|
|
|
prompt = SimplePrompt(prompt_path)
|
|
prompt = SimplePrompt(prompt_path)
|
|
|
- _apply_prompt_placeholders(base_dir, prompt, persona_dir=args.persona)
|
|
|
|
|
-
|
|
|
|
|
- logger.info("\n替换后的 prompt:")
|
|
|
|
|
- logger.info("=" * 60)
|
|
|
|
|
- logger.info("System:")
|
|
|
|
|
- logger.info("-" * 60)
|
|
|
|
|
- logger.info(prompt._messages.get("system", ""))
|
|
|
|
|
- logger.info("=" * 60)
|
|
|
|
|
- if "user" in prompt._messages:
|
|
|
|
|
- logger.info("\nUser:")
|
|
|
|
|
- logger.info("-" * 60)
|
|
|
|
|
- logger.info(prompt._messages["user"])
|
|
|
|
|
- logger.info("=" * 60)
|
|
|
|
|
- logger.info("")
|
|
|
|
|
-
|
|
|
|
|
- logger.info("4. 构建任务消息...")
|
|
|
|
|
- messages = prompt.build_messages()
|
|
|
|
|
|
|
|
|
|
- logger.info("5. 创建 Agent Runner...")
|
|
|
|
|
- logger.info(" - 加载自定义工具: topic_search")
|
|
|
|
|
- import examples.create.tool # noqa: F401
|
|
|
|
|
|
|
+ # 2. 构建消息(仅新建时使用,恢复时消息已在 trace 中)
|
|
|
|
|
+ print("2. 构建任务消息...")
|
|
|
|
|
+ messages = prompt.build_messages()
|
|
|
|
|
|
|
|
- model_from_prompt = prompt.config.get("model")
|
|
|
|
|
- model_from_config = RUN_CONFIG.model
|
|
|
|
|
- default_model = f"anthropic/{model_from_config}" if "/" not in model_from_config else model_from_config
|
|
|
|
|
- model = model_from_prompt or default_model
|
|
|
|
|
|
|
+ # 3. 创建 Agent Runner(配置 skills)
|
|
|
|
|
+ print("3. 创建 Agent Runner...")
|
|
|
|
|
+ print(f" - Skills 目录: {skills_dir}")
|
|
|
|
|
+ print(f" - 模型: {prompt.config.get('model', 'sonnet-4.5')}")
|
|
|
|
|
|
|
|
- skills_dir = str((base_dir / SKILLS_DIR).resolve()) if not Path(SKILLS_DIR).is_absolute() else SKILLS_DIR
|
|
|
|
|
- logger.info(f" - Skills 目录: {skills_dir}")
|
|
|
|
|
- logger.info(f" - 模型: {model}")
|
|
|
|
|
|
|
+ # 加载自定义工具
|
|
|
|
|
+ print(" - 加载自定义工具: nanobanana")
|
|
|
|
|
+ import examples.how.tool # 导入自定义工具模块,触发 @tool 装饰器注册
|
|
|
|
|
|
|
|
- store = FileSystemTraceStore(base_path=TRACE_STORE_PATH)
|
|
|
|
|
|
|
+ store = FileSystemTraceStore(base_path=".trace")
|
|
|
runner = AgentRunner(
|
|
runner = AgentRunner(
|
|
|
trace_store=store,
|
|
trace_store=store,
|
|
|
- llm_call=create_openrouter_llm_call(model=model),
|
|
|
|
|
|
|
+ llm_call=create_openrouter_llm_call(model=DEFAULT_MODEL),
|
|
|
skills_dir=skills_dir,
|
|
skills_dir=skills_dir,
|
|
|
- debug=DEBUG,
|
|
|
|
|
|
|
+ experiences_path="./.cache/experiences_how.md",
|
|
|
|
|
+ debug=True
|
|
|
)
|
|
)
|
|
|
|
|
|
|
|
- interactive = InteractiveController(
|
|
|
|
|
- runner=runner,
|
|
|
|
|
- store=store,
|
|
|
|
|
- enable_stdin_check=True,
|
|
|
|
|
- )
|
|
|
|
|
-
|
|
|
|
|
- task_name = RUN_CONFIG.name or base_dir.name
|
|
|
|
|
- logger.info("=" * 60)
|
|
|
|
|
- logger.info(task_name)
|
|
|
|
|
- logger.info("=" * 60)
|
|
|
|
|
- logger.info("💡 交互提示:")
|
|
|
|
|
- logger.info(" - 执行过程中输入 'p' 或 'pause' 暂停并进入交互模式")
|
|
|
|
|
- logger.info(" - 执行过程中输入 'q' 或 'quit' 停止执行")
|
|
|
|
|
- logger.info("=" * 60)
|
|
|
|
|
- logger.info("")
|
|
|
|
|
-
|
|
|
|
|
|
|
+ # 4. 判断是新建还是恢复
|
|
|
resume_trace_id = args.trace
|
|
resume_trace_id = args.trace
|
|
|
if resume_trace_id:
|
|
if resume_trace_id:
|
|
|
|
|
+ # 验证 trace 存在
|
|
|
existing_trace = await store.get_trace(resume_trace_id)
|
|
existing_trace = await store.get_trace(resume_trace_id)
|
|
|
if not existing_trace:
|
|
if not existing_trace:
|
|
|
- logger.error(f"\n错误: Trace 不存在: {resume_trace_id}")
|
|
|
|
|
|
|
+ print(f"\n错误: Trace 不存在: {resume_trace_id}")
|
|
|
sys.exit(1)
|
|
sys.exit(1)
|
|
|
- logger.info(f"恢复已有 Trace: {resume_trace_id[:8]}...")
|
|
|
|
|
- logger.info(f" - 状态: {existing_trace.status}")
|
|
|
|
|
- logger.info(f" - 消息数: {existing_trace.total_messages}")
|
|
|
|
|
|
|
+ print(f"4. 恢复已有 Trace: {resume_trace_id[:8]}...")
|
|
|
|
|
+ print(f" - 状态: {existing_trace.status}")
|
|
|
|
|
+ print(f" - 消息数: {existing_trace.total_messages}")
|
|
|
|
|
+ print(f" - 任务: {existing_trace.task}")
|
|
|
else:
|
|
else:
|
|
|
- logger.info("启动新 Agent...")
|
|
|
|
|
- logger.info("")
|
|
|
|
|
|
|
+ print(f"4. 启动新 Agent 模式...")
|
|
|
|
|
+
|
|
|
|
|
+ print()
|
|
|
|
|
|
|
|
final_response = ""
|
|
final_response = ""
|
|
|
current_trace_id = resume_trace_id
|
|
current_trace_id = resume_trace_id
|
|
@@ -368,181 +334,235 @@ async def main():
|
|
|
should_exit = False
|
|
should_exit = False
|
|
|
|
|
|
|
|
try:
|
|
try:
|
|
|
- run_config = copy.deepcopy(RUN_CONFIG)
|
|
|
|
|
- run_config.model = model
|
|
|
|
|
- run_config.temperature = float(prompt.config.get("temperature", run_config.temperature))
|
|
|
|
|
- run_config.max_iterations = int(prompt.config.get("max_iterations", run_config.max_iterations))
|
|
|
|
|
-
|
|
|
|
|
|
|
+ # 恢复模式:不发送初始消息,只指定 trace_id 续跑
|
|
|
if resume_trace_id:
|
|
if resume_trace_id:
|
|
|
- initial_messages = None
|
|
|
|
|
- run_config.trace_id = resume_trace_id
|
|
|
|
|
|
|
+ initial_messages = None # None = 未设置,触发早期菜单检查
|
|
|
|
|
+ config = RunConfig(
|
|
|
|
|
+ model=f"claude-{prompt.config.get('model', 'sonnet-4.5')}",
|
|
|
|
|
+ temperature=float(prompt.config.get('temperature', 0.3)),
|
|
|
|
|
+ max_iterations=1000,
|
|
|
|
|
+ trace_id=resume_trace_id,
|
|
|
|
|
+ )
|
|
|
else:
|
|
else:
|
|
|
initial_messages = messages
|
|
initial_messages = messages
|
|
|
- run_config.name = "社交媒体内容解构、建构、评估任务"
|
|
|
|
|
|
|
+ config = RunConfig(
|
|
|
|
|
+ model=f"claude-{prompt.config.get('model', 'sonnet-4.5')}",
|
|
|
|
|
+ temperature=float(prompt.config.get('temperature', 0.3)),
|
|
|
|
|
+ max_iterations=1000,
|
|
|
|
|
+ name="社交媒体内容解构、建构、评估任务",
|
|
|
|
|
+ )
|
|
|
|
|
|
|
|
while not should_exit:
|
|
while not should_exit:
|
|
|
|
|
+ # 如果是续跑,需要指定 trace_id
|
|
|
if current_trace_id:
|
|
if current_trace_id:
|
|
|
- run_config.trace_id = current_trace_id
|
|
|
|
|
|
|
+ config.trace_id = current_trace_id
|
|
|
|
|
|
|
|
|
|
+ # 清理上一轮的响应,避免失败后显示旧内容
|
|
|
final_response = ""
|
|
final_response = ""
|
|
|
|
|
|
|
|
|
|
+ # 如果 trace 已完成/失败且没有新消息,直接进入交互菜单
|
|
|
|
|
+ # 注意:initial_messages 为 None 表示未设置(首次加载),[] 表示有意为空(用户选择"继续")
|
|
|
if current_trace_id and initial_messages is None:
|
|
if current_trace_id and initial_messages is None:
|
|
|
check_trace = await store.get_trace(current_trace_id)
|
|
check_trace = await store.get_trace(current_trace_id)
|
|
|
if check_trace and check_trace.status in ("completed", "failed"):
|
|
if check_trace and check_trace.status in ("completed", "failed"):
|
|
|
if check_trace.status == "completed":
|
|
if check_trace.status == "completed":
|
|
|
- logger.info("\n[Trace] ✅ 已完成")
|
|
|
|
|
- logger.info(f" - Total messages: {check_trace.total_messages}")
|
|
|
|
|
- logger.info(f" - Total cost: ${check_trace.total_cost:.4f}")
|
|
|
|
|
|
|
+ print(f"\n[Trace] ✅ 已完成")
|
|
|
|
|
+ print(f" - Total messages: {check_trace.total_messages}")
|
|
|
|
|
+ print(f" - Total cost: ${check_trace.total_cost:.4f}")
|
|
|
else:
|
|
else:
|
|
|
- logger.error(f"\n[Trace] ❌ 已失败: {check_trace.error_message}")
|
|
|
|
|
|
|
+ print(f"\n[Trace] ❌ 已失败: {check_trace.error_message}")
|
|
|
current_sequence = check_trace.head_sequence
|
|
current_sequence = check_trace.head_sequence
|
|
|
|
|
|
|
|
- menu_result = await interactive.show_menu(current_trace_id, current_sequence)
|
|
|
|
|
|
|
+ menu_result = await show_interactive_menu(
|
|
|
|
|
+ runner, current_trace_id, current_sequence, store
|
|
|
|
|
+ )
|
|
|
|
|
+
|
|
|
if menu_result["action"] == "stop":
|
|
if menu_result["action"] == "stop":
|
|
|
break
|
|
break
|
|
|
- if menu_result["action"] == "continue":
|
|
|
|
|
|
|
+ elif menu_result["action"] == "continue":
|
|
|
new_messages = menu_result.get("messages", [])
|
|
new_messages = menu_result.get("messages", [])
|
|
|
if new_messages:
|
|
if new_messages:
|
|
|
initial_messages = new_messages
|
|
initial_messages = new_messages
|
|
|
- run_config.after_sequence = menu_result.get("after_sequence")
|
|
|
|
|
|
|
+ config.after_sequence = menu_result.get("after_sequence")
|
|
|
else:
|
|
else:
|
|
|
|
|
+ # 无新消息:对 failed trace 意味着重试,对 completed 意味着继续
|
|
|
initial_messages = []
|
|
initial_messages = []
|
|
|
- run_config.after_sequence = None
|
|
|
|
|
|
|
+ config.after_sequence = None
|
|
|
continue
|
|
continue
|
|
|
break
|
|
break
|
|
|
|
|
|
|
|
|
|
+ # 对 stopped/running 等非终态的 trace,直接续跑
|
|
|
initial_messages = []
|
|
initial_messages = []
|
|
|
|
|
|
|
|
- logger.info(f"{'▶️ 开始执行...' if not current_trace_id else '▶️ 继续执行...'}")
|
|
|
|
|
|
|
+ print(f"{'▶️ 开始执行...' if not current_trace_id else '▶️ 继续执行...'}")
|
|
|
|
|
|
|
|
|
|
+ # 执行 Agent
|
|
|
paused = False
|
|
paused = False
|
|
|
try:
|
|
try:
|
|
|
- async for item in runner.run(messages=initial_messages, config=run_config):
|
|
|
|
|
- cmd = interactive.check_stdin()
|
|
|
|
|
- if cmd == "pause":
|
|
|
|
|
- logger.info("\n⏸️ 正在暂停执行...")
|
|
|
|
|
|
|
+ async for item in runner.run(messages=initial_messages, config=config):
|
|
|
|
|
+ # 检查用户中断
|
|
|
|
|
+ cmd = check_stdin()
|
|
|
|
|
+ if cmd == 'pause':
|
|
|
|
|
+ # 暂停执行
|
|
|
|
|
+ print("\n⏸️ 正在暂停执行...")
|
|
|
if current_trace_id:
|
|
if current_trace_id:
|
|
|
await runner.stop(current_trace_id)
|
|
await runner.stop(current_trace_id)
|
|
|
|
|
+
|
|
|
|
|
+ # 等待一小段时间让 runner 处理 stop 信号
|
|
|
await asyncio.sleep(0.5)
|
|
await asyncio.sleep(0.5)
|
|
|
|
|
|
|
|
- menu_result = await interactive.show_menu(current_trace_id, current_sequence)
|
|
|
|
|
|
|
+ # 显示交互菜单
|
|
|
|
|
+ menu_result = await show_interactive_menu(
|
|
|
|
|
+ runner, current_trace_id, current_sequence, store
|
|
|
|
|
+ )
|
|
|
|
|
+
|
|
|
if menu_result["action"] == "stop":
|
|
if menu_result["action"] == "stop":
|
|
|
should_exit = True
|
|
should_exit = True
|
|
|
paused = True
|
|
paused = True
|
|
|
break
|
|
break
|
|
|
- if menu_result["action"] == "continue":
|
|
|
|
|
|
|
+ elif menu_result["action"] == "continue":
|
|
|
|
|
+ # 检查是否有新消息需要插入
|
|
|
new_messages = menu_result.get("messages", [])
|
|
new_messages = menu_result.get("messages", [])
|
|
|
if new_messages:
|
|
if new_messages:
|
|
|
|
|
+ # 有干预消息,需要重新启动循环
|
|
|
initial_messages = new_messages
|
|
initial_messages = new_messages
|
|
|
after_seq = menu_result.get("after_sequence")
|
|
after_seq = menu_result.get("after_sequence")
|
|
|
if after_seq is not None:
|
|
if after_seq is not None:
|
|
|
- run_config.after_sequence = after_seq
|
|
|
|
|
|
|
+ config.after_sequence = after_seq
|
|
|
|
|
+ paused = True
|
|
|
|
|
+ break
|
|
|
else:
|
|
else:
|
|
|
|
|
+ # 没有新消息,需要重启执行
|
|
|
initial_messages = []
|
|
initial_messages = []
|
|
|
- run_config.after_sequence = None
|
|
|
|
|
- paused = True
|
|
|
|
|
- break
|
|
|
|
|
|
|
+ config.after_sequence = None
|
|
|
|
|
+ paused = True
|
|
|
|
|
+ break
|
|
|
|
|
|
|
|
- elif cmd == "quit":
|
|
|
|
|
- logger.info("\n🛑 用户请求停止...")
|
|
|
|
|
|
|
+ elif cmd == 'quit':
|
|
|
|
|
+ print("\n🛑 用户请求停止...")
|
|
|
if current_trace_id:
|
|
if current_trace_id:
|
|
|
await runner.stop(current_trace_id)
|
|
await runner.stop(current_trace_id)
|
|
|
should_exit = True
|
|
should_exit = True
|
|
|
break
|
|
break
|
|
|
|
|
|
|
|
|
|
+ # 处理 Trace 对象(整体状态变化)
|
|
|
if isinstance(item, Trace):
|
|
if isinstance(item, Trace):
|
|
|
current_trace_id = item.trace_id
|
|
current_trace_id = item.trace_id
|
|
|
if item.status == "running":
|
|
if item.status == "running":
|
|
|
- logger.info(f"[Trace] 开始: {item.trace_id[:8]}...")
|
|
|
|
|
|
|
+ print(f"[Trace] 开始: {item.trace_id[:8]}...")
|
|
|
elif item.status == "completed":
|
|
elif item.status == "completed":
|
|
|
- logger.info("\n[Trace] ✅ 完成")
|
|
|
|
|
- logger.info(f" - Total messages: {item.total_messages}")
|
|
|
|
|
- logger.info(f" - Total tokens: {item.total_tokens}")
|
|
|
|
|
- logger.info(f" - Total cost: ${item.total_cost:.4f}")
|
|
|
|
|
|
|
+ print(f"\n[Trace] ✅ 完成")
|
|
|
|
|
+ print(f" - Total messages: {item.total_messages}")
|
|
|
|
|
+ print(f" - Total tokens: {item.total_tokens}")
|
|
|
|
|
+ print(f" - Total cost: ${item.total_cost:.4f}")
|
|
|
elif item.status == "failed":
|
|
elif item.status == "failed":
|
|
|
- logger.error(f"\n[Trace] ❌ 失败: {item.error_message}")
|
|
|
|
|
|
|
+ print(f"\n[Trace] ❌ 失败: {item.error_message}")
|
|
|
elif item.status == "stopped":
|
|
elif item.status == "stopped":
|
|
|
- logger.info("\n[Trace] ⏸️ 已停止")
|
|
|
|
|
|
|
+ print(f"\n[Trace] ⏸️ 已停止")
|
|
|
|
|
+
|
|
|
|
|
+ # 处理 Message 对象(执行过程)
|
|
|
elif isinstance(item, Message):
|
|
elif isinstance(item, Message):
|
|
|
current_sequence = item.sequence
|
|
current_sequence = item.sequence
|
|
|
- _print_message_details(item)
|
|
|
|
|
|
|
|
|
|
if item.role == "assistant":
|
|
if item.role == "assistant":
|
|
|
content = item.content
|
|
content = item.content
|
|
|
if isinstance(content, dict):
|
|
if isinstance(content, dict):
|
|
|
text = content.get("text", "")
|
|
text = content.get("text", "")
|
|
|
tool_calls = content.get("tool_calls")
|
|
tool_calls = content.get("tool_calls")
|
|
|
|
|
+
|
|
|
if text and not tool_calls:
|
|
if text and not tool_calls:
|
|
|
|
|
+ # 纯文本回复(最终响应)
|
|
|
final_response = text
|
|
final_response = text
|
|
|
|
|
+ print(f"\n[Response] Agent 回复:")
|
|
|
|
|
+ print(text)
|
|
|
|
|
+ elif text:
|
|
|
|
|
+ preview = text[:150] + "..." if len(text) > 150 else text
|
|
|
|
|
+ print(f"[Assistant] {preview}")
|
|
|
|
|
+
|
|
|
|
|
+ if tool_calls:
|
|
|
|
|
+ for tc in tool_calls:
|
|
|
|
|
+ tool_name = tc.get("function", {}).get("name", "unknown")
|
|
|
|
|
+ print(f"[Tool Call] 🛠️ {tool_name}")
|
|
|
|
|
+
|
|
|
|
|
+ elif item.role == "tool":
|
|
|
|
|
+ content = item.content
|
|
|
|
|
+ if isinstance(content, dict):
|
|
|
|
|
+ tool_name = content.get("tool_name", "unknown")
|
|
|
|
|
+ print(f"[Tool Result] ✅ {tool_name}")
|
|
|
|
|
+ if item.description:
|
|
|
|
|
+ desc = item.description[:80] if len(item.description) > 80 else item.description
|
|
|
|
|
+ print(f" {desc}...")
|
|
|
|
|
+
|
|
|
except Exception as e:
|
|
except Exception as e:
|
|
|
- logger.error(f"\n执行出错: {e}")
|
|
|
|
|
- logger.exception("Exception details:")
|
|
|
|
|
|
|
+ print(f"\n执行出错: {e}")
|
|
|
|
|
+ import traceback
|
|
|
|
|
+ traceback.print_exc()
|
|
|
|
|
|
|
|
|
|
+ # paused → 菜单已在暂停时内联显示过
|
|
|
if paused:
|
|
if paused:
|
|
|
if should_exit:
|
|
if should_exit:
|
|
|
break
|
|
break
|
|
|
continue
|
|
continue
|
|
|
|
|
|
|
|
|
|
+ # quit → 直接退出
|
|
|
if should_exit:
|
|
if should_exit:
|
|
|
break
|
|
break
|
|
|
|
|
|
|
|
|
|
+ # Runner 退出(完成/失败/停止/异常)→ 显示交互菜单
|
|
|
if current_trace_id:
|
|
if current_trace_id:
|
|
|
- menu_result = await interactive.show_menu(current_trace_id, current_sequence)
|
|
|
|
|
|
|
+ menu_result = await show_interactive_menu(
|
|
|
|
|
+ runner, current_trace_id, current_sequence, store
|
|
|
|
|
+ )
|
|
|
|
|
+
|
|
|
if menu_result["action"] == "stop":
|
|
if menu_result["action"] == "stop":
|
|
|
break
|
|
break
|
|
|
- if menu_result["action"] == "continue":
|
|
|
|
|
|
|
+ elif menu_result["action"] == "continue":
|
|
|
new_messages = menu_result.get("messages", [])
|
|
new_messages = menu_result.get("messages", [])
|
|
|
if new_messages:
|
|
if new_messages:
|
|
|
initial_messages = new_messages
|
|
initial_messages = new_messages
|
|
|
- run_config.after_sequence = menu_result.get("after_sequence")
|
|
|
|
|
|
|
+ config.after_sequence = menu_result.get("after_sequence")
|
|
|
else:
|
|
else:
|
|
|
initial_messages = []
|
|
initial_messages = []
|
|
|
- run_config.after_sequence = None
|
|
|
|
|
|
|
+ config.after_sequence = None
|
|
|
continue
|
|
continue
|
|
|
break
|
|
break
|
|
|
|
|
|
|
|
except KeyboardInterrupt:
|
|
except KeyboardInterrupt:
|
|
|
- logger.info("\n\n用户中断 (Ctrl+C)")
|
|
|
|
|
|
|
+ print("\n\n用户中断 (Ctrl+C)")
|
|
|
if current_trace_id:
|
|
if current_trace_id:
|
|
|
await runner.stop(current_trace_id)
|
|
await runner.stop(current_trace_id)
|
|
|
- finally:
|
|
|
|
|
- if current_trace_id:
|
|
|
|
|
- try:
|
|
|
|
|
- html_path = store.base_path / current_trace_id / "messages.html"
|
|
|
|
|
- await trace_to_html(current_trace_id, html_path, base_path=str(store.base_path))
|
|
|
|
|
- logger.info(f"\n✓ Messages 可视化已保存: {html_path}")
|
|
|
|
|
- except Exception as e:
|
|
|
|
|
- logger.error(f"\n⚠ 生成 HTML 失败: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
+ # 6. 输出结果
|
|
|
if final_response:
|
|
if final_response:
|
|
|
- logger.info("")
|
|
|
|
|
- logger.info("=" * 60)
|
|
|
|
|
- logger.info("Agent 响应:")
|
|
|
|
|
- logger.info("=" * 60)
|
|
|
|
|
- logger.info(final_response)
|
|
|
|
|
- logger.info("=" * 60)
|
|
|
|
|
- logger.info("")
|
|
|
|
|
-
|
|
|
|
|
|
|
+ print()
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+ print("Agent 响应:")
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+ print(final_response)
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+ print()
|
|
|
|
|
+
|
|
|
|
|
+ # 7. 保存结果
|
|
|
output_file = output_dir / "result.txt"
|
|
output_file = output_dir / "result.txt"
|
|
|
- with open(output_file, "w", encoding="utf-8") as f:
|
|
|
|
|
|
|
+ with open(output_file, 'w', encoding='utf-8') as f:
|
|
|
f.write(final_response)
|
|
f.write(final_response)
|
|
|
|
|
|
|
|
- logger.info(f"✓ 结果已保存到: {output_file}")
|
|
|
|
|
- logger.info("")
|
|
|
|
|
|
|
+ print(f"✓ 结果已保存到: {output_file}")
|
|
|
|
|
+ print()
|
|
|
|
|
|
|
|
|
|
+ # 可视化提示
|
|
|
if current_trace_id:
|
|
if current_trace_id:
|
|
|
- html_path = store.base_path / current_trace_id / "messages.html"
|
|
|
|
|
- logger.info("=" * 60)
|
|
|
|
|
- logger.info("可视化:")
|
|
|
|
|
- logger.info("=" * 60)
|
|
|
|
|
- logger.info(f"1. 本地 HTML: {html_path}")
|
|
|
|
|
- logger.info("")
|
|
|
|
|
- logger.info("2. API Server:")
|
|
|
|
|
- logger.info(" python3 api_server.py")
|
|
|
|
|
- logger.info(" http://localhost:8000/api/traces")
|
|
|
|
|
- logger.info("")
|
|
|
|
|
- logger.info(f"3. Trace ID: {current_trace_id}")
|
|
|
|
|
- logger.info("=" * 60)
|
|
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+ print("可视化 Step Tree:")
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+ print("1. 启动 API Server:")
|
|
|
|
|
+ print(" python3 api_server.py")
|
|
|
|
|
+ print()
|
|
|
|
|
+ print("2. 浏览器访问:")
|
|
|
|
|
+ print(" http://localhost:8000/api/traces")
|
|
|
|
|
+ print()
|
|
|
|
|
+ print(f"3. Trace ID: {current_trace_id}")
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if __name__ == "__main__":
|