# Agent SSE Events 本文档描述 `GET /api/v1/agent/runs/{thread_id}/events` 的事件协议。 --- ## 1) 事件管道 后端事件流转如下: 1. Runtime 直接产出 AG-UI 事件(如 `RUN_STARTED`、`TOOL_CALL_RESULT`) 2. `agui_codec` 仅做协议对齐与字段净化(例如移除仅后端内部统计字段) 3. 事件同时: - 持久化到数据库(用于 history) - 发布到 Redis Stream(用于 SSE) 4. `/runs/{thread_id}/events` 从 Redis Stream 读取并输出 SSE --- ## 2) SSE 帧格式 每条事件遵循标准 SSE: ```text id: event: data: ``` - `id` 可用于断点续流(`Last-Event-ID`) - `event` 与 JSON 内 `type` 一致(例如 `RUN_STARTED`) - 空闲时可能出现 keep-alive 注释帧: ```text : keep-alive ``` --- ## 3) 事件类型(当前实现) ### 3.1 Run 生命周期 #### `RUN_STARTED` ```json { "type": "RUN_STARTED", "threadId": "...", "runId": "..." } ``` #### `RUN_FINISHED` ```json { "type": "RUN_FINISHED", "threadId": "...", "runId": "..." } ``` #### `RUN_ERROR` ```json { "type": "RUN_ERROR", "threadId": "...", "runId": "...", "message": "runtime execution failed", "code": null } ``` ### 3.2 阶段事件 #### `STEP_STARTED` ```json { "type": "STEP_STARTED", "threadId": "...", "runId": "...", "stepName": "router" | "worker" } ``` #### `STEP_FINISHED` ```json { "type": "STEP_FINISHED", "threadId": "...", "runId": "...", "stepName": "router" | "worker" } ``` ### 3.3 Tool 事件 #### `TOOL_CALL_START` ```json { "type": "TOOL_CALL_START", "threadId": "...", "runId": "...", "messageId": "...", "toolCallId": "...", "toolCallName": "...", "stage": "worker" } ``` #### `TOOL_CALL_ARGS` ```json { "type": "TOOL_CALL_ARGS", "threadId": "...", "runId": "...", "messageId": "...", "toolCallId": "...", "toolCallName": "...", "args": {}, "stage": "worker" } ``` #### `TOOL_CALL_END` ```json { "type": "TOOL_CALL_END", "threadId": "...", "runId": "...", "messageId": "...", "toolCallId": "...", "toolCallName": "...", "stage": "worker" } ``` #### `TOOL_CALL_RESULT` ```json { "type": "TOOL_CALL_RESULT", "threadId": "...", "runId": "...", "messageId": "...", "role": "tool", "stage": "worker", "tool_name": "...", "tool_call_id": "...", "tool_call_args": {}, "status": "success" | "failed", "result_summary": "...", "ui_schema": {}, "error": null } ``` ### 3.4 文本完成事件 #### `TEXT_MESSAGE_END` 当前实现仅在 worker 输出完成后发送完整结果,不发送 token delta 事件。 ```json { "type": "TEXT_MESSAGE_END", "threadId": "...", "runId": "...", "messageId": "...", "role": "assistant", "stage": "worker", "status": "success" | "partial_success" | "failed", "answer": "...", "key_points": [], "result_type": "execution_report" | "clarification" | "error_report" | "unknown", "suggested_actions": [], "error": null, "ui_schema": {} } ``` `inputTokens`、`outputTokens`、`cost`、`latencyMs`、`model` 属于后端内部统计字段,不在 SSE 对外协议中暴露。 ### 3.5 快照事件 编码器支持以下 AG-UI 类型映射: - `STATE_SNAPSHOT` - `MESSAGES_SNAPSHOT` 当前 `/runs/{thread_id}/events` 主流程通常不主动产出这两类事件;历史查询请使用 `/history`。 --- ## 4) 字段命名约定 - 事件顶层通用字段使用 AG-UI 风格:`type`、`threadId`、`runId` - 部分业务字段沿运行时模型历史命名保留下划线: - `tool_name` - `tool_call_id` - `tool_call_args` - `ui_schema` 这部分命名属于当前后端实现约束,文档与实现保持一致。