> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zeus.agentspro.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 智能体循环

> Zeus Agent 执行循环 — 从用户消息到流式响应的完整数据流

Agent Loop 是一次完整的 Agent 运行：消息接收 → 上下文组装 → 模型推理 → 工具执行 → 流式响应 → 状态持久化。它是将一条用户消息转化为行动和最终回复的核心路径。

在 Zeus 中，每次 Loop 是一个按 Session 序列化的运行，在模型推理、工具调用和流式输出的过程中发射生命周期事件和流事件。

***

## Entry Points

| 入口            | 路由                       | 说明                              |
| ------------- | ------------------------ | ------------------------------- |
| Web 前端        | `POST /api/agent/invoke` | Next.js API Route，代理到 Python 后端 |
| Python API    | `POST /api/agent/invoke` | FastAPI 路由，直接调用 AgentService    |
| Resume (HITL) | `POST /api/agent/resume` | 用户审批后恢复执行                       |

***

## How It Works (High-level)

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Web as Frontend
    participant API as Next.js → FastAPI
    participant Agent as DeepAgent
    participant LLM
    participant Tools

    User->>Web: 发送消息
    Web->>API: POST /api/agent/invoke

    rect rgb(248, 255, 240)
        Note over API,Agent: 上下文组装
        API->>Agent: 初始化 LLM + 加载工具 + 构建 Prompt
    end

    rect rgb(255, 248, 240)
        Note over Agent,Tools: 执行循环
        loop Agent Loop
            Agent->>LLM: 推理请求
            LLM-->>Web: SSE: TextMessage (token 流)

            opt 工具调用
                alt 需要审批
                    Agent-->>Web: SSE: ToolCallMessage (pending)
                    Note over User,Web: 等待用户审批...
                else 自动执行
                    Agent->>Tools: 执行工具
                    Tools-->>Web: SSE: ToolCallResultMessage
                end
            end
        end
    end

    Agent-->>Web: SSE: CompleteMessage
```

1. **请求接收** — Next.js API 验证身份、检查信用额度、加载 LLM 和工具配置，异步保存用户消息，转发到 Python 后端
2. **上下文组装** — `_init_context()` 按序加载工具（MCP + OAuth + Built-in）、初始化 LLM、检索 Memory/Profile、激活 Skills、构建 System Prompt，缓存至 `context_cache`
3. **Agent 创建** — 通过 DeepAgents 创建 LangGraph 图，装配 LLM、工具、中间件管线、Checkpointer 和 HITL 中断配置
4. **消息构建** — 前端 chat\_history 转换为 LangChain 消息类型（最多 30 条），追加当前用户消息
5. **流式执行** — 进入 `_astream_events()` 核心循环，框架事件转换为 SSE 消息流式发送
6. **完成** — 发送 `CompleteMessage`，Checkpointer 自动保存状态

***

## Context Assembly

```mermaid theme={null}
flowchart TD
    start["_init_context()"]
    validate["参数验证"]
    session["Session ID 生成"]

    subgraph ToolLoading["工具加载"]
        mcp["MCP Tools"]
        oauth["OAuth Tools"]
        browser["Browser Tools"]
        desktop["Desktop Tools"]
        sandbox["Sandbox Tools"]
    end

    llm["LLM 初始化"]
    memory["Memory 检索"]
    profile["Profile 获取"]
    skills["Skills 激活"]
    prompt["System Prompt 构建"]

    start --> validate --> session --> ToolLoading --> llm --> memory --> profile --> skills --> prompt
```

上下文组装完成后缓存至 `_context_cache[session_id]`，供 HITL `resume()` 复用。

<CardGroup cols={2}>
  <Card title="Context 详解" icon="brain" href="/en/ai-backend/fundamentals/Context">
    System Prompt 组装、Token 管理与优化策略
  </Card>

  <Card title="System Prompt" icon="file-lines" href="/en/ai-backend/fundamentals/System-Prompt">
    系统提示词 — CORE、SOUL、TOOLS、WORKFLOW、MEMORY、动态注入
  </Card>
</CardGroup>

***

## Event Streaming

`_astream_events()` 监听 DeepAgents 框架的内部事件，转换为标准 SSE 消息发送到前端：

```mermaid theme={null}
graph LR
    subgraph DeepAgentsEvents["DeepAgents 内部事件"]
        e1["on_chat_model_stream"]
        e2["on_chat_model_end"]
        e3["on_tool_end"]
        e4["on_interrupt"]
    end

    subgraph SSEMessages["SSE 消息"]
        m1["TextMessage"]
        m2["ToolCallMessage"]
        m3["ToolCallResultMessage"]
        m4["CompleteMessage"]
        m5["ErrorMessage"]
        m6["TokenUsageMessage"]
    end

    e1 -->|"token 流"| m1
    e2 -->|"tool_calls 检测"| m2
    e2 -->|"usage_metadata"| m6
    e3 -->|"工具结果"| m3
    e4 -->|"HITL 中断"| m2
