|
@@ -1,5 +1,13 @@
|
|
|
"""
|
|
"""
|
|
|
-新搜索测试 - 测试 Research Agent 与 Knowledge Manager 的 IM 通信
|
|
|
|
|
|
|
+ToolHub 工具测试流程 — mini_restore
|
|
|
|
|
+
|
|
|
|
|
+精简版运行脚本,仅测试 ToolHub 搜索和调用。
|
|
|
|
|
+不启用浏览器、知识管理等复杂功能。
|
|
|
|
|
+
|
|
|
|
|
+功能:
|
|
|
|
|
+1. 使用框架提供的 InteractiveController
|
|
|
|
|
+2. 支持命令行交互('p' 暂停,'q' 退出)
|
|
|
|
|
+3. 支持通过 --trace <ID> 恢复已有 Trace 继续执行
|
|
|
"""
|
|
"""
|
|
|
|
|
|
|
|
import argparse
|
|
import argparse
|
|
@@ -8,8 +16,13 @@ import sys
|
|
|
import asyncio
|
|
import asyncio
|
|
|
from pathlib import Path
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
|
|
+# Clash Verge TUN 模式兼容:禁止 httpx/urllib 自动检测系统 HTTP 代理
|
|
|
os.environ.setdefault("no_proxy", "*")
|
|
os.environ.setdefault("no_proxy", "*")
|
|
|
|
|
|
|
|
|
|
+# ToolHub 指向本地服务(tool_agent)
|
|
|
|
|
+os.environ.setdefault("TOOLHUB_BASE_URL", "http://localhost:8001")
|
|
|
|
|
+
|
|
|
|
|
+# 添加项目根目录到 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
|
|
@@ -17,189 +30,340 @@ load_dotenv()
|
|
|
|
|
|
|
|
from agent.llm.prompts import SimplePrompt
|
|
from agent.llm.prompts import SimplePrompt
|
|
|
from agent.core.runner import AgentRunner, RunConfig
|
|
from agent.core.runner import AgentRunner, RunConfig
|
|
|
-from agent.trace import FileSystemTraceStore, Trace, Message
|
|
|
|
|
|
|
+from agent.trace import (
|
|
|
|
|
+ FileSystemTraceStore,
|
|
|
|
|
+ Trace,
|
|
|
|
|
+ Message,
|
|
|
|
|
+)
|
|
|
from agent.llm import create_qwen_llm_call
|
|
from agent.llm import create_qwen_llm_call
|
|
|
from agent.cli import InteractiveController
|
|
from agent.cli import InteractiveController
|
|
|
from agent.utils import setup_logging
|
|
from agent.utils import setup_logging
|
|
|
-from agent.tools.builtin.browser.baseClass import init_browser_session, kill_browser_session
|
|
|
|
|
|
|
|
|
|
-from config import (
|
|
|
|
|
- RUN_CONFIG, SKILLS_DIR, TRACE_STORE_PATH, DEBUG, LOG_LEVEL, LOG_FILE,
|
|
|
|
|
- BROWSER_TYPE, HEADLESS, OUTPUT_DIR,
|
|
|
|
|
- IM_ENABLED, IM_CONTACT_ID, IM_SERVER_URL, IM_WINDOW_MODE, IM_NOTIFY_INTERVAL,
|
|
|
|
|
- KNOWLEDGE_MANAGER_ENABLED, KNOWLEDGE_MANAGER_CONTACT_ID,
|
|
|
|
|
-)
|
|
|
|
|
|
|
+# 导入 ToolHub 工具(触发 @tool 注册)
|
|
|
|
|
+from agent.tools.builtin.toolhub import toolhub_health, toolhub_search, toolhub_call # noqa: F401
|
|
|
|
|
+
|
|
|
|
|
+# 导入项目配置
|
|
|
|
|
+from config import RUN_CONFIG, SKILLS_DIR, TRACE_STORE_PATH, DEBUG, LOG_LEVEL, LOG_FILE, INPUT_DIR, OUTPUT_DIR
|
|
|
|
|
|
|
|
|
|
|
|
|
async def main():
|
|
async def main():
|
|
|
- parser = argparse.ArgumentParser(description="新搜索测试(KM 通信)")
|
|
|
|
|
- parser.add_argument("--trace", type=str, default=None, help="恢复 Trace ID")
|
|
|
|
|
|
|
+ # 解析命令行参数
|
|
|
|
|
+ parser = argparse.ArgumentParser(description="ToolHub 工具测试 (mini_restore)")
|
|
|
|
|
+ parser.add_argument(
|
|
|
|
|
+ "--trace", type=str, default=None,
|
|
|
|
|
+ help="已有的 Trace ID,用于恢复继续执行(不指定则新建)",
|
|
|
|
|
+ )
|
|
|
|
|
+ parser.add_argument(
|
|
|
|
|
+ "--task", type=str, default=None,
|
|
|
|
|
+ help="自定义任务描述(覆盖 prompt 中的默认任务)",
|
|
|
|
|
+ )
|
|
|
args = parser.parse_args()
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
|
|
+ # 路径配置
|
|
|
base_dir = Path(__file__).parent
|
|
base_dir = Path(__file__).parent
|
|
|
project_root = base_dir.parent.parent
|
|
project_root = base_dir.parent.parent
|
|
|
- prompt_path = base_dir / "new_search.prompt"
|
|
|
|
|
|
|
+ prompt_path = base_dir / "toolhub_test.prompt"
|
|
|
output_dir = project_root / OUTPUT_DIR
|
|
output_dir = project_root / OUTPUT_DIR
|
|
|
output_dir.mkdir(parents=True, exist_ok=True)
|
|
output_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
|
|
- # 1. 日志
|
|
|
|
|
|
|
+ # 1. 配置日志
|
|
|
setup_logging(level=LOG_LEVEL, file=LOG_FILE)
|
|
setup_logging(level=LOG_LEVEL, file=LOG_FILE)
|
|
|
|
|
|
|
|
- # 2. Prompt
|
|
|
|
|
- print("1. 加载 prompt...")
|
|
|
|
|
|
|
+ # 2. 加载项目级 presets
|
|
|
|
|
+ print("2. 加载 presets...")
|
|
|
|
|
+ presets_path = base_dir / "presets.json"
|
|
|
|
|
+ if presets_path.exists():
|
|
|
|
|
+ from agent.core.presets import load_presets_from_json
|
|
|
|
|
+ load_presets_from_json(str(presets_path))
|
|
|
|
|
+ print(f" - 已加载项目 presets")
|
|
|
|
|
+ else:
|
|
|
|
|
+ print(f" - 未找到 presets.json,跳过")
|
|
|
|
|
+
|
|
|
|
|
+ # 3. 加载 prompt
|
|
|
|
|
+ print("3. 加载 prompt...")
|
|
|
prompt = SimplePrompt(prompt_path)
|
|
prompt = SimplePrompt(prompt_path)
|
|
|
- messages = prompt.build_messages(output_dir=str(output_dir))
|
|
|
|
|
-
|
|
|
|
|
- # 3. 浏览器
|
|
|
|
|
- print("2. 初始化浏览器...")
|
|
|
|
|
- await init_browser_session(browser_type=BROWSER_TYPE, headless=HEADLESS, url="https://www.google.com/", profile_name="")
|
|
|
|
|
- print(" ✅ 浏览器就绪\n")
|
|
|
|
|
-
|
|
|
|
|
- # 4. IM Client + Knowledge Manager
|
|
|
|
|
- km_task = None
|
|
|
|
|
- if IM_ENABLED:
|
|
|
|
|
- from agent.tools.builtin.im.chat import im_setup, im_open_window
|
|
|
|
|
- print("3. 初始化 IM Client...")
|
|
|
|
|
- print(f" - 身份: {IM_CONTACT_ID}, 服务器: {IM_SERVER_URL}")
|
|
|
|
|
- result = await im_setup(
|
|
|
|
|
- contact_id=IM_CONTACT_ID,
|
|
|
|
|
- server_url=IM_SERVER_URL,
|
|
|
|
|
- notify_interval=IM_NOTIFY_INTERVAL,
|
|
|
|
|
- )
|
|
|
|
|
- print(f" ✅ {result.output}")
|
|
|
|
|
-
|
|
|
|
|
- if IM_WINDOW_MODE:
|
|
|
|
|
- window_result = await im_open_window(contact_id=IM_CONTACT_ID)
|
|
|
|
|
- print(f" ✅ {window_result.output}\n")
|
|
|
|
|
-
|
|
|
|
|
- if KNOWLEDGE_MANAGER_ENABLED:
|
|
|
|
|
- print("4. 启动 Knowledge Manager...")
|
|
|
|
|
- print(f" - Contact ID: {KNOWLEDGE_MANAGER_CONTACT_ID}")
|
|
|
|
|
- try:
|
|
|
|
|
- sys.path.insert(0, str(Path(__file__).parent.parent.parent / "knowhub"))
|
|
|
|
|
- from agents.knowledge_manager import start_knowledge_manager
|
|
|
|
|
-
|
|
|
|
|
- km_task = asyncio.create_task(start_knowledge_manager(
|
|
|
|
|
- contact_id=KNOWLEDGE_MANAGER_CONTACT_ID,
|
|
|
|
|
- server_url=IM_SERVER_URL,
|
|
|
|
|
- chat_id="main"
|
|
|
|
|
- ))
|
|
|
|
|
- # 等待一下让 KM 连接完成
|
|
|
|
|
- await asyncio.sleep(2)
|
|
|
|
|
- print(f" ✅ Knowledge Manager 已启动\n")
|
|
|
|
|
- except Exception as e:
|
|
|
|
|
- print(f" ⚠️ 启动失败: {e}\n")
|
|
|
|
|
|
|
|
|
|
- # 5. Agent Runner
|
|
|
|
|
|
|
+ # 4. 构建任务消息
|
|
|
|
|
+ print("4. 构建任务消息...")
|
|
|
|
|
+ print(f" - 输入目录: {INPUT_DIR}")
|
|
|
|
|
+ print(f" - 输出目录: {OUTPUT_DIR}")
|
|
|
|
|
+
|
|
|
|
|
+ if args.task:
|
|
|
|
|
+ # 使用命令行自定义任务
|
|
|
|
|
+ messages = prompt.build_messages(input_dir=INPUT_DIR, output_dir=OUTPUT_DIR)
|
|
|
|
|
+ # 替换最后一条 user 消息为自定义任务
|
|
|
|
|
+ for i in range(len(messages) - 1, -1, -1):
|
|
|
|
|
+ if messages[i].get("role") == "user":
|
|
|
|
|
+ messages[i]["content"] = args.task
|
|
|
|
|
+ break
|
|
|
|
|
+ print(f" - 自定义任务: {args.task[:80]}...")
|
|
|
|
|
+ else:
|
|
|
|
|
+ messages = prompt.build_messages(input_dir=INPUT_DIR, output_dir=OUTPUT_DIR)
|
|
|
|
|
+
|
|
|
|
|
+ # 5. 创建 Agent Runner(无浏览器)
|
|
|
print("5. 创建 Agent Runner...")
|
|
print("5. 创建 Agent Runner...")
|
|
|
|
|
+ print(f" - Skills 目录: {SKILLS_DIR}")
|
|
|
|
|
+
|
|
|
|
|
+ # 从 prompt 的 frontmatter 中提取模型配置(优先于 config.py)
|
|
|
prompt_model = prompt.config.get("model", None)
|
|
prompt_model = prompt.config.get("model", None)
|
|
|
- model_for_llm = prompt_model or RUN_CONFIG.model
|
|
|
|
|
- print(f" - 模型: {model_for_llm}")
|
|
|
|
|
|
|
+ if prompt_model:
|
|
|
|
|
+ model_for_llm = prompt_model
|
|
|
|
|
+ print(f" - 模型 (from prompt): {model_for_llm}")
|
|
|
|
|
+ else:
|
|
|
|
|
+ model_for_llm = RUN_CONFIG.model
|
|
|
|
|
+ print(f" - 模型 (from config): {model_for_llm}")
|
|
|
|
|
|
|
|
store = FileSystemTraceStore(base_path=TRACE_STORE_PATH)
|
|
store = FileSystemTraceStore(base_path=TRACE_STORE_PATH)
|
|
|
runner = AgentRunner(
|
|
runner = AgentRunner(
|
|
|
trace_store=store,
|
|
trace_store=store,
|
|
|
llm_call=create_qwen_llm_call(model=model_for_llm),
|
|
llm_call=create_qwen_llm_call(model=model_for_llm),
|
|
|
skills_dir=SKILLS_DIR,
|
|
skills_dir=SKILLS_DIR,
|
|
|
- debug=DEBUG,
|
|
|
|
|
- logger_name="agents.research_agent"
|
|
|
|
|
|
|
+ debug=DEBUG
|
|
|
)
|
|
)
|
|
|
|
|
|
|
|
- interactive = InteractiveController(runner=runner, store=store, enable_stdin_check=True)
|
|
|
|
|
|
|
+ # 6. 创建交互控制器
|
|
|
|
|
+ interactive = InteractiveController(
|
|
|
|
|
+ runner=runner,
|
|
|
|
|
+ store=store,
|
|
|
|
|
+ enable_stdin_check=True
|
|
|
|
|
+ )
|
|
|
runner.stdin_check = interactive.check_stdin
|
|
runner.stdin_check = interactive.check_stdin
|
|
|
|
|
|
|
|
- # 6. 执行
|
|
|
|
|
|
|
+ # 7. 任务信息
|
|
|
task_name = RUN_CONFIG.name or base_dir.name
|
|
task_name = RUN_CONFIG.name or base_dir.name
|
|
|
print("=" * 60)
|
|
print("=" * 60)
|
|
|
print(f"{task_name}")
|
|
print(f"{task_name}")
|
|
|
print("=" * 60)
|
|
print("=" * 60)
|
|
|
- print("💡 输入 'p' 暂停,'q' 退出")
|
|
|
|
|
|
|
+ print("💡 交互提示:")
|
|
|
|
|
+ print(" - 执行过程中输入 'p' 或 'pause' 暂停并进入交互模式")
|
|
|
|
|
+ print(" - 执行过程中输入 'q' 或 'quit' 停止执行")
|
|
|
print("=" * 60)
|
|
print("=" * 60)
|
|
|
print()
|
|
print()
|
|
|
|
|
|
|
|
- run_config = RUN_CONFIG
|
|
|
|
|
- current_trace_id = args.trace
|
|
|
|
|
- current_sequence = 0
|
|
|
|
|
|
|
+ # 8. 判断是新建还是恢复
|
|
|
|
|
+ resume_trace_id = args.trace
|
|
|
|
|
+ if resume_trace_id:
|
|
|
|
|
+ existing_trace = await store.get_trace(resume_trace_id)
|
|
|
|
|
+ if not existing_trace:
|
|
|
|
|
+ print(f"\n错误: Trace 不存在: {resume_trace_id}")
|
|
|
|
|
+ sys.exit(1)
|
|
|
|
|
+ print(f"恢复已有 Trace: {resume_trace_id[:8]}...")
|
|
|
|
|
+ print(f" - 状态: {existing_trace.status}")
|
|
|
|
|
+ print(f" - 消息数: {existing_trace.total_messages}")
|
|
|
|
|
+ else:
|
|
|
|
|
+ print(f"启动新 Agent...")
|
|
|
|
|
|
|
|
- # 注入 IM 配置到 context(用于周期性通知检查)
|
|
|
|
|
- if IM_ENABLED:
|
|
|
|
|
- run_config.context["im_config"] = {
|
|
|
|
|
- "contact_id": IM_CONTACT_ID,
|
|
|
|
|
- "chat_id": "main"
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ print()
|
|
|
|
|
|
|
|
- if current_trace_id:
|
|
|
|
|
- run_config.trace_id = current_trace_id
|
|
|
|
|
- initial_messages = None
|
|
|
|
|
- else:
|
|
|
|
|
- initial_messages = messages
|
|
|
|
|
|
|
+ final_response = ""
|
|
|
|
|
+ current_trace_id = resume_trace_id
|
|
|
|
|
+ current_sequence = 0
|
|
|
|
|
+ should_exit = False
|
|
|
|
|
|
|
|
try:
|
|
try:
|
|
|
- async for item in runner.run(messages=initial_messages, config=run_config):
|
|
|
|
|
- cmd = interactive.check_stdin()
|
|
|
|
|
- if cmd == 'quit':
|
|
|
|
|
- print("\n🛑 停止...")
|
|
|
|
|
- if current_trace_id:
|
|
|
|
|
- await runner.stop(current_trace_id)
|
|
|
|
|
- break
|
|
|
|
|
- elif cmd == 'pause':
|
|
|
|
|
- print("\n⏸️ 暂停...")
|
|
|
|
|
- if current_trace_id:
|
|
|
|
|
- await runner.stop(current_trace_id)
|
|
|
|
|
|
|
+ # 配置
|
|
|
|
|
+ run_config = RUN_CONFIG
|
|
|
|
|
+ if resume_trace_id:
|
|
|
|
|
+ initial_messages = None
|
|
|
|
|
+ run_config.trace_id = resume_trace_id
|
|
|
|
|
+ else:
|
|
|
|
|
+ initial_messages = messages
|
|
|
|
|
+ run_config.name = f"{task_name}:测试任务"
|
|
|
|
|
+
|
|
|
|
|
+ while not should_exit:
|
|
|
|
|
+ if current_trace_id:
|
|
|
|
|
+ run_config.trace_id = current_trace_id
|
|
|
|
|
+
|
|
|
|
|
+ final_response = ""
|
|
|
|
|
+
|
|
|
|
|
+ # 如果是恢复 trace,进入交互菜单
|
|
|
|
|
+ if current_trace_id and initial_messages is None:
|
|
|
|
|
+ check_trace = await store.get_trace(current_trace_id)
|
|
|
|
|
+ if check_trace:
|
|
|
|
|
+ if check_trace.status == "completed":
|
|
|
|
|
+ print(f"\n[Trace] ✅ 已完成")
|
|
|
|
|
+ print(f" - Total messages: {check_trace.total_messages}")
|
|
|
|
|
+ print(f" - Total cost: ${check_trace.total_cost:.4f}")
|
|
|
|
|
+ elif check_trace.status == "failed":
|
|
|
|
|
+ print(f"\n[Trace] ❌ 已失败: {check_trace.error_message}")
|
|
|
|
|
+ elif check_trace.status == "stopped":
|
|
|
|
|
+ print(f"\n[Trace] ⏸️ 已停止")
|
|
|
|
|
+ print(f" - Total messages: {check_trace.total_messages}")
|
|
|
|
|
+ else:
|
|
|
|
|
+ print(f"\n[Trace] 📊 状态: {check_trace.status}")
|
|
|
|
|
+ print(f" - Total messages: {check_trace.total_messages}")
|
|
|
|
|
+
|
|
|
|
|
+ current_sequence = check_trace.head_sequence
|
|
|
|
|
+
|
|
|
|
|
+ menu_result = await interactive.show_menu(current_trace_id, current_sequence)
|
|
|
|
|
+
|
|
|
|
|
+ if menu_result["action"] == "stop":
|
|
|
|
|
+ break
|
|
|
|
|
+ elif menu_result["action"] == "continue":
|
|
|
|
|
+ new_messages = menu_result.get("messages", [])
|
|
|
|
|
+ if new_messages:
|
|
|
|
|
+ initial_messages = new_messages
|
|
|
|
|
+ run_config.after_sequence = menu_result.get("after_sequence")
|
|
|
|
|
+ else:
|
|
|
|
|
+ initial_messages = []
|
|
|
|
|
+ run_config.after_sequence = None
|
|
|
|
|
+ continue
|
|
|
|
|
+ break
|
|
|
|
|
+
|
|
|
|
|
+ if initial_messages is None:
|
|
|
|
|
+ initial_messages = []
|
|
|
|
|
+
|
|
|
|
|
+ print(f"{'▶️ 开始执行...' if not current_trace_id else '▶️ 继续执行...'}")
|
|
|
|
|
+
|
|
|
|
|
+ # 执行 Agent
|
|
|
|
|
+ paused = False
|
|
|
|
|
+ try:
|
|
|
|
|
+ async for item in runner.run(messages=initial_messages, config=run_config):
|
|
|
|
|
+ # 检查用户中断
|
|
|
|
|
+ cmd = interactive.check_stdin()
|
|
|
|
|
+ if cmd == 'pause':
|
|
|
|
|
+ print("\n⏸️ 正在暂停执行...")
|
|
|
|
|
+ if current_trace_id:
|
|
|
|
|
+ await runner.stop(current_trace_id)
|
|
|
|
|
+ await asyncio.sleep(0.5)
|
|
|
|
|
+
|
|
|
|
|
+ menu_result = await interactive.show_menu(current_trace_id, current_sequence)
|
|
|
|
|
+
|
|
|
|
|
+ if menu_result["action"] == "stop":
|
|
|
|
|
+ should_exit = True
|
|
|
|
|
+ paused = True
|
|
|
|
|
+ break
|
|
|
|
|
+ elif menu_result["action"] == "continue":
|
|
|
|
|
+ new_messages = menu_result.get("messages", [])
|
|
|
|
|
+ if new_messages:
|
|
|
|
|
+ initial_messages = new_messages
|
|
|
|
|
+ after_seq = menu_result.get("after_sequence")
|
|
|
|
|
+ if after_seq is not None:
|
|
|
|
|
+ run_config.after_sequence = after_seq
|
|
|
|
|
+ paused = True
|
|
|
|
|
+ break
|
|
|
|
|
+ else:
|
|
|
|
|
+ initial_messages = []
|
|
|
|
|
+ run_config.after_sequence = None
|
|
|
|
|
+ paused = True
|
|
|
|
|
+ break
|
|
|
|
|
+
|
|
|
|
|
+ elif cmd == 'quit':
|
|
|
|
|
+ print("\n🛑 用户请求停止...")
|
|
|
|
|
+ if current_trace_id:
|
|
|
|
|
+ await runner.stop(current_trace_id)
|
|
|
|
|
+ should_exit = True
|
|
|
|
|
+ break
|
|
|
|
|
+
|
|
|
|
|
+ # 处理 Trace 对象
|
|
|
|
|
+ if isinstance(item, Trace):
|
|
|
|
|
+ current_trace_id = item.trace_id
|
|
|
|
|
+ if item.status == "running":
|
|
|
|
|
+ print(f"[Trace] 开始: {item.trace_id[:8]}...")
|
|
|
|
|
+ elif item.status == "completed":
|
|
|
|
|
+ print(f"\n[Trace] ✅ 完成")
|
|
|
|
|
+ print(f" - Total messages: {item.total_messages}")
|
|
|
|
|
+ print(f" - Total cost: ${item.total_cost:.4f}")
|
|
|
|
|
+ elif item.status == "failed":
|
|
|
|
|
+ print(f"\n[Trace] ❌ 失败: {item.error_message}")
|
|
|
|
|
+ elif item.status == "stopped":
|
|
|
|
|
+ print(f"\n[Trace] ⏸️ 已停止")
|
|
|
|
|
+
|
|
|
|
|
+ # 处理 Message 对象
|
|
|
|
|
+ elif isinstance(item, Message):
|
|
|
|
|
+ current_sequence = item.sequence
|
|
|
|
|
+
|
|
|
|
|
+ if item.role == "assistant":
|
|
|
|
|
+ content = item.content
|
|
|
|
|
+ if isinstance(content, dict):
|
|
|
|
|
+ text = content.get("text", "")
|
|
|
|
|
+ tool_calls = content.get("tool_calls")
|
|
|
|
|
+
|
|
|
|
|
+ if text and not tool_calls:
|
|
|
|
|
+ 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}")
|
|
|
|
|
+
|
|
|
|
|
+ elif item.role == "tool":
|
|
|
|
|
+ content = item.content
|
|
|
|
|
+ tool_name = "unknown"
|
|
|
|
|
+ if isinstance(content, dict):
|
|
|
|
|
+ tool_name = content.get("tool_name", "unknown")
|
|
|
|
|
+
|
|
|
|
|
+ if item.description and item.description != tool_name:
|
|
|
|
|
+ desc = item.description[:80] if len(item.description) > 80 else item.description
|
|
|
|
|
+ print(f"[Tool Result] ✅ {tool_name}: {desc}...")
|
|
|
|
|
+ else:
|
|
|
|
|
+ print(f"[Tool Result] ✅ {tool_name}")
|
|
|
|
|
+
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ print(f"\n执行出错: {e}")
|
|
|
|
|
+ import traceback
|
|
|
|
|
+ traceback.print_exc()
|
|
|
|
|
+
|
|
|
|
|
+ if paused:
|
|
|
|
|
+ if should_exit:
|
|
|
|
|
+ break
|
|
|
|
|
+ continue
|
|
|
|
|
+
|
|
|
|
|
+ if should_exit:
|
|
|
break
|
|
break
|
|
|
|
|
|
|
|
- if isinstance(item, Trace):
|
|
|
|
|
- current_trace_id = item.trace_id
|
|
|
|
|
- if item.status == "running":
|
|
|
|
|
- print(f"[Trace] 开始: {item.trace_id[:8]}...")
|
|
|
|
|
- elif item.status == "completed":
|
|
|
|
|
- print(f"\n[Trace] ✅ 完成 (消息: {item.total_messages}, 费用: ${item.total_cost:.4f})")
|
|
|
|
|
- elif item.status == "failed":
|
|
|
|
|
- print(f"\n[Trace] ❌ 失败: {item.error_message}")
|
|
|
|
|
-
|
|
|
|
|
- elif isinstance(item, Message):
|
|
|
|
|
- current_sequence = item.sequence
|
|
|
|
|
- if item.role == "assistant":
|
|
|
|
|
- content = item.content
|
|
|
|
|
- if isinstance(content, dict):
|
|
|
|
|
- text = content.get("text", "")
|
|
|
|
|
- tool_calls = content.get("tool_calls")
|
|
|
|
|
- if text and not tool_calls:
|
|
|
|
|
- print(f"\n[Response] {text}")
|
|
|
|
|
- elif text:
|
|
|
|
|
- preview = text[:150] + "..." if len(text) > 150 else text
|
|
|
|
|
- print(f"[Assistant] {preview}")
|
|
|
|
|
-
|
|
|
|
|
- elif item.role == "tool":
|
|
|
|
|
- content = item.content
|
|
|
|
|
- tool_name = content.get("tool_name", "unknown") if isinstance(content, dict) else "unknown"
|
|
|
|
|
- desc = item.description or ""
|
|
|
|
|
- if desc and desc != tool_name:
|
|
|
|
|
- desc = desc[:80]
|
|
|
|
|
- print(f"[Tool] ✅ {tool_name}: {desc}...")
|
|
|
|
|
|
|
+ # Runner 退出后显示交互菜单
|
|
|
|
|
+ if current_trace_id:
|
|
|
|
|
+ menu_result = await interactive.show_menu(current_trace_id, current_sequence)
|
|
|
|
|
+
|
|
|
|
|
+ if menu_result["action"] == "stop":
|
|
|
|
|
+ break
|
|
|
|
|
+ elif menu_result["action"] == "continue":
|
|
|
|
|
+ new_messages = menu_result.get("messages", [])
|
|
|
|
|
+ if new_messages:
|
|
|
|
|
+ initial_messages = new_messages
|
|
|
|
|
+ run_config.after_sequence = menu_result.get("after_sequence")
|
|
|
else:
|
|
else:
|
|
|
- print(f"[Tool] ✅ {tool_name}")
|
|
|
|
|
|
|
+ initial_messages = []
|
|
|
|
|
+ run_config.after_sequence = None
|
|
|
|
|
+ continue
|
|
|
|
|
+ break
|
|
|
|
|
|
|
|
except KeyboardInterrupt:
|
|
except KeyboardInterrupt:
|
|
|
print("\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 km_task and not km_task.done():
|
|
|
|
|
- print("正在关闭 Knowledge Manager...")
|
|
|
|
|
- km_task.cancel()
|
|
|
|
|
- try:
|
|
|
|
|
- await km_task
|
|
|
|
|
- except asyncio.CancelledError:
|
|
|
|
|
- pass
|
|
|
|
|
|
|
|
|
|
- try:
|
|
|
|
|
- await kill_browser_session()
|
|
|
|
|
- except Exception:
|
|
|
|
|
- pass
|
|
|
|
|
|
|
+ # 输出结果
|
|
|
|
|
+ if final_response:
|
|
|
|
|
+ print()
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+ print("Agent 响应:")
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+ print(final_response)
|
|
|
|
|
+ print("=" * 60)
|
|
|
|
|
+ print()
|
|
|
|
|
+
|
|
|
|
|
+ output_file = output_dir / "result.txt"
|
|
|
|
|
+ with open(output_file, 'w', encoding='utf-8') as f:
|
|
|
|
|
+ f.write(final_response)
|
|
|
|
|
+
|
|
|
|
|
+ print(f"✓ 结果已保存到: {output_file}")
|
|
|
|
|
+ print()
|
|
|
|
|
|
|
|
|
|
+ # 可视化提示
|
|
|
if current_trace_id:
|
|
if current_trace_id:
|
|
|
- print(f"\nTrace ID: {current_trace_id}")
|
|
|
|
|
|
|
+ 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__":
|