Skip to content

Commit 3a27410

Browse files
authored
Merge pull request #1240 from mrcaidev/feat/ve-skill-registry-search-mode
feat: support search_mode in VeSkillRegistry
2 parents d2f186d + a3ad511 commit 3a27410

6 files changed

Lines changed: 117 additions & 17 deletions

File tree

‎docs/content/docs/framework/agent/skills.en.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ agent = Agent(
3434
)
3535
```
3636

37+
`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.
38+
3739
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.
3840

3941
## Skill Directory Structure

‎docs/content/docs/framework/agent/skills.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ agent = Agent(
3434
)
3535
```
3636

37+
`VeSkillRegistry` 接受一个 `search_mode` 参数。其默认值为 `"all"`,即一次性加载空间中所有技能的 frontmatter 到 agent 的上下文中。对于 AgentKit 的技能空间,可以选择 `"exact"` 进行关键词精确搜索、`"semantic"` 进行向量语义搜索,或 `"rrf"` 进行混合搜索。SkillHub 的技能空间暂不支持指定搜索模式。
38+
3739
该方式不会在初始化阶段全量下载技能;缓存仅用于已下载的具体技能版本。远端 metadata 每次 search / get 都会重新拉取,因此远端版本变化后会按新版本重新下载。
3840

3941
## 技能目录结构

‎tests/skills/test_adk_skill_registry.py‎

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,11 @@
1616

1717
import asyncio
1818
from pathlib import Path
19+
from unittest.mock import Mock
1920

2021
import pytest
2122

22-
from veadk.skills import VeSkillRegistry
23+
from veadk.skills import VeSkillRegistry, utils
2324
from veadk.skills import registry as registry_module
2425
from veadk.skills.skill import Skill as VeADKSkill
2526

@@ -70,7 +71,10 @@ def test_registry_search_ignores_query_and_fetches_all_remote_skills(
7071
),
7172
]
7273

73-
def load_skills_from_cloud(skill_source_id: str) -> list[VeADKSkill]:
74+
def load_skills_from_cloud(
75+
skill_source_id: str, *, search_filter=None
76+
) -> list[VeADKSkill]:
77+
assert search_filter is None
7478
calls.append(skill_source_id)
7579
return remote_skills
7680

@@ -296,3 +300,59 @@ def test_registry_get_skill_raises_when_name_is_missing(
296300

297301
with pytest.raises(ValueError, match="Skill 'missing' not found"):
298302
asyncio.run(registry.get_skill(name="missing"))
303+
304+
305+
@pytest.mark.parametrize("mode", [None, "all", "exact", "semantic", "rrf"])
306+
@pytest.mark.parametrize("query", ["", " find skill "])
307+
def test_space_search_request(monkeypatch, mode, query):
308+
monkeypatch.delenv("SKILL_SPACE_POLICY", raising=False)
309+
monkeypatch.setattr(utils, "_get_cloud_credentials", lambda: ("", "", ""))
310+
request = Mock(
311+
return_value={
312+
"Items": [
313+
{"Name": "beta", "Description": "Beta skill"},
314+
{"Name": "alpha", "Description": "Alpha skill"},
315+
]
316+
}
317+
)
318+
monkeypatch.setattr(utils, "ve_request", request)
319+
options = {"search_mode": mode} if mode is not None else {}
320+
registry = VeSkillRegistry(skill_source_id="ss-test", **options)
321+
322+
skills = asyncio.run(registry.search_skills(query=query))
323+
assert [skill.name for skill in skills] == ["beta", "alpha"]
324+
body = {"SkillSpaceId": "ss-test", "InnerTags": {"source": "sandbox"}}
325+
if mode not in (None, "all"):
326+
body["Filter"] = {"Query": query, "QueryMode": mode}
327+
assert request.call_args.kwargs["request_body"] == body
328+
329+
with pytest.raises(ValueError, match="not found"):
330+
asyncio.run(registry.get_skill(name="missing"))
331+
assert "Filter" not in request.call_args.kwargs["request_body"]
332+
333+
334+
@pytest.mark.parametrize("mode", ["all", "exact", "semantic", "rrf"])
335+
def test_skillhub_search_request_ignores_mode(monkeypatch, mode):
336+
monkeypatch.delenv("SKILL_SPACE_POLICY", raising=False)
337+
request = Mock(return_value={"Items": [], "TotalCount": 0})
338+
monkeypatch.setattr(utils, "_skillhub_request", request)
339+
registry = VeSkillRegistry(skill_source_id="sp-test", search_mode=mode)
340+
asyncio.run(registry.search_skills(query="hello"))
341+
assert request.call_args.args[1]["Filter"] == {"SkillSpaceId": "sp-test"}
342+
assert "query is ignored" in registry.search_tool_description()
343+
344+
345+
def test_registry_rejects_unknown_search_mode():
346+
with pytest.raises(ValueError, match="unknown"):
347+
VeSkillRegistry(skill_source_id="ss-test", search_mode="unknown")
348+
349+
350+
def test_filtered_search_returns_empty_on_request_error(monkeypatch):
351+
monkeypatch.delenv("SKILL_SPACE_POLICY", raising=False)
352+
monkeypatch.setattr(utils, "_get_cloud_credentials", lambda: ("", "", ""))
353+
request = Mock(side_effect=RuntimeError("offline"))
354+
monkeypatch.setattr(utils, "ve_request", request)
355+
registry = VeSkillRegistry(skill_source_id="ss-test", search_mode="exact")
356+
357+
assert asyncio.run(registry.search_skills(query="hello")) == []
358+
request.assert_called_once()

‎tests/skills/test_skill_space_policy.py‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ def test_load_skills_from_cloud_applies_policy(
128128
monkeypatch.setattr(
129129
utils,
130130
"_load_skills_from_space_id",
131-
lambda _space_id, *, raise_on_error=False: [
131+
lambda _space_id, *, raise_on_error=False, search_filter=None: [
132132
_skill("skill-1", "one"),
133133
_skill("skill-2", "two"),
134134
],
@@ -168,7 +168,7 @@ def fake_load(space_id: str, *, raise_on_error=False):
168168
monkeypatch.setattr(
169169
utils,
170170
"_load_skills_from_space_id",
171-
lambda space_id, *, raise_on_error=False: {
171+
lambda space_id, *, raise_on_error=False, search_filter=None: {
172172
"ss-one": [
173173
Skill(
174174
id="skill-1",
@@ -219,7 +219,7 @@ def test_missing_policy_keeps_all_remote_skills(monkeypatch: pytest.MonkeyPatch)
219219
monkeypatch.setattr(
220220
utils,
221221
"_load_skills_from_space_id",
222-
lambda _space_id, *, raise_on_error=False: [
222+
lambda _space_id, *, raise_on_error=False, search_filter=None: [
223223
_skill("skill-1", "one"),
224224
_skill("skill-2", "two"),
225225
],
@@ -240,7 +240,9 @@ def test_policy_excludes_remote_skills_without_stable_ids(
240240
monkeypatch.setattr(
241241
utils,
242242
"_load_skills_from_space_id",
243-
lambda _space_id, *, raise_on_error=False: [_skill(None, "missing-id")],
243+
lambda _space_id, *, raise_on_error=False, search_filter=None: [
244+
_skill(None, "missing-id")
245+
],
244246
)
245247

246248
assert utils.load_skills_from_cloud("ss-test") == []
@@ -269,7 +271,9 @@ def test_registry_get_skill_cannot_bypass_deny_policy(
269271
monkeypatch.setattr(
270272
utils,
271273
"_load_skills_from_space_id",
272-
lambda _space_id, *, raise_on_error=False: [_skill("skill-1", "one")],
274+
lambda _space_id, *, raise_on_error=False, search_filter=None: [
275+
_skill("skill-1", "one")
276+
],
273277
)
274278
monkeypatch.setattr(
275279
registry_module,

‎veadk/skills/registry.py‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,14 @@
1717
from __future__ import annotations
1818

1919
import asyncio
20+
from enum import Enum
2021
from pathlib import Path
2122
from typing import Any
2223

2324
from google.adk.skills import Frontmatter
2425
from google.adk.skills import Skill as ADKSkill
25-
from google.adk.skills import models as adk_skill_models
2626
from google.adk.skills import _utils as adk_skill_utils
27+
from google.adk.skills import models as adk_skill_models
2728

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

4142

43+
class SkillSearchMode(str, Enum):
44+
ALL = "all"
45+
EXACT = "exact"
46+
SEMANTIC = "semantic"
47+
RRF = "rrf"
48+
49+
4250
class VeSkillRegistry(SkillRegistry):
4351
"""ADK ``SkillRegistry`` implementation for one remote VeADK skill space."""
4452

@@ -47,20 +55,34 @@ def __init__(
4755
*,
4856
skill_source_id: str,
4957
cache_dir: Path | None = None,
58+
search_mode: SkillSearchMode | str = SkillSearchMode.ALL,
5059
) -> None:
5160
normalized_skill_source_id = skill_source_id.strip()
5261
if not normalized_skill_source_id or "," in normalized_skill_source_id:
5362
raise ValueError("VeSkillRegistry requires exactly one skill_source_id.")
5463

5564
self.skill_source_id = normalized_skill_source_id
5665
self.cache_dir = cache_dir
66+
self.search_mode = SkillSearchMode(search_mode)
67+
68+
@property
69+
def _uses_search_filter(self) -> bool:
70+
return (
71+
self.search_mode != SkillSearchMode.ALL
72+
and not self.skill_source_id.startswith("sp-")
73+
)
5774

5875
async def search_skills(self, *, query: str) -> list[Frontmatter]:
59-
"""Return all remote skills in this skill space, ignoring ``query``."""
60-
del query
76+
"""Search the remote skill space using the configured search mode."""
77+
search_filter = (
78+
{"Query": query, "QueryMode": self.search_mode.value}
79+
if self._uses_search_filter
80+
else None
81+
)
6182
skills = await asyncio.to_thread(
6283
load_skills_from_cloud,
6384
self.skill_source_id,
85+
search_filter=search_filter,
6486
)
6587
return [self._to_frontmatter(skill) for skill in skills]
6688

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

89111
def search_tool_description(self) -> str | None:
112+
if self._uses_search_filter:
113+
return f"Search the remote skill space using the query in {self.search_mode.value} mode."
90114
return (
91115
"Search all skills available in the configured VeADK remote skill space. "
92116
"The query is ignored; every remote skill is returned for discovery."

‎veadk/skills/utils.py‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,21 @@
1313
# limitations under the License.
1414

1515
import json
16-
from pathlib import Path
1716
import os
18-
import frontmatter
19-
from typing import Literal
17+
from pathlib import Path
18+
from typing import Any, Callable, Dict, Literal, Optional
2019
from urllib.parse import urlparse
2120

21+
import frontmatter
2222
from google.adk.tools import BaseTool, ToolContext
23-
from typing import Any, Dict, Optional, Callable
2423

25-
from veadk.skills.skill import Skill
2624
from veadk.skills.policy import (
2725
SKILL_SPACE_POLICY_ENV,
2826
SkillSpacePolicyError,
2927
SkillSpacePolicySet,
3028
parse_skill_space_policy,
3129
)
30+
from veadk.skills.skill import Skill
3231
from veadk.utils.logger import get_logger
3332
from veadk.utils.volcengine_sign import ve_request, volcengine_signed_request
3433

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

143142

144143
def load_skills_from_cloud(
145-
skill_space_ids: str, *, raise_on_error: bool = False
144+
skill_space_ids: str,
145+
*,
146+
raise_on_error: bool = False,
147+
search_filter: dict[str, str] | None = None,
146148
) -> list[Skill]:
147149
skill_space_ids_list = [x.strip() for x in skill_space_ids.split(",") if x.strip()]
148150
logger.info(f"Load skills from cloud skill sources: {skill_space_ids_list}")
@@ -169,6 +171,7 @@ def load_skills_from_cloud(
169171
skills.extend(
170172
_load_skills_from_space_id(
171173
skill_space_id,
174+
search_filter=search_filter,
172175
raise_on_error=raise_on_error,
173176
)
174177
)
@@ -345,7 +348,10 @@ def _build_skill_from_skillhub_item(
345348

346349

347350
def _load_skills_from_space_id(
348-
skill_space_id: str, *, raise_on_error: bool = False
351+
skill_space_id: str,
352+
*,
353+
raise_on_error: bool = False,
354+
search_filter: dict[str, str] | None = None,
349355
) -> list[Skill]:
350356
logger.info(f"Load skills from skill space: {skill_space_id}")
351357

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

0 commit comments

Comments
 (0)