Skip to main content
技能是可复用的代理能力,提供专门的工作流程和领域知识。 你可以使用 Agent Skills 为你的深度代理提供新的能力和专业知识。要获取能提升代理在 LangChain 生态系统任务上表现的现成技能,请参阅 LangChain Skills 仓库。 深度代理技能遵循 Agent Skills 规范

什么是技能

技能是一个文件夹目录,其中每个文件夹包含一个或多个文件,这些文件提供了代理可以使用的上下文:
  • 一个 SKILL.md 文件,包含关于该技能的说明和元数据
  • 附加脚本(可选)
  • 附加参考信息,例如文档(可选)
  • 附加资源,例如模板和其他资源(可选)
任何附加资源(脚本、文档、模板或其他资源)必须在 SKILL.md 文件中被引用,并说明文件包含的内容以及如何使用它,以便代理能够决定何时使用它们。

技能如何工作

当你创建一个深度代理时,你可以传入一个包含技能的目录列表。当代理启动时,它会读取每个 SKILL.md 文件的 frontmatter。 当代理收到提示时,它会检查在完成提示时是否可以使用任何技能。如果找到匹配的提示,它会接着审查技能文件的其余部分。这种仅在需要时才审查技能信息的模式称为渐进式披露

示例

你可能有一个技能文件夹,其中包含一个以特定方式使用文档站点的技能,以及另一个用于搜索 arXiv 预印本研究论文库的技能:
    skills/
    ├── langgraph-docs
    │   └── SKILL.md
    └── arxiv_search
        ├── SKILL.md
        └── arxiv_search.py # 用于搜索 arXiv 的代码
SKILL.md 文件始终遵循相同的模式,以 frontmatter 中的元数据开始,后跟技能的说明。 以下示例展示了一个技能,它提供了在收到提示时如何提供相关 langgraph 文档的说明:
---
name: langgraph-docs
description: Use this skill for requests related to LangGraph in order to fetch relevant documentation to provide accurate, up-to-date guidance.
---

# langgraph-docs

## Overview

This skill explains how to access LangGraph Python documentation to help answer questions and guide implementation.

## Instructions

### 1. Fetch the Documentation Index

Use the fetch_url tool to read the following URL:
https://docs.langchain.com/llms.txt

This provides a structured list of all available documentation with descriptions.

### 2. Select Relevant Documentation

Based on the question, identify 2-4 most relevant documentation URLs from the index. Prioritize:

- Specific how-to guides for implementation questions
- Core concept pages for understanding questions
- Tutorials for end-to-end examples
- Reference docs for API details

### 3. Fetch Selected Documentation

Use the fetch_url tool to read the selected documentation URLs.

### 4. Provide Accurate Guidance

After reading the documentation, complete the user's request.
更多示例技能,请参阅 Deep Agents 示例技能
重要有关编写技能文件时的约束和最佳实践,请参阅完整的 Agent Skills 规范。特别注意:
  • 如果 description 字段超过 1024 个字符,将被截断。
  • 在 Deep Agents 中,SKILL.md 文件必须小于 10 MB。超过此限制的文件在技能加载时将被跳过。

完整示例

以下示例展示了一个使用所有可用 frontmatter 字段的 SKILL.md 文件:
---
name: langgraph-docs
description: Use this skill for requests related to LangGraph in order to fetch relevant documentation to provide accurate, up-to-date guidance.
license: MIT
compatibility: Requires internet access for fetching documentation URLs
metadata:
  author: langchain
  version: "1.0"
allowed-tools: fetch_url
---

# langgraph-docs

## Overview

This skill explains how to access LangGraph Python documentation to help answer questions and guide implementation.

## Instructions

### 1. Fetch the documentation index

Use the fetch_url tool to read the following URL:
https://docs.langchain.com/llms.txt

This provides a structured list of all available documentation with descriptions.

### 2. Select relevant documentation

Based on the question, identify 2-4 most relevant documentation URLs from the index. Prioritize:

- Specific how-to guides for implementation questions
- Core concept pages for understanding questions
- Tutorials for end-to-end examples
- Reference docs for API details

### 3. Fetch selected documentation

