Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/content/docs/framework/agent/skills.en.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ agent = Agent(
)
```

`VeSkillRegistry` accepts a `search_mode` parameter. The default value is `"all"`, which loads the frontmatter of every available skill under that skill space into the agent context. For AgentKit Skill Space, `"exact"` performs keyword-based exact search, `"semantic"` performs vector-based semantic search, and `"rrf"` performs hybrid search. SkillHub Skill Space does not yet support specifying a search mode.

This path does not download every skill at initialization time. The cache only stores concrete downloaded skill versions; remote metadata is fetched again on every search / get, so remote version changes are picked up before loading.

## Skill Directory Structure
Expand Down
2 changes: 2 additions & 0 deletions docs/content/docs/framework/agent/skills.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ agent = Agent(
)
```

`VeSkillRegistry` 接受一个 `search_mode` 参数。其默认值为 `"all"`,即一次性加载空间中所有技能的 frontmatter 到 agent 的上下文中。对于 AgentKit 的技能空间,可以选择 `"exact"` 进行关键词精确搜索、`"semantic"` 进行向量语义搜索,或 `"rrf"` 进行混合搜索。SkillHub 的技能空间暂不支持指定搜索模式。

该方式不会在初始化阶段全量下载技能;缓存仅用于已下载的具体技能版本。远端 metadata 每次 search / get 都会重新拉取,因此远端版本变化后会按新版本重新下载。

## 技能目录结构
Expand Down
64 changes: 62 additions & 2 deletions tests/skills/test_adk_skill_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@

import asyncio
from pathlib import Path
from unittest.mock import Mock

import pytest

from veadk.skills import VeSkillRegistry
from veadk.skills import VeSkillRegistry, utils
from veadk.skills import registry as registry_module
from veadk.skills.skill import Skill as VeADKSkill

Expand Down Expand Up @@ -70,7 +71,10 @@ def test_registry_search_ignores_query_and_fetches_all_remote_skills(
),
]

def load_skills_from_cloud(skill_source_id: str) -> list[VeADKSkill]:
def load_skills_from_cloud(
skill_source_id: str, *, search_filter=None
) -> list[VeADKSkill]:
assert search_filter is None
calls.append(skill_source_id)
return remote_skills

