run_api.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. """
  2. Trace 控制 API — 新建 / 运行 / 停止 / 反思
  3. 提供 POST 端点触发 Agent 执行和控制。需要通过 set_runner() 注入 AgentRunner 实例。
  4. 执行在后台异步进行,客户端通过 WebSocket (/api/traces/{trace_id}/watch) 监听实时更新。
  5. 端点:
  6. POST /api/traces — 新建 Trace 并执行
  7. POST /api/traces/{id}/run — 运行(统一续跑 + 回溯)
  8. POST /api/traces/{id}/stop — 停止运行中的 Trace
  9. POST /api/traces/{id}/reflect — 反思,在 trace 末尾追加反思 prompt 运行,结果追加到 experiences 文件
  10. GET /api/traces/running — 列出正在运行的 Trace
  11. GET /api/experiences — 读取经验文件内容
  12. """
  13. import asyncio
  14. import logging
  15. import os
  16. from typing import Any, Dict, List, Optional
  17. from fastapi import APIRouter, HTTPException
  18. from pydantic import BaseModel, Field
  19. logger = logging.getLogger(__name__)
  20. router = APIRouter(prefix="/api/traces", tags=["run"])
  21. # 经验 API 使用独立 prefix
  22. experiences_router = APIRouter(prefix="/api", tags=["experiences"])
  23. # ===== 全局 Runner(由 api_server.py 注入)=====
  24. _runner = None
  25. _project_environment_resolver = None
  26. def set_runner(runner):
  27. """注入 AgentRunner 实例"""
  28. global _runner
  29. _runner = runner
  30. def set_project_environment_resolver(resolver):
  31. """Inject optional Host adapter; the framework never imports projects."""
  32. global _project_environment_resolver
  33. _project_environment_resolver = resolver
  34. def _get_runner():
  35. if _runner is None:
  36. raise HTTPException(
  37. status_code=503,
  38. detail="AgentRunner not configured. Server is in read-only mode.",
  39. )
  40. return _runner
  41. # ===== Request / Response 模型 =====
  42. class CreateRequest(BaseModel):
  43. """新建执行"""
  44. messages: List[Dict[str, Any]] = Field(
  45. ...,
  46. description="OpenAI SDK 格式的输入消息。可包含 system + user 消息;若无 system 消息则从 skills 自动构建",
  47. )
  48. model: str = Field("gpt-4o", description="模型名称")
  49. temperature: float = Field(0.3)
  50. max_iterations: int = Field(200)
  51. tools: Optional[List[str]] = Field(None, description="工具白名单(None = 全部)")
  52. name: Optional[str] = Field(None, description="任务名称(None = 自动生成)")
  53. uid: Optional[str] = Field(None)
  54. project_name: Optional[str] = Field(None, description="示例项目名称,若提供则动态加载其执行环境")
  55. class TraceRunRequest(BaseModel):
  56. """运行(统一续跑 + 回溯)"""
  57. messages: List[Dict[str, Any]] = Field(
  58. default_factory=list,
  59. description="追加的新消息(可为空,用于重新生成场景)",
  60. )
  61. after_message_id: Optional[str] = Field(
  62. None,
  63. description="从哪条消息后续跑。None = 从末尾续跑,message_id = 从该消息后运行(自动判断续跑/回溯)",
  64. )
  65. class ReflectRequest(BaseModel):
  66. """反思请求"""
  67. focus: Optional[str] = Field(None, description="反思重点(可选)")
  68. class RunResponse(BaseModel):
  69. """操作响应(立即返回,后台执行)"""
  70. trace_id: str
  71. status: str = "started"
  72. message: str = ""
  73. class StopResponse(BaseModel):
  74. """停止响应"""
  75. trace_id: str
  76. status: str # "stopping" | "not_running"
  77. class ReflectResponse(BaseModel):
  78. """反思响应"""
  79. trace_id: str
  80. reflection: str
  81. class CompactResponse(BaseModel):
  82. """压缩响应"""
  83. trace_id: str
  84. previous_count: int
  85. new_count: int
  86. message: str = ""
  87. # ===== 提取审核(见 agent/docs/memory.md 第三节) =====
  88. class PendingExtractionModel(BaseModel):
  89. extraction_id: str
  90. sequence: Optional[int] = None
  91. goal_id: Optional[str] = None
  92. branch_id: Optional[str] = None
  93. payload: Dict[str, Any]
  94. reviewed: bool = False
  95. decision: Optional[str] = None
  96. committed: bool = False
  97. class ListExtractionsResponse(BaseModel):
  98. trace_id: str
  99. count: int
  100. items: List[PendingExtractionModel]
  101. class ReviewRequest(BaseModel):
  102. decision: str = Field(..., description="approve / edit / discard")
  103. edited_payload: Optional[Dict[str, Any]] = Field(
  104. None, description="decision=edit 时必填;只对本次 review 生效"
  105. )
  106. class ReviewResponse(BaseModel):
  107. trace_id: str
  108. extraction_id: str
  109. decision: str
  110. class CommitResponse(BaseModel):
  111. trace_id: str
  112. committed_count: int
  113. failed_count: int
  114. skipped_count: int
  115. committed: List[str]
  116. knowledge_ids: List[str]
  117. failed: List[Dict[str, str]]
  118. skipped: List[str]
  119. # ===== 后台执行 =====
  120. _running_tasks: Dict[str, asyncio.Task] = {}
  121. async def _run_in_background(trace_id: str, messages: List[Dict], config, runner_instance=None):
  122. """后台执行 agent,消费 run() 的所有 yield"""
  123. runner = runner_instance or _get_runner()
  124. try:
  125. async for _item in runner.run(messages=messages, config=config):
  126. pass # WebSocket 广播由 runner 内部的 store 事件驱动
  127. except Exception as e:
  128. logger.error(f"Background run failed for {trace_id}: {e}")
  129. finally:
  130. _running_tasks.pop(trace_id, None)
  131. async def _run_trace_background(runner, messages: List[Dict], config):
  132. """Compatibility wrapper used by reflect/compact background endpoints."""
  133. await _run_in_background(config.trace_id, messages, config, runner_instance=runner)
  134. async def _run_with_trace_signal(
  135. messages: List[Dict], config, trace_id_future: asyncio.Future, runner_instance=None
  136. ):
  137. """后台执行 agent,通过 Future 将 trace_id 传回给等待的 endpoint"""
  138. from agent.trace.models import Trace
  139. runner = runner_instance or _get_runner()
  140. trace_id: Optional[str] = None
  141. try:
  142. async for item in runner.run(messages=messages, config=config):
  143. if isinstance(item, Trace) and not trace_id_future.done():
  144. trace_id = item.trace_id
  145. trace_id_future.set_result(trace_id)
  146. except Exception as e:
  147. if not trace_id_future.done():
  148. trace_id_future.set_exception(e)
  149. logger.error(f"Background run failed: {e}")
  150. finally:
  151. if trace_id:
  152. _running_tasks.pop(trace_id, None)
  153. # ===== 路由 =====
  154. @router.post("", response_model=RunResponse)
  155. async def create_and_run(req: CreateRequest):
  156. """
  157. 新建 Trace 并开始执行
  158. 立即返回 trace_id,后台异步执行。
  159. 通过 WebSocket /api/traces/{trace_id}/watch 监听实时更新。
  160. """
  161. from agent.core.runner import RunConfig
  162. runner = None
  163. config = None
  164. messages = req.messages
  165. if req.project_name:
  166. try:
  167. environment = None
  168. if _project_environment_resolver:
  169. environment = await _project_environment_resolver.resolve(req.project_name, req.messages)
  170. if environment:
  171. # 获取该 example 专属的 runner, 带上下文 messages, 以及默认 config
  172. runner = environment.runner
  173. default_config = environment.default_config
  174. messages = environment.messages
  175. # 合并请求配置和 example 默认配置
  176. config = RunConfig(
  177. model=req.model or default_config.model,
  178. temperature=req.temperature if req.temperature is not None else default_config.temperature,
  179. max_iterations=req.max_iterations or default_config.max_iterations,
  180. tools=req.tools or default_config.tools,
  181. name=req.name or default_config.name,
  182. uid=req.uid or default_config.uid,
  183. enable_research_flow=default_config.enable_research_flow,
  184. context={"project_name": req.project_name}
  185. )
  186. except Exception:
  187. import traceback
  188. logger.error(f"Unexpected error loading project environment for {req.project_name}:\n{traceback.format_exc()}")
  189. if not runner:
  190. _get_runner() # 验证全局默认 Runner 已配置
  191. config = RunConfig(
  192. model=req.model,
  193. temperature=req.temperature,
  194. max_iterations=req.max_iterations,
  195. tools=req.tools,
  196. name=req.name,
  197. uid=req.uid,
  198. context={"project_name": req.project_name} if req.project_name else {}
  199. )
  200. # 启动后台执行,通过 Future 等待 trace_id(Phase 1 完成后即返回)
  201. trace_id_future: asyncio.Future[str] = asyncio.get_running_loop().create_future()
  202. task = asyncio.create_task(
  203. _run_with_trace_signal(messages, config, trace_id_future, runner_instance=runner)
  204. )
  205. trace_id = await trace_id_future
  206. _running_tasks[trace_id] = task
  207. return RunResponse(
  208. trace_id=trace_id,
  209. status="started",
  210. message=f"Execution started. Watch via WebSocket: /api/traces/{trace_id}/watch",
  211. )
  212. async def _cleanup_incomplete_tool_calls(store, trace_id: str, after_sequence: int) -> int:
  213. """
  214. 找到安全的插入点,保证不会把新消息插在一个不完整的工具调用序列中间。
  215. 场景:
  216. 1. after_sequence 刚好是一条带 tool_calls 的 assistant 消息,
  217. 但其部分/全部 tool response 还没生成 → 回退到该 assistant 之前。
  218. 2. after_sequence 是某条 tool response,但同一批 tool_calls 中
  219. 还有其他 response 未生成 → 回退到该 assistant 之前。
  220. 核心逻辑:从 after_sequence 往前找,定位到包含它的那条 assistant 消息,
  221. 检查该 assistant 的所有 tool_calls 是否都有对应的 tool response。
  222. 如果不完整,就把截断点回退到该 assistant 消息之前(即其 parent_sequence)。
  223. Args:
  224. store: TraceStore
  225. trace_id: Trace ID
  226. after_sequence: 用户指定的插入位置
  227. Returns:
  228. 调整后的安全截断点(<= after_sequence)
  229. """
  230. all_messages = await store.get_trace_messages(trace_id)
  231. if not all_messages:
  232. return after_sequence
  233. by_seq = {msg.sequence: msg for msg in all_messages}
  234. target = by_seq.get(after_sequence)
  235. if target is None:
  236. return after_sequence
  237. # 找到"所属的 assistant 消息":
  238. # - 如果 target 本身是 assistant → 就是它
  239. # - 如果 target 是 tool → 沿 parent_sequence 往上找 assistant
  240. assistant_msg = None
  241. if target.role == "assistant":
  242. assistant_msg = target
  243. elif target.role == "tool":
  244. cur = target
  245. while cur and cur.role == "tool":
  246. parent_seq = cur.parent_sequence
  247. cur = by_seq.get(parent_seq) if parent_seq is not None else None
  248. if cur and cur.role == "assistant":
  249. assistant_msg = cur
  250. if assistant_msg is None:
  251. return after_sequence
  252. # 该 assistant 是否带 tool_calls?
  253. content = assistant_msg.content
  254. if not isinstance(content, dict) or not content.get("tool_calls"):
  255. return after_sequence
  256. # 收集所有 tool_call_ids
  257. expected_ids = set()
  258. for tc in content["tool_calls"]:
  259. if isinstance(tc, dict) and tc.get("id"):
  260. expected_ids.add(tc["id"])
  261. if not expected_ids:
  262. return after_sequence
  263. # 查找已有的 tool responses
  264. found_ids = set()
  265. for msg in all_messages:
  266. if msg.role == "tool" and msg.tool_call_id in expected_ids:
  267. found_ids.add(msg.tool_call_id)
  268. missing = expected_ids - found_ids
  269. if not missing:
  270. # 全部 tool response 都在,这是一个完整的序列
  271. return after_sequence
  272. # 不完整 → 回退到 assistant 之前
  273. safe = assistant_msg.parent_sequence
  274. if safe is None:
  275. # assistant 已经是第一条消息,没有更早的位置
  276. safe = assistant_msg.sequence - 1
  277. logger.info(
  278. "检测到不完整的工具调用 (assistant seq=%d, 缺少 %d/%d tool responses),"
  279. "自动回退插入点:%d -> %d",
  280. assistant_msg.sequence, len(missing), len(expected_ids),
  281. after_sequence, safe,
  282. )
  283. return safe
  284. def _parse_sequence_from_message_id(message_id: str) -> int:
  285. """从 message_id 末尾解析 sequence 整数(格式:{trace_id}-{sequence:04d})"""
  286. try:
  287. return int(message_id.rsplit("-", 1)[-1])
  288. except (ValueError, IndexError):
  289. raise HTTPException(
  290. status_code=422,
  291. detail=f"Invalid after_message_id format: {message_id!r}",
  292. )
  293. @router.post("/{trace_id}/run", response_model=RunResponse)
  294. async def run_trace(trace_id: str, req: TraceRunRequest):
  295. """
  296. 运行已有 Trace(统一续跑 + 回溯)
  297. - after_message_id 为 null(或省略):从末尾续跑
  298. - after_message_id 为 message_id 字符串:从该消息后运行(Runner 自动判断续跑/回溯)
  299. - messages 为空 + after_message_id 有值:重新生成(从该位置重跑,不插入新消息)
  300. **自动清理不完整工具调用**:
  301. 如果人工插入 message 的位置打断了一个工具调用过程(assistant 消息有 tool_calls
  302. 但缺少对应的 tool responses),框架会自动检测并调整插入位置,确保不会产生不一致的状态。
  303. """
  304. from agent.core.runner import RunConfig
  305. runner = _get_runner()
  306. # 将 message_id 转换为内部使用的 sequence 整数
  307. after_sequence: Optional[int] = None
  308. if req.after_message_id is not None:
  309. after_sequence = _parse_sequence_from_message_id(req.after_message_id)
  310. # 验证 trace 存在
  311. if runner.trace_store:
  312. trace = await runner.trace_store.get_trace(trace_id)
  313. if not trace:
  314. raise HTTPException(status_code=404, detail=f"Trace not found: {trace_id}")
  315. try:
  316. runner.validate_resume_position(trace, after_sequence)
  317. except ValueError as exc:
  318. raise HTTPException(
  319. status_code=409,
  320. detail=str(exc),
  321. ) from exc
  322. # 自动检查并清理不完整的工具调用
  323. if after_sequence is not None and req.messages:
  324. adjusted_seq = await _cleanup_incomplete_tool_calls(
  325. runner.trace_store, trace_id, after_sequence
  326. )
  327. if adjusted_seq != after_sequence:
  328. logger.info(
  329. f"已自动调整插入位置:{after_sequence} -> {adjusted_seq}"
  330. )
  331. after_sequence = adjusted_seq
  332. # 检查是否已在运行
  333. if trace_id in _running_tasks and not _running_tasks[trace_id].done():
  334. # 竞态窗口修复:task 还没退出,但 store 里 trace 已经是 stopped/failed
  335. # 这发生在 cancel_event 触发后 → store 更新 → task finally 块还未执行之间
  336. # 此时可以安全地强制清除旧 task,允许续跑
  337. store_trace = None
  338. if runner.trace_store:
  339. store_trace = await runner.trace_store.get_trace(trace_id)
  340. if store_trace and store_trace.status in ("stopped", "failed", "incomplete", "completed"):
  341. logger.info(
  342. f"run_trace: task for {trace_id} not done yet but store status={store_trace.status!r}, "
  343. "forcing cleanup to allow resume"
  344. )
  345. _running_tasks[trace_id].cancel()
  346. _running_tasks.pop(trace_id, None)
  347. else:
  348. raise HTTPException(status_code=409, detail="Trace is already running")
  349. # 检测 trace 中是否包含 project_name 环境定义
  350. trace_context = trace.context or {}
  351. project_name = trace_context.get("project_name")
  352. if project_name:
  353. try:
  354. environment = None
  355. if _project_environment_resolver:
  356. environment = await _project_environment_resolver.resolve(project_name)
  357. if environment:
  358. logger.info(f"Trace {trace_id} 绑定了项目 {project_name},动态加载执行环境...")
  359. runner = environment.runner
  360. except Exception:
  361. import traceback
  362. logger.error(f"Unexpected error loading run.py environment for project {project_name} in trace {trace_id}:\n{traceback.format_exc()}")
  363. config = RunConfig(trace_id=trace_id, after_sequence=after_sequence)
  364. # 恢复运行时,将状态从 stopped 改回 running,并广播状态变化
  365. if runner.trace_store and trace_id:
  366. current_trace = await runner.trace_store.get_trace(trace_id)
  367. if current_trace and current_trace.status == "stopped":
  368. await runner.trace_store.update_trace(trace_id, status="running")
  369. # 广播状态变化给前端
  370. from agent.trace.websocket import broadcast_trace_status_changed
  371. await broadcast_trace_status_changed(trace_id, "running")
  372. task = asyncio.create_task(_run_in_background(trace_id, req.messages, config, runner_instance=runner))
  373. _running_tasks[trace_id] = task
  374. mode = "rewind" if after_sequence is not None else "continue"
  375. return RunResponse(
  376. trace_id=trace_id,
  377. status="started",
  378. message=f"Run ({mode}) started. Watch via WebSocket: /api/traces/{trace_id}/watch",
  379. )
  380. @router.post("/{trace_id}/stop", response_model=StopResponse)
  381. async def stop_trace(trace_id: str):
  382. """
  383. 停止运行中的 Trace
  384. 设置取消信号,agent loop 在下一个 LLM 调用前检查并退出。
  385. Trace 状态置为 "stopped"。
  386. """
  387. runner = _get_runner()
  388. # 通过 runner 的 stop 方法设置取消信号
  389. stopped = await runner.stop(trace_id)
  390. if not stopped:
  391. # 检查是否在 _running_tasks 但 runner 不知道(可能已完成)
  392. if trace_id in _running_tasks:
  393. task = _running_tasks[trace_id]
  394. if not task.done():
  395. task.cancel()
  396. _running_tasks.pop(trace_id, None)
  397. return StopResponse(trace_id=trace_id, status="stopping")
  398. return StopResponse(trace_id=trace_id, status="not_running")
  399. return StopResponse(trace_id=trace_id, status="stopping")
  400. @router.post("/{trace_id}/reflect", response_model=ReflectResponse)
  401. async def reflect_trace(trace_id: str, req: ReflectRequest):
  402. """
  403. 触发反思
  404. 通过 force_side_branch="reflection" 触发侧分支多轮 agent 模式,
  405. LLM 可以调用工具(如 knowledge_search, knowledge_save)进行多轮推理。
  406. 反思消息标记为侧分支(branch_type="reflection"),不在主路径上。
  407. """
  408. from agent.core.runner import RunConfig
  409. runner = _get_runner()
  410. if not runner.trace_store:
  411. raise HTTPException(status_code=503, detail="TraceStore not configured")
  412. # 验证 trace 存在
  413. trace = await runner.trace_store.get_trace(trace_id)
  414. if not trace:
  415. raise HTTPException(status_code=404, detail=f"Trace not found: {trace_id}")
  416. # 检查是否仍在运行
  417. if trace_id in _running_tasks and not _running_tasks[trace_id].done():
  418. raise HTTPException(status_code=409, detail="Cannot reflect on a running trace. Stop it first.")
  419. # 使用 force_side_branch 触发反思侧分支
  420. config = RunConfig(
  421. trace_id=trace_id,
  422. model=trace.model or "gpt-4o",
  423. force_side_branch=["reflection"], # 使用列表格式
  424. max_iterations=20, # 给侧分支足够的轮次
  425. enable_prompt_caching=True,
  426. )
  427. # 如果有 focus,可以通过追加消息传递(可选)
  428. messages = []
  429. if req.focus:
  430. messages = [{"role": "user", "content": f"反思重点:{req.focus}"}]
  431. # 启动反思任务(后台执行)
  432. task = asyncio.create_task(_run_trace_background(runner, messages, config))
  433. _running_tasks[trace_id] = task
  434. return ReflectResponse(
  435. trace_id=trace_id,
  436. reflection="反思任务已启动,通过 WebSocket 监听实时更新",
  437. )
  438. @router.get("/{trace_id}/extractions", response_model=ListExtractionsResponse)
  439. async def list_extractions(trace_id: str, include_reviewed: bool = False):
  440. """列出 trace 的待审核提取条目。"""
  441. runner = _get_runner()
  442. if not runner.trace_store:
  443. raise HTTPException(status_code=503, detail="TraceStore not configured")
  444. from agent.trace.extraction_review import list_pending
  445. pendings = await list_pending(
  446. runner.trace_store, trace_id, include_reviewed=include_reviewed
  447. )
  448. return ListExtractionsResponse(
  449. trace_id=trace_id,
  450. count=len(pendings),
  451. items=[
  452. PendingExtractionModel(
  453. extraction_id=p.extraction_id,
  454. sequence=p.sequence,
  455. goal_id=p.goal_id,
  456. branch_id=p.branch_id,
  457. payload=p.payload,
  458. reviewed=p.reviewed,
  459. decision=p.decision,
  460. committed=p.committed,
  461. )
  462. for p in pendings
  463. ],
  464. )
  465. @router.post(
  466. "/{trace_id}/extractions/{extraction_id}/review",
  467. response_model=ReviewResponse,
  468. )
  469. async def review_extraction(trace_id: str, extraction_id: str, req: ReviewRequest):
  470. """对单条 pending 提交 review 决策(approve/edit/discard)。"""
  471. runner = _get_runner()
  472. if not runner.trace_store:
  473. raise HTTPException(status_code=503, detail="TraceStore not configured")
  474. if req.decision not in ("approve", "edit", "discard"):
  475. raise HTTPException(
  476. status_code=400,
  477. detail=f"decision must be approve/edit/discard, got {req.decision}",
  478. )
  479. if req.decision == "edit" and not req.edited_payload:
  480. raise HTTPException(
  481. status_code=400, detail="decision=edit 必须提供 edited_payload"
  482. )
  483. from agent.trace.extraction_review import review_one
  484. await review_one(
  485. runner.trace_store,
  486. trace_id,
  487. extraction_id,
  488. req.decision, # type: ignore[arg-type]
  489. edited_payload=req.edited_payload,
  490. )
  491. return ReviewResponse(
  492. trace_id=trace_id, extraction_id=extraction_id, decision=req.decision
  493. )
  494. @router.post("/{trace_id}/extractions/commit", response_model=CommitResponse)
  495. async def commit_extractions(trace_id: str):
  496. """批量把已 approved/edited 的条目上传到 KnowHub。"""
  497. runner = _get_runner()
  498. if not runner.trace_store:
  499. raise HTTPException(status_code=503, detail="TraceStore not configured")
  500. from agent.trace.extraction_review import commit_approved
  501. report = await commit_approved(runner.trace_store, trace_id)
  502. return CommitResponse(
  503. trace_id=trace_id,
  504. committed_count=len(report.committed),
  505. failed_count=len(report.failed),
  506. skipped_count=len(report.skipped),
  507. committed=report.committed,
  508. knowledge_ids=report.knowledge_ids,
  509. failed=report.failed,
  510. skipped=report.skipped,
  511. )
  512. @router.post("/{trace_id}/compact", response_model=CompactResponse)
  513. async def compact_trace(trace_id: str):
  514. """
  515. 压缩 Trace 的上下文 (Compact)
  516. 通过 force_side_branch="compression" 触发侧分支多轮 agent 模式,
  517. LLM 可以调用工具(如 goal)进行多轮推理。
  518. 压缩消息标记为侧分支(branch_type="compression"),不在主路径上。
  519. """
  520. from agent.core.runner import RunConfig
  521. runner = _get_runner()
  522. if not runner.trace_store:
  523. raise HTTPException(status_code=503, detail="TraceStore not configured")
  524. # 验证 trace 存在
  525. trace = await runner.trace_store.get_trace(trace_id)
  526. if not trace:
  527. raise HTTPException(status_code=404, detail=f"Trace not found: {trace_id}")
  528. # 检查是否仍在运行
  529. if trace_id in _running_tasks and not _running_tasks[trace_id].done():
  530. raise HTTPException(status_code=409, detail="Cannot compact a running trace. Stop it first.")
  531. # 使用 force_side_branch 触发压缩侧分支
  532. config = RunConfig(
  533. trace_id=trace_id,
  534. model=trace.model or "gpt-4o",
  535. force_side_branch=["compression"], # 使用列表格式
  536. max_iterations=20, # 给侧分支足够的轮次
  537. enable_prompt_caching=True,
  538. )
  539. # 启动压缩任务(后台执行)
  540. task = asyncio.create_task(_run_trace_background(runner, [], config))
  541. _running_tasks[trace_id] = task
  542. return CompactResponse(
  543. trace_id=trace_id,
  544. previous_count=0, # 无法立即获取,需通过 WebSocket 监听
  545. new_count=0,
  546. message="压缩任务已启动,通过 WebSocket 监听实时更新",
  547. )
  548. @router.get("/running", tags=["run"])
  549. async def list_running():
  550. """列出正在运行的 Trace(包含活跃状态判断)"""
  551. from datetime import datetime
  552. runner = _get_runner()
  553. running = []
  554. for tid, task in list(_running_tasks.items()):
  555. if task.done():
  556. _running_tasks.pop(tid, None)
  557. else:
  558. # 获取trace详情,检查最后活动时间
  559. trace_info = {"trace_id": tid, "is_active": True}
  560. if runner.trace_store:
  561. try:
  562. trace = await runner.trace_store.get_trace(tid)
  563. if trace:
  564. # 判断是否真正活跃:最后活动时间在30秒内
  565. if hasattr(trace, 'last_activity_at') and trace.last_activity_at:
  566. time_since_activity = (datetime.now() - trace.last_activity_at).total_seconds()
  567. trace_info["is_active"] = time_since_activity < 30
  568. trace_info["seconds_since_activity"] = int(time_since_activity)
  569. trace_info["status"] = trace.status
  570. except Exception as exc:
  571. logger.debug("Failed to inspect running trace %s: %s", tid, exc)
  572. running.append(trace_info)
  573. return {"running": running}
  574. async def reconcile_traces():
  575. """
  576. 状态对齐:启动时清理残留的 running 状态。
  577. 当服务异常停止或重启后,磁盘上的 trace 状态可能仍显示为 running,
  578. 但对应的内存任务已不存在。本函数将其强制标记为 stopped。
  579. """
  580. runner = _get_runner()
  581. if not runner or not runner.trace_store:
  582. logger.warning("[Reconciliation] Runner or TraceStore not initialized, skipping.")
  583. return
  584. try:
  585. # 获取所有 running 状态的 trace
  586. running_traces = await runner.trace_store.list_traces(status="running", limit=1000)
  587. if not running_traces:
  588. return
  589. count = 0
  590. for trace in running_traces:
  591. tid = trace.trace_id
  592. # 如果不在活跃任务字典中(服务初次启动时此字典为空),则视为异常残留
  593. if tid not in _running_tasks:
  594. logger.info(f"[Reconciliation] Fixing trace {tid}: running -> stopped")
  595. await runner.trace_store.update_trace(
  596. tid,
  597. status="stopped",
  598. result_summary="[Reconciliation] 任务由于服务重启或异常中断已自动停止。"
  599. )
  600. count += 1
  601. if count > 0:
  602. logger.info(f"[Reconciliation] Successfully reconciled {count} traces.")
  603. except Exception as e:
  604. logger.error(f"[Reconciliation] Failed to reconcile traces: {e}")
  605. # ===== 经验 API =====
  606. @experiences_router.get("/experiences")
  607. async def list_experiences():
  608. """读取经验文件内容"""
  609. runner = _get_runner()
  610. experiences_path = getattr(runner, "experiences_path", "./.cache/experiences.md")
  611. if not experiences_path or not os.path.exists(experiences_path):
  612. return {"content": "", "path": experiences_path}
  613. with open(experiences_path, "r", encoding="utf-8") as f:
  614. content = f.read()
  615. return {"content": content, "path": experiences_path}