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

# 自定义 Deep Agents

> 了解如何使用系统提示、工具、子代理等自定义 Deep Agents

`create_deep_agent` 具有以下核心配置选项：

* [模型](#model)
* [工具](#tools)
* [系统提示](#system-prompt)
* [中间件](#middleware)
* [子代理](#subagents)
* [后端（虚拟文件系统）](#backends)
* [人机回环](#human-in-the-loop)
* [技能](#skills)
* [记忆](#memory)

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
create_deep_agent(
    name: str | None = None,
    model: str | BaseChatModel | None = None,
    tools: Sequence[BaseTool | Callable | dict[str, Any]] | None = None,
    *,
    system_prompt: str | SystemMessage | None = None
) -> CompiledStateGraph
```

有关更多信息，请参阅 [`create_deep_agent`](https://reference.langchain.com/python/deepagents/graph/create_deep_agent) API 参考。

### 连接弹性

LangChain 聊天模型会自动重试失败的 API 请求，并采用指数退避策略。默认情况下，模型会针对网络错误、速率限制（429）和服务器错误（5xx）**最多重试 6 次**。像 401（未授权）或 404 这样的客户端错误不会重试。

您可以在创建模型时调整 `max_retries` 参数，以便根据您的环境调整此行为：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.chat_models import init_chat_model
from deepagents import create_deep_agent

agent = create_deep_agent(
    model=init_chat_model(
        model="claude-sonnet-4-6",
        max_retries=10,  # 增加以应对不可靠的网络（默认值：6）
        timeout=120,     # 增加超时时间以应对慢速连接
    ),
)
```

<Tip>对于在不可靠网络上运行的长时间运行代理任务，建议将 `max_retries` 增加到 10–15，并将其与 [检查点器](/oss/python/langgraph/persistence) 配对，以便在故障之间保留进度。</Tip>

## 模型

默认情况下，`deepagents` 使用 [`claude-sonnet-4-6`](https://platform.claude.com/docs/en/about-claude/models/overview)。您可以通过传递任何支持的 <Tooltip tip="遵循 `provider:model` 格式的字符串（例如 openai:gpt-5）" cta="查看映射" href="https://reference.langchain.com/python/langchain/models/#langchain.chat_models.init_chat_model(model)">模型标识符字符串</Tooltip> 或 [LangChain 模型对象](/oss/python/integrations/chat) 来自定义模型。

<Tip>
  使用 `provider:model` 格式（例如 `openai:gpt-5`）可以快速切换模型。
</Tip>

<Tabs>
  <Tab title="OpenAI">
    👉 阅读 [OpenAI 聊天模型集成文档](/oss/python/integrations/chat/openai/)

    ```shell theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    pip install -U "langchain[openai]"
    ```

    <CodeGroup>
      ```python default parameters theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from deepagents import create_deep_agent

      os.environ["OPENAI_API_KEY"] = "sk-..."

      agent = create_deep_agent(model="openai:gpt-5.2")
      # this calls init_chat_model for the specified model with default parameters
      # to use specific modele parameters, use init_chat_model directly
      ```

      ```python init_chat_model theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from langchain.chat_models import init_chat_model
      from deepagents import create_deep_agent

      os.environ["OPENAI_API_KEY"] = "sk-..."

      model = init_chat_model(model="openai:gpt-5.2")
      agent = create_deep_agent(model=model)
      ```

      ```python Model Class theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from langchain_openai import ChatOpenAI
      from deepagents import create_deep_agent

      os.environ["OPENAI_API_KEY"] = "sk-..."

      model = ChatOpenAI(model="gpt-5.2")
      agent = create_deep_agent(model=model)
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Anthropic">
    👉 阅读 [Anthropic 聊天模型集成文档](/oss/python/integrations/chat/anthropic/)

    ```shell theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    pip install -U "langchain[anthropic]"
    ```

    <CodeGroup>
      ```python default parameters theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from deepagents import create_deep_agent

      os.environ["ANTHROPIC_API_KEY"] = "sk-..."

      agent = create_deep_agent(model="claude-sonnet-4-6")
      # this calls init_chat_model for the specified model with default parameters
      # to use specific modele parameters, use init_chat_model directly
      ```

      ```python init_chat_model theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from langchain.chat_models import init_chat_model
      from deepagents import create_deep_agent

      os.environ["ANTHROPIC_API_KEY"] = "sk-..."

      model = init_chat_model(model="claude-sonnet-4-6")
      agent = create_deep_agent(model=model)
      ```

      ```python Model Class theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from langchain_anthropic import ChatAnthropic
      from deepagents import create_deep_agent

      os.environ["ANTHROPIC_API_KEY"] = "sk-..."

      model = ChatAnthropic(model="claude-sonnet-4-6")
      agent = create_deep_agent(model=model)
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Azure">
    👉 阅读 [Azure 聊天模型集成文档](/oss/python/integrations/chat/azure_chat_openai/)

    ```shell theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    pip install -U "langchain[openai]"
    ```

    <CodeGroup>
      ```python default parameters theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from deepagents import create_deep_agent

      os.environ["AZURE_OPENAI_API_KEY"] = "..."
      os.environ["AZURE_OPENAI_ENDPOINT"] = "..."
      os.environ["OPENAI_API_VERSION"] = "2025-03-01-preview"

      agent = create_deep_agent(model="azure_openai:gpt-5.2")
      # this calls init_chat_model for the specified model with default parameters
      # to use specific modele parameters, use init_chat_model directly
      ```

      ```python init_chat_model theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from langchain.chat_models import init_chat_model
      from deepagents import create_deep_agent

      os.environ["AZURE_OPENAI_API_KEY"] = "..."
      os.environ["AZURE_OPENAI_ENDPOINT"] = "..."
      os.environ["OPENAI_API_VERSION"] = "2025-03-01-preview"

      model = init_chat_model(
          model="azure_openai:gpt-5.2",
          azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],
      )
      agent = create_deep_agent(model=model)
      ```

      ```python Model Class theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from langchain_openai import AzureChatOpenAI
      from deepagents import create_deep_agent

      os.environ["AZURE_OPENAI_API_KEY"] = "..."
      os.environ["AZURE_OPENAI_ENDPOINT"] = "..."
      os.environ["OPENAI_API_VERSION"] = "2025-03-01-preview"

      model = AzureChatOpenAI(
          model="gpt-5.2",
          azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],
      )
      agent = create_deep_agent(model=model)
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Google Gemini">
    👉 阅读 [Google GenAI 聊天模型集成文档](/oss/python/integrations/chat/google_generative_ai/)

    ```shell theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    pip install -U "langchain[google-genai]"
    ```

    <CodeGroup>
      ```python default parameters theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from deepagents import create_deep_agent

      os.environ["GOOGLE_API_KEY"] = "..."

      agent = create_deep_agent(model="google_genai:gemini-2.5-flash-lite")
      # this calls init_chat_model for the specified model with default parameters
      # to use specific modele parameters, use init_chat_model directly
      ```

      ```python init_chat_model theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from langchain.chat_models import init_chat_model
      from deepagents import create_deep_agent

      os.environ["GOOGLE_API_KEY"] = "..."

      model = init_chat_model(model="google_genai:gemini-2.5-flash-lite")
      agent = create_deep_agent(model=model)
      ```

      ```python Model Class theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from langchain_google_genai import ChatGoogleGenerativeAI
      from deepagents import create_deep_agent

      os.environ["GOOGLE_API_KEY"] = "..."

      model = ChatGoogleGenerativeAI(model="gemini-2.5-flash-lite")
      agent = create_deep_agent(model=model)
      ```
    </CodeGroup>
  </Tab>

  <Tab title="AWS Bedrock">
    👉 阅读 [AWS Bedrock 聊天模型集成文档](/oss/python/integrations/chat/bedrock/)

    ```shell theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    pip install -U "langchain[aws]"
    ```

    <CodeGroup>
      ```python default parameters theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      from deepagents import create_deep_agent

      # Follow the steps here to configure your credentials:
      # https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html

      agent = create_deep_agent(
          model="anthropic.claude-3-5-sonnet-20240620-v1:0",
          model_provider="bedrock_converse",
      )
      # this calls init_chat_model for the specified model with default parameters
      # to use specific modele parameters, use init_chat_model directly
      ```

      ```python init_chat_model theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      from langchain.chat_models import init_chat_model
      from deepagents import create_deep_agent

      # Follow the steps here to configure your credentials:
      # https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html

      model = init_chat_model(
          model="anthropic.claude-3-5-sonnet-20240620-v1:0",
          model_provider="bedrock_converse",
      )
      agent = create_deep_agent(model=model)
      ```

      ```python Model Class theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      from langchain_aws import ChatBedrock
      from deepagents import create_deep_agent

      # Follow the steps here to configure your credentials:
      # https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html

      model = ChatBedrock(model="anthropic.claude-3-5-sonnet-20240620-v1:0")
      agent = create_deep_agent(model=model)
      ```
    </CodeGroup>
  </Tab>

  <Tab title="HuggingFace">
    👉 阅读 [HuggingFace 聊天模型集成文档](/oss/python/integrations/chat/huggingface/)

    ```shell theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    pip install -U "langchain[huggingface]"
    ```

    <CodeGroup>
      ```python default parameters theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from deepagents import create_deep_agent

      os.environ["HUGGINGFACEHUB_API_TOKEN"] = "hf_..."

      agent = create_deep_agent(
          model="microsoft/Phi-3-mini-4k-instruct",
          model_provider="huggingface",
          temperature=0.7,
          max_tokens=1024,
      )
      # this calls init_chat_model for the specified model with default parameters
      # to use specific modele parameters, use init_chat_model directly
      ```

      ```python init_chat_model theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from langchain.chat_models import init_chat_model
      from deepagents import create_deep_agent

      os.environ["HUGGINGFACEHUB_API_TOKEN"] = "hf_..."

      model = init_chat_model(
          model="microsoft/Phi-3-mini-4k-instruct",
          model_provider="huggingface",
          temperature=0.7,
          max_tokens=1024,
      )
      agent = create_deep_agent(model=model)
      ```

      ```python Model Class theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      import os
      from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
      from deepagents import create_deep_agent

      os.environ["HUGGINGFACEHUB_API_TOKEN"] = "hf_..."

      llm = HuggingFaceEndpoint(
          repo_id="microsoft/Phi-3-mini-4k-instruct",
          temperature=0.7,
          max_length=1024,
      )
      model = ChatHuggingFace(llm=llm)
      agent = create_deep_agent(model=model)
      ```
    </CodeGroup>
  </Tab>
</Tabs>

## 工具

除了用于规划、文件管理和子代理生成的 [内置工具](/oss/python/deepagents/overview#core-capabilities) 之外，您还可以提供自定义工具：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os
from typing import Literal
from tavily import TavilyClient
from deepagents import create_deep_agent

tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])

def internet_search(
    query: str,
    max_results: int = 5,
    topic: Literal["general", "news", "finance"] = "general",
    include_raw_content: bool = False,
):
    """运行网络搜索"""
    return tavily_client.search(
        query,
        max_results=max_results,
        include_raw_content=include_raw_content,
        topic=topic,
    )

agent = create_deep_agent(
    tools=[internet_search]
)
```

## 系统提示

Deep Agents 自带内置系统提示。默认系统提示包含使用内置规划工具、文件系统工具和子代理的详细指令。
当中间件添加特殊工具（如文件系统工具）时，它们会被附加到系统提示中。

每个深度代理还应包含针对其特定用例的自定义系统提示：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from deepagents import create_deep_agent

research_instructions = """\
你是一名专家研究员。你的工作是进行彻底的研究，然后撰写一份精美的报告。 \
"""

agent = create_deep_agent(
    system_prompt=research_instructions,
)
```

## 中间件

默认情况下，Deep Agents 可以访问以下 [中间件](/oss/python/langchain/middleware/overview)：

* [`TodoListMiddleware`](https://reference.langchain.com/python/langchain/agents/middleware/todo/TodoListMiddleware)：跟踪和管理待办事项列表，以组织代理任务和作业
* [`FilesystemMiddleware`](https://reference.langchain.com/python/deepagents/middleware/filesystem/FilesystemMiddleware)：处理文件系统操作，如读取、写入和导航目录
* [`SubAgentMiddleware`](https://reference.langchain.com/python/deepagents/middleware/subagents/SubAgentMiddleware)：生成和协调子代理，以便将任务委托给专用代理
* [`SummarizationMiddleware`](https://reference.langchain.com/python/langchain/agents/middleware/summarization/SummarizationMiddleware)：压缩消息历史记录，以便在对话变长时保持在上下文限制内
* [`AnthropicPromptCachingMiddleware`](https://reference.langchain.com/python/langchain-anthropic/middleware/prompt_caching/AnthropicPromptCachingMiddleware)：在使用 Anthropic 模型时自动减少冗余令牌处理
* [`PatchToolCallsMiddleware`](https://reference.langchain.com/python/deepagents/middleware/patch_tool_calls/PatchToolCallsMiddleware)：当工具调用在收到结果之前被中断或取消时，自动修复消息历史记录

如果您正在使用记忆、技能或人机回环，还包括以下中间件：

* [`MemoryMiddleware`](https://reference.langchain.com/python/deepagents/middleware/memory/MemoryMiddleware)：当提供 `memory` 参数时，跨会话持久化和检索对话上下文
* [`SkillsMiddleware`](https://reference.langchain.com/python/deepagents/middleware/skills/SkillsMiddleware)：当提供 `skills` 参数时启用自定义技能
* `HumanInTheLoopMiddleware`：当提供 `interruptOn` 参数时，在指定点暂停以获取人类批准或输入

### 预构建中间件

LangChain 暴露了其他预构建中间件，让您能够添加各种功能，如重试、降级或 PII 检测。有关更多信息，请参阅 [预构建中间件](/oss/python/langchain/middleware/built-in)。

`deepagents` 库还暴露了 [create\_summarization\_tool\_middleware](https://reference.langchain.com/python/deepagents/middleware/summarization/create_summarization_tool_middleware)，使代理能够在适当的时候触发摘要——例如在任务之间——而不是在固定的令牌间隔。有关更多详细信息，请参阅 [Harness 中的摘要](/oss/python/deepagents/harness#summarization)。

### 自定义中间件

您可以提供额外的中间件来扩展功能、添加工具或实现自定义钩子：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.tools import tool
from langchain.agents.middleware import wrap_tool_call
from deepagents import create_deep_agent


@tool
def get_weather(city: str) -> str:
    """获取城市天气。"""
    return f"{city} 的天气是晴朗的。"


call_count = [0]  # 使用列表以允许在嵌套函数中修改

@wrap_tool_call
def log_tool_calls(request, handler):
    """拦截并记录每次工具调用 - 演示横切关注点。"""
    call_count[0] += 1
    tool_name = request.name if hasattr(request, 'name') else str(request)

    print(f"[中间件] 工具调用 #{call_count[0]}: {tool_name}")
    print(f"[中间件] 参数：{request.args if hasattr(request, 'args') else 'N/A'}")

    # 执行工具调用
    result = handler(request)

    # 记录结果
    print(f"[中间件] 工具调用 #{call_count[0]} 完成")

    return result


agent = create_deep_agent(
    tools=[get_weather],
    middleware=[log_tool_calls],
)
```

<Warning>
  **初始化后不要修改属性**

  如果您需要在钩子调用之间跟踪值（例如计数器或累积数据），请使用图状态。
  图状态按设计是针对线程范围的，因此更新在并发下是安全的。

  **这样做：**

  ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  class CustomMiddleware(AgentMiddleware):
      def __init__(self):
          pass

      def before_agent(self, state, runtime):
          return {"x": state.get("x", 0) + 1}  # 更新图状态而不是直接修改
  ```

  **不要这样做：**

  ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  class CustomMiddleware(AgentMiddleware):
      def __init__(self):
          self.x = 1

      def before_agent(self, state, runtime):
          self.x += 1  # 修改会导致竞态条件
  ```

  就地修改，例如在 `before_agent` 中修改 `self.x` 或在钩子中更改其他共享值，可能会导致细微的错误和竞态条件，因为许多操作是并发运行的（子代理、并行工具和不同线程上的并行调用）。

  有关使用自定义属性扩展状态的完整详细信息，请参阅 [自定义中间件 - 自定义状态模式](/oss/python/langchain/middleware/custom#custom-state-schema)。
  如果您必须在自定义中间件中使用修改，请考虑当子代理、并行工具或并发代理调用同时运行时会发生什么。
</Warning>

## 子代理

为了隔离详细工作并避免上下文膨胀，请使用子代理：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os
from typing import Literal
from tavily import TavilyClient
from deepagents import create_deep_agent

tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])

def internet_search(
    query: str,
    max_results: int = 5,
    topic: Literal["general", "news", "finance"] = "general",
    include_raw_content: bool = False,
):
    """运行网络搜索"""
    return tavily_client.search(
        query,
        max_results=max_results,
        include_raw_content=include_raw_content,
        topic=topic,
    )

research_subagent = {
    "name": "research-agent",
    "description": "用于深入研究更复杂的问题",
    "system_prompt": "你是一位优秀的研究员",
    "tools": [internet_search],
    "model": "openai:gpt-5.2",  # 可选覆盖，默认为主代理模型
}
subagents = [research_subagent]

agent = create_deep_agent(
    model="claude-sonnet-4-6",
    subagents=subagents
)
```

有关更多信息，请参阅 [子代理](/oss/python/deepagents/subagents)。

{/* ## 上下文 - 您可以在运行之间持久化代理状态以存储用户 ID 等信息。*/}

## 后端

深度代理工具可以使用虚拟文件系统来存储、访问和编辑文件。默认情况下，Deep Agents 使用 [`StateBackend`](https://reference.langchain.com/python/deepagents/backends/state/StateBackend)。

如果您正在使用 [技能](#skills) 或 [记忆](#memory)，您必须在创建代理之前将预期的技能或记忆文件添加到后端。

<Tabs>
  <Tab title="StateBackend">
    存储在 `langgraph` 状态中的临时文件系统后端。

    此文件系统仅 *在一个线程内* 持久存在。

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    # 默认情况下，我们提供一个 StateBackend
    agent = create_deep_agent()

    # 底层实现如下
    from deepagents.backends import StateBackend

    agent = create_deep_agent(
        backend=(lambda rt: StateBackend(rt))   # 注意工具通过 runtime.state 访问 State
    )
    ```
  </Tab>

  <Tab title="FilesystemBackend">
    本地机器的文件系统。

    <Warning>
      此后端授予代理直接的文件系统读写访问权限。
      请谨慎使用，仅在合适的环境中使用。
      有关更多信息，请参阅 [`FilesystemBackend`](/oss/python/deepagents/backends#filesystembackend-local-disk)。
    </Warning>

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from deepagents.backends import FilesystemBackend

    agent = create_deep_agent(
        backend=FilesystemBackend(root_dir=".", virtual_mode=True)
    )
    ```
  </Tab>

  <Tab title="LocalShellBackend">
    直接在主机上执行 Shell 的文件系统。提供文件系统工具以及用于运行命令的 `execute` 工具。

    <Warning>
      此后端授予代理直接的文件系统读写访问权限 **以及** 在您主机上的无限制 Shell 执行权限。
      请极其谨慎使用，仅在合适的环境中使用。
      有关更多信息，请参阅 [`LocalShellBackend`](/oss/python/deepagents/backends#localshellbackend-local-shell)。
    </Warning>

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from deepagents.backends import LocalShellBackend

    agent = create_deep_agent(
        backend=LocalShellBackend(root_dir=".", env={"PATH": "/usr/bin:/bin"})
    )
    ```
  </Tab>

  <Tab title="StoreBackend">
    提供 *跨线程持久化* 长期存储的文件系统。

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from langgraph.store.memory import InMemoryStore
    from deepagents.backends import StoreBackend

    agent = create_deep_agent(
        backend=lambda rt: StoreBackend(
            rt,
            namespace=lambda ctx: (ctx.runtime.context.user_id,),
        ),
        store=InMemoryStore()  # 适用于本地开发；LangSmith Deployment 时省略
    )
    ```

    <Note>
      当部署到 [LangSmith Deployment](/langsmith/deployment) 时，请省略 `store` 参数。平台会自动为您的智能体配置存储。
    </Note>

    <Tip>
      `namespace` 参数控制数据隔离。对于多用户部署，始终设置 [命名空间工厂](/oss/python/deepagents/backends#namespace-factories) 以按用户或租户隔离数据。
    </Tip>
  </Tab>

  <Tab title="CompositeBackend">
    一个灵活的后端，您可以在其中指定文件系统中的不同路由指向不同的后端。

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from deepagents import create_deep_agent
    from deepagents.backends import CompositeBackend, StateBackend, StoreBackend
    from langgraph.store.memory import InMemoryStore

    composite_backend = lambda rt: CompositeBackend(
        default=StateBackend(rt),
        routes={
            "/memories/": StoreBackend(rt),
        }
    )

    agent = create_deep_agent(
        backend=composite_backend,
        store=InMemoryStore()  # Store passed to create_deep_agent, not backend
    )
    ```
  </Tab>
</Tabs>

有关更多信息，请参阅 [后端](/oss/python/deepagents/backends)。

### 沙箱

沙箱是专门的 [后端](/oss/python/deepagents/backends)，它们在具有自己的文件系统和用于 Shell 命令的 `execute` 工具的隔离环境中运行代理代码。
当您希望深度代理写入文件、安装依赖项和运行命令而不更改本地机器上的任何内容时，请使用沙箱后端。

您可以通过在创建深度代理时将沙箱后端传递给 `backend` 来配置沙箱：

<Tabs>
  <Tab title="Modal">
    <CodeGroup>
      ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pip install langchain-modal
      ```

      ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      uv add langchain-modal
      ```
    </CodeGroup>

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import modal
    from deepagents import create_deep_agent
    from langchain_anthropic import ChatAnthropic
    from langchain_modal import ModalSandbox

    app = modal.App.lookup("your-app")
    modal_sandbox = modal.Sandbox.create(app=app)
    backend = ModalSandbox(sandbox=modal_sandbox)

    agent = create_deep_agent(
        model=ChatAnthropic(model="claude-sonnet-4-20250514"),
        system_prompt="You are a Python coding assistant with sandbox access.",
        backend=backend,
    )
    try:
        result = agent.invoke(
            {
                "messages": [
                    {
                        "role": "user",
                        "content": "Create a small Python package and run pytest",
                    }
                ]
            }
        )
    finally:
        modal_sandbox.terminate()
    ```
  </Tab>

  <Tab title="Runloop">
    <CodeGroup>
      ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pip install langchain-runloop
      ```

      ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      uv add langchain-runloop
      ```
    </CodeGroup>

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import os

    from deepagents import create_deep_agent
    from langchain_anthropic import ChatAnthropic
    from langchain_runloop import RunloopSandbox
    from runloop_api_client import RunloopSDK

    client = RunloopSDK(bearer_token=os.environ["RUNLOOP_API_KEY"])

    devbox = client.devbox.create()
    backend = RunloopSandbox(devbox=devbox)

    agent = create_deep_agent(
        model=ChatAnthropic(model="claude-sonnet-4-20250514"),
        system_prompt="You are a Python coding assistant with sandbox access.",
        backend=backend,
    )

    try:
        result = agent.invoke(
            {
                "messages": [
                    {
                        "role": "user",
                        "content": "Create a small Python package and run pytest",
                    }
                ]
            }
        )
    finally:
        devbox.shutdown()
    ```
  </Tab>

  <Tab title="Daytona">
    <CodeGroup>
      ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pip install langchain-daytona
      ```

      ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      uv add langchain-daytona
      ```
    </CodeGroup>

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from daytona import Daytona
    from deepagents import create_deep_agent
    from langchain_anthropic import ChatAnthropic
    from langchain_daytona import DaytonaSandbox

    sandbox = Daytona().create()
    backend = DaytonaSandbox(sandbox=sandbox)

    agent = create_deep_agent(
        model=ChatAnthropic(model="claude-sonnet-4-20250514"),
        system_prompt="You are a Python coding assistant with sandbox access.",
        backend=backend,
    )

    try:
        result = agent.invoke(
            {
                "messages": [
                    {
                        "role": "user",
                        "content": "Create a small Python package and run pytest",
                    }
                ]
            }
        )
    finally:
        sandbox.stop()
    ```
  </Tab>
</Tabs>

有关更多信息，请参阅 [沙箱](/oss/python/deepagents/sandboxes)。

## 人机回环

某些工具操作可能很敏感，需要执行前获得人类批准。
您可以为每个工具配置批准：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain.tools import tool
from deepagents import create_deep_agent
from langgraph.checkpoint.memory import MemorySaver

@tool
def delete_file(path: str) -> str:
    """从文件系统中删除一个文件。"""
    return f"Deleted {path}"

@tool
def read_file(path: str) -> str:
    """从文件系统中读取一个文件。"""
    return f"Contents of {path}"

@tool
def send_email(to: str, subject: str, body: str) -> str:
    """发送一封电子邮件。"""
    return f"Sent email to {to}"

# 检查点器对于人机回环是必需的
checkpointer = MemorySaver()

agent = create_deep_agent(
    model="claude-sonnet-4-6",
    tools=[delete_file, read_file, send_email],
    interrupt_on={
        "delete_file": True,  # 默认：批准、编辑、拒绝
        "read_file": False,   # 无需中断
        "send_email": {"allowed_decisions": ["approve", "reject"]},  # 不可编辑
    },
    checkpointer=checkpointer  # 必需！
)
```

您还可以为代理和子代理配置工具调用期间以及工具调用内部的中断。
有关更多信息，请参阅 [人机回环](/oss/python/deepagents/human-in-the-loop)。

## 技能

您可以使用 [技能](/oss/python/deepagents/overview) 为您的深度代理提供新的能力和专业知识。
虽然 [工具](/oss/python/deepagents/customization#tools) 通常涵盖低级功能，如原生文件系统操作或规划，但技能可以包含完成任务的详细指令、参考信息和其他资源，例如模板。
这些文件仅在代理确定该技能对当前提示有用时才由代理加载。
这种渐进式披露减少了代理在启动时必须考虑的令牌和上下文数量。

有关示例技能，请参阅 [深度代理示例技能](https://github.com/langchain-ai/deepagentsjs/tree/main/examples/skills)。

要将技能添加到您的深度代理，请将它们作为参数传递给 `create_deep_agent`：

<Tabs>
  <Tab title="StateBackend">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from urllib.request import urlopen
    from deepagents import create_deep_agent
    from deepagents.backends.utils import create_file_data
    from langgraph.checkpoint.memory import MemorySaver

    checkpointer = MemorySaver()

    skill_url = "https://raw.githubusercontent.com/langchain-ai/deepagents/refs/heads/main/libs/cli/examples/skills/langgraph-docs/SKILL.md"
    with urlopen(skill_url) as response:
        skill_content = response.read().decode('utf-8')

    skills_files = {
        "/skills/langgraph-docs/SKILL.md": create_file_data(skill_content)
    }

    agent = create_deep_agent(
        skills=["/skills/"],
        checkpointer=checkpointer,
    )

    result = agent.invoke(
        {
            "messages": [
                {
                    "role": "user",
                    "content": "What is langgraph?",
                }
            ],
            # 初始化默认 StateBackend 的内存文件系统（虚拟路径必须以 "/" 开头）。
            "files": skills_files
        },
        config={"configurable": {"thread_id": "12345"}},
    )
    ```
  </Tab>

  <Tab title="StoreBackend">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from urllib.request import urlopen
    from deepagents import create_deep_agent
    from deepagents.backends import StoreBackend
    from deepagents.backends.utils import create_file_data
    from langgraph.store.memory import InMemoryStore


    store = InMemoryStore()

    skill_url = "https://raw.githubusercontent.com/langchain-ai/deepagents/refs/heads/main/libs/cli/examples/skills/langgraph-docs/SKILL.md"
    with urlopen(skill_url) as response:
        skill_content = response.read().decode('utf-8')

    store.put(
        namespace=("filesystem",),
        key="/skills/langgraph-docs/SKILL.md",
        value=create_file_data(skill_content)
    )

    agent = create_deep_agent(
        backend=(lambda rt: StoreBackend(rt)),
        store=store,
        skills=["/skills/"]
    )

    result = agent.invoke(
        {
            "messages": [
                {
                    "role": "user",
                    "content": "What is langgraph?",
                }
            ]
        },
        config={"configurable": {"thread_id": "12345"}},
    )
    ```
  </Tab>

  <Tab title="FilesystemBackend">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from deepagents import create_deep_agent
    from langgraph.checkpoint.memory import MemorySaver
    from deepagents.backends.filesystem import FilesystemBackend

    # 检查点器对于人工介入流程是必需的
    checkpointer = MemorySaver()

    agent = create_deep_agent(
        backend=FilesystemBackend(root_dir="/Users/user/{project}"),
        skills=["/Users/user/{project}/skills/"],
        interrupt_on={
            "write_file": True,  # 默认：批准、编辑、拒绝
            "read_file": False,  # 无需中断
            "edit_file": True    # 默认：批准、编辑、拒绝
        },
        checkpointer=checkpointer,  # 必需！
    )

    result = agent.invoke(
        {
            "messages": [
                {
                    "role": "user",
                    "content": "What is langgraph?",
                }
            ]
        },
        config={"configurable": {"thread_id": "12345"}},
    )
    ```
  </Tab>
</Tabs>

## 记忆

使用 [`AGENTS.md` 文件](https://agents.md/) 为您的深度代理提供额外上下文。

您可以在创建深度代理时将一个或多个文件路径传递给 `memory` 参数：

<Tabs>
  <Tab title="StateBackend">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from urllib.request import urlopen

    from deepagents import create_deep_agent
    from deepagents.backends.utils import create_file_data
    from langgraph.checkpoint.memory import MemorySaver

    with urlopen("https://raw.githubusercontent.com/langchain-ai/deepagents/refs/heads/main/examples/text-to-sql-agent/AGENTS.md") as response:
        agents_md = response.read().decode("utf-8")
    checkpointer = MemorySaver()

    agent = create_deep_agent(
        memory=[
            "/AGENTS.md"
        ],
        checkpointer=checkpointer,
    )

    result = agent.invoke(
        {
            "messages": [
                {
                    "role": "user",
                    "content": "Please tell me what's in your memory files.",
                }
            ],
            # 引导默认 StateBackend 的状态内文件系统（虚拟路径必须以 "/" 开头）。
            "files": {"/AGENTS.md": create_file_data(agents_md)},
        },
        config={"configurable": {"thread_id": "123456"}},
    )
    ```
  </Tab>

  <Tab title="StoreBackend">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from urllib.request import urlopen

    from deepagents import create_deep_agent
    from deepagents.backends import StoreBackend
    from deepagents.backends.utils import create_file_data
    from langgraph.store.memory import InMemoryStore

    with urlopen("https://raw.githubusercontent.com/langchain-ai/deepagents/refs/heads/main/examples/text-to-sql-agent/AGENTS.md") as response:
        agents_md = response.read().decode("utf-8")

    # 创建存储并将文件添加到其中
    store = InMemoryStore()
    file_data = create_file_data(agents_md)
    store.put(
        namespace=("filesystem",),
        key="/AGENTS.md",
        value=file_data
    )

    agent = create_deep_agent(
        backend=(lambda rt: StoreBackend(rt)),
        store=store,
        memory=[
            "/AGENTS.md"
        ]
    )

    result = agent.invoke(
        {
            "messages": [
                {
                    "role": "user",
                    "content": "Please tell me what's in your memory files.",
                }
            ],
            "files": {"/AGENTS.md": create_file_data(agents_md)},
        },
        config={"configurable": {"thread_id": "12345"}},
    )
    ```
  </Tab>

  <Tab title="FilesystemBackend">
    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from deepagents import create_deep_agent
    from langgraph.checkpoint.memory import MemorySaver
    from deepagents.backends import FilesystemBackend

    # 检查点器对于人机回环是必需的
    checkpointer = MemorySaver()

    agent = create_deep_agent(
        backend=FilesystemBackend(root_dir="/Users/user/{project}"),
        memory=[
            "./AGENTS.md"
        ],
        interrupt_on={
            "write_file": True,  # 默认：批准、编辑、拒绝
            "read_file": False,  # 不需要中断
            "edit_file": True    # 默认：批准、编辑、拒绝
        },
        checkpointer=checkpointer,  # 必需！
    )
    ```
  </Tab>
</Tabs>

## 结构化输出

Deep Agents 支持 [结构化输出](/oss/python/langchain/structured-output)。
您可以通过将所需的结构化输出模式作为 `response_format` 参数传递给 `create_deep_agent()` 调用来设置它。
当模型生成结构化数据时，它会被捕获、验证，并返回在深度代理状态的 'structured\_response' 键中。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os
from typing import Literal
from pydantic import BaseModel, Field
from tavily import TavilyClient
from deepagents import create_deep_agent

tavily_client = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])

def internet_search(
    query: str,
    max_results: int = 5,
    topic: Literal["general", "news", "finance"] = "general",
    include_raw_content: bool = False,
):
    """运行网络搜索"""
    return tavily_client.search(
        query,
        max_results=max_results,
        include_raw_content=include_raw_content,
        topic=topic,
    )

class WeatherReport(BaseModel):
    """带有当前条件和预报的结构化天气报告。"""
    location: str = Field(description="此天气报告的地点")
    temperature: float = Field(description="当前摄氏温度")
    condition: str = Field(description="当前天气状况（例如，晴朗、多云、下雨）")
    humidity: int = Field(description="湿度百分比")
    wind_speed: float = Field(description="风速（公里/小时）")
    forecast: str = Field(description="未来 24 小时的简要预报")


agent = create_deep_agent(
    response_format=WeatherReport,
    tools=[internet_search]
)

result = agent.invoke({
    "messages": [{
        "role": "user",
        "content": "What's the weather like in San Francisco?"
    }]
})

print(result["structured_response"])
# location='San Francisco, California' temperature=18.3 condition='Sunny' humidity=48 wind_speed=7.6 forecast='Pleasant sunny conditions expected to continue with temperatures around 64°F (18°C) during the day, dropping to around 52°F (11°C) at night. Clear skies with minimal precipitation expected.'
```

有关更多信息和示例，请参阅 [响应格式](/oss/python/langchain/structured-output#response-format)。

***

<div className="source-links">
  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\deepagents\customization.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