Expand Down Expand Up @@ -296,3 +300,59 @@ def test_registry_get_skill_raises_when_name_is_missing(

with pytest.raises(ValueError, match="Skill 'missing' not found"):
asyncio.run(registry.get_skill(name="missing"))


@pytest.mark.parametrize("mode", [None, "all", "exact", "semantic", "rrf"])
@pytest.mark.parametrize("query", ["", " find skill "])
def test_space_search_request(monkeypatch, mode, query):
monkeypatch.delenv("SKILL_SPACE_POLICY", raising=False)
monkeypatch.setattr(utils, "_get_cloud_credentials", lambda: ("", "", ""))
request = Mock(
return_value={
"Items": [
{"Name": "beta", "Description": "Beta skill"},
{"Name": "alpha", "Description": "Alpha skill"},
]
}
)
monkeypatch.setattr(utils, "ve_request", request)
options = {"search_mode": mode} if mode is not None else {}
registry = VeSkillRegistry(skill_source_id="ss-test", **options)

skills = asyncio.run(registry.search_skills(query=query))
assert [skill.name for skill in skills] == ["beta", "alpha"]
body = {"SkillSpaceId": "ss-test", "InnerTags": {"source": "sandbox"}}
if mode not in (None, "all"):
body["Filter"] = {"Query": query, "QueryMode": mode}
assert request.call_args.kwargs["request_body"] == body

with pytest.raises(ValueError, match="not found"):
asyncio.run(registry.get_skill(name="missing"))
assert "Filter" not in request.call_args.kwargs["request_body"]


@pytest.mark.parametrize("mode", ["all", "exact", "semantic", "rrf"])
def test_skillhub_search_request_ignores_mode(monkeypatch, mode):
monkeypatch.delenv("SKILL_SPACE_POLICY", raising=False)
request = Mock(return_value={"Items": [], "TotalCount": 0})
monkeypatch.setattr(utils, "_skillhub_request", request)
registry = VeSkillRegistry(skill_source_id="sp-test", search_mode=mode)
asyncio.run(registry.search_skills(query="hello"))
assert request.call_args.args[1]["Filter"] == {"SkillSpaceId": "sp-test"}
assert "query is ignored" in registry.search_tool_description()


def test_registry_rejects_unknown_search_mode():
with pytest.raises(ValueError, match="unknown"):
VeSkillRegistry(skill_source_id="ss-test", search_mode="unknown")


def test_filtered_search_returns_empty_on_request_error(monkeypatch):
monkeypatch.delenv("SKILL_SPACE_POLICY", raising=False)
monkeypatch.setattr(utils, "_get_cloud_credentials", lambda: ("", "", ""))
request = Mock(side_effect=RuntimeError("offline"))
monkeypatch.setattr(utils, "ve_request", request)
registry = VeSkillRegistry(skill_source_id="ss-test", search_mode="exact")

assert asyncio.run(registry.search_skills(query="hello")) == []
request.assert_called_once()
14 changes: 9 additions & 5 deletions tests/skills/test_skill_space_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def test_load_skills_from_cloud_applies_policy(
monkeypatch.setattr(
utils,
"_load_skills_from_space_id",
lambda _space_id, *, raise_on_error=False: [
lambda _space_id, *, raise_on_error=False, search_filter=None: [
_skill("skill-1", "one"),
_skill("skill-2", "two"),
],
Expand Down Expand Up @@ -168,7 +168,7 @@ def fake_load(space_id: str, *, raise_on_error=False):
monkeypatch.setattr(
utils,
"_load_skills_from_space_id",
lambda space_id, *, raise_on_error=False: {
lambda space_id, *, raise_on_error=False, search_filter=None: {
"ss-one": [
Skill(
id="skill-1",
Expand Down Expand Up @@ -219,7 +219,7 @@ def test_missing_policy_keeps_all_remote_skills(monkeypatch: pytest.MonkeyPatch)
monkeypatch.setattr(
utils,
"_load_skills_from_space_id",
lambda _space_id, *, raise_on_error=False: [
lambda _space_id, *, raise_on_error=False, search_filter=None: [
_skill("skill-1", "one"),
_skill("skill-2", "two"),
],
Expand All @@ -240,7 +240,9 @@ def test_policy_excludes_remote_skills_without_stable_ids(
monkeypatch.setattr(
utils,
"_load_skills_from_space_id",
lambda _space_id, *, raise_on_error=False: [_skill(None, "missing-id")],
lambda _space_id, *, raise_on_error=False, search_filter=None: [
_skill(None, "missing-id")
],
)

assert utils.load_skills_from_cloud("ss-test") == []
Expand Down Expand Up @@ -269,7 +271,9 @@ def test_registry_get_skill_cannot_bypass_deny_policy(
monkeypatch.setattr(
utils,
"_load_skills_from_space_id",
lambda _space_id, *, raise_on_error=False: [_skill("skill-1", "one")],
lambda _space_id, *, raise_on_error=False, search_filter=None: [
_skill("skill-1", "one")
],
)
monkeypatch.setattr(
registry_module,
Expand Down
30 changes: 27 additions & 3 deletions veadk/skills/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@
from __future__ import annotations

import asyncio
from enum import Enum
from pathlib import Path
from typing import Any

from google.adk.skills import Frontmatter
from google.adk.skills import Skill as ADKSkill
from google.adk.skills import models as adk_skill_models
from google.adk.skills import _utils as adk_skill_utils
from google.adk.skills import models as adk_skill_models

try:
from google.adk.skills import SkillRegistry
Expand All @@ -39,6 +40,13 @@ class SkillRegistry: # type: ignore[no-redef]
from veadk.skills.utils import load_skills_from_cloud


class SkillSearchMode(str, Enum):
ALL = "all"
EXACT = "exact"
SEMANTIC = "semantic"
RRF = "rrf"


class VeSkillRegistry(SkillRegistry):
"""ADK ``SkillRegistry`` implementation for one remote VeADK skill space."""

Expand All @@ -47,20 +55,34 @@ def __init__(
*,
skill_source_id: str,
cache_dir: Path | None = None,
search_mode: SkillSearchMode | str = SkillSearchMode.ALL,
) -> None:
normalized_skill_source_id = skill_source_id.strip()
if not normalized_skill_source_id or "," in normalized_skill_source_id:
raise ValueError("VeSkillRegistry requires exactly one skill_source_id.")

self.skill_source_id = normalized_skill_source_id
self.cache_dir = cache_dir
self.search_mode = SkillSearchMode(search_mode)

@property
def _uses_search_filter(self) -> bool:
return (
self.search_mode != SkillSearchMode.ALL
and not self.skill_source_id.startswith("sp-")
)

async def search_skills(self, *, query: str) -> list[Frontmatter]:
"""Return all remote skills in this skill space, ignoring ``query``."""
del query
"""Search the remote skill space using the configured search mode."""
search_filter = (
{"Query": query, "QueryMode": self.search_mode.value}
if self._uses_search_filter
else None
)
skills = await asyncio.to_thread(
load_skills_from_cloud,
self.skill_source_id,
search_filter=search_filter,
)
return [self._to_frontmatter(skill) for skill in skills]

Expand All @@ -87,6 +109,8 @@ async def get_skill(self, *, name: str) -> ADKSkill:
return loaded

def search_tool_description(self) -> str | None:
if self._uses_search_filter:
return f"Search the remote skill space using the query in {self.search_mode.value} mode."
return (
"Search all skills available in the configured VeADK remote skill space. "
"The query is ignored; every remote skill is returned for discovery."
Expand Down
22 changes: 15 additions & 7 deletions veadk/skills/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,21 @@
# limitations under the License.

import json
from pathlib import Path
import os
import frontmatter
from typing import Literal
from pathlib import Path
from typing import Any, Callable, Dict, Literal, Optional
from urllib.parse import urlparse

import frontmatter
from google.adk.tools import BaseTool, ToolContext
from typing import Any, Dict, Optional, Callable

from veadk.skills.skill import Skill
from veadk.skills.policy import (
SKILL_SPACE_POLICY_ENV,
SkillSpacePolicyError,
SkillSpacePolicySet,
parse_skill_space_policy,
)
from veadk.skills.skill import Skill
from veadk.utils.logger import get_logger
from veadk.utils.volcengine_sign import ve_request, volcengine_signed_request

Expand Down Expand Up @@ -142,7 +141,10 @@ def load_skills_from_directory(skills_directory: Path) -> list[Skill]:


def load_skills_from_cloud(
skill_space_ids: str, *, raise_on_error: bool = False
skill_space_ids: str,
*,
raise_on_error: bool = False,
search_filter: dict[str, str] | None = None,
) -> list[Skill]:
skill_space_ids_list = [x.strip() for x in skill_space_ids.split(",") if x.strip()]
logger.info(f"Load skills from cloud skill sources: {skill_space_ids_list}")
Expand All @@ -169,6 +171,7 @@ def load_skills_from_cloud(
skills.extend(
_load_skills_from_space_id(
skill_space_id,
search_filter=search_filter,
raise_on_error=raise_on_error,
)
)
Expand Down Expand Up @@ -345,7 +348,10 @@ def _build_skill_from_skillhub_item(


def _load_skills_from_space_id(
skill_space_id: str, *, raise_on_error: bool = False
skill_space_id: str,
*,
raise_on_error: bool = False,
search_filter: dict[str, str] | None = None,
) -> list[Skill]:
logger.info(f"Load skills from skill space: {skill_space_id}")

Expand All @@ -359,6 +365,8 @@ def _load_skills_from_space_id(
"SkillSpaceId": skill_space_id,
"InnerTags": {"source": "sandbox"},
}
if search_filter is not None:
request_body["Filter"] = search_filter
logger.debug(f"ListSkillsBySpaceId request body: {request_body}")
scheme = os.getenv("AGENTKIT_TOP_SCHEME", "https").lower()

Expand Down
Loading