跳到主要内容

文档索引

在以下地址获取完整的文档索引:https://docs.langchain.org.cn/llms.txt

在进一步探索之前,请使用此文件发现所有可用页面。

create_deep_agent 具有以下核心配置选项
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 API 参考文档。

模型

传递 provider:model 格式的模型字符串,或者一个已初始化的模型实例。请参阅支持的模型以查看所有提供商,以及建议的模型以获取经过测试的推荐方案。
使用 provider:model 格式(例如 openai:gpt-5.4)可以在模型之间快速切换。
👉 阅读 OpenAI 聊天模型集成文档
pip install -U "langchain[openai]"
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

连接韧性

LangChain 聊天模型会自动以指数退避的方式重试失败的 API 请求。默认情况下,对于网络错误、速率限制 (429) 和服务器错误 (5xx),模型最多重试 **6 次**。诸如 401(未授权)或 404 之类的客户端错误不会重试。 您可以在创建模型时调整 max_retries 参数,以针对您的环境微调此行为:
from langchain.chat_models import init_chat_model
from deepagents import create_deep_agent

agent = create_deep_agent(
    model=init_chat_model(
        model="google_genai:gemini-3.1-pro-preview",
        max_retries=10,  # Increase for unreliable networks (default: 6)
        timeout=120,     # Increase timeout for slow connections
    ),
)
对于在不可靠网络上运行的长时间运行的智能体任务,请考虑将 max_retries 增加到 10–15,并配合检查点 (checkpointer) 使用,以便在发生故障时保留进度。

工具

除了用于规划、文件管理和子智能体生成的内置工具之外,您还可以提供自定义工具
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]
)

系统提示

Deep Agents 自带内置的系统提示词。Deep Agent 的价值来自于 SDK 在模型之上提供的编排层——规划、虚拟文件系统工具和子智能体——而模型需要知道这些组件的存在以及何时使用它们。内置提示词教会智能体如何使用这些框架,因此您无需为每个项目重新推导这些内容;建议通过 profile 或您自己的 system_prompt= 参数对其进行微调,而不是逐字复制。 当中间件添加特殊工具(如文件系统工具)时,它会将这些工具附加到系统提示词中。 每个 Deep Agent 还应该包含一个针对其特定用例的自定义系统提示词:
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,
)

提示词组装

Deep Agents 通过最多四个命名部分来构建系统提示词,以便调用者提供的指令、SDK 的内置智能体指南以及任何模型特定的 profile 覆盖可以以可预测的优先级并存。如果没有这种分层,为 Claude 调整的 profile 后缀(例如)可能会根据调用顺序覆盖或被您的 system_prompt= 参数覆盖;命名插槽使顺序显式且稳定。 在实践中,大多数调用者只会遇到两个插槽:USER(您的 system_prompt=)和 BASE(SDK 默认值)。选择一个带有内置 profile 的模型(目前为 Anthropic 或 OpenAI)会添加 SUFFIX。只有当您编写自定义 HarnessProfile 或调试 profile 文本出现位置的原因时,完整的四部分组装才具有相关性。 四个命名部分如下(每个部分都可以缺失):
名称来源备注
USER传递给 create_deep_agentsystem_prompt= 参数strSystemMessage;未设置时省略。
BASESDK 默认提示词 (BASE_AGENT_PROMPT)除非被 profile 的 CUSTOM 替换,否则始终存在。
CUSTOMHarnessProfile.base_system_prompt当匹配的 profile 设置了此项时,直接替换 BASE
SUFFIXHarnessProfile.system_prompt_suffix当匹配的 profile 设置了此项时,最后附加。
顺序始终为 **USER -> (BASECUSTOM) -> SUFFIX**,并由空行 (\n\n) 连接。由此产生两个不变性:
  1. **USER 始终在最前面。** 调用者的文本优先于任何 SDK 或 profile 内容,因此无论选择哪个模型,角色/指令都具有最高优先级。
  2. **SUFFIX 始终在最后面。** Profile 后缀最接近对话历史记录,这是模型微调指南最可靠生效的地方。