```

### SSE 事件类型

| SSE 事件             | 触发时机            | 关键字段                                           |
| ------------------ | --------------- | ---------------------------------------------- |
| `text`             | LLM 每输出一个 token | `content`, `role`                              |
| `tool_call`        | LLM 决定调用工具      | `tool_name`, `parameters`, `requires_approval` |
| `tool_call_result` | 工具执行完成          | `tool_name`, `result`, `is_error`              |
| `complete`         | Agent 执行结束      | `content`, `summary`                           |
| `error`            | 发生异常            | `error`, `error_code`, `details`               |
| `token_usage`      | LLM 调用结束后       | `prompt_tokens`, `completion_tokens`           |

<Card title="Messages" icon="comments" href="/en/ai-backend/messages/Messages">
  了解完整的消息流程、状态管理和持久化
</Card>

***

## Tool Execution

### 执行决策

```mermaid theme={null}
flowchart TD
    llm_end["LLM 返回 tool_calls"]
    check{"需要审批?"}

    auto["自动执行工具"]
    tool_end["返回 ToolCallResultMessage"]

    hitl["保存 Checkpoint"]
    send_pending["发送 ToolCallMessage<br/>(requires_approval=true)"]
    wait["等待用户决定"]
    resume["resume() 恢复"]

    llm_end --> check
    check -->|"否"| auto --> tool_end
    check -->|"是"| hitl --> send_pending --> wait --> resume
```

审批决策基于 Auto-Run 模式（Run Everything / Use Allowlist / Ask Everytime）。Tool Call ID 通过 FIFO 队列匹配，按工具名分组存储，`on_chat_model_end` 时入队，`on_tool_end` 时出队。

### HITL 中断与恢复

当工具需要审批时，Agent Loop 被挂起，状态通过 Checkpointer 持久化。恢复流程：

```mermaid theme={null}
flowchart TD
    resume_start["resume(session_id, tool_call_results)"]
    init["重新初始化 LLM + 恢复上下文缓存"]
    process["处理审批结果"]

    subgraph Results["审批决策"]
        approved["approved → 执行工具"]
        rejected["rejected → 拒绝消息 + 防重试"]
        timeout_result["timeout → 超时跳过"]
    end

    checkpoint["获取 Checkpoint 状态"]
    inject["注入 ToolMessage"]
    continue["继续 Agent Loop"]

    resume_start --> init --> process --> Results --> checkpoint --> inject --> continue
```

被拒绝的工具会附加 SystemMessage，明确告知 Agent 不要重试。

<Card title="HITL 详解" icon="user-check" href="/en/ai-backend/fundamentals/HITL">
  Auto-Run 模式、审批 UI、中断恢复机制的完整说明
</Card>

***

## Frontend Processing

前端 `handleStreamMessage()` 消费 SSE 流，将事件路由到对应的状态管理：

```mermaid theme={null}
flowchart TD
    fetch["fetch POST /api/agent/invoke"]
    reader["ReadableStream Reader"]
    parse["解析 SSE data 行"]

    subgraph Handlers["事件路由"]
        h_text["TextMessage → 追加 token"]
        h_tool["ToolCallMessage → 添加到 trajectory"]
        h_result["ToolCallResultMessage → 更新状态"]
        h_complete["CompleteMessage → 标记完成"]
        h_error["ErrorMessage → Toast 通知"]
    end

    subgraph Stores["状态更新"]
        chat["chatStore — 消息列表"]
        trajectory["trajectoryStore — 工具调用 + Todos"]
        approval["pendingApprovals — 待审批队列"]
    end

    saver["RealtimeEventSaver — 批量持久化"]

    fetch --> reader --> parse --> Handlers
    Handlers --> Stores
    Handlers --> saver
```

### Event Persistence

`RealtimeEventSaver` 批量持久化实时事件：

| 配置   | 值               |
| ---- | --------------- |
| 批量大小 | 3 个事件           |
| 批量间隔 | 100ms           |
| 重试策略 | 指数退避，最多 3 次     |
| 降级方案 | LocalStorage 备份 |

***

## Error Handling

### 后端错误

| 错误类型    | 检测条件                                     | 用户提示            |
| ------- | ---------------------------------------- | --------------- |
| 输入长度超限  | Range of input length / InvalidParameter | 建议缩短输入          |
| 上下文窗口溢出 | context length / token limit             | 建议开启新会话         |
| 通用异常    | 其他所有 Exception                           | 包含 traceback 详情 |

错误通过 `ErrorMessage` SSE 事件发送，包含 `error_code` 和 `details`。

### 前端错误

| HTTP 状态码 | 含义     | 处理       |
| -------- | ------ | -------- |
| 401      | 未授权    | 重定向到登录   |
| 403      | 信用额度不足 | Toast 提示 |
| 503      | 后端未启动  | 连接错误提示   |
| 504      | 请求超时   | 超时提示     |

流错误（AbortError、网络断开、解析错误）均有对应的异常处理和用户提示。

***

## Timeouts

| 超时项            | 默认值           | 说明              |
| -------------- | ------------- | --------------- |
| Agent 最大执行时长   | 7200s (2h)    | FastAPI 单次调用上限  |
| MCP 服务器        | 1800s (30min) | 每个 MCP 服务器的连接超时 |
| HITL 工具审批      | 可配置           | 每个工具独立设置        |
| LangGraph 递归限制 | 999           | Agent 循环的最大迭代次数 |

***

## Concurrency & Isolation

* 每个 Session 拥有独立的 Checkpointer 状态（`thread_id` 隔离）
* Context Cache 按 `session_id` 隔离，resume 只能恢复对应会话
* 工具执行是序列化的（LangGraph 保证同一 Session 内不会并发执行工具）
* 用户工作空间按 `user_id` 完全隔离

***

## Where Things Can End Early

* **Agent 超时** — 超过 7200s 最大执行时长
* **HITL 审批超时** — 用户未在规定时间内响应
* **前端断开** — 网络中断或用户关闭页面
* **信用额度耗尽** — 调用前检查失败
* **模型错误** — 上下文窗口溢出或 API 异常
