跳转到内容

ADK代理所需的技能

在 ADK 中得到支持。Python v1.25.0TypeScript v0.6.1Go v1.2.0Kotlin v0.1.0

一名代理人 技能 它是一个功能自包含的单元,ADK(Android Development Kit)代理可以使用它来执行特定任务。代理技能(Agent Skill)封装了完成任务所需的所有指令、资源和工具。 代理技能规范(Agent Skill Specification)技能(Skill)的结构使其能够被分阶段地加载,从而将对该智能体(agent)的运行环境(operating context)的影响降到最低。

这个特性在 TypeScript 和 Kotlin 中仍处于实验阶段(即尚未正式发布或稳定使用)。

“Skills”功能在 ADK TypeScript 和 ADK Kotlin 中仍处于实验阶段。我们欢迎您通过相应的 ADK 代码仓库提供反馈。 ADK TypeScript, ADK Kotlin.

立即开始使用吧!

使用 SkillToolset 这个类用于让你的代理(agent)能够使用一个或多个技能(Skills)。你可以自行定义这些技能的具体内容。 编程技能 或者加载 从文件系统中获取的技能(或信息).

import pathlib

from google.adk import Agent
from google.adk.skills import load_skill_from_dir
from google.adk.tools import skill_toolset

weather_skill = load_skill_from_dir(
    pathlib.Path(__file__).parent / "skills" / "weather-skill"
)

def get_weather_tool(city: str) -> dict:
    """Retrieves the current weather report for a specified city."""
    return {
        "status": "success",
        "report": f"The weather in {city} is sunny with a temperature of 25°C.",
    }

my_skill_toolset = skill_toolset.SkillToolset(
    skills=[weather_skill],
    additional_tools=[get_weather_tool],
)

root_agent = Agent(
    model="gemini-flash-latest",
    name="skill_user_agent",
    description="An agent that can use specialized skills.",
    instruction=(
        "You are a helpful assistant that can leverage skills to perform tasks."
    ),
    tools=[
        my_skill_toolset,
    ],
)

有关包含技能(Skill)的 ADK 代理的完整代码示例(包括基于文件的技能定义和内联(in-line)技能定义),请参阅代码示例。 skills_agent.

import {Agent, FunctionTool, SkillToolset, loadSkillFromDir} from '@google/adk';
import * as path from 'node:path';
import {z} from 'zod';

const weatherSkill = await loadSkillFromDir(
  path.join(__dirname, 'skills/weather_skill')
);

const getWeatherTool = new FunctionTool({
  name: 'get_weather',
  description: 'Gets the weather for a given location.',
  parameters: z.object({
    location: z.string().describe('The city and state, e.g. San Francisco, CA'),
  }),
  execute: async ({location}) => {
    return {
      location,
      temperature: '72°F',
      condition: 'Sunny',
    };
  },
});

const mySkillToolset = new SkillToolset([weatherSkill], {
  additionalTools: [getWeatherTool],
});

const rootAgent = new Agent({
  model: 'gemini-flash-latest',
  name: 'skill_user_agent',
  description: 'An agent that can use specialized skills.',
  instruction:
    'You are a helpful assistant that can leverage skills to perform tasks.',
  tools: [mySkillToolset],
});

export default rootAgent;
import (
    "context"
    "os"

    "google.golang.org/adk/v2/agent/llmagent"
    "google.golang.org/adk/v2/tool/skilltoolset/skill"
    "google.golang.org/adk/v2/tool/skilltoolset"
    "google.golang.org/adk/v2/tool"
)

mySkillToolset, err := skilltoolset.New(ctx, skilltoolset.Config{
    Source: skill.NewFileSystemSource(os.DirFS("./skills")),
})
if err != nil {
    // handle error
}

rootAgent, err := llmagent.New(llmagent.Config{
    Name:        "skill_user_agent",
    Model:       model,
    Description: "An agent that can use specialized skills.",
    Instruction: "You are a helpful assistant that can leverage skills to perform tasks.",
    Toolsets:    []tool.Toolset{mySkillToolset},
})
if err != nil {
    // handle error
}

有关完整的示例,请参阅代码示例。 技能.

// NewFileSystemSource discovers every skill directory under the base directory,
// so there is no per-skill load call.
val mySkillToolset = SkillToolset(NewFileSystemSource("skills"))