组装形式(✓ = 字段已设置,- = 字段未设置)
system_prompt=profile base_system_prompt (CUSTOM)profile system_prompt_suffix (SUFFIX)最终组装的系统提示词
--BASE
-BASE + SUFFIX
-CUSTOM
CUSTOM + SUFFIX
str--USER + BASE
str-USER + BASE + SUFFIX
str-USER + CUSTOM
strUSER + CUSTOM + SUFFIX
运行示例 —— 内置 profile(Anthropic, OpenAI)仅提供 system_prompt_suffix,因此典型的调用会落在 str + - + 这一行。
agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    system_prompt="You are a customer-support agent for ACME Corp.",
)
# Final = USER + BASE + SUFFIX
#       = "You are a customer-support agent for ACME Corp."
#         + "\n\n"
#         + BASE_AGENT_PROMPT
#         + "\n\n"
#         + <Claude-specific guidance>
传递 SystemMessage(而非字符串)会触发不同的连接路径:右侧的组装(BASE-或-CUSTOM 加上任何 SUFFIX)将作为额外的文本内容块附加到该消息现有的 content_blocks 中。相同的逻辑顺序依然适用(调用者提供的块在前),并且调用者块上的任何 cache_control 标记都会被保留 —— 这对于放置显式的 Anthropic 提示词缓存断点非常有用。
同样的覆盖规则也适用于声明式子智能体 —— 每个子智能体都会根据**其自己的模型**重新运行 profile 解析,然后将解析出的 profile 的 base_system_prompt / system_prompt_suffix 应用于其编写的 system_prompt。子智能体的 system_prompt 扮演 BASE 角色;CUSTOMSUFFIX 来自与该子智能体模型匹配的 profile(该模型可能与主智能体的模型不同)。
spec["system_prompt"]profile base_system_prompt (CUSTOM)profile system_prompt_suffix (SUFFIX)最终子智能体系统提示词
已编写的内容--已编写的内容
已编写的内容-已编写的内容 + SUFFIX
已编写的内容-CUSTOM
已编写的内容CUSTOM + SUFFIX
子智能体没有 USER 段 —— spec 中编写的 system_prompt 是最接近的模拟并占据 BASE 插槽。仅提供 system_prompt_suffix 的 profile(这是内置 Anthropic / OpenAI profile 的常见情况)只需附加到子智能体作者编写的任何内容之后;设置了 base_system_prompt 的 profile 将彻底*替换*编写的提示词,因此请谨慎使用该字段。
自动添加的通用子智能体 (GP subagent) 遵循同样的覆盖规则,但多了一个额外层:GP 基础提示词的解析顺序为 **general_purpose_subagent.system_prompt (如果设置) -> HarnessProfile.base_system_prompt (如果设置) -> SDK GP 默认值**。无论哪种方式,profile 后缀都会叠加上去。这两个覆盖字段都可以承载基础提示词替换,但它们不可互换。general_purpose_subagent.system_prompt 是特定于 GP 的配置;base_system_prompt 是主要针对主智能体的全局覆盖。当两者都设置时,**特定于 GP 的意图在 GP 子智能体中获胜**,这样调整这两个字段的用户永远不会看到他们的 GP 覆盖被静默丢弃:
register_harness_profile(
    "anthropic",
    HarnessProfile(
        base_system_prompt="You are ACME's support orchestrator.",  # main agent
        general_purpose_subagent=GeneralPurposeSubagentProfile(
            system_prompt="You are a research subagent. Cite sources.",  # GP subagent
        ),
        system_prompt_suffix="Always think step by step.",
    ),
)
堆栈最终系统提示词
主智能体"You are ACME's support orchestrator." + SUFFIX
GP 子智能体"You are a research subagent. Cite sources." + SUFFIX
如果未设置 general_purpose_subagent.system_prompt,GP 子智能体将回退到 base_system_prompt(如果已设置),最后回退到 SDK GP 默认值。

中间件

默认情况下,Deep Agents 可以访问以下中间件 如果您使用记忆 (memory)、技能 (skills) 或人在回路 (human-in-the-loop),则还会包含以下中间件
  • MemoryMiddleware:提供 memory 参数时,跨会话持久化并检索对话上下文
  • SkillsMiddleware:提供 skills 参数时,启用自定义技能
  • HumanInTheLoopMiddleware:提供 interruptOn 参数时,在指定点暂停以等待人工批准或输入

预构建中间件

LangChain 提供了额外的预构建中间件,允许您添加各种功能,例如重试、回退或 PII 检测。有关更多信息,请参阅预构建中间件 deepagents 库还提供了 create_summarization_tool_middleware,使智能体能够在合适的时机(例如任务之间)触发总结,而不是在固定的 token 间隔处。有关更多详细信息,请参阅总结 (Summarization)

特定提供商中间件

有关针对特定 LLM 提供商优化的特定于提供商的中间件,请参阅官方集成社区集成

自定义中间件

您可以提供额外的中间件来扩展功能、添加工具或实现自定义钩子 (hooks)
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:
    """Get the weather in a city."""
    return f"The weather in {city} is sunny."


call_count = [0]  # Use list to allow modification in nested function

@wrap_tool_call
def log_tool_calls(request, handler):
    """Intercept and log every tool call - demonstrates cross-cutting concern."""
    call_count[0] += 1
    tool_name = request.name if hasattr(request, 'name') else str(request)

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

    # Execute the tool call
    result = handler(request)

    # Log the result
    print(f"[Middleware] Tool call #{call_count[0]} completed")

    return result


agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    tools=[get_weather],
    middleware=[log_tool_calls],
)
**初始化后请勿更改属性**如果您需要在钩子调用之间跟踪值(例如计数器或累积数据),请使用 graph 状态。Graph 状态在设计上被限定在特定线程内,因此在并发环境下更新是安全的。**请这样做:**
class CustomMiddleware(AgentMiddleware):
    def __init__(self):
        pass

    def before_agent(self, state, runtime):
        return {"x": state.get("x", 0) + 1}  # Update graph state instead
**不要**这样处理
class CustomMiddleware(AgentMiddleware):
    def __init__(self):
        self.x = 1

    def before_agent(self, state, runtime):
        self.x += 1  # Mutation causes race conditions
就地变动(例如在 before_agent 中修改 self.x 或在钩子中更改其他共享值)可能会导致难以察觉的错误和竞态条件,因为许多操作是并发运行的(子智能体、并行工具以及不同线程上的并行调用)。有关使用自定义属性扩展状态的完整详细信息,请参阅自定义中间件 - 自定义状态模式。如果您必须在自定义中间件中使用变动,请考虑当子智能体、并行工具或并发智能体调用同时运行时会发生什么。

子代理

为了隔离详细的工作并避免上下文膨胀,请使用子智能体
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
)
有关更多信息,请参阅子智能体

后端

Deep Agent 的工具可以利用虚拟文件系统来存储、访问和编辑文件。默认情况下,Deep Agents 使用 StateBackend 如果您使用技能 (skills)记忆 (memory),则必须在创建智能体之前将预期的技能或记忆文件添加到后端。
存储在 langgraph 状态中的临时文件系统后端。此文件系统仅在*单个线程*中持久存在。
# By default 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()
)
有关更多信息,请参阅后端 (Backends)

沙盒

沙箱 (Sandboxes) 是专门的后端,它们在隔离的环境中运行智能体代码,具有自己的文件系统和用于 shell 命令的 execute 工具。如果您希望 Deep Agent 编写文件、安装依赖项并运行命令而不更改本地机器上的任何内容,请使用沙箱后端。 您可以通过在创建 Deep Agent 时将沙箱后端传递给 backend 来配置沙箱: 有关更多信息,请参阅沙箱 (Sandboxes)

人工干预

某些工具操作可能非常敏感,在执行前需要人工批准。您可以为每个工具配置审批流程
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!
)
您可以为智能体和子智能体配置工具调用时中断,也可以在工具调用内部进行配置。有关更多信息,请参阅人在回路 (Human-in-the-loop)

技能

您可以使用技能 (skills)为您的 Deep Agent 提供新的能力和专业知识。虽然工具 (tools)往往涵盖较低级别的功能,如原生文件系统操作或规划,但技能可以包含关于如何完成任务的详细说明、参考信息和其他资产(如模板)。这些文件仅在智能体确定该技能对当前提示词有用时才会被加载。这种渐进式披露减少了智能体在启动时必须考虑的 token 数量和上下文。 有关技能示例,请参阅 Deep Agents 技能示例 要为您的 Deep Agent 添加技能,请将它们作为参数传递给 create_deep_agent
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(
    model="google_genai:gemini-3.1-pro-preview",
    skills=["/skills/"],
    checkpointer=checkpointer,
)

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

内存

使用 AGENTS.md 文件为您的 Deep Agent 提供额外的上下文。 在创建 Deep Agent 时,您可以向 memory 参数传递一个或多个文件路径:
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.",
            }
        ],
        # Seed the default StateBackend's in-state filesystem (virtual paths must start with "/").
        "files": {"/AGENTS.md": create_file_data(agents_md)},
    },
    config={"configurable": {"thread_id": "123456"}},
)

配置文件

harness profile 打包了针对每个提供商或每个模型的微调(系统提示词后缀、工具描述覆盖、排除的工具或中间件、额外的中间件以及通用子智能体编辑),以便在选择匹配模型时 create_deep_agent 自动应用它们。
from deepagents import HarnessProfile, register_harness_profile

# Append a system-prompt suffix whenever gpt-5.4 is selected.
register_harness_profile(
    "openai:gpt-5.4",
    HarnessProfile(system_prompt_suffix="Respond in under 100 words."),
)
有关注册密钥、合并语义和插件打包,请参阅Profiles。一个更窄的伴随 API —— provider profiles,打包了针对提供商的模型构建参数。

结构化输出

Deep Agents 支持结构化输出。您可以通过在调用 create_deep_agent() 时将所需的结构化输出模式作为 response_format 参数传递。当模型生成结构化数据时,它会被捕获、验证并返回在 Deep Agent 状态的 ‘structured_response’ 键中。
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):
    """A structured weather report with current conditions and forecast."""
    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="google_genai:gemini-3.1-pro-preview",
    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.'
有关更多信息和示例,请参阅响应格式 (response format)
© . This site is unofficial and not affiliated with LangChain, Inc.