Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
refactor(skill): refactor the skill in the toolkit by adding a new skill loader class (#1513)
DavdGao410afb686cff
diff --git a/src/agentscope/tool/__init__.py b/src/agentscope/tool/__init__.pyindex 840e7edb0..aa5a3f348 100644--- a/src/agentscope/tool/__init__.py+++ b/src/agentscope/tool/__init__.py@@ -1,7 +1,7 @@# -*- coding: utf-8 -*-"""The tool module in agentscope."""-from ._types import ToolChoice, Function+from ._types import ToolChoice, Function, Skillfrom ._response import ToolResponse, ToolChunkfrom ._toolkit import Toolkitfrom ._base import ToolBase@@ -15,6 +15,10 @@ from ._permission import (PermissionMode,PermissionBehavior,)+from ._skill import (+ SkillLoaderBase,+ LocalSkillLoader,+)from ._builtin import (ResetTools,Bash,@@ -47,4 +51,7 @@ __all__ = ["Grep","Read","Write",+ "Skill",+ "SkillLoaderBase",+ "LocalSkillLoader",]diff --git a/src/agentscope/tool/_builtin/__init__.py b/src/agentscope/tool/_builtin/__init__.pyindex 66e2c22ab..48215f950 100644--- a/src/agentscope/tool/_builtin/__init__.py+++ b/src/agentscope/tool/_builtin/__init__.py@@ -2,6 +2,7 @@"""The builtin tools in agentscope."""from ._meta import ResetTools+from ._skill import SkillViewerfrom ._bash import Bashfrom ._edit import Editfrom ._glob import Glob@@ -12,6 +13,7 @@ from ._write import Write__all__ = ["ResetTools",+ "SkillViewer","Bash","Edit","Glob",diff --git a/src/agentscope/tool/_builtin/_skill.py b/src/agentscope/tool/_builtin/_skill.pynew file mode 100644index 000000000..2da14bf80--- /dev/null+++ b/src/agentscope/tool/_builtin/_skill.py@@ -0,0 +1,102 @@+# -*- coding: utf-8 -*-+"""The builtin skill viewer tool."""+from typing import Any, Callable, Awaitable++from .._permission import (+ PermissionContext,+ PermissionDecision,+ PermissionBehavior,+)+from .._response import ToolChunk+from .._base import ToolBase+from .._types import Skill+from ...message import TextBlock+++class SkillViewer(ToolBase):+ """The builtin skill viewer tool."""++ name: str = "Skill"+ """The name of the skill viewer tool to the agent."""++ description = (+ "Retrieve a skill within the conversation. "+ "When users asks you to perform tasks, check if any of the available "+ "skills match. "+ "Skills provide specialized capabilities and domain knowledge."+ )+ """The tool description of the skill viewer tool to the agent."""++ input_schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "skill": {+ "type": "string",+ "description": "The exact name of the skill to view. ",+ },+ },+ "required": ["skill"],+ }+ """The input schema of the skill viewer tool."""++ is_concurrency_safe: bool = True+ """The skill viewer is concurrency safe."""++ is_read_only: bool = True+ """The skill viewer is read-only."""++ is_mcp: bool = False+ """The skill viewer is not an MCP tool."""++ mcp_name: str | None = None+ """The skill viewer does not belong to any MCP server."""++ def __init__(+ self,+ get_skills_method: Callable[..., Awaitable[dict[str, Skill]]],+ ) -> None:+ """Initialize the skill viewer with the list of skills.++ Args:+ get_skills_method (`Callable[..., dict[str, Skill]]`):+ An async method that returns the current skills of the agent.+ """+ self._get_skills_method = get_skills_method++ async def check_permissions(+ self,+ tool_input: dict[str, Any],+ context: PermissionContext,+ ) -> PermissionDecision:+ """The skill viewer is always allowed to be called."""+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message="The skill viewer is always allowed to be called.",+ )++ async def __call__(self, skill: str) -> ToolChunk:+ """View the details of the skill with the given name.++ Args:+ skill (`str`):+ The name of the skill to be viewed.++ Returns:+ `ToolChunk`:+ The details of the skill.+ """++ skills = await self._get_skills_method()+ target_skill = skills.get(skill)+ if not target_skill:+ return ToolChunk(+ content=[+ TextBlock(+ text=f"SkillNotFoundError: Skill '{skill}' "+ f"not found.",+ ),+ ],+ state="error",+ )++ return ToolChunk(content=[TextBlock(text=target_skill.markdown)])diff --git a/src/agentscope/tool/_skill/__init__.py b/src/agentscope/tool/_skill/__init__.pynew file mode 100644index 000000000..4e84844f0--- /dev/null+++ b/src/agentscope/tool/_skill/__init__.py@@ -0,0 +1,10 @@+# -*- coding: utf-8 -*-+"""The skill related classes and functions."""++from ._base import SkillLoaderBase+from ._local_loader import LocalSkillLoader++__all__ = [+ "SkillLoaderBase",+ "LocalSkillLoader",+]diff --git a/src/agentscope/tool/_skill/_base.py b/src/agentscope/tool/_skill/_base.pynew file mode 100644index 000000000..7c3877313--- /dev/null+++ b/src/agentscope/tool/_skill/_base.py@@ -0,0 +1,14 @@+# -*- coding: utf-8 -*-+"""The skill loader base class."""+from abc import abstractmethod, ABC++from .._types import Skill+++class SkillLoaderBase(ABC):+ """The base class for skill loader."""++ @abstractmethod+ async def list_skills(self) -> list[Skill]:+ """List all the skills that can be loaded by this loader."""+ raise NotImplementedErrordiff --git a/src/agentscope/tool/_skill/_local_loader.py b/src/agentscope/tool/_skill/_local_loader.pynew file mode 100644index 000000000..7f109d790--- /dev/null+++ b/src/agentscope/tool/_skill/_local_loader.py@@ -0,0 +1,171 @@+# -*- coding: utf-8 -*-+"""The local skill loader class."""+import asyncio+import os++import aiofiles+import aiofiles.ospath+import frontmatter++from ._base import SkillLoaderBase+from ..._logging import logger+from .._types import Skill+++class LocalSkillLoader(SkillLoaderBase):+ """The skill loader that loads skills from a local directory."""++ def __init__(self, directory: str, scan_subdir: bool = False) -> None:+ """Initialize the loader with the directory.++ Args:+ directory (`str`):+ The directory to load skills from.+ scan_subdir (`bool`, defaults to False):+ Whether to scan subdirectories. Defaults to False (only+ scan current directory).+ """+ self.directory = os.path.abspath(directory)+ self.scan_subdir = scan_subdir+ self._cache: dict[str, Skill] = {}++ async def _load_single_skill(self, skill_root: str) -> Skill | None:+ """Load a single skill from a skill root directory.++ Args:+ skill_root (`str`): The skill root directory containing SKILL.md.++ Returns:+ `Skill | None`: A Skill object or None if loading failed.+ """+ skill_md_path = os.path.join(skill_root, "SKILL.md")++ try:+ # Check if SKILL.md exists+ if not await aiofiles.ospath.isfile(skill_md_path):+ return None++ # Get file modification time+ updated_at = await aiofiles.ospath.getmtime(skill_md_path)++ # Check cache: if cached skill exists and updated_at matches,+ # return cached+ if skill_root in self._cache:+ cached_skill = self._cache[skill_root]+ if cached_skill.updated_at == updated_at:+ return cached_skill++ # Read and parse SKILL.md+ async with aiofiles.open(+ skill_md_path,+ "r",+ encoding="utf-8",+ ) as f:+ content_str = await f.read()+ content = frontmatter.loads(content_str)++ name = content.get("name")+ description = content.get("description")++ if not name or not description:+ logger.warning(+ "SKILL.md in %s is missing required fields "+ "(name or description). Skipping.",+ skill_root,+ )+ return None++ skill = Skill(+ name=str(name),+ description=str(description),+ dir=skill_root,+ markdown=content.content,+ updated_at=updated_at,+ )++ # Update cache+ self._cache[skill_root] = skill++ return skill++ except Exception as e:+ logger.warning(+ "Failed to load skill from %s: %s",+ skill_root,+ str(e),+ )+ return None++ async def list_skills(self) -> list[Skill]:+ """List all the available skills from the directory.++ This method will:+ 1. Search for SKILL.md in the current directory+ 2. If scan_subdir is True, search for SKILL.md in all subdirectories+ 3. Load all SKILL.md files concurrently++ Returns:+ `list[Skill]`: A list of Skill objects.+ """+ try:+ # Check if directory exists+ if not await aiofiles.ospath.isdir(self.directory):+ logger.warning(+ "Skill directory %s does not exist.",+ self.directory,+ )+ return []++ # Find all directories containing SKILL.md+ def _find_skill_dirs() -> list[str]:+ """Find all directories containing SKILL.md file."""+ dirs = []++ if os.path.isfile(os.path.join(self.directory, "SKILL.md")):+ dirs.append(self.directory)++ if self.scan_subdir:+ for root, _, filenames in os.walk(self.directory):+ if root == self.directory:+ continue+ if "SKILL.md" in filenames:+ dirs.append(root)++ return dirs++ skill_dirs = await asyncio.to_thread(_find_skill_dirs)++ if not skill_dirs:+ logger.info(+ "No SKILL.md files found in %s",+ self.directory,+ )+ return []++ # Load all skills concurrently+ tasks = [+ self._load_single_skill(skill_dir) for skill_dir in skill_dirs+ ]+ results = await asyncio.gather(*tasks, return_exceptions=True)++ # Filter out None results and exceptions+ skills: list = []+ for i, result in enumerate(results):+ if isinstance(result, Exception):+ logger.warning(+ "Failed to load skill from %s: %s",+ skill_dirs[i],+ str(result),+ )+ elif result is not None:+ skills.append(result)++ return skills++ except Exception as e:+ logger.warning(+ "Failed to list skills from directory %s: %s",+ self.directory,+ str(e),+ )+ return []diff --git a/src/agentscope/tool/_toolkit.py b/src/agentscope/tool/_toolkit.pyindex c15ff5758..69fafc1b3 100644--- a/src/agentscope/tool/_toolkit.py+++ b/src/agentscope/tool/_toolkit.py@@ -2,7 +2,7 @@"""The toolkit class for tool calls in AgentScope."""import asyncioimport inspect-import os+import warningsfrom collections import OrderedDictfrom copy import deepcopyfrom functools import wraps@@ -17,17 +17,19 @@ from typing import ()import mcp+from jinja2 import Templatefrom pydantic import (BaseModel,Field,create_model,)-from ._builtin import ResetTools, Edit, Write, Read+from ._builtin import ResetTools, Edit, Write, Read, SkillViewerfrom ._base import ToolBasefrom ._adapters import _FunctionToolfrom ._response import ToolResponse, ToolChunk-from ._types import ToolGroup, AgentSkill, RegisteredTool+from ._skill import SkillLoaderBase, LocalSkillLoader+from ._types import ToolGroup, Skill, RegisteredToolfrom .._utils._common import _json_loads_with_repairfrom ..exception import DeveloperOrientedExceptionfrom ..mcp import (@@ -114,6 +116,21 @@ The tool instructions are a collection of suggestions, rules and notifications a</tool-instructions>{% endif %}{% endif %}""" # noqa: E501+DEFAULT_SKILL_INSTRUCTION = """<agent-skills>+Skills are a collection of instructions, scripts, and resources to extend your capabilities.++**IMPORTANT**: Skills are NOT tools, and you cannot call a skill directly. To use a skill, you MUST use the `{{ skill_viewer }}` tool to read the skill's full instructions, and then follow those instructions to use the tools and resources provided by the skill.++# Available Skills:+{% for skill in skills %}<skill>+<name>{{ skill.name }}</name>+<description>{{ skill.description }}</description>+<dir>{{ skill.dir }}</dir>+</skill>{% endfor %}+</agent-skills>+""" # noqa: E501++class Toolkit:"""Toolkit is the core module to register, manage and delete toolfunctions, MCP clients, Agent skills in AgentScope.@@ -136,19 +153,6 @@ class Toolkit:- Provide prompt for the registered skills to the agent."""- _DEFAULT_AGENT_SKILL_INSTRUCTION = (- "# Agent Skills\n"- "The agent skills are a collection of folds of instructions, scripts, "- "and resources that you can load dynamically to improve performance "- "on specialized tasks. Each agent skill has a `SKILL.md` file in its "- "folder that describes how to use the skill. If you want to use a "- "skill, you MUST read its `SKILL.md` file carefully."- )-- _DEFAULT_AGENT_SKILL_TEMPLATE = """## {name}-{description}-Check "{dir}/SKILL.md" for how to use this skill"""-def _get_meta_tool_schema(self) -> Type[BaseModel]:"""Get the meta tool schema based on the current tool groups."""fields = {}@@ -167,51 +171,65 @@ Check "{dir}/SKILL.md" for how to use this skill"""def __init__(self,tools: list[ToolBase] | None = None,+ skills: list[str | SkillLoaderBase] | None = None,meta_tool_response_template: str = DEFAULT_META_TOOL_RESPONSE_TEMPLATE,mcp_tool_name: str = "mcp__{server}__{tool}",- agent_skill_instruction: str | None = None,- agent_skill_template: str | None = None,+ skill_viewer_enabled: bool = True,+ skill_instruction_template: str = DEFAULT_SKILL_INSTRUCTION,) -> None:"""Initialize the toolkit.Args:tools (`list[ToolProtocol] | None`, optional):The tool objects that implement the ToolProtocol interface.+ skills (`list[str] | None`, optional):+ The agent skill directories to be registered.meta_tool_response_template (`str`, optional):The template for meta tool responses.mcp_tool_name (`str`, optional):The naming pattern for MCP tools.- agent_skill_instruction (`str | None`, optional):- The instruction for agent skills in the system prompt. If not- provided, a default instruction will be used.- agent_skill_template (`str | None`, optional):- The template to present one agent skill in the system prompt,- which should contain `{name}`, `{description}`, and `{dir}`- placeholders. If not provided, a default template will be used.+ skill_viewer_enabled (`bool`, defaults to `True`):+ Whether enable the built-in skill viewer tool function.+ skill_instruction_template (`str`):+ A Jinja2 template for generating the agent skill instruction."""super().__init__()self.tools: dict[str, RegisteredTool] = OrderedDict()+ self.groups: dict[str, ToolGroup] = {}+ self.skills: list[SkillLoaderBase] = []++ self._middlewares: list = [] # Store registered middlewares+ # ================================================+ # Handle the initial tools+ # ================================================if tools:for tool in tools:# TODO: handle the name conflict hereself.tools[tool.name] = RegisteredTool(tool=tool)- self.meta_tool_response_template = meta_tool_response_template+ # ================================================+ # Handle the initial skills+ # ================================================+ if skills:+ for skill in skills:+ if isinstance(skill, str):+ self.skills.append(LocalSkillLoader(skill))+ elif isinstance(skill, SkillLoaderBase):+ self.skills.append(skill)+ else:+ raise TypeError(+ f"Invalid skill type: {type(skill)}. Skills should "+ "be either a directory path string or an instance "+ "of SkillLoaderBase.",+ )+ self.meta_tool_response_template = meta_tool_response_templateself.mcp_tool_name = mcp_tool_name- self.groups: dict[str, ToolGroup] = {}- self.skills: dict[str, AgentSkill] = {}- self._middlewares: list = [] # Store registered middlewares-- self._agent_skill_instruction = (- agent_skill_instruction or self._DEFAULT_AGENT_SKILL_INSTRUCTION- )- self._agent_skill_template = (- agent_skill_template or self._DEFAULT_AGENT_SKILL_TEMPLATE- )+ self.skill_instruction_template = skill_instruction_template+ self.skill_viewer_enabled = skill_viewer_enabledself.builtin_meta_tool = RegisteredTool(tool=ResetTools(@@ -222,6 +240,12 @@ Check "{dir}/SKILL.md" for how to use this skill"""),)+ self.builtin_skill_viewer = RegisteredTool(+ tool=SkillViewer(+ get_skills_method=self._get_all_skills,+ ),+ )+def create_tool_group(self,group_name: str,@@ -738,102 +762,40 @@ Check "{dir}/SKILL.md" for how to use this skill"""def clear(self) -> None:"""Clear the toolkit, removing all tool functions and groups."""+ self.skills.clear()self.tools.clear()self.groups.clear()- def _validate_tool_function(self, func_name: str) -> None:- """Check if the tool function already registered in the toolkit. If- so, raise a ValueError."""- if func_name in self.tools:- raise ValueError(- f"A function with name '{func_name}' is already registered "- "in the toolkit.",- )-- def register_agent_skill(- self,- skill_dir: str,- ) -> None:- """Register agent skills from a given directory. This function will- scan the directory, read metadata from the SKILL.md file, and add- it to the skill related prompt. Developers can obtain the- skills-related prompt by calling `toolkit.get_agent_skill_prompt()`.-- .. note:: This directory- - Must include a SKILL.md file at the top level- - The SKILL.md must have a YAML Front Matter including `name` and- `description` fields- - All files must specify a common root directory in their paths-- Args:- skill_dir (`str`):- The path to the skill directory.+ async def _get_all_skills(self) -> dict[str, Skill]:+ """A unified method to collect all skills from the registered skill+ loaders. Including the name conflict handling for skills with the+ same name."""- import frontmatter-- # Check the skill directory- if not os.path.isdir(skill_dir):- raise ValueError(- f"The skill directory '{skill_dir}' does not exist or is "- "not a directory.",- )-- # Check SKILL.md file- path_skill_md = os.path.join(skill_dir, "SKILL.md")- if not os.path.isfile(path_skill_md):- raise ValueError(- f"The skill directory '{skill_dir}' must include a "- "SKILL.md file at the top level.",- )-- # Check YAML Front Matter- with open(path_skill_md, "r", encoding="utf-8") as f:- post = frontmatter.load(f)-- name = post.get("name", None)- description = post.get("description", None)-- if not name or not description:- raise ValueError(- f"The SKILL.md file in '{skill_dir}' must have a YAML Front "- "Matter including `name` and `description` fields.",- )-- name, description = str(name), str(description)- if name in self.skills:- raise ValueError(- f"An agent skill with name '{name}' is already registered "- "in the toolkit.",- )-- self.skills[name] = AgentSkill(- name=name,- description=description,- dir=skill_dir,- )-- logger.info(- "Registered agent skill '%s' from directory '%s'.",- name,- skill_dir,- )-- def remove_agent_skill(self, name: str) -> None:- """Remove an agent skill by its name.-- Args:- name (`str`):- The name of the agent skill to be removed.- """- if name in self.skills:- self.skills.pop(name)- else:- logger.warning(- "Agent skill '%s' not found in the toolkit, skipping removal.",- name,- )-- def get_agent_skill_prompt(self) -> str | None:+ skills = OrderedDict()+ for loader in self.skills:+ new_skills = await loader.list_skills()+ # Handle duplicated skill names+ for skill in new_skills:+ if skill.name not in skills:+ skills[skill.name] = skill+ else:+ # Rename the skill with a suffix to avoid duplication+ suffix = 1+ while f"{skill.name}_{suffix}" in skills:+ suffix += 1+ new_name = f"{skill.name}_{suffix}"+ warnings.warn(+ f"Duplicate skill name '{skill.name}' found in "+ f"directory '{skill.dir}'. "+ f"Renaming it to '{new_name}'.",+ )+ # Avoid affect the skill loader cache+ copied_skill = deepcopy(skill)+ copied_skill.name = new_name+ skills[new_name] = copied_skill+ return skills++ async def get_skill_instructions(self) -> str | None:"""Get the prompt for all registered agent skills, which can beattached to the system prompt for the agent.@@ -851,17 +813,19 @@ Check "{dir}/SKILL.md" for how to use this skill"""if len(self.skills) == 0:return None- skill_descriptions = [- self._agent_skill_instruction,- ] + [- self._agent_skill_template.format(- name=_["name"],- description=_["description"],- dir=_["dir"],- )- for _ in self.skills.values()- ]- return "\n".join(skill_descriptions)+ skills = await self._get_all_skills()++ # If no skills were collected, return None+ if len(skills) == 0:+ return None++ # Generate the skill instruction prompt with the template+ template = Template(self.skill_instruction_template)++ return template.render(+ skills=skills.values(),+ skill_viewer=self.builtin_skill_viewer.tool.name,+ )def register_middleware(self,@@ -982,11 +946,22 @@ AsyncGenerator[ToolResponse, None]] | AsyncGenerator[ToolResponse, None]]`):RegisteredTool objects."""available_tools = {}++ # Builtin meta tool is only included when there is at least one tool+ # groupif len(self.groups) > 0:available_tools[self.builtin_meta_tool.tool.name] = self.builtin_meta_tool+ # Builtin skill viewer is included when enabled and at least on skill+ # is registered+ if self.skill_viewer_enabled and len(self.skills) > 0:+ available_tools[+ self.builtin_skill_viewer.tool.name+ ] = self.builtin_skill_viewer++ # The tools in the activated groups and the "basic" group are includedgroups_filter = ["basic"] + (groups or [])for tool_name, tool in self.tools.items():if tool.group in groups_filter:diff --git a/src/agentscope/tool/_types.py b/src/agentscope/tool/_types.pyindex 7b5ae2b62..e020a653f 100644--- a/src/agentscope/tool/_types.py+++ b/src/agentscope/tool/_types.py@@ -6,7 +6,6 @@ from typing import (Literal,Type,Any,- TypedDict,TypeAlias,Coroutine,AsyncGenerator,@@ -170,8 +169,9 @@ class ToolGroup:activated."""-class AgentSkill(TypedDict):- """The agent skill typed dict class"""+@dataclass+class Skill:+ """The agent skill class"""name: str"""The name of the skill."""@@ -179,6 +179,10 @@ class AgentSkill(TypedDict):"""The description of the skill."""dir: str"""The directory of the agent skill."""+ markdown: str+ """The markdown content of the agent skill."""+ updated_at: float+ """The last updated time of the skill."""# The function types that can be registered as tools in AgentScope.diff --git a/tests/skill_loader_test.py b/tests/skill_loader_test.pynew file mode 100644index 000000000..eb653601c--- /dev/null+++ b/tests/skill_loader_test.py@@ -0,0 +1,212 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Test cases for LocalSkillLoader."""+import os+import tempfile+import shutil+import time+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.tool import LocalSkillLoader+++class SkillLoaderTest(IsolatedAsyncioTestCase):+ """Test cases for LocalSkillLoader."""++ async def asyncSetUp(self) -> None:+ """Set up test fixtures."""+ # Create a temporary directory for testing+ self.test_dir = tempfile.mkdtemp()++ # Create test SKILL.md files+ # 1. Root level skill+ self.root_skill_content = """---+name: root_skill+description: A skill in the root directory+---++This is the root skill content.+"""+ with open(+ os.path.join(self.test_dir, "SKILL.md"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write(self.root_skill_content)++ # 2. Subdirectory skill+ self.subdir1 = os.path.join(self.test_dir, "subdir1")+ os.makedirs(self.subdir1)+ self.subdir1_skill_content = """---+name: subdir1_skill+description: A skill in subdirectory 1+---++This is the subdir1 skill content.+"""+ with open(+ os.path.join(self.subdir1, "SKILL.md"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write(self.subdir1_skill_content)++ # 3. Nested subdirectory skill+ self.subdir2 = os.path.join(self.test_dir, "subdir1", "subdir2")+ os.makedirs(self.subdir2)+ self.subdir2_skill_content = """---+name: subdir2_skill+description: A skill in nested subdirectory 2+---++This is the subdir2 skill content.+"""+ with open(+ os.path.join(self.subdir2, "SKILL.md"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write(self.subdir2_skill_content)++ async def asyncTearDown(self) -> None:+ """Clean up test fixtures."""+ # Remove the temporary directory+ if os.path.exists(self.test_dir):+ shutil.rmtree(self.test_dir)++ async def test_nonexistent_skill(self) -> None:+ """Test loading from a directory without SKILL.md."""+ # Create a directory without SKILL.md+ empty_dir = tempfile.mkdtemp()+ try:+ loader = LocalSkillLoader(empty_dir, scan_subdir=False)+ skills = await loader.list_skills()+ self.assertEqual(len(skills), 0)+ finally:+ shutil.rmtree(empty_dir)++ async def test_scan_subdir_flag_controls_subdirectory_scanning(+ self,+ ) -> None:+ """Test that scan_subdir only controls subdirectory scanning.++ The root directory is always scanned regardless of scan_subdir.+ When scan_subdir=False, only root SKILL.md is loaded.+ When scan_subdir=True, root + all subdirectory SKILL.md files+ are loaded.+ """+ loader_no_scan = LocalSkillLoader(self.test_dir, scan_subdir=False)+ skills_no_scan = await loader_no_scan.list_skills()++ loader_with_scan = LocalSkillLoader(self.test_dir, scan_subdir=True)+ skills_with_scan = await loader_with_scan.list_skills()++ # scan_subdir=False: only root skill+ self.assertEqual(len(skills_no_scan), 1)+ self.assertEqual(skills_no_scan[0].name, "root_skill")++ # scan_subdir=True: root skill + both subdirectory skills+ self.assertEqual(len(skills_with_scan), 3)+ skill_names = {s.name for s in skills_with_scan}+ self.assertIn("root_skill", skill_names)+ self.assertIn("subdir1_skill", skill_names)+ self.assertIn("subdir2_skill", skill_names)++ async def test_load_skill_without_scan_subdir(self) -> None:+ """Test loading skill from root directory only (scan_subdir=False)."""+ loader = LocalSkillLoader(self.test_dir, scan_subdir=False)+ skills = await loader.list_skills()++ # Should only load the root skill+ self.assertEqual(len(skills), 1)+ self.assertEqual(skills[0].name, "root_skill")+ self.assertEqual(+ skills[0].description,+ "A skill in the root directory",+ )+ self.assertEqual(skills[0].dir, self.test_dir)+ self.assertIn("This is the root skill content.", skills[0].markdown)+ self.assertIsInstance(skills[0].updated_at, float)+ self.assertGreater(skills[0].updated_at, 0)++ async def test_load_skill_with_scan_subdir(self) -> None:+ """Test loading skills from subdirectories (scan_subdir=True)."""+ loader = LocalSkillLoader(self.test_dir, scan_subdir=True)+ skills = await loader.list_skills()++ # Should load all three skills+ self.assertEqual(len(skills), 3)++ # Check skill names+ skill_names = {skill.name for skill in skills}+ self.assertEqual(+ skill_names,+ {"root_skill", "subdir1_skill", "subdir2_skill"},+ )++ # Verify each skill has correct attributes+ for skill in skills:+ self.assertIsInstance(skill.name, str)+ self.assertIsInstance(skill.description, str)+ self.assertIsInstance(skill.dir, str)+ self.assertIsInstance(skill.markdown, str)+ self.assertIsInstance(skill.updated_at, float)+ self.assertGreater(skill.updated_at, 0)++ async def test_cache_mechanism(self) -> None:+ """Test that cache is used when file is not modified."""+ loader = LocalSkillLoader(self.test_dir, scan_subdir=False)++ # First load - should read from file+ skills_first = await loader.list_skills()+ self.assertEqual(len(skills_first), 1)+ first_skill = skills_first[0]++ # Verify cache is populated+ self.assertIn(self.test_dir, loader._cache)+ cached_skill = loader._cache[self.test_dir]+ self.assertEqual(cached_skill.name, first_skill.name)+ self.assertEqual(cached_skill.updated_at, first_skill.updated_at)++ # Second load - should use cache (file not modified)+ skills_second = await loader.list_skills()+ self.assertEqual(len(skills_second), 1)+ second_skill = skills_second[0]++ # Should return the same cached object+ self.assertIs(second_skill, cached_skill)+ self.assertEqual(second_skill.updated_at, first_skill.updated_at)++ # Modify the file+ time.sleep(0.01) # Ensure different mtime+ modified_content = """---+name: modified_root_skill+description: Modified skill description+---++This is the modified content.+"""+ with open(+ os.path.join(self.test_dir, "SKILL.md"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write(modified_content)++ # Third load - should detect change and reload+ skills_third = await loader.list_skills()+ self.assertEqual(len(skills_third), 1)+ third_skill = skills_third[0]++ # Should have new content+ self.assertEqual(third_skill.name, "modified_root_skill")+ self.assertEqual(third_skill.description, "Modified skill description")+ self.assertIn("This is the modified content.", third_skill.markdown)+ self.assertNotEqual(third_skill.updated_at, first_skill.updated_at)++ # Cache should be updated+ self.assertIn(self.test_dir, loader._cache)+ self.assertEqual(+ loader._cache[self.test_dir].name,+ "modified_root_skill",+ )diff --git a/tests/toolkit_skill_test.py b/tests/toolkit_skill_test.pynew file mode 100644index 000000000..0e9b66ca1--- /dev/null+++ b/tests/toolkit_skill_test.py@@ -0,0 +1,322 @@+# -*- coding: utf-8 -*-+"""Test cases for Toolkit skill-related functionality."""+import json+import warnings+from unittest.async_case import IsolatedAsyncioTestCase++from utils import AnyString++from agentscope.tool import SkillLoaderBase, LocalSkillLoader+from agentscope.tool import Toolkit+from agentscope.tool import Skill, ToolChunk, ToolResponse+from agentscope.message import ToolCallBlock+from agentscope.agent import AgentState+++def _make_skill(+ name: str,+ description: str = "desc",+ dir_: str = "/tmp",+) -> Skill:+ """Helper function to create a Skill object for testing."""+ return Skill(+ name=name,+ description=description,+ dir=dir_,+ markdown="",+ updated_at=0.0,+ )+++class MockSkillLoader(SkillLoaderBase):+ """A mock skill loader for testing."""++ def __init__(self, skills: list[Skill]) -> None:+ self._skills = skills++ async def list_skills(self) -> list[Skill]:+ return self._skills+++class ToolkitSkillTest(IsolatedAsyncioTestCase):+ """Test cases for Toolkit skill functionality."""++ async def test_init_with_skill_loader(self) -> None:+ """Test that Toolkit accepts SkillLoaderBase instances in+ constructor."""+ loader = MockSkillLoader([_make_skill("skill_a")])+ toolkit = Toolkit(skills=[loader])++ self.assertEqual(len(toolkit.skills), 1)+ self.assertIs(toolkit.skills[0], loader)++ async def test_init_with_string_path(self) -> None:+ """Test that Toolkit wraps string paths in LocalSkillLoader."""++ toolkit = Toolkit(skills=["/some/path"])++ self.assertEqual(len(toolkit.skills), 1)+ self.assertIsInstance(toolkit.skills[0], LocalSkillLoader)++ async def test_init_with_mixed_skills(self) -> None:+ """Test that Toolkit handles mixed string and loader inputs."""++ loader = MockSkillLoader([_make_skill("skill_b")])+ toolkit = Toolkit(skills=["/some/path", loader])++ self.assertEqual(len(toolkit.skills), 2)+ self.assertIsInstance(toolkit.skills[0], LocalSkillLoader)+ self.assertIs(toolkit.skills[1], loader)++ async def test_init_with_invalid_skill_type(self) -> None:+ """Test that Toolkit raises TypeError for invalid skill types."""+ with self.assertRaises(TypeError):+ Toolkit(skills=[123]) # type: ignore++ async def test_get_skill_instructions_no_skills(self) -> None:+ """Test that get_skill_instructions returns None when no skills+ registered."""+ toolkit = Toolkit()+ result = await toolkit.get_skill_instructions()+ self.assertIsNone(result)++ async def test_get_skill_instructions_with_skills(self) -> None:+ """Test that get_skill_instructions returns correct prompt."""+ skill = _make_skill(+ "my_skill",+ description="Does something useful",+ dir_="/skills/my_skill",+ )+ loader = MockSkillLoader([skill])+ toolkit = Toolkit(skills=[loader])++ result = await toolkit.get_skill_instructions()++ self.assertIsNotNone(result)+ self.assertIn("my_skill", result)+ self.assertIn("Does something useful", result)+ self.assertIn("/skills/my_skill", result)++ async def test_get_skill_instructions_multiple_loaders(self) -> None:+ """Test that get_skill_instructions aggregates skills from multiple+ loaders."""+ loader1 = MockSkillLoader([_make_skill("skill_x")])+ loader2 = MockSkillLoader([_make_skill("skill_y")])+ toolkit = Toolkit(skills=[loader1, loader2])++ result = await toolkit.get_skill_instructions()++ self.assertIsNotNone(result)+ self.assertIn("skill_x", result)+ self.assertIn("skill_y", result)++ async def test_duplicate_skill_name_renamed(self) -> None:+ """Test that duplicate skill names are renamed with a numeric+ suffix."""+ loader1 = MockSkillLoader(+ [_make_skill("duplicate_skill", dir_="/dir1")],+ )+ loader2 = MockSkillLoader(+ [_make_skill("duplicate_skill", dir_="/dir2")],+ )+ toolkit = Toolkit(skills=[loader1, loader2])++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ result = await toolkit.get_skill_instructions()++ self.assertIsNotNone(result)+ self.assertIn("duplicate_skill", result)+ self.assertIn("duplicate_skill_1", result)++ # A warning should have been issued+ self.assertTrue(+ any("duplicate_skill" in str(w.message) for w in caught),+ "Expected a warning about duplicate skill name",+ )++ async def test_duplicate_skill_name_multiple_conflicts(self) -> None:+ """Test that multiple duplicates get incrementing suffixes."""+ loader1 = MockSkillLoader([_make_skill("dup", dir_="/dir1")])+ loader2 = MockSkillLoader([_make_skill("dup", dir_="/dir2")])+ loader3 = MockSkillLoader([_make_skill("dup", dir_="/dir3")])+ toolkit = Toolkit(skills=[loader1, loader2, loader3])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ result = await toolkit.get_skill_instructions()++ self.assertIsNotNone(result)+ self.assertIn("dup", result)+ self.assertIn("dup_1", result)+ self.assertIn("dup_2", result)++ async def test_get_skill_instructions_empty_loader(self) -> None:+ """Test that an empty loader contributes no skills."""+ loader = MockSkillLoader([])+ toolkit = Toolkit(skills=[loader])++ result = await toolkit.get_skill_instructions()+ self.assertIsNone(result)+++class ToolkitSkillViewerTest(IsolatedAsyncioTestCase):+ """Test cases for Toolkit SkillViewer functionality."""++ async def test_register_skill_and_get_function_schemas(self) -> None:+ """Test that registering skills makes SkillViewer available in+ function schemas."""+ skill = _make_skill("test_skill", description="A test skill")+ loader = MockSkillLoader([skill])+ toolkit = Toolkit(skills=[loader])++ schemas = toolkit.get_function_schemas()++ self.assertListEqual(+ schemas,+ [+ {+ "type": "function",+ "function": {+ "name": "Skill",+ "description": (+ "Retrieve a skill within the conversation. "+ "When users asks you to perform tasks, check if "+ "any of the available skills match. "+ "Skills provide specialized capabilities and "+ "domain knowledge."+ ),+ "parameters": {+ "type": "object",+ "properties": {+ "skill": {+ "type": "string",+ "description": "The exact name of the "+ "skill to view. ",+ },+ },+ "required": ["skill"],+ },+ },+ },+ ],+ )++ async def test_call_skill_viewer_success(self) -> None:+ """Test calling SkillViewer with an existing skill."""+ skill = _make_skill(+ "my_skill",+ description="My test skill",+ dir_="/test/dir",+ )+ skill.markdown = "# My Skill\nThis is the skill content."+ loader = MockSkillLoader([skill])+ toolkit = Toolkit(skills=[loader])++ tool_call = ToolCallBlock(+ id="test_call_1",+ name="Skill",+ input=json.dumps({"skill": "my_skill"}),+ )+ state = AgentState()++ chunks = []+ response = None+ async for result in toolkit.call_tool(tool_call, state):+ if isinstance(result, ToolChunk):+ chunks.append(result)+ elif isinstance(result, ToolResponse):+ response = result++ self.assertEqual(len(chunks), 1)+ self.assertDictEqual(+ chunks[0].model_dump(),+ {+ "content": [+ {+ "type": "text",+ "id": AnyString(),+ "text": "# My Skill\nThis is the skill content.",+ },+ ],+ "state": "running",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ self.assertIsNotNone(response)+ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "type": "text",+ "id": AnyString(),+ "text": "# My Skill\nThis is the skill content.",+ },+ ],+ "state": "finished",+ "metadata": {},+ "id": "test_call_1",+ },+ )++ async def test_call_skill_viewer_not_found(self) -> None:+ """Test calling SkillViewer with a non-existent skill."""+ skill = _make_skill("existing_skill")+ loader = MockSkillLoader([skill])+ toolkit = Toolkit(skills=[loader])++ tool_call = ToolCallBlock(+ id="test_call_2",+ name="Skill",+ input=json.dumps({"skill": "non_existent_skill"}),+ )+ state = AgentState()++ chunks = []+ response = None+ async for result in toolkit.call_tool(tool_call, state):+ if isinstance(result, ToolChunk):+ chunks.append(result)+ elif isinstance(result, ToolResponse):+ response = result++ self.assertEqual(len(chunks), 1)+ self.assertDictEqual(+ chunks[0].model_dump(),+ {+ "content": [+ {+ "type": "text",+ "id": AnyString(),+ "text": "SkillNotFoundError: "+ "Skill 'non_existent_skill' not found.",+ },+ ],+ "state": "error",+ "is_last": True,+ "metadata": {},+ "id": AnyString(),+ },+ )++ self.assertIsNotNone(response)+ self.assertDictEqual(+ response.model_dump(),+ {+ "content": [+ {+ "type": "text",+ "id": AnyString(),+ "text": "SkillNotFoundError: "+ "Skill 'non_existent_skill' not found.",+ },+ ],+ "state": "error",+ "metadata": {},+ "id": "test_call_2",+ },+ )