---
title: "Dex Agent Framework"
description: "Dex Agent Framework 不需要其他 agent SDK 就能运行持久化的 Agent，每个 Session 都有提问、持久化 wait、plan、steering、compaction 和 MCP tool。"
canonical_url: "https://docs.superdurable.io/zh-Hans/build-ai-agents/dex-agent-framework/"
source: "docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/agent-frameworks/dex-agent-framework.mdx"
locale: "zh-Hans"
language: "python"
---

> 供 AI Agent 使用的全部页面索引：https://docs.superdurable.io/zh-Hans/llms.txt

# Dex Agent Framework

本页代码为 Python。其他语言：[TypeScript](https://docs.superdurable.io/zh-Hans/build-ai-agents/dex-agent-framework.typescript.md)

Dex Agent Framework 不需要其他 agent SDK 就能运行持久化的 Agent。新的 Agent 用它：每个 Session 都有提问、持久化 wait、plan、steering、compaction 和 MCP tool。如果你的 Agent 已经在用某个 agent SDK，见[在 Agent SDK 中使用 Dex](https://docs.superdurable.io/zh-Hans/build-ai-agents/use-dex-with-agent-sdks.md)。

<a id="when-to-use-it"></a>

<a id="how-a-session-runs"></a>

## Session 如何运行

每次模型调用是一个 `RunModel` Step，每次 Tool Call 是独立的 Step。Dex 用 Session 存下的 message 构建每次模型输入，所以 Agent 不需要 provider 的 conversation API。两个 turn 之间，Session 持久化地等待下一条用户 message，不占用 Worker。[Step graph](https://docs.superdurable.io/zh-Hans/reference/agents/dex-agent-framework.md#step-graph) 展示每个 Step，以及 turn 如何在它们之间流转。

<a id="install"></a>

## 安装

**Python**

```bash
pip install "dex-agents[litellm,mcp]"
```

例子: [agents/python/core](https://github.com/superdurable/dex/tree/main/agents/python/core)

**litellm** extra 和 **ai** package 提供 model client。**mcp** extra 和 `@modelcontextprotocol/sdk` 提供 MCP tool。不用的就不装。

<a id="the-example"></a>

## 示例

AI Agent 示例有 Python 和 TypeScript 版本，它和用户对话，并调用受信任的 MCP tool。外部写操作之前它会等待审批，会向用户提问，会等待持久化的 Timer，还会起草 plan 供审阅。

<a id="the-session-flow"></a>

### Session Flow

Session Flow 的类型是 **AIAgentSession**。每个 Session 从 Worker 允许的模型中选一个：

**Python**

```python
def build_ai_agent_session_flow(
    models: Sequence[str],
    system_prompt: str,
    context_window_tokens: int,
    mcp_servers: Sequence[McpServerConfig],
    slack_connection: slack.Connection | None,
) -> AgentSessionFlow:
    """Builds the agent; ``models`` are the allowed model names, and the first is the default.

    ``slack_connection`` None leaves out the Slack connector tools.
    """
    clients = {model: _model_client(model) for model in models}
    mcp_tool_sources = (
        [McpToolSource(mcp_servers, resource_and_prompt_tools_enabled=True)] if mcp_servers else []
    )
    definition = AgentDefinition(
        name="ai-agent",
        instructions=system_prompt,
        model=clients[models[0]],
        # Settings hold only a model name; an unknown one gets the default, never a new client.
        resolve_model=lambda settings: clients.get(str(settings.get("model")), clients[models[0]]),
        tool_sources=[*mcp_tool_sources, *build_slack_tool_sources(slack_connection)],
        built_in_tools=frozenset(BuiltInTool),
        plan_mode_enabled=True,
        compaction=CompactionPolicy(context_window_tokens=context_window_tokens),
    )
    return stepwise_agent_session_flow(definition, flow_type=AI_AGENT_SESSION_FLOW_TYPE)
```

例子: [examples/python/dex_examples/products/ai-agent/ai_agent_session.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/ai-agent/ai_agent_session.py)

允许的模型、system prompt、context window 和 MCP server 都是 Worker 配置；原因见 [Model per session](https://docs.superdurable.io/zh-Hans/reference/agents/dex-agent-framework.md#model-per-session)。

<a id="worker"></a>

### Worker

Worker 把 Session Flow 和应用的其他 Flow 一起注册。Agent Session 的 Step 是 async 的，所以 Python 的 Registry 允许 async handler。

**Python**

```python
        self.ai_agent_mcp_servers = load_mcp_servers(config.agent_mcp_config)
        self.ai_agent = build_ai_agent_session_flow(
            config.agent_models,
            config.agent_system_prompt,
            config.agent_context_tokens,
            self.ai_agent_mcp_servers,
            ai_agent_slack_connection,
        )
        # ...
        self.registry = Registry(tuple(flows), allow_async_handlers=True)
```

例子: [examples/python/dex_examples/app.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/app.py)

<a id="what-a-session-can-do"></a>

## Session 能做什么

<a id="durable-context"></a>

<a id="queued-messages-and-steer"></a>

<a id="questions-and-durable-waits"></a>

<a id="durable-plans"></a>

<a id="mcp-tools-and-approvals"></a>

<a id="live-events"></a>

<a id="connect-connectors"></a>

- **持久化 context 与 compaction。** Session 存下每条 message，模型输入超出 window 之前，`CompactContext` Step 会摘要较早的 message（[Durable context](https://docs.superdurable.io/zh-Hans/reference/agents/dex-agent-framework.md#durable-context)）。
- **排队的 message 与 Steer。** turn 进行中发送的 message 在持久化队列中等待，**Steer** 在 turn 的下一个安全 Step 边界应用它（[Queued messages and Steer](https://docs.superdurable.io/zh-Hans/reference/agents/dex-agent-framework.md#queued-messages-and-steer)）。
- **提问与持久化 wait。** `ask_user` tool 等待用户的答案，`durable_wait` 等待一个 Timer，等待期间都不占用 Worker（[Questions and durable waits](https://docs.superdurable.io/zh-Hans/reference/agents/dex-agent-framework.md#questions-and-durable-waits)）。
- **持久化 plan。** **Plan mode** 把计划起草在 `AgentPlan` Attribute 中，用户用 **Execute plan** 执行它（[Plans](https://docs.superdurable.io/zh-Hans/reference/agents/dex-agent-framework.md#durable-plans)）。
- **MCP tool 与审批。** Worker 配置中受信任的 MCP server 提供 tool，每次调用在自己的 Step 中按 tool policy 运行（[MCP tools and approvals](https://docs.superdurable.io/zh-Hans/reference/agents/dex-agent-framework.md#mcp-tools-and-approvals)）。
- **Connector tool。** 官方 Connector 操作可以作为 tool，和任何 agent SDK 一样（[把 Connector 用作 tool](https://docs.superdurable.io/zh-Hans/build-ai-agents/connectors-as-tools.md?framework=built-in-agent-loop#connect-connectors)）。
- **实时事件。** 文本、reasoning summary、tool activity、审批和 plan 更新出现在 Session 的 `AgentEvents` Stream 上（[Read the stream](https://docs.superdurable.io/zh-Hans/reference/agents/event-stream.md#read-the-stream)）。

<a id="run-the-example"></a>

## 在本地运行

按[从 playground 运行示例](https://docs.superdurable.io/zh-Hans/install.md)启动 **dexcli dev**，然后启动一个示例。两个示例都在 `http://127.0.0.1:8080/products/ai-agent/` 提供页面，因此一次只运行一个。

**Python**

```bash
cd examples/python
uv sync --locked
cd ai-agent
npm ci
npm run build
cd ..
export DEX_AGENT_MCP_CONFIG="$PWD/ai-agent/mcp-servers.local.yaml"
export DEX_AGENT_SESSION_KEY="$(openssl rand -hex 32)"
uv run --frozen python main.py
```

例子: [examples/python/ai-agent](https://github.com/superdurable/dex/tree/main/examples/python/ai-agent)

默认的 demo model 不需要 credential，所以无需 key 就能体验所有功能。[Example configuration](https://docs.superdurable.io/zh-Hans/reference/agents/dex-agent-framework.md#example-configuration) 列出它的斜杠命令和真实模型用的变量，[Session access](https://docs.superdurable.io/zh-Hans/reference/agents/dex-agent-framework.md#session-access) 解释 Session token。代码在 [examples/python/dex_examples/products/ai-agent](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/ai-agent)、[examples/python/ai-agent](https://github.com/superdurable/dex/tree/main/examples/python/ai-agent) 和 [examples/typescript/src/products/ai-agent](https://github.com/superdurable/dex/tree/main/examples/typescript/src/products/ai-agent) 下。

<a id="next"></a>

## 下一步

- [生产环境检查清单](https://docs.superdurable.io/zh-Hans/production-operations/production-checklist.md#agents)：为真实用户运行 Session 之前要准备什么。
- [Dex Agent Framework 参考](https://docs.superdurable.io/zh-Hans/reference/agents/dex-agent-framework.md)：Step graph、Session 规则和限制。
- [Agents 参考](https://docs.superdurable.io/zh-Hans/reference/agents.md)