Use the fetch_url tool to read the selected documentation URLs.

### 4. Provide accurate guidance

After reading the documentation, complete the user's request.

用法

在创建深度代理时传入技能目录:
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?",
            }
        ],
        # 为默认 StateBackend 的内部状态文件系统提供种子(虚拟路径必须以 "/" 开头)。
        "files": skills_files
    },
    config={"configurable": {"thread_id": "12345"}},
)
skills
list[str]
技能源路径列表。路径必须使用正斜杠指定,并且相对于后端的根目录。
  • 如果省略,则不加载任何技能。
  • 使用 StateBackend(默认)时,通过 invoke(files={...}) 提供技能文件。使用 deepagents.backends.utils 中的 create_file_data() 来格式化文件内容;不支持原始字符串。
  • 使用 FilesystemBackend 时,技能从相对于后端 root_dir 的磁盘加载。
对于同名技能,后面的源会覆盖前面的源(后者优先)。
SDK 仅加载你在 skills 中传入的源。它不会自动扫描 CLI 目录,如 ~/.deepagents/...~/.agents/...有关 CLI 存储约定,请参阅 应用数据
如果你希望在 SDK 代码中实现类似 CLI 的分层,请按从低到高的优先级顺序显式传入所有所需的源:
[
"<user-home>/.deepagents/{agent}/skills/",
"<user-home>/.agents/skills/",
"<project-root>/.deepagents/skills/",
"<project-root>/.agents/skills/",
]
然后在创建代理时将该有序列表作为 skills 传入。

源优先级

当多个技能源包含同名技能时,skills 数组中列出较后的源中的技能优先(后者优先)。这允许你分层来自不同来源的技能。
# 如果两个源都包含名为 "web-search" 的技能,
# 来自 "/skills/project/" 的那个将获胜(最后加载)。
agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    skills=["/skills/user/", "/skills/project/"],
    ...
)

子代理的技能

当你使用子代理时,你可以配置每种类型可以访问哪些技能:
  • 通用子代理:当你向 create_deep_agent 传入 skills 时,会自动继承主代理的技能。无需额外配置。
  • 自定义子代理:不继承主代理的技能。在每个子代理定义中添加一个 skills 参数,指定该子代理的技能源路径。
技能状态是完全隔离的:主代理的技能对子代理不可见,子代理的技能对主代理也不可见。
from deepagents import create_deep_agent

research_subagent = {
    "name": "researcher",
    "description": "Research assistant with specialized skills",
    "system_prompt": "You are a researcher.",
    "tools": [web_search],
    "skills": ["/skills/research/", "/skills/web-search/"],  # 子代理特定的技能
}

agent = create_deep_agent(
    model="google_genai:gemini-3.1-pro-preview",
    skills=["/skills/main/"],  # 主代理和通用子代理获得这些技能
    subagents=[research_subagent],  # 研究员只获得自己的技能
)
有关子代理配置和技能继承的更多信息,请参阅子代理

代理看到的内容

当配置了技能时,一个“技能系统”部分会被注入到代理的系统提示中。代理使用此信息来遵循一个三步流程:
  1. 匹配—当用户提示到达时,代理检查是否有任何技能的描述与任务匹配。
  2. 读取—如果某个技能适用,代理会使用其技能列表中显示的路径读取完整的 SKILL.md 文件。
  3. 执行—代理遵循技能的说明,并根据需要访问任何支持文件(脚本、模板、参考文档)。
在你的 SKILL.md frontmatter 中编写清晰、具体的描述。代理仅根据描述来决定是否使用技能——详细的描述能带来更好的技能匹配。

在沙箱中执行技能脚本

技能可以包含与 SKILL.md 文件一起的脚本,例如,执行搜索或数据转换的 Python 文件。代理可以从任何后端读取这些脚本,但要执行它们,代理需要访问 shell——这只有沙箱后端才能提供。 当你使用 CompositeBackend 将技能路由到 StoreBackend 进行持久化,同时使用沙箱作为默认后端时,技能文件存储在存储中,而不是代码运行的沙箱中。为了让沙箱能够使用这些脚本,你必须在代理启动之前使用自定义中间件将技能脚本上传到沙箱:
import asyncio
from pathlib import Path
from typing import Any