val skillUserAgent =
    LlmAgent(
        name = "skill_user_agent",
        model = Gemini(name = "gemini-flash-latest"),
        description = "An agent that can use specialized skills.",
        instruction =
            Instruction("You are a helpful assistant that can leverage skills to perform tasks."),
        // A SkillToolset contributes only the skill tools. Any other tool the agent
        // needs is passed separately in `tools`.
        toolsets = listOf(mySkillToolset),
    )

有关完整的示例,请参阅代码示例。 技能.

检查一下……在哪里。 skills/ 从……中解析得出

上面的 Python 和 TypeScript 示例已经成功解决了相关问题(即实现了预期的功能)。 skills/ 相对于存放代理源文件的目录来说,因此请将其放置在相应的位置。 skills/ 除此之外,Go 和 Kotlin 的示例都是传递一个相对路径(即相对于某个基准位置的路径)。 skills 路径(`path`)是相对于当前工作目录来解析的。

技能结构

“Skills”功能允许您创建包含技能说明及相关资源的模块化包,这些包可以被客服代表根据需要随时加载。这种做法有助于您更好地组织客服代表的能力,并通过仅在需要时才加载相关说明来优化系统的运行效率。技能的结构分为三个层级:

  • L1(元数据): 提供用于技能发现的元数据。这些信息在文档的“前言”(frontmatter)部分中进行了定义。 SKILL.md 文件中包含了诸如技能名称和描述之类的属性。
  • L2(指令): 该文件包含了该技能(Skill)的主要使用说明;当代理(agent)触发该技能时,这些说明会被加载并执行。这些详细信息是在该文件的主体部分(即文件的正文部分)中定义的。 SKILL.md file.
  • L3(资源): 包含额外的资源,如参考资料、资产文件和脚本等,可以根据需要随时加载这些资源。这些资源被组织在以下目录中:
    • references/:额外的 Markdown 文件,其中包含更详细的说明、工作流程或指导内容。
    • assets/资源材料,例如数据库模式、API文档、模板或示例。
    • scripts/:代理运行时支持的可执行脚本。

关于如何使用各项技能的系统说明

The SkillToolset 为代理程序提供了一条默认的系统指令,该指令明确了代理程序应如何与各种“技能”(即系统功能或模块)进行交互。这些指令包括以下关键内容:

  • 你必须使用…… load_skill 这是一个用于在使用某项技能之前阅读其使用说明的工具。
  • 你必须严格按照技能定义中的说明来操作。
  • 你必须使用…… load_skill_resource 用于查看某个技能(skill)目录内文件的工具。
  • 你必须使用…… run_skill_script 用于从某个技能中运行脚本 scripts/ directory.

技能验证

某项技能相关文档的“前言”(或“导言”)部分…… SKILL.md 文件会经过验证,以确保其满足以下要求:

  • 名称:
    • 长度必须不超过 64 个字符。
    • 名称必须使用小写字母,并采用“kebab-case”格式(即只包含字母 a-z、数字 0-9 以及连字符 -)。
    • 名称前面、后面或中间不得包含连字符(-),也不允许有多个连续的连字符。
  • 描述(description):
    • 此字段不能为空。
    • 长度必须不超过 1024 个字符。

目录名称必须与文件名相匹配。

在从文件系统中加载某个技能(或功能)时,目录的名称必须与相应的文件名完全匹配。 名称 如果在“前言”(front matter)部分中尝试加载相关内容,或者加载过程失败,那么就会出现这个问题。

技能目录结构

以下目录结构展示了在您的 ADK 代理项目中引入相关功能的推荐方式。 example-skill/ 下图所示的目录结构,以及任何与之平行的技能目录(Skill directories),都必须遵循相同的规则或结构要求。 代理技能规范(Agent Skill Specification) `file` `structure`。仅这些内容。 SKILL.md 需要提供一个文件。

my_agent/
    agent.py (or agent.ts / main.go)
    .env
    skills/
        example-skill/        # Skill
            SKILL.md          # main instructions (required)
            references/
                REFERENCE.md  # detailed API reference
                FORMS.md      # form-filling guide
                *.md          # domain-specific information
            assets/
                *.*           # templates, images, data
            scripts/
                *.py          # utility scripts (Python)
                *.js          # utility scripts (JavaScript)
                *.ts          # utility scripts (TypeScript)

技能来源(Skill Sources)

您可以进行定义。 代码中的相关技能(即用于实现特定功能的编程技术或方法) 或阅读 从文件系统中获取的技能(或信息).

在代码中定义技能(即定义实现特定功能的逻辑或方法)

你可以在代理的代码中定义相应的技能(Skills),如下所示。

