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

# 自定义 Deep Agents

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

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

* [模型](#model)
* [工具](#tools)
* [系统提示词](#system-prompt)
* [Middleware](#middleware)，包括[预构建 Middleware](#prebuilt-middleware) 和[自定义 Middleware](#custom-middleware)
* [解释器](#interpreters)
* [子 Agent](#subagents)
* [后端（虚拟文件系统）](#backends)
* [人机协作](#human-in-the-loop)
* [技能](#skills)
* [记忆](#memory)
* [配置文件](#profiles)

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
create_deep_agent(
    model: str | BaseChatModel | None = None,
    tools: Sequence[BaseTool | Callable | dict[str, Any]] | None = None,
    *,
    system_prompt: str | SystemMessage | None = None,
    middleware: Sequence[AgentMiddleware] = (),
    subagents: Sequence[SubAgent | CompiledSubAgent | AsyncSubAgent] | None = None,
    skills: list[str] | None = None,
    memory: list[str] | None = None,
    permissions: list[FilesystemPermission] | None = None,
    backend: BackendProtocol | BackendFactory | None = None,
    interrupt_on: dict[str, bool | InterruptOnConfig] | None = None,
    response_format: ResponseFormat[ResponseT] | type[ResponseT] | dict[str, Any] | None = None,
    context_schema: type[ContextT] | None = None,
    checkpointer: Checkpointer | None = None,
    store: BaseStore | None = None,
    debug: bool = False,
    name: str | None = None,
    cache: BaseCache | None = None
) -> CompiledStateGraph[AgentState[ResponseT], ContextT, _InputAgentState, _OutputAgentState[ResponseT]]
```

完整参数列表请参阅 [`create_deep_agent`](https://reference.langchain.com/python/deepagents/graph/create_deep_agent) API 参考。

## 模型

传入 `provider:model` 格式的 `model` 字符串，或已初始化的模型实例。查看[支持的模型](/oss/python/deepagents/models#supported-models)了解所有提供商，查看[推荐模型](/oss/python/deepagents/models#suggested-models)了解经过测试的推荐方案。

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

<Tabs>
  <Tab title="OpenAI">
    👉 Read the [OpenAI chat model integration docs](/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.4")
      # this calls init_chat_model for the specified model with default parameters
      # to use specific model 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.4")
      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.4")
      agent = create_deep_agent(model=model)
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Anthropic">
    👉 Read the [Anthropic chat model integration docs](/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="anthropic:claude-sonnet-4-6")
      # this calls init_chat_model for the specified model with default parameters
      # to use specific model 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">
    👉 Read the [Azure chat model integration docs](/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.4")
      # this calls init_chat_model for the specified model with default parameters
      # to use specific model 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.4",
          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.4",
          azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],
      )
      agent = create_deep_agent(model=model)
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Google Gemini">
    👉 Read the [Google GenAI chat model integration docs](/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-3.1-pro-preview")
      # this calls init_chat_model for the specified model with default parameters
      # to use specific model 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-3.1-pro-preview")
      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-3.1-pro-preview")
      agent = create_deep_agent(model=model)
      ```
    </CodeGroup>
  </Tab>

  <Tab title="AWS Bedrock">
    👉 Read the [AWS Bedrock chat model integration docs](/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-sonnet-4-6",
          model_provider="bedrock_converse",
      )
      # this calls init_chat_model for the specified model with default parameters
      # to use specific model 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-sonnet-4-6",
          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-sonnet-4-6")
      agent = create_deep_agent(model=model)
      ```
    </CodeGroup>
  </Tab>

  <Tab title="HuggingFace">
    👉 Read the [HuggingFace chat model integration docs](/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 model 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>

  <Tab title="Other">
    Pass any [supported model string](/oss/python/deepagents/models#supported-models), or an initialized model instance:

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

      agent = create_deep_agent(model="provider:model-name")
      ```

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

      model = init_chat_model("provider:model-name")
      agent = create_deep_agent(model=model)
      ```

      ```python model class theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      from langchain_<provider> import Chat<Provider>
      from deepagents import create_deep_agent

      model = Chat<Provider>(model="model-name")
      agent = create_deep_agent(model=model)
      ```
    </CodeGroup>
  </Tab>
</Tabs>

<Tip>
  Chat Model 会自动重试临时 API 故障（使用指数退避）。有关默认值、限制以及调整 `max_retries` / `timeout` 的代码示例，请参阅 LangChain [模型](/oss/python/langchain/models#connection-resilience)页面。
</Tip>

## 工具

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

<CodeGroup>
  ```python Google 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,
  ):
      """Run a web search"""
      return tavily_client.search(
          query,
          max_results=max_results,
          include_raw_content=include_raw_content,
          topic=topic,
      )


  agent = create_deep_agent(
      model="google_genai:gemini-3.1-pro-preview",
      tools=[internet_search],
  )
  ```

  ```python OpenAI 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,
  ):
      """Run a web search"""
      return tavily_client.search(
          query,
          max_results=max_results,
          include_raw_content=include_raw_content,
          topic=topic,
      )


  agent = create_deep_agent(
      model="openai:gpt-5.4",
      tools=[internet_search],
  )
  ```

  ```python Anthropic 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,
  ):
      """Run a web search"""
      return tavily_client.search(
          query,
          max_results=max_results,
          include_raw_content=include_raw_content,
          topic=topic,
      )


  agent = create_deep_agent(
      model="anthropic:claude-sonnet-4-6",
      tools=[internet_search],
  )
  ```

  ```python OpenRouter 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,
  ):
      """Run a web search"""
      return tavily_client.search(
          query,
          max_results=max_results,
          include_raw_content=include_raw_content,
          topic=topic,
      )


  agent = create_deep_agent(
      model="openrouter:anthropic/claude-sonnet-4-6",
      tools=[internet_search],
  )
  ```

  ```python Fireworks 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,
  ):
      """Run a web search"""
      return tavily_client.search(
          query,
          max_results=max_results,
          include_raw_content=include_raw_content,
          topic=topic,
      )


  agent = create_deep_agent(
      model="fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
      tools=[internet_search],
  )
  ```

  ```python Baseten 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,
  ):
      """Run a web search"""
      return tavily_client.search(
          query,
          max_results=max_results,
          include_raw_content=include_raw_content,
          topic=topic,
      )


  agent = create_deep_agent(
      model="baseten:zai-org/GLM-5",
      tools=[internet_search],
  )
  ```

  ```python Ollama 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,
  ):
      """Run a web search"""
      return tavily_client.search(
          query,
          max_results=max_results,
          include_raw_content=include_raw_content,
          topic=topic,
      )


  agent = create_deep_agent(
      model="ollama:devstral-2",
      tools=[internet_search],
  )
  ```
</CodeGroup>

## 系统提示词

Deep Agents 内置了系统提示词。Deep Agent 的价值来自 SDK 在模型之上提供的编排层——规划、虚拟文件系统工具和子 Agent——模型需要知道这些工具的存在以及何时使用它们。内置提示词教会 Agent 如何使用这些脚手架，因此你不需要在每个项目中重新推导；通过[配置文件](/oss/python/deepagents/profiles#harness-profiles)或你自己的 `system_prompt=` 来调整，而不是逐字复制。

当 Middleware 添加特殊工具（如文件系统工具）时，它会将工具追加到系统提示词中。

每个 Deep Agent 还应包含针对其特定用例的自定义系统提示词：

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

  research_instructions = """\
  You are an expert researcher. Your job is to conduct \
  thorough research, and then write a polished report. \
  """

  agent = create_deep_agent(
      model="google_genai:gemini-3.1-pro-preview",
      system_prompt=research_instructions,
  )
  ```

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

  research_instructions = """\
  You are an expert researcher. Your job is to conduct \
  thorough research, and then write a polished report. \
  """

  agent = create_deep_agent(
      model="openai:gpt-5.4",
      system_prompt=research_instructions,
  )
  ```

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

  research_instructions = """\
  You are an expert researcher. Your job is to conduct \
  thorough research, and then write a polished report. \
  """

  agent = create_deep_agent(
      model="anthropic:claude-sonnet-4-6",
      system_prompt=research_instructions,
  )
  ```

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

  research_instructions = """\
  You are an expert researcher. Your job is to conduct \
  thorough research, and then write a polished report. \
  """

  agent = create_deep_agent(
      model="openrouter:anthropic/claude-sonnet-4-6",
      system_prompt=research_instructions,
  )
  ```

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

  research_instructions = """\
  You are an expert researcher. Your job is to conduct \
  thorough research, and then write a polished report. \
  """

  agent = create_deep_agent(
      model="fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
      system_prompt=research_instructions,
  )
  ```

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

  research_instructions = """\
  You are an expert researcher. Your job is to conduct \
  thorough research, and then write a polished report. \
  """

  agent = create_deep_agent(
      model="baseten:zai-org/GLM-5",
      system_prompt=research_instructions,
  )
  ```

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

  research_instructions = """\
  You are an expert researcher. Your job is to conduct \
  thorough research, and then write a polished report. \
  """

  agent = create_deep_agent(
      model="ollama:devstral-2",
      system_prompt=research_instructions,
  )
  ```
</CodeGroup>

### 提示词组装

Deep Agents 从最多四个命名部分构建系统提示词，使得调用方提供的指令、SDK 内置的 Agent 指导和任何模型特定的[配置文件](/oss/python/deepagents/profiles)覆盖可以以可预测的优先级共存。如果没有这种分层，针对 Claude 调优的配置后缀（例如）可能会根据调用顺序覆盖或被你的 `system_prompt=` 参数覆盖；命名槽使排序显式且稳定。

在实践中，大多数调用方只会遇到两个槽：`USER`（你的 `system_prompt=`）和 `BASE`（SDK 默认值）。选择带有内置配置的模型（目前是 Anthropic 或 OpenAI）会添加一个 `SUFFIX`。完整的四部分组装主要与你编写自定义 `HarnessProfile` 或调试配置文本出现位置时相关。

四个命名部分（每个可能不存在）：

| 名称       | 来源                                                                                        | 说明                              |
| -------- | ----------------------------------------------------------------------------------------- | ------------------------------- |
| `USER`   | `create_deep_agent` 的 `system_prompt=` 参数                                                 | `str` 或 `SystemMessage`；未设置时省略。 |
| `BASE`   | SDK 默认值（`BASE_AGENT_PROMPT`）                                                              | 始终存在，除非被配置的 `CUSTOM` 替换。        |
| `CUSTOM` | [`HarnessProfile.base_system_prompt`](/oss/python/deepagents/profiles#harness-profiles)   | 当匹配的配置设置时，直接替换 `BASE`。          |
| `SUFFIX` | [`HarnessProfile.system_prompt_suffix`](/oss/python/deepagents/profiles#harness-profiles) | 当匹配的配置设置时，追加到最后。                |

顺序始终为 **`USER` -> (`BASE` 或 `CUSTOM`) -> `SUFFIX`**，用空行（`\n\n`）连接。由此得出两个不变量：

1. **`USER` 始终在最前面。** 调用方的文本先于任何 SDK 或配置内容，因此无论选择哪个模型，角色/指令都具有最高优先级。
2. **`SUFFIX` 始终在最后。** 配置后缀最靠近对话历史，这是模型调优指导最可靠落地的位置。

组装形态（✓ = 已设置字段，- = 未设置字段）：

| `system_prompt=` | 配置 `base_system_prompt`（`CUSTOM`） | 配置 `system_prompt_suffix`（`SUFFIX`） | 最终组装的系统提示词                   |
| ---------------- | :-------------------------------: | :---------------------------------: | ---------------------------- |
| `None`           |                 -                 |                  -                  | `BASE`                       |
| `None`           |                 -                 |                  ✓                  | `BASE` + `SUFFIX`            |
| `None`           |                 ✓                 |                  -                  | `CUSTOM`                     |
| `None`           |                 ✓                 |                  ✓                  | `CUSTOM` + `SUFFIX`          |
| `str`            |                 -                 |                  -                  | `USER` + `BASE`              |
| `str`            |                 -                 |                  ✓                  | `USER` + `BASE` + `SUFFIX`   |
| `str`            |                 ✓                 |                  -                  | `USER` + `CUSTOM`            |
| `str`            |                 ✓                 |                  ✓                  | `USER` + `CUSTOM` + `SUFFIX` |

实例——内置配置（Anthropic、OpenAI）仅提供 `system_prompt_suffix`，因此典型调用落在 `str` + `-` + `✓` 行：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    system_prompt="You are a customer-support agent for ACME Corp.",
)
# 最终 = USER + BASE + SUFFIX
#      = "You are a customer-support agent for ACME Corp."
#        + "\n\n"
#        + BASE_AGENT_PROMPT
#        + "\n\n"
#        + <Claude 特定指导>
```

<Note>
  传递 `SystemMessage`（而不是字符串）会触发不同的拼接路径：右侧组装（`BASE` 或 `CUSTOM` 加上任何 `SUFFIX`）作为额外的文本内容块追加到消息的现有 `content_blocks` 上。相同的逻辑排序适用（调用方的块在前），调用方块上的任何 `cache_control` 标记会被保留——这对于放置显式的 Anthropic Prompt 缓存断点很有用。
</Note>

<AccordionGroup>
  <Accordion title="子 Agent 提示词">
    相同的覆盖规则适用于声明式[子 Agent](/oss/python/deepagents/subagents)——每个子 Agent 针对**自己的模型**重新运行配置解析，然后将解析后的配置的 `base_system_prompt` / `system_prompt_suffix` 应用于其编写的 `system_prompt`。子 Agent 的 `system_prompt` 扮演 `BASE` 角色；`CUSTOM` 和 `SUFFIX` 来自匹配子 Agent 模型的配置（可能与主 Agent 的配置不同）。

    | `spec["system_prompt"]` | 配置 `base_system_prompt`（`CUSTOM`） | 配置 `system_prompt_suffix`（`SUFFIX`） | 最终子 Agent 系统提示词     |
    | ----------------------- | :-------------------------------: | :---------------------------------: | ------------------- |
    | 已编写                     |                 -                 |                  -                  | 已编写                 |
    | 已编写                     |                 -                 |                  ✓                  | 已编写 + `SUFFIX`      |
    | 已编写                     |                 ✓                 |                  -                  | `CUSTOM`            |
    | 已编写                     |                 ✓                 |                  ✓                  | `CUSTOM` + `SUFFIX` |

    子 Agent 没有 `USER` 段——规格中编写的 `system_prompt` 是最接近的类比，保留在 `BASE` 槽中。仅提供 `system_prompt_suffix` 的配置（内置 Anthropic / OpenAI 配置的常见情况）只是追加到子 Agent 作者编写的内容之后；设置 `base_system_prompt` 的配置会*直接替换*编写的提示词，因此请谨慎使用该字段。
  </Accordion>

  <Accordion title="通用子 Agent 提示词">
    自动添加的[通用子 Agent](/oss/python/deepagents/subagents#the-general-purpose-subagent) 遵循相同的覆盖规则，但多了一层：GP 基础提示词的解析顺序为 **`general_purpose_subagent.system_prompt`（如果设置）-> `HarnessProfile.base_system_prompt`（如果设置）-> SDK GP 默认值**。配置后缀无论如何都会叠加在上面。

    这两个覆盖字段都可以承载基础提示词替换，但它们不可互换。`general_purpose_subagent.system_prompt` 是 GP 特定的配置；`base_system_prompt` 是主要针对主 Agent 的全局覆盖。当两者都设置时，**GP 特定的意图对 GP 子 Agent 优先生效**，这样同时调整两个字段的用户不会看到其 GP 覆盖被静默丢弃：

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    register_harness_profile(
        "anthropic",
        HarnessProfile(
            base_system_prompt="You are ACME's support orchestrator.",  # 主 Agent
            general_purpose_subagent=GeneralPurposeSubagentProfile(
                system_prompt="You are a research subagent. Cite sources.",  # GP 子 Agent
            ),
            system_prompt_suffix="Always think step by step.",
        ),
    )
    ```

    | 栈          | 最终系统提示词                                                 |
    | ---------- | ------------------------------------------------------- |
    | 主 Agent    | `"You are ACME's support orchestrator." + SUFFIX`       |
    | GP 子 Agent | `"You are a research subagent. Cite sources." + SUFFIX` |

    如果 `general_purpose_subagent.system_prompt` 未设置，GP 子 Agent 回退到 `base_system_prompt`（如果设置），最终回退到 SDK GP 默认值。
  </Accordion>
</AccordionGroup>

## Middleware

Deep Agents 支持任何 [Middleware](/oss/python/langchain/middleware/overview)，包括下面列出的内置 Middleware、LangChain 的预构建 Middleware、特定提供商的 Middleware，以及你自己编写的自定义 Middleware。将 Middleware 传递给 `create_deep_agent` 的 `middleware` 参数。

默认情况下，Deep Agents 可以使用以下 Middleware：

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

如果你使用记忆、技能或人机协作，还会包含以下 Middleware：

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

### 预构建 Middleware

LangChain 提供额外的预构建 Middleware，让你可以添加各种功能，如重试、回退或 PII 检测。参见[预构建 Middleware](/oss/python/langchain/middleware/built-in) 了解更多。

`deepagents` 库还暴露了 [`create_summarization_tool_middleware`](https://reference.langchain.com/python/deepagents/middleware/summarization/create_summarization_tool_middleware)，使 Agent 能够在适当的时机触发摘要——例如在任务之间——而不是在固定的 Token 间隔。更多详情请参阅[摘要](/oss/python/deepagents/context-engineering#summarization)。

### 特定提供商 Middleware

有关针对特定 LLM 提供商优化的 Middleware，请参阅[官方集成](/oss/python/integrations/middleware#official-integrations)和[社区集成](/oss/python/integrations/middleware#community-integrations)。

### 自定义 Middleware

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

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


  @tool
  def get_weather(city: str) -> str:
      """Get the weather in a city."""
      return f"The weather in {city} is sunny."


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


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

      print(f"[Middleware] Tool 调用 #{call_count[0]}: {tool_name}")
      print(f"[Middleware] 参数: {request.args if hasattr(request, 'args') else 'N/A'}")

      # 执行 Tool 调用
      result = handler(request)

      # 记录结果
      print(f"[Middleware] Tool 调用 #{call_count[0]} 完成")

      return result


  agent = create_deep_agent(
      model="google_genai:gemini-3.1-pro-preview",
      tools=[get_weather],
      middleware=[log_tool_calls],
  )
  ```

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


  @tool
  def get_weather(city: str) -> str:
      """Get the weather in a city."""
      return f"The weather in {city} is sunny."


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


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

      print(f"[Middleware] Tool 调用 #{call_count[0]}: {tool_name}")
      print(f"[Middleware] 参数: {request.args if hasattr(request, 'args') else 'N/A'}")

      # 执行 Tool 调用
      result = handler(request)

      # 记录结果
      print(f"[Middleware] Tool 调用 #{call_count[0]} 完成")

      return result


  agent = create_deep_agent(
      model="openai:gpt-5.4",
      tools=[get_weather],
      middleware=[log_tool_calls],
  )
  ```

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


  @tool
  def get_weather(city: str) -> str:
      """Get the weather in a city."""
      return f"The weather in {city} is sunny."


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


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

      print(f"[Middleware] Tool 调用 #{call_count[0]}: {tool_name}")
      print(f"[Middleware] 参数: {request.args if hasattr(request, 'args') else 'N/A'}")

      # 执行 Tool 调用
      result = handler(request)

      # 记录结果
      print(f"[Middleware] Tool 调用 #{call_count[0]} 完成")

      return result


  agent = create_deep_agent(
      model="anthropic:claude-sonnet-4-6",
      tools=[get_weather],
      middleware=[log_tool_calls],
  )
  ```

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


  @tool
  def get_weather(city: str) -> str:
      """Get the weather in a city."""
      return f"The weather in {city} is sunny."


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


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

      print(f"[Middleware] Tool 调用 #{call_count[0]}: {tool_name}")
      print(f"[Middleware] 参数: {request.args if hasattr(request, 'args') else 'N/A'}")

      # 执行 Tool 调用
      result = handler(request)

      # 记录结果
      print(f"[Middleware] Tool 调用 #{call_count[0]} 完成")

      return result


  agent = create_deep_agent(
      model="openrouter:anthropic/claude-sonnet-4-6",
      tools=[get_weather],
      middleware=[log_tool_calls],
  )
  ```

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


  @tool
  def get_weather(city: str) -> str:
      """Get the weather in a city."""
      return f"The weather in {city} is sunny."


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


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

      print(f"[Middleware] Tool 调用 #{call_count[0]}: {tool_name}")
      print(f"[Middleware] 参数: {request.args if hasattr(request, 'args') else 'N/A'}")

      # 执行 Tool 调用
      result = handler(request)

      # 记录结果
      print(f"[Middleware] Tool 调用 #{call_count[0]} 完成")

      return result


  agent = create_deep_agent(
      model="fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
      tools=[get_weather],
      middleware=[log_tool_calls],
  )
  ```

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


  @tool
  def get_weather(city: str) -> str:
      """Get the weather in a city."""
      return f"The weather in {city} is sunny."


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


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

      print(f"[Middleware] Tool 调用 #{call_count[0]}: {tool_name}")
      print(f"[Middleware] 参数: {request.args if hasattr(request, 'args') else 'N/A'}")

      # 执行 Tool 调用
      result = handler(request)

      # 记录结果
      print(f"[Middleware] Tool 调用 #{call_count[0]} 完成")

      return result


  agent = create_deep_agent(
      model="baseten:zai-org/GLM-5",
      tools=[get_weather],
      middleware=[log_tool_calls],
  )
  ```

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


  @tool
  def get_weather(city: str) -> str:
      """Get the weather in a city."""
      return f"The weather in {city} is sunny."


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


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

      print(f"[Middleware] Tool 调用 #{call_count[0]}: {tool_name}")
      print(f"[Middleware] 参数: {request.args if hasattr(request, 'args') else 'N/A'}")

      # 执行 Tool 调用
      result = handler(request)

      # 记录结果
      print(f"[Middleware] Tool 调用 #{call_count[0]} 完成")

      return result


  agent = create_deep_agent(
      model="ollama:devstral-2",
      tools=[get_weather],
      middleware=[log_tool_calls],
  )
  ```
</CodeGroup>

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

  如果你需要在钩子调用之间跟踪值（例如计数器或累积数据），请使用 Graph State。
  Graph State 在设计上限定于线程作用域，因此在并发下更新是安全的。

  **应该这样做：**

  ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  from langchain.agents.middleware import AgentMiddleware


  class CustomMiddleware(AgentMiddleware):
      def __init__(self):
          pass

      def before_agent(self, state, runtime):
          return {"x": state.get("x", 0) + 1}  # 改为更新 Graph State
  ```

  **不要**这样做：

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

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

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

  有关使用自定义属性扩展状态的完整详情，请参阅[自定义 Middleware - 自定义状态 Schema](/oss/python/langchain/middleware/custom#custom-state-schema)。
  如果你必须在自定义 Middleware 中使用变更，请考虑当子 Agent、并行工具或并发 Agent 调用同时运行时会发生什么。
</Warning>

### 解释器

使用[解释器](/oss/python/deepagents/interpreters)添加一个 `eval` 工具，在限定范围的 QuickJS 运行时中运行 JavaScript。当 Agent 需要以编程方式组合工具、批量处理工作、在代码中处理错误或转换结构化数据而不需要完整的 Shell 环境时，解释器非常有用。

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

  agent = create_deep_agent(
      model="google_genai:gemini-3.1-pro-preview",
      middleware=[CodeInterpreterMiddleware()],
  )
  ```

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

  agent = create_deep_agent(
      model="openai:gpt-5.4",
      middleware=[CodeInterpreterMiddleware()],
  )
  ```

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

  agent = create_deep_agent(
      model="anthropic:claude-sonnet-4-6",
      middleware=[CodeInterpreterMiddleware()],
  )
  ```

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

  agent = create_deep_agent(
      model="openrouter:anthropic/claude-sonnet-4-6",
      middleware=[CodeInterpreterMiddleware()],
  )
  ```

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

  agent = create_deep_agent(
      model="fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
      middleware=[CodeInterpreterMiddleware()],
  )
  ```

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

  agent = create_deep_agent(
      model="baseten:zai-org/GLM-5",
      middleware=[CodeInterpreterMiddleware()],
  )
  ```

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

  agent = create_deep_agent(
      model="ollama:devstral-2",
      middleware=[CodeInterpreterMiddleware()],
  )
  ```
</CodeGroup>

有关设置、程序化工具调用、解释器技能和限制，请参阅[解释器](/oss/python/deepagents/interpreters)。

## 子 Agent

要隔离详细工作并避免上下文膨胀，请使用子 Agent：

```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,
):
    """Run a web search"""
    return tavily_client.search(
        query,
        max_results=max_results,
        include_raw_content=include_raw_content,
        topic=topic,
    )

research_subagent = {
    "name": "research-agent",
    "description": "Used to research more in depth questions",
    "system_prompt": "You are a great researcher",
    "tools": [internet_search],
    "model": "openai:gpt-5.4",  # Optional override, defaults to main agent model
}
subagents = [research_subagent]

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

更多信息请参阅[子 Agent](/oss/python/deepagents/subagents)。

{/* ## Context - You can persist agent state between runs to store information like user IDs. */}

## 后端

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

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

<Tabs>
  <Tab title="StateBackend">
    线程作用域的文件系统后端，存储在 `langgraph` State 中。

    文件在同一线程内跨轮次持久化（通过 Checkpointer），不会跨线程共享。

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    # 默认情况下 we provide a StateBackend
    agent = create_deep_agent(model="google_genai:gemini-3.1-pro-preview")

    # Under the hood, it looks like
    from deepagents.backends import StateBackend

    agent = create_deep_agent(
        model="google_genai:gemini-3.1-pro-preview",
        backend=StateBackend()
    )
    ```
  </Tab>

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

    <Warning>
      此后端授予 Agent 直接的文件系统读写访问权限。
      请谨慎使用，仅在适当的环境中使用。
      更多信息请参阅 [`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(
        model="google_genai:gemini-3.1-pro-preview",
        backend=FilesystemBackend(root_dir=".", virtual_mode=True)
    )
    ```
  </Tab>

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

    <Warning>
      此后端授予 Agent 直接的文件系统读写访问权限**以及**在主机上不受限的 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(
        model="google_genai:gemini-3.1-pro-preview",
        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(
        model="google_genai:gemini-3.1-pro-preview",
        backend=StoreBackend(
            namespace=lambda ctx: (ctx.runtime.context.user_id,),
        ),
        store=InMemoryStore()  # Good for local dev; omit for LangSmith Deployment
    )
    ```

    <Note>
      When deploying to [LangSmith Deployment](/langsmith/deployment), omit the `store` parameter. The platform automatically provisions a store for your agent.
    </Note>

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

  <Tab title="ContextHubBackend">
    LangSmith Hub 仓库中的持久化文件系统存储。

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

    agent = create_deep_agent(
        model="google_genai:gemini-3.1-pro-preview",
        backend=ContextHubBackend("my-agent")
    )
    ```

    更多详情请参阅 [`ContextHubBackend`](/oss/python/deepagents/backends#contexthubbackend)。
  </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

    agent = create_deep_agent(
        model="google_genai:gemini-3.1-pro-preview",
        backend=CompositeBackend(
            default=StateBackend(),
            routes={
                "/memories/": StoreBackend(),
            }
        ),
        store=InMemoryStore()  # Store passed to create_deep_agent, not backend
    )
    ```
  </Tab>
</Tabs>

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

### Sandbox

Sandbox 是专门的[后端](/oss/python/deepagents/backends)，在隔离环境中运行 Agent 代码，拥有自己的文件系统和用于 Shell 命令的 `execute` 工具。
当你希望 Deep Agent 写文件、安装依赖和运行命令而不影响本地机器时，使用 Sandbox 后端。

通过在创建 Deep Agent 时将 Sandbox 后端传递给 `backend` 来配置 Sandbox：

<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-6"),
        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-6"),
        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-6"),
        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>

  <Tab title="LangSmith">
    <Note>
      LangSmith sandboxes are currently in private beta.
    </Note>

    <CodeGroup>
      ```bash pip theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      pip install "langsmith[sandbox]"
      ```

      ```bash uv theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
      uv add "langsmith[sandbox]"
      ```
    </CodeGroup>

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    from deepagents import create_deep_agent
    from deepagents.backends import LangSmithSandbox
    from langchain_anthropic import ChatAnthropic
    from langsmith.sandbox import SandboxClient

    client = SandboxClient()
    ls_sandbox = client.create_sandbox(template_name="my-template")
    backend = LangSmithSandbox(sandbox=ls_sandbox)

    agent = create_deep_agent(
        model=ChatAnthropic(model="claude-sonnet-4-6"),
        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:
        client.delete_sandbox(ls_sandbox.name)
    ```
  </Tab>
</Tabs>

更多信息请参阅 [Sandbox](/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:
    """Delete a file from the filesystem."""
    return f"Deleted {path}"

@tool
def read_file(path: str) -> str:
    """Read a file from the filesystem."""
    return f"Contents of {path}"

@tool
def send_email(to: str, subject: str, body: str) -> str:
    """Send an email."""
    return f"Sent email to {to}"

# Checkpointer is REQUIRED for human-in-the-loop
checkpointer = MemorySaver()

agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    tools=[delete_file, read_file, send_email],
    interrupt_on={
        "delete_file": True,  # Default: approve, edit, reject, respond
        "read_file": False,   # No interrupts needed
        "send_email": {"allowed_decisions": ["approve", "reject"]},  # No editing
    },
    checkpointer=checkpointer  # Required!
)
```

你可以在工具调用时以及工具调用内部为 Agent 和子 Agent 配置 Interrupt。
更多信息请参阅[人机协作](/oss/python/deepagents/human-in-the-loop)。

## 技能

你可以使用[技能](/oss/python/deepagents/overview)为 Deep Agent 提供新的能力和专业知识。
虽然[工具](/oss/python/deepagents/customization#tools)倾向于覆盖较低级别的功能，如原生文件系统操作或规划，技能可以包含关于如何完成任务的详细说明、参考信息和其他资产（如模板）。
这些文件仅在 Agent 确定该技能对当前 Prompt 有用时才由 Agent 加载。
这种渐进式披露减少了 Agent 在启动时需要考虑的 Token 和上下文量。

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

要将技能添加到 Deep Agent，将它们作为参数传递给 `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
    from deepagents.backends import StateBackend
    from langchain_quickjs import CodeInterpreterMiddleware

    checkpointer = MemorySaver()
    backend = StateBackend()

    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(
        model="google_genai:gemini-3.1-pro-preview",
        backend=backend,
        skills=["/skills/"],
        checkpointer=checkpointer,
        middleware=[CodeInterpreterMiddleware(skills_backend=backend)] # for interpreter skills
    )

    result = agent.invoke(
        {
            "messages": [
                {
                    "role": "user",
                    "content": "What is langgraph?",
                }
            ],
            # Seed the default StateBackend's in-state filesystem (virtual paths must start with "/").
            "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
    from langchain_quickjs import CodeInterpreterMiddleware


    store = InMemoryStore()
    backend = StoreBackend()

    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(
        model="google_genai:gemini-3.1-pro-preview",
        backend=backend,
        store=store,
        skills=["/skills/"],
        middleware=[CodeInterpreterMiddleware(skills_backend=backend)] # for interpreter 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
    from langchain_quickjs import CodeInterpreterMiddleware

    # Checkpointer is REQUIRED for human-in-the-loop
    checkpointer = MemorySaver()
    backend = FilesystemBackend(root_dir="/Users/user/{project}")

    agent = create_deep_agent(
        model="google_genai:gemini-3.1-pro-preview",
        backend=,
        skills=["/Users/user/{project}/skills/"],
        interrupt_on={
            "write_file": True,  # Default: approve, edit, reject
            "read_file": False,  # No interrupts needed
            "edit_file": True    # Default: approve, edit, reject
        },
        checkpointer=checkpointer,  # Required!
        middleware=[CodeInterpreterMiddleware(skills_backend=backend)] # for interpreter skills
    )

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

## 记忆

使用 [`AGENTS.md` 文件](https://agents.md/)为 Deep Agent 提供额外上下文。

创建 Deep Agent 时，你可以将一个或多个文件路径传递给 `memory` 参数：

<Tabs>
  <Tab title="StateBackend">
    <CodeGroup>
      ```python Google 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(
          model="google_genai:gemini-3.1-pro-preview",
          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"}},
      )
      ```

      ```python OpenAI 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(
          model="openai:gpt-5.4",
          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"}},
      )
      ```

      ```python Anthropic 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(
          model="anthropic:claude-sonnet-4-6",
          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"}},
      )
      ```

      ```python OpenRouter 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(
          model="openrouter:anthropic/claude-sonnet-4-6",
          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"}},
      )
      ```

      ```python Fireworks 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(
          model="fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
          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"}},
      )
      ```

      ```python Baseten 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(
          model="baseten:zai-org/GLM-5",
          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"}},
      )
      ```

      ```python Ollama 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(
          model="ollama:devstral-2",
          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"}},
      )
      ```
    </CodeGroup>
  </Tab>

  <Tab title="StoreBackend">
    <CodeGroup>
      ```python Google 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 并将文件添加到其中
      store = InMemoryStore()
      file_data = create_file_data(agents_md)
      store.put(
          namespace=("filesystem",),
          key="/AGENTS.md",
          value=file_data,
      )

      agent = create_deep_agent(
          model="google_genai:gemini-3.1-pro-preview",
          backend=StoreBackend(),
          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"}},
      )
      ```

      ```python OpenAI 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 并将文件添加到其中
      store = InMemoryStore()
      file_data = create_file_data(agents_md)
      store.put(
          namespace=("filesystem",),
          key="/AGENTS.md",
          value=file_data,
      )

      agent = create_deep_agent(
          model="openai:gpt-5.4",
          backend=StoreBackend(),
          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"}},
      )
      ```

      ```python Anthropic 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 并将文件添加到其中
      store = InMemoryStore()
      file_data = create_file_data(agents_md)
      store.put(
          namespace=("filesystem",),
          key="/AGENTS.md",
          value=file_data,
      )

      agent = create_deep_agent(
          model="anthropic:claude-sonnet-4-6",
          backend=StoreBackend(),
          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"}},
      )
      ```

      ```python OpenRouter 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 并将文件添加到其中
      store = InMemoryStore()
      file_data = create_file_data(agents_md)
      store.put(
          namespace=("filesystem",),
          key="/AGENTS.md",
          value=file_data,
      )

      agent = create_deep_agent(
          model="openrouter:anthropic/claude-sonnet-4-6",
          backend=StoreBackend(),
          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"}},
      )
      ```

      ```python Fireworks 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 并将文件添加到其中
      store = InMemoryStore()
      file_data = create_file_data(agents_md)
      store.put(
          namespace=("filesystem",),
          key="/AGENTS.md",
          value=file_data,
      )

      agent = create_deep_agent(
          model="fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
          backend=StoreBackend(),
          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"}},
      )
      ```

      ```python Baseten 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 并将文件添加到其中
      store = InMemoryStore()
      file_data = create_file_data(agents_md)
      store.put(
          namespace=("filesystem",),
          key="/AGENTS.md",
          value=file_data,
      )

      agent = create_deep_agent(
          model="baseten:zai-org/GLM-5",
          backend=StoreBackend(),
          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"}},
      )
      ```

      ```python Ollama 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 并将文件添加到其中
      store = InMemoryStore()
      file_data = create_file_data(agents_md)
      store.put(
          namespace=("filesystem",),
          key="/AGENTS.md",
          value=file_data,
      )

      agent = create_deep_agent(
          model="ollama:devstral-2",
          backend=StoreBackend(),
          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"}},
      )
      ```
    </CodeGroup>
  </Tab>

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

      # 人机协作（human-in-the-loop）必须配置 Checkpointer
      checkpointer = MemorySaver()

      agent = create_deep_agent(
          model="google_genai:gemini-3.1-pro-preview",
          backend=FilesystemBackend(root_dir="/Users/user/{project}"),
          memory=[
              "./AGENTS.md"
          ],
          interrupt_on={
              "write_file": True,  # 默认：批准、编辑、拒绝
              "read_file": False,  # 无需中断
              "edit_file": True,   # 默认：批准、编辑、拒绝
          },
          checkpointer=checkpointer,  # 必需！
      )
      ```

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

      # 人机协作（human-in-the-loop）必须配置 Checkpointer
      checkpointer = MemorySaver()

      agent = create_deep_agent(
          model="openai:gpt-5.4",
          backend=FilesystemBackend(root_dir="/Users/user/{project}"),
          memory=[
              "./AGENTS.md"
          ],
          interrupt_on={
              "write_file": True,  # 默认：批准、编辑、拒绝
              "read_file": False,  # 无需中断
              "edit_file": True,   # 默认：批准、编辑、拒绝
          },
          checkpointer=checkpointer,  # 必需！
      )
      ```

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

      # 人机协作（human-in-the-loop）必须配置 Checkpointer
      checkpointer = MemorySaver()

      agent = create_deep_agent(
          model="anthropic:claude-sonnet-4-6",
          backend=FilesystemBackend(root_dir="/Users/user/{project}"),
          memory=[
              "./AGENTS.md"
          ],
          interrupt_on={
              "write_file": True,  # 默认：批准、编辑、拒绝
              "read_file": False,  # 无需中断
              "edit_file": True,   # 默认：批准、编辑、拒绝
          },
          checkpointer=checkpointer,  # 必需！
      )
      ```

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

      # 人机协作（human-in-the-loop）必须配置 Checkpointer
      checkpointer = MemorySaver()

      agent = create_deep_agent(
          model="openrouter:anthropic/claude-sonnet-4-6",
          backend=FilesystemBackend(root_dir="/Users/user/{project}"),
          memory=[
              "./AGENTS.md"
          ],
          interrupt_on={
              "write_file": True,  # 默认：批准、编辑、拒绝
              "read_file": False,  # 无需中断
              "edit_file": True,   # 默认：批准、编辑、拒绝
          },
          checkpointer=checkpointer,  # 必需！
      )
      ```

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

      # 人机协作（human-in-the-loop）必须配置 Checkpointer
      checkpointer = MemorySaver()

      agent = create_deep_agent(
          model="fireworks:accounts/fireworks/models/qwen3p5-397b-a17b",
          backend=FilesystemBackend(root_dir="/Users/user/{project}"),
          memory=[
              "./AGENTS.md"
          ],
          interrupt_on={
              "write_file": True,  # 默认：批准、编辑、拒绝
              "read_file": False,  # 无需中断
              "edit_file": True,   # 默认：批准、编辑、拒绝
          },
          checkpointer=checkpointer,  # 必需！
      )
      ```

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

      # 人机协作（human-in-the-loop）必须配置 Checkpointer
      checkpointer = MemorySaver()

      agent = create_deep_agent(
          model="baseten:zai-org/GLM-5",
          backend=FilesystemBackend(root_dir="/Users/user/{project}"),
          memory=[
              "./AGENTS.md"
          ],
          interrupt_on={
              "write_file": True,  # 默认：批准、编辑、拒绝
              "read_file": False,  # 无需中断
              "edit_file": True,   # 默认：批准、编辑、拒绝
          },
          checkpointer=checkpointer,  # 必需！
      )
      ```

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

      # 人机协作（human-in-the-loop）必须配置 Checkpointer
      checkpointer = MemorySaver()

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

## 配置文件

[Harness 配置文件](/oss/python/deepagents/profiles#harness-profiles)封装了按提供商或按模型的调整（系统提示词后缀、工具描述覆盖、排除的工具或 Middleware、额外 Middleware 和通用子 Agent 编辑），使 `create_deep_agent` 在选择匹配模型时自动应用它们。

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

# 当选择 gpt-5.4 时，追加一段系统提示词后缀。
register_harness_profile(
    "openai:gpt-5.4",
    HarnessProfile(system_prompt_suffix="Respond in under 100 words."),
)
```

参见[配置文件](/oss/python/deepagents/profiles)了解注册键、合并语义和插件打包。更窄范围的配套 API [提供商配置文件](/oss/python/deepagents/profiles#provider-profiles)封装了提供商的模型构造参数。

## 结构化输出

Deep Agents 支持[结构化输出](/oss/python/langchain/structured-output)。
你可以通过将所需的结构化输出 Schema 作为 `response_format` 参数传递给 `create_deep_agent()` 来设置。
当模型生成结构化数据时，它会被捕获、验证并返回在 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,
):
    """Run a web search"""
    return tavily_client.search(
        query,
        max_results=max_results,
        include_raw_content=include_raw_content,
        topic=topic,
    )


class WeatherReport(BaseModel):
    """包含当前天气状况和预报的结构化天气报告。"""
    location: str = Field(description="The location for this weather report")
    temperature: float = Field(description="Current temperature in Celsius")
    condition: str = Field(
        description="Current weather condition (e.g., sunny, cloudy, rainy)"
    )
    humidity: int = Field(description="Humidity percentage")
    wind_speed: float = Field(description="Wind speed in km/h")
    forecast: str = Field(description="Brief forecast for the next 24 hours")


agent = create_deep_agent(
    model=model,
    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="terminal-2">
    [连接这些文档](/use-these-docs)到 Claude、VSCode 等工具，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/deepagents/customization.mdx)或[提交 Issue](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