from daytona import Daytona
from deepagents import create_deep_agent
from deepagents.backends import CompositeBackend, StoreBackend
from deepagents.backends.utils import create_file_data
from langchain.agents.middleware import AgentMiddleware, AgentState

from langchain_daytona import DaytonaSandbox
from langgraph.runtime import Runtime
from langgraph.store.memory import InMemoryStore

# 为每个用户提供相同的技能包:一个共享的存储命名空间。
SKILLS_SHARED_NAMESPACE = ("skills", "builtin")


class SkillSandboxSyncMiddleware(AgentMiddleware[AgentState, Any, Any]):
    """在每次代理运行前,将共享技能文件从存储复制到沙箱中。"""

    def __init__(self, backend: CompositeBackend) -> None:
        super().__init__()
        self.backend = backend

    async def abefore_agent(self, state: AgentState, runtime: Runtime[Any]) -> None:
        store = runtime.store

        files: list[tuple[str, bytes]] = []
        for item in await store.asearch(SKILLS_SHARED_NAMESPACE):
            key = str(item.key)
            if ".." in key or any(c in key for c in ("*", "?")):
                msg = f"无效的键: {key}"
                raise ValueError(msg)
            normalized = key if key.startswith("/") else f"/{key}"
            # CompositeBackend 路由路径并将批量上传到正确的后端。
            files.append((f"/skills{normalized}", item.value["content"].encode()))

        if files:
            await self.backend.aupload_files(files)


async def seed_skill_store(store: InMemoryStore) -> None:
    """将规范的技能文件从磁盘加载到共享存储命名空间(部署时运行一次)。
    您可以从任何来源(本地文件系统、远程 URL 等)检索技能。
    """
    skills_dir = Path(__file__).resolve().parent / "skills"
    for file_path in sorted(p for p in skills_dir.rglob("*") if p.is_file()):
        rel = file_path.relative_to(skills_dir).as_posix()
        key = f"/{rel}"
        await store.aput(
            SKILLS_SHARED_NAMESPACE,
            key,
            create_file_data(file_path.read_text(encoding="utf-8")),
        )


async def main() -> None:
    store = InMemoryStore()
    await seed_skill_store(store)

    daytona = Daytona()
    sandbox = daytona.create()
    sandbox_backend = DaytonaSandbox(sandbox=sandbox)

    backend = CompositeBackend(
        default=sandbox_backend,
        routes={
            "/skills/": StoreBackend(
                store=store,
                namespace=lambda _rt: SKILLS_SHARED_NAMESPACE,
            ),
        },
    )

    try:
        agent = create_deep_agent(
            model="google_genai:gemini-3.1-pro-preview",
            backend=backend,
            skills=["/skills/"],
            store=store,
            middleware=[SkillSandboxSyncMiddleware(backend)],
        )

    finally:
        sandbox.stop()


if __name__ == "__main__":
    asyncio.run(main())
中间件的 before_agent 钩子在每次代理调用之前运行,从该共享命名空间读取技能文件并将其上传到沙箱文件系统。同步后,代理就可以像使用沙箱中的任何其他文件一样,使用 execute 工具执行脚本。 有关一个更完整的示例,该示例还双向同步记忆,请参阅使用自定义中间件同步技能和记忆

技能与记忆

技能和记忆AGENTS.md 文件)服务于不同的目的:
技能记忆
目的通过渐进式披露发现的按需能力启动时始终加载的持久上下文
加载仅在代理确定相关性时读取始终注入系统提示
格式命名目录中的 SKILL.mdAGENTS.md 文件
分层用户 → 项目(后者优先)用户 → 项目(合并)
使用场景说明是特定于任务的,可能很大上下文始终相关(项目约定、偏好)

何时使用技能和工具

以下是使用工具和技能的一些通用指南:
  • 当有大量上下文时使用技能,以减少系统提示中的令牌数量。
  • 使用技能将能力捆绑成更大的操作,并提供超出单个工具描述的额外上下文。
  • 如果代理无法访问文件系统,则使用工具。