from google.adk.skills import models

greeting_skill = models.Skill(
    frontmatter=models.Frontmatter(
        name="greeting-skill",
        description=(
            "A friendly greeting skill that can say hello to a specific person."
        ),
    ),
    instructions=(
        "Step 1: Read the 'references/hello_world.txt' file to understand how"
        " to greet the user. Step 2: Return a greeting based on the reference."
    ),
    resources=models.Resources(
        references={
            "hello_world.txt": "Hello! So glad to have you here!",
            "example.md": "This is an example reference.",
        },
    ),
)
import {Agent, Skill, SkillToolset} from '@google/adk';

const greetingSkill: Skill = {
  frontmatter: {
    name: 'greeting-skill',
    description: 'A friendly greeting skill that can say hello to a specific person.',
  },
  instructions:
    "Step 1: Read the 'references/hello_world.txt' file to understand how to greet the user. Step 2: Return a greeting based on the reference.",
  resources: {
    references: {
      'hello_world.txt': 'Hello! So glad to have you here!',
      'example.md': 'This is an example reference.',
    },
  },
};

const mySkillToolset = new SkillToolset([greetingSkill]);

const rootAgent = new Agent({
  model: 'gemini-flash-latest',
  name: 'greeting_agent',
  description: 'An agent that uses an inline greeting skill.',
  instruction: 'You are a helpful assistant that uses skills to greet people.',
  tools: [mySkillToolset],
});

export default rootAgent;

注意:

ADK Go 目前尚未提供用于内联技能(inline skills)的标准接口或功能,不过这一功能未来可能会被添加。 如果想要直接在代码中定义技能,你需要自己实现相应的逻辑或接口。 skill.Source 按照下面的步骤进行操作。

import (
    "context"
    "io"
    "slices"
    "strings"

    "google.golang.org/adk/v2/tool/skilltoolset/skill"
)

// Example implementation of a static in-memory skill.Source:
type StaticSource struct{}

func (s *StaticSource) ListFrontmatters(ctx context.Context) ([]*skill.Frontmatter, error) {
    return []*skill.Frontmatter{
        {Name: "greeting-skill", Description: "A friendly greeting skill that can say hello to a specific person."},
    }, nil
}

func (s *StaticSource) LoadFrontmatter(ctx context.Context, name string) (*skill.Frontmatter, error) {
    if name != "greeting-skill" {
        return nil, skill.ErrSkillNotFound
    }
    return &skill.Frontmatter{Name: "greeting-skill", Description: "A friendly greeting skill that can say hello to a specific person."}, nil
}

func (s *StaticSource) LoadInstructions(ctx context.Context, name string) (string, error) {
    if name != "greeting-skill" {
        return "", skill.ErrSkillNotFound
    }
    return "Step 1: Read the 'references/hello_world.txt' file to understand how to greet the user. Step 2: Return a greeting based on the reference.", nil
}

func (s *StaticSource) ListResources(ctx context.Context, name, subpath string) ([]string, error) {
    if name != "greeting-skill" {
        return nil, skill.ErrSkillNotFound
    }
    if !slices.Contains([]string{"", ".", "references", "references/"}, subpath) {
        return nil, skill.ErrResourceNotFound
    }
    return []string{"references/hello_world.txt", "references/example.md"}, nil
}

func (s *StaticSource) LoadResource(ctx context.Context, name, resourcePath string) (io.ReadCloser, error) {
    if name != "greeting-skill" {
        return nil, skill.ErrSkillNotFound
    }
    switch resourcePath {
    case "references/hello_world.txt":
        return io.NopCloser(strings.NewReader("Hello! So glad to have you here!")), nil
    case "references/example.md":
        return io.NopCloser(strings.NewReader("This is an example reference.")), nil
    default:
        return nil, skill.ErrResourceNotFound
    }
}

注意:

ADK Kotlin 目前尚未提供用于内联技能(inline skills)的标准源代码(standard source code)。 如果想要直接在代码中定义这些技能,你必须自行实现相应的逻辑。 SkillSource 按照下面的步骤进行操作。

/**
 * ADK Kotlin does not provide a standard [SkillSource] for skills defined in code, so implement the
 * interface yourself to serve them from memory.
 */
class StaticSkillSource : SkillSource {
    private val greetingSkill =
        Frontmatter(
            name = "greeting-skill",
            description = "A friendly greeting skill that can say hello to a specific person.",
        )

    private val instructions =
        "Step 1: Read the 'references/hello_world.txt' file to understand how to greet the " +
            "user. Step 2: Return a greeting based on the reference."

    private val resources =
        mapOf(
            "references/hello_world.txt" to "Hello! So glad to have you here!",
            "references/example.md" to "This is an example reference.",
        )

    private fun notFound(skillName: String) = SkillSourceException("Skill $skillName not found.")

    override suspend fun listFrontmatters(): Result<List<Frontmatter>> =
        Result.success(listOf(greetingSkill))

    override suspend fun loadFrontmatter(skillName: String): Result<Frontmatter> =
        if (skillName == greetingSkill.name) {
            Result.success(greetingSkill)
        } else {
            Result.failure(notFound(skillName))
        }

    override suspend fun loadInstructions(skillName: String): Result<String> =
        if (skillName == greetingSkill.name) {
            Result.success(instructions)
        } else {
            Result.failure(notFound(skillName))
        }

    override suspend fun listResources(
        skillName: String,
        resourceDirectoryPath: String,
    ): Result<List<String>> {
        if (skillName != greetingSkill.name) return Result.failure(notFound(skillName))
        val prefix = resourceDirectoryPath.removePrefix("./").removeSuffix("/")
        if (prefix.isEmpty() || prefix == ".") return Result.success(resources.keys.toList())
        // Skill resources live only under references/, assets/ and scripts/.
        if (prefix.substringBefore("/") !in SkillSource.VALID_RESOURCE_DIRS) {
            return Result.failure(
                SkillSourceException("Invalid resource path: $resourceDirectoryPath"),
            )
        }
        return Result.success(resources.keys.filter { it.startsWith("$prefix/") })
    }

    override suspend fun loadResource(
        skillName: String,
        resourcePath: String,
    ): Result<ByteArray> {
        if (skillName != greetingSkill.name) return Result.failure(notFound(skillName))
        val content =
            resources[resourcePath]
                ?: return Result.failure(
                    SkillSourceException("Resource $resourcePath not found in skill $skillName."),
                )
        return Result.success(content.encodeToByteArray())
    }
}

val inlineSkillAgent =
    LlmAgent(
        name = "greeting_agent",
        model = Gemini(name = "gemini-flash-latest"),
        instruction = Instruction("Greet the user by following the greeting skill."),
        toolsets = listOf(SkillToolset(StaticSkillSource())),
    )

注意:

The Source 该接口可以由任何数据存储系统(例如数据库)来支持,从而满足动态使用场景的需求,比如实时更新和个性化设置。

从文件系统中读取相关技能信息(即数据或配置)。

import pathlib

from google.adk.skills import load_skill_from_dir
from google.adk.tools import skill_toolset

greeting_skill = load_skill_from_dir(
    pathlib.Path(__file__).parent / "skills" / "greeting-skill"
)
weather_skill = load_skill_from_dir(
    pathlib.Path(__file__).parent / "skills" / "weather-skill"
)

my_skill_toolset = skill_toolset.SkillToolset(
    skills=[weather_skill, greeting_skill],
)
import (
    "os"

    "google.golang.org/adk/v2/tool/skilltoolset/skill"
    "google.golang.org/adk/v2/tool/skilltoolset"
)

// ...

source := skill.NewFileSystemSource(os.DirFS("./skills"))

// This example doesn't use any optional wrappers, but you can use them if
// needed, e.g.:
//   source, _, err = skill.WithFrontmatterPreloadSource(ctx, source)
//   source, _, err = skill.WithCompletePreloadSource(ctx, source)
// For more information about these and other wrappers, see
// https://pkg.go.dev/google.golang.org/adk/v2/tool/skilltoolset/skill#Source.

skillToolset, err := skilltoolset.New(ctx, skilltoolset.Config{
    Source: source,
})
if err != nil {
    // handle error
}
// Every immediate subdirectory of "skills" that contains a SKILL.md is exposed as
// a skill, so individual skills are discovered rather than named one by one.
val filesystemSource = NewFileSystemSource("skills")

val filesystemSkillToolset = SkillToolset(filesystemSource)

技能的处理与验证

当你在代理(agent)中添加某些“技能”(skills)时,该代理会使用一个标准化的流程来与这些技能进行交互。这个流程包括:系统级别的使用说明(即如何使用这些技能)、定义技能表示方式的格式,以及用于验证技能定义的一系列规则。

下一步骤

请查看这些资源,以帮助您构建具备特定技能(Skills)的代理程序(agents)。