Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(agent-skill): support Anthropic agent skills in `ReActAgent` and `Toolkit` class (#952)
DavdGao811c127bdd27
diff --git a/README.md b/README.mdindex b83a5bf29..adf4f1a1f 100644--- a/README.md+++ b/README.md@@ -54,10 +54,11 @@</p>## 📢 News-- **[2025-11]** AgentScope open-sources [**Alias-Agent**](https://github.com/agentscope-ai/agentscope-samples/tree/main/alias) for diverse real-world tasks and [**Data-Juicer Agent**](https://github.com/agentscope-ai/agentscope-samples/tree/main/data_juicer_agent) for data processing.-- **[2025-11]** AgentScope supports [**Agentic RL**](https://github.com/agentscope-ai/agentscope/tree/main/examples/training/react_agent) via integrating [Trinity-RFT](https://github.com/modelscope/Trinity-RFT) library.-- **[2025-11]** AgentScope integrates [**ReMe**](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/long_term_memory/reme) for enhanced long-term memory.-- **[2025-11]** AgentScope launches [**agentscope-samples**](https://github.com/agentscope-ai/agentscope-samples) repository and upgrades [**agentscope-runtime**](https://github.com/agentscope-ai/agentscope-runtime) with Docker/K8s deployment and VNC-powered GUI sandboxes.+- **[2025-11]** AgentScope supports [Anthropic Agent Skill](https://claude.com/blog/skills) now! Check our [example](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/agent_skill) and [tutorial](https://doc.agentscope.io/tutorial/task_agent_skill.html) for more details.+- **[2025-11]** AgentScope open-sources [Alias-Agent](https://github.com/agentscope-ai/agentscope-samples/tree/main/alias) for diverse real-world tasks and [Data-Juicer Agent](https://github.com/agentscope-ai/agentscope-samples/tree/main/data_juicer_agent) for data processing.+- **[2025-11]** AgentScope supports [Agentic RL](https://github.com/agentscope-ai/agentscope/tree/main/examples/training/react_agent) via integrating [Trinity-RFT](https://github.com/modelscope/Trinity-RFT) library.+- **[2025-11]** AgentScope integrates [ReMe](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/long_term_memory/reme) for enhanced long-term memory.+- **[2025-11]** AgentScope launches [agentscope-samples](https://github.com/agentscope-ai/agentscope-samples) repository and upgrades [agentscope-runtime](https://github.com/agentscope-ai/agentscope-runtime) with Docker/K8s deployment and VNC-powered GUI sandboxes.- **[2025-11]** [Contributing Guide](./CONTRIBUTING.md) is online now! Welcome to contribute to AgentScope.- **[2025-09]** **RAG** module in AgentScope 1.0 is online now! Check our [tutorial](https://doc.agentscope.io/tutorial/task_rag.html) and [example](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/rag) for more details.- **[2025-09]** **Voice agent** is online! `ReActAgent` supports Qwen-Omni and GPT-Audio natively now, check our [new example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/voice_agent) and [roadmap](https://github.com/agentscope-ai/agentscope/issues/773).@@ -381,6 +382,7 @@ as_studio- [Examples](https://github.com/agentscope-ai/agentscope/tree/main/examples)- Functionality- [MCP](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/mcp)+ - [Anthropic Agent Skill](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/agent_skill)- [Plan](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/plan)- [Structured Output](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/structured_output)- [RAG](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/rag)diff --git a/README_zh.md b/README_zh.mdindex 3b2795552..bd5be58d4 100644--- a/README_zh.md+++ b/README_zh.md@@ -54,10 +54,11 @@</p>## 📢 新闻-- **[2025-11]** AgentScope 开源 [**Alias-Agent**](https://github.com/agentscope-ai/agentscope-samples/tree/main/alias) 用于处理多样化的真实任务,以及 [**Data-Juicer Agent**](https://github.com/agentscope-ai/agentscope-samples/tree/main/data_juicer_agent) 用于自然语言驱动的数据处理。-- **[2025-11]** AgentScope 通过集成 [Trinity-RFT](https://github.com/modelscope/Trinity-RFT) 实现对 [**Agentic RL**](https://github.com/agentscope-ai/agentscope/tree/main/examples/training/react_agent) 的支持。-- **[2025-11]** AgentScope 集成 [**ReMe**](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/long_term_memory/reme) 增强长期记忆能力。-- **[2025-11]** AgentScope 推出 [**agentscope-samples**](https://github.com/agentscope-ai/agentscope-samples) 样例库,并升级 [**agentscope-runtime**](https://github.com/agentscope-ai/agentscope-runtime) 支持 Docker/K8s 部署和 VNC 驱动的图形化沙盒。+- **[2025-11]** AgentScope 已支持 [Anthropic Agent Skill](https://claude.com/blog/skills) !欢迎查看 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/agent_skill) 和 [教程](https://doc.agentscope.io/zh_CN/tutorial/task_agent_skill.html) 了解更多详情。+- **[2025-11]** AgentScope 开源 [Alias-Agent](https://github.com/agentscope-ai/agentscope-samples/tree/main/alias) 用于处理多样化的真实任务,以及 [Data-Juicer Agent](https://github.com/agentscope-ai/agentscope-samples/tree/main/data_juicer_agent) 用于自然语言驱动的数据处理。+- **[2025-11]** AgentScope 通过集成 [Trinity-RFT](https://github.com/modelscope/Trinity-RFT) 实现对 [Agentic RL](https://github.com/agentscope-ai/agentscope/tree/main/examples/training/react_agent) 的支持。+- **[2025-11]** AgentScope 集成 [ReMe](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/long_term_memory/reme) 增强长期记忆能力。+- **[2025-11]** AgentScope 推出 [agentscope-samples](https://github.com/agentscope-ai/agentscope-samples) 样例库,并升级 [agentscope-runtime](https://github.com/agentscope-ai/agentscope-runtime) 支持 Docker/K8s 部署和 VNC 驱动的图形化沙盒。- **[2025-11]** [Contributing Guide](./CONTRIBUTING.md) 已更新,欢迎贡献到 AgentScope!- **[2025-09]** AgentScope 1.0 **RAG** 模块已上线!欢迎查看 [文档](https://doc.agentscope.io/zh_CN/tutorial/task_rag.html) 和 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/rag)。- **[2025-09]** **Voice agent** 已上线!`ReActAgent` 已原生支持 Qwen-Omni 和 GPT-Audio 系列模型,欢迎查看 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/voice_agent) 和 [roadmap](https://github.com/agentscope-ai/agentscope/issues/773)。@@ -382,6 +383,7 @@ as_studio- [示例](https://github.com/agentscope-ai/agentscope/tree/main/examples)- 功能演示- [MCP](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/mcp)+ - [Anthropic 智能体技能](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/agent_skill)- [计划](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/plan)- [结构化输出](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/structured_output)- [RAG](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/rag)diff --git a/docs/tutorial/en/index.rst b/docs/tutorial/en/index.rstindex ff076b475..a9f53b16c 100644--- a/docs/tutorial/en/index.rst+++ b/docs/tutorial/en/index.rst@@ -47,6 +47,7 @@ Welcome to AgentScope's documentation!tutorial/task_statetutorial/task_hooktutorial/task_mcp+ tutorial/task_agent_skilltutorial/task_studiotutorial/task_tracingtutorial/task_evaldiff --git a/docs/tutorial/en/src/task_agent_skill.py b/docs/tutorial/en/src/task_agent_skill.pynew file mode 100644index 000000000..ad1d10928--- /dev/null+++ b/docs/tutorial/en/src/task_agent_skill.py@@ -0,0 +1,137 @@+# -*- coding: utf-8 -*-+"""+.. _agent_skill:++Agent Skill+============================++`Agent skill <https://claude.com/blog/skills>`_ is an approach proposed by+Anthropic to improve agent capabilities on specific tasks.++AgentScope provides built-in support for Agent Skills through the ``Toolkit``+class, allowing users to easily register and manage agent skills.++The related APIs are as follows:++.. list-table:: Agent skill API in ``Toolkit`` class+ :header-rows: 1++ * - API+ - Description+ * - ``register_agent_skill``+ - Register agent skills from a given directory.+ * - ``remove_agent_skill``+ - Remove a registered agent skill by name.+ * - ``get_agent_skill_prompt``+ - Get the prompt for all registered agent skills, which can be+ attached to the system prompt for the agent.++In this section we demonstrate how to register agent skills and use them in an+ReAct agent.+"""+import os++from agentscope.agent import ReActAgent+from agentscope.formatter import DashScopeChatFormatter+from agentscope.memory import InMemoryMemory+from agentscope.model import DashScopeChatModel+from agentscope.tool import Toolkit++# %%+# Registering Agent Skills+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+#+# First, we need to prepare an agent skill directory, which follows the+# requirements specified in the `Anthropic blog <https://claude.com/blog/skills>`_.+#+# .. note:: The skill directory must contain a ``SKILL.md`` file containing+# YAML frontmatter and instructions.+#+# Here, we fake an example skill directory ``sample_skill`` with the following files:+#+# .. code-block:: markdown+#+# ---+# name: sample_skill+# description: A sample agent skill for demonstration.+# ---+#+# # Sample Skill+# ...+#++os.makedirs("sample_skill", exist_ok=True)+with open("sample_skill/SKILL.md", "w", encoding="utf-8") as f:+ f.write(+ """---+name: sample_skill+description: A sample agent skill for demonstration.+---++# Sample Skill+...+""",+ )++# %%+# Then, we can register the skill using the ``register_agent_skill`` API of+# the ``Toolkit`` class.+#++toolkit = Toolkit()++toolkit.register_agent_skill("sample_skill")++# %%+# After that, we can get the prompt for all registered agent skills using the+# ``get_agent_skill_prompt`` API++agent_skill_prompt = toolkit.get_agent_skill_prompt()+print("Agent Skill Prompt:")+print(agent_skill_prompt)++# %%+# Of course, we can customize the prompt template when creating the ``Toolkit``+# instance.++toolkit = Toolkit(+ # The instruction that introduces how to use the skill to the agent/llm+ agent_skill_instruction="<system-info>You're provided a collection of skills, each in a directory and described by a SKILL.md file.</system-info>\n",+ # The template for formatting each skill's prompt, must contain+ # {name}, {description}, and {dir} fields+ agent_skill_template="- {name}({dir}): {description}",+)++toolkit.register_agent_skill("sample_skill")+agent_skill_prompt = toolkit.get_agent_skill_prompt()+print("Customized Agent Skill Prompt:")+print(agent_skill_prompt)++# %%+# Integrating Agent Skills with ReActAgent+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+#+# The `ReActAgent` class in AgentScope will attach the agent skill prompt to+# the system prompt automatically.+#+# We can create a ReAct agent with the registered agent skills as follows:+#+# .. important:: When using agent skills, the agent must be equipped with text+# file reading or shell command tools to access the skill instructions in+# `SKILL.md` files.+#++agent = ReActAgent(+ name="Friday",+ sys_prompt="You are a helpful assistant named Friday.",+ model=DashScopeChatModel(+ model_name="qwen3-max",+ api_key=os.environ["DASHSCOPE_API_KEY"],+ ),+ memory=InMemoryMemory(),+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+)++print("Agent's System Prompt with Agent Skills:")+print(agent.sys_prompt)diff --git a/docs/tutorial/zh_CN/index.rst b/docs/tutorial/zh_CN/index.rstindex ff076b475..a9f53b16c 100644--- a/docs/tutorial/zh_CN/index.rst+++ b/docs/tutorial/zh_CN/index.rst@@ -47,6 +47,7 @@ Welcome to AgentScope's documentation!tutorial/task_statetutorial/task_hooktutorial/task_mcp+ tutorial/task_agent_skilltutorial/task_studiotutorial/task_tracingtutorial/task_evaldiff --git a/docs/tutorial/zh_CN/src/task_agent_skill.py b/docs/tutorial/zh_CN/src/task_agent_skill.pynew file mode 100644index 000000000..c2710f3aa--- /dev/null+++ b/docs/tutorial/zh_CN/src/task_agent_skill.py@@ -0,0 +1,124 @@+# -*- coding: utf-8 -*-+"""+.. _agent_skill:++智能体技能+============================++`智能体技能(Agent skill) <https://claude.com/blog/skills>`_ 是 Anthropic 提出的一种提升智能体在特定任务上能力的方法。++AgentScope 通过 ``Toolkit`` 类提供了对智能体技能的内置支持,让开发者可以注册和管理智能体技能。++相关 API 如下:++.. list-table:: ``Toolkit`` 类中的智能体技能 API+ :header-rows: 1++ * - API+ - 描述+ * - ``register_agent_skill``+ - 从指定目录注册智能体技能+ * - ``remove_agent_skill``+ - 根据名称移除已注册的智能体技能+ * - ``get_agent_skill_prompt``+ - 获取所有已注册智能体技能的提示词,可以附加到智能体的系统提示词中++本节将演示如何注册智能体技能并在 ReActAgent 类中使用它们。+"""+import os++from agentscope.agent import ReActAgent+from agentscope.formatter import DashScopeChatFormatter+from agentscope.memory import InMemoryMemory+from agentscope.model import DashScopeChatModel+from agentscope.tool import Toolkit++# %%+# 注册智能体技能+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+#+# 首先,我们需要准备一个智能体技能目录,该目录需要遵循 `Anthropic blog <https://claude.com/blog/skills>`_ 中指定的要求。+#+# .. note:: 技能目录必须包含一个 ``SKILL.md`` 文件,其中包含 YAML 前置元数据和指令说明。+#+# 这里我们创建一个示例技能目录 ``sample_skill``,包含以下文件:+#+# .. code-block:: markdown+#+# ---+# name: sample_skill+# description: 用于演示的示例智能体技能+# ---+#+# # 示例技能+# ...+#++os.makedirs("sample_skill", exist_ok=True)+with open("sample_skill/SKILL.md", "w", encoding="utf-8") as f:+ f.write(+ """---+name: sample_skill+description: 用于演示的示例智能体技能+---++# 示例技能+...+""",+ )++# %%+# 然后,我们可以使用 ``Toolkit`` 类的 ``register_agent_skill`` API 注册技能。+#++toolkit = Toolkit()++toolkit.register_agent_skill("sample_skill")++# %%+# 之后,我们可以使用 ``get_agent_skill_prompt`` API 获取所有已注册智能体技能的提示词++agent_skill_prompt = toolkit.get_agent_skill_prompt()+print("智能体技能提示词:")+print(agent_skill_prompt)++# %%+# 当然,我们也可以在创建 ``Toolkit`` 实例时自定义提示词模板。++custom_toolkit = Toolkit(+ # 向智能体/大语言模型介绍如何使用技能的指令+ agent_skill_instruction="<system-info>为你提供了一组技能,每个技能都在一个目录中,并由 SKILL.md 文件进行描述。</system-info>",+ # 用于格式化每个技能提示词的模板,必须包含 {name}、{description} 和 {dir} 字段+ agent_skill_template="- {name}(in directory '{dir}'): {description}",+)++custom_toolkit.register_agent_skill("sample_skill")+agent_skill_prompt = custom_toolkit.get_agent_skill_prompt()+print("自定义智能体技能提示词:")+print(agent_skill_prompt)++# %%+# 在 ReActAgent 中集成智能体技能+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+#+# AgentScope 中的 `ReActAgent` 类会自动将智能体技能提示词附加到系统提示词中。+#+# 我们可以按如下方式创建一个带有已注册智能体技能的 ReAct 智能体:+#+# .. important:: 使用智能体技能时,智能体必须配备文本文件读取或 shell 命令工具,以便访问 `SKILL.md` 文件中的技能指令。+#++agent = ReActAgent(+ name="Friday",+ sys_prompt="你是一个名为 Friday 的智能助手。",+ model=DashScopeChatModel(+ model_name="qwen3-max",+ api_key=os.environ["DASHSCOPE_API_KEY"],+ ),+ memory=InMemoryMemory(),+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+)++print("带有智能体技能的系统提示词:")+print(agent.sys_prompt)diff --git a/examples/agent/react_agent/main.py b/examples/agent/react_agent/main.pyindex ea3506a1d..b4b68e3af 100644--- a/examples/agent/react_agent/main.py+++ b/examples/agent/react_agent/main.py@@ -18,6 +18,7 @@ from agentscope.tool import (async def main() -> None:"""The main entry point for the ReAct agent example."""toolkit = Toolkit()+toolkit.register_tool_function(execute_shell_command)toolkit.register_tool_function(execute_python_code)toolkit.register_tool_function(view_text_file)@@ -35,6 +36,7 @@ async def main() -> None:toolkit=toolkit,memory=InMemoryMemory(),)+user = UserAgent("User")msg = Nonediff --git a/examples/functionality/agent_skill/README.md b/examples/functionality/agent_skill/README.mdnew file mode 100644index 000000000..f42243e99--- /dev/null+++ b/examples/functionality/agent_skill/README.md@@ -0,0 +1,33 @@+# Agent Skills in AgentScope++[Agent Skill](https://claude.com/blog/skills) is an approach proposed by+Anthropic to improve agent capabilities on specific tasks.++In this example, we demonstrate how to integrate Agent Skills into an+ReAct agent in AgentScope via the `toolkit.register_agent_skill` API.++Specifically, we prepare a demonstration skill that helps the agent to+learn about the AgentScope framework itself in the `skill` directory.+In `main.py`, we register this skill to the agent's toolkit, and ask it+to answer questions about AgentScope.++## Quick Start++Install the latest version of AgentScope to run this example:++```bash+pip install agentscope --upgrade+```++Then, run the example with:++```bash+python main.py+```++> Note:+> - The example is built with DashScope chat model. If you want to change the model used in this example, don't+> forget to change the formatter at the same time! The corresponding relationship between built-in models and+> formatters are list in [our tutorial](https://doc.agentscope.io/tutorial/task_prompt.html#id1)+> - For local models, ensure the model service (like Ollama) is running before starting the agent.+diff --git a/examples/functionality/agent_skill/main.py b/examples/functionality/agent_skill/main.pynew file mode 100644index 000000000..21d6c0d71--- /dev/null+++ b/examples/functionality/agent_skill/main.py@@ -0,0 +1,79 @@+# -*- coding: utf-8 -*-+"""The main entry point of the agent skill example."""+import asyncio+import os++from agentscope.agent import ReActAgent+from agentscope.formatter import DashScopeChatFormatter+from agentscope.memory import InMemoryMemory+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel+from agentscope.tool import (+ Toolkit,+ execute_shell_command,+ execute_python_code,+ view_text_file,+)+++async def main() -> None:+ """The main entry point for the ReAct agent example."""+ toolkit = Toolkit()++ # To use agent skills, your agent must be equipped with text file viewing+ # tools.+ toolkit.register_tool_function(execute_shell_command)+ toolkit.register_tool_function(execute_python_code)+ toolkit.register_tool_function(view_text_file)++ # Register the agent skill+ toolkit.register_agent_skill(+ "./skill/analyzing-agentscope-library",+ )++ agent = ReActAgent(+ name="Friday",+ sys_prompt="""You are a helpful assistant named Friday.++# IMPORTANT+- Don't make any assumptions. All your knowledge about AgentScope library must come from your equipped skills.+""", # noqa: E501+ model=DashScopeChatModel(+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ model_name="qwen3-max",+ enable_thinking=False,+ stream=True,+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+ memory=InMemoryMemory(),+ )++ # First, let's take a look at the agent's system prompt+ print("\033[1;32mAgent System Prompt:\033[0m")+ print(agent.sys_prompt)+ print("\n")++ print(+ "\033[1;32mResponse to Question 'What skills do you have?':\033[0m",+ )+ # We prepare two questions+ await agent(+ Msg("user", "What skills do you have?", "user"),+ )++ print(+ "\n\033[1;32mResponse to Question 'How to create my own tool function "+ "for the agent in agentscope?':\033[0m",+ )+ # The second question+ await agent(+ Msg(+ "user",+ "How to custom tool function for the agent in agentscope?",+ "user",+ ),+ )+++asyncio.run(main())diff --git a/examples/functionality/agent_skill/skill/analyzing-agentscope-library/SKILL.md b/examples/functionality/agent_skill/skill/analyzing-agentscope-library/SKILL.mdnew file mode 100644index 000000000..86a5f2da2--- /dev/null+++ b/examples/functionality/agent_skill/skill/analyzing-agentscope-library/SKILL.md@@ -0,0 +1,78 @@+---+name: Analyzing AgentScope Library+description: This skill provides a way to retrieve information from the AgentScope library for analysis and decision-making.+---++# Analyzing AgentScope Library++## Overview++This guide covers the essential operations for retrieving and answering questions about the AgentScope library.+If you need to answer questions regarding the AgentScope library, or look up specific information, functions/classes,+examples or guidance, this skill will help you achieve that.++## Quick Start++The skill provides the following key scripts:++- Search for guidance in the AgentScope tutorial.+- Search for official examples and recommended implementations provided by AgentScope.+- A quick interface to view AgentScope's Python library by given a module name (e.g. agentscope), and return the module's submodules, classes, and functions.++When being asked an AgentScope-related question, you can follow the steps below to find the relevant information:++First decide which of the three scripts to use based on the user's question.+- If user asks for "how to use" types of questions, use the "Search for Guidance" script to find the relevant tutorial+- If user asks for "how to implement/build" types of questions, first search for relevant examples. If not found, then+ consider what functions are needed and search in the guide/tutorial+- If user asks for "how to initialize" types of questions, first search for relevant tutorials. If not found, then+ consider to search for the corresponding modules, classes, or functions in the library.+++### Search for Examples++First ask for the user's permission to clone the agentscope GitHub repository if you haven't done so:++```bash+git clone -b main https://github.com/agentscope-ai/agentscope+```++In this repo, the `examples` folder contains various examples demonstrating how to use different features of the+AgentScope library.+They are organized in a tree structure by different functionalities. You should use shell command like `ls` or `cat` to+navigate and view the examples. Avoid using `find` command to search for examples, as the name of the example+files may not directly relate to the functionality being searched for.++### Search for Guidance++Similarly, first ensure you have cloned the agentscope GitHub repository.++The source agentscope tutorial is located in the `docs/tutorials` folder of the agentscope GitHub repository. It's+organized by the different sections. To search for guidance, go to the `docs/tutorials` folder and view the tutorial+files by shell command like `ls` or `cat`.+++### Search for Targeted Modules++First, ensure you have installed the agentscope library in your environment:++```bash+pip list | grep agentscope+```++If not installed, ask the user for permission to install it by command:++```bash+pip install agentscope+```++Then, run the following script to search for specific modules, classes, or functions. It's suggested to start with+`agentscope` as the root module name, and then specify the submodule name you want to search for.++```bash+python view_agentscope_module.py --module agentscope+```++About detailed usage, please refer to the `./view_agentscope_module.py` script (located in the same folder as this+SKILL.md file).+diff --git a/examples/functionality/agent_skill/skill/analyzing-agentscope-library/view_agentscope_module.py b/examples/functionality/agent_skill/skill/analyzing-agentscope-library/view_agentscope_module.pynew file mode 100644index 000000000..777b303ce--- /dev/null+++ b/examples/functionality/agent_skill/skill/analyzing-agentscope-library/view_agentscope_module.py@@ -0,0 +1,306 @@+# -*- coding: utf-8 -*-+# pylint: skip-file+"""Get the signatures of functions and classes in the agentscope library."""+from typing import Literal, Callable++import agentscope+import inspect+from pydantic import BaseModel+++def get_class_signature(cls: type) -> str:+ """Get the signature of a class.++ Args:+ cls (`type`):+ A class object.++ Returns:+ str: The signature of the class.+ """+ # Obtain class name and docstring+ class_name = cls.__name__+ class_docstring = cls.__doc__ or ""++ # Construct the class string+ class_str = f"class {class_name}:\n"+ if class_docstring:+ class_str += f' """{class_docstring}"""\n'++ # Obtain the module of the class+ methods = []+ for name, method in inspect.getmembers(cls, predicate=inspect.isfunction):+ # Skip methods that are not part of the class+ if method.__qualname__.split(".")[0] != class_name:+ continue++ if name.startswith("_") and name not in ["__init__", "__call__"]:+ continue++ # Obtain the method's signature+ sig = inspect.signature(method)++ # Construct the method string+ method_str = f" def {name}{sig}:\n"++ # Add the method's docstring if it exists+ method_docstring = method.__doc__ or ""+ if method_docstring:+ method_str += f' """{method_docstring}"""\n'++ methods.append(method_str)++ class_str += "\n".join(methods)+ return class_str+++def get_function_signature(func: Callable) -> str:+ """Get the signature of a function."""+ sig = inspect.signature(func)+ method_str = f"def {func.__name__}{sig}:\n"++ method_docstring = func.__doc__ or ""+ if method_docstring:+ method_str += f' """{method_docstring}"""\n'++ return method_str+++class FuncOrCls(BaseModel):+ """The class records the module, signature, docstring, reference, and+ type"""++ module: str+ """The module of the function or class."""+ signature: str+ """The signature of the function or class."""+ docstring: str+ """The docstring of the function or class."""+ reference: str+ """The reference to the source code of the function or class"""+ type: Literal["function", "class"]+ """The type of the function or class, either 'function' or 'class'."""++ def __init__(+ self,+ module: str,+ signature: str,+ docstring: str,+ reference: str,+ # pylint: disable=redefined-builtin+ type: Literal["function", "class"],+ ) -> None:+ """Initialize the FuncOrCls instance."""+ super().__init__(+ module=module,+ signature=signature.strip(),+ docstring=docstring.strip(),+ reference=reference,+ type=type,+ )+++def _truncate_docstring(docstring: str, max_length: int = 200) -> str:+ """Truncate the docstring to a maximum length.++ Args:+ docstring (`str`):+ The docstring to truncate.+ max_length (`int`, *optional*, defaults to 200):+ The maximum length of the docstring.++ Returns:+ `str`:+ The truncated docstring.+ """+ if len(docstring) > max_length:+ return docstring[:max_length] + "..."+ return docstring+++def get_agentscope_module_signatures() -> list[FuncOrCls]:+ """Get the signatures of functions and classes in the agentscope library.++ Returns:+ `list[FuncOrCls]`:+ A list of FuncOrCls instances representing the functions and+ classes in the agentscope library.+ """+ signatures = []+ for module in agentscope.__all__:+ as_module = getattr(agentscope, module)+ path_module = ".".join(["agentscope", module])++ # Functions+ if inspect.isfunction(as_module):+ file = inspect.getfile(as_module)+ source_lines, start_line = inspect.getsourcelines(as_module)+ signatures.append(+ FuncOrCls(+ module=path_module,+ signature=get_function_signature(as_module),+ docstring=_truncate_docstring(as_module.__doc__ or ""),+ reference=f"{file}: {start_line}-"+ f"{start_line + len(source_lines)}",+ type="function",+ ),+ )++ else:+ if not hasattr(as_module, "__all__"):+ continue++ # Modules with __all__ attribute+ for name in as_module.__all__:+ func_or_cls = getattr(as_module, name)+ path_func_or_cls = ".".join([path_module, name])++ if inspect.isclass(func_or_cls):+ file = inspect.getfile(func_or_cls)+ source_lines, start_line = inspect.getsourcelines(+ func_or_cls,+ )+ signatures.append(+ FuncOrCls(+ module=path_func_or_cls,+ signature=get_class_signature(func_or_cls),+ docstring=_truncate_docstring(+ func_or_cls.__doc__ or "",+ ),+ reference=(+ f"{file}: {start_line}-"+ f"{start_line + len(source_lines)}"+ ),+ type="class",+ ),+ )++ elif inspect.isfunction(func_or_cls):+ file = inspect.getfile(func_or_cls)+ source_lines, start_line = inspect.getsourcelines(+ func_or_cls,+ )+ signatures.append(+ FuncOrCls(+ module=path_func_or_cls,+ signature=get_function_signature(func_or_cls),+ docstring=_truncate_docstring(+ func_or_cls.__doc__ or "",+ ),+ reference=(+ f"{file}: {start_line}-"+ f"{start_line + len(source_lines)}"+ ),+ type="function",+ ),+ )++ return signatures+++def view_agentscope_library(+ module: str,+) -> str:+ """View AgentScope's Python library by given a module name+ (e.g. agentscope), and return the module's submodules, classes, and+ functions. Given a class name, return the class's documentation, methods,+ and their signatures. Given a function name, return the function's+ documentation and signature. If you don't have any information about+ AgentScope library, try to use "agentscope" to view the available top+ modules.++ Note this function only provide the module's brief information.+ For more information, you should view the source code.++ Args:+ module (`str`):+ The module name to view, which should be a module path separated+ by dots (e.g. "agentscope.models"). It can refer to a module,+ a class, or a function.+ """+ if not module.startswith("agentscope"):+ return (+ f"Module '{module}' is invalid. The input module should be "+ f"'agentscope' or submodule of 'agentscope.xxx.xxx' "+ f"(separated by dots)."+ )++ agentscope_top_modules = {}+ for as_module in agentscope.__all__:+ if as_module in ["__version__", "logger"]:+ continue+ agentscope_top_modules[as_module] = getattr(+ agentscope,+ as_module,+ ).__doc__++ # top modules+ if module == "agentscope":+ top_modules_description = (+ [+ "The top-level modules in AgentScope library:",+ ]+ + [+ f"- agentscope.{k}: {v}"+ for k, v in agentscope_top_modules.items()+ ]+ + [+ "You can further view the classes/function within above "+ "modules by calling this function with the above module name.",+ ]+ )+ return "\n".join(top_modules_description)++ # class, functions+ modules = get_agentscope_module_signatures()+ for as_module in modules:+ if as_module.module == module:+ return f"""- The signature of '{module}':+```python+{as_module.signature}+```++- Source code reference: {as_module.reference}"""++ # two-level modules+ collected_modules = []+ for as_module in modules:+ if as_module.module.startswith(module):+ collected_modules.append(as_module)++ if len(collected_modules) > 0:+ collected_modules_content = (+ [+ f"The classes/functions and their truncated docstring in "+ f"'{module}' module:",+ ]+ + [f"- {_.module}: {repr(_.docstring)}" for _ in collected_modules]+ + [+ "The docstring is truncated for limited context. For detailed "+ "signature and methods, call this function with the above "+ "module name",+ ]+ )++ return "\n".join(collected_modules_content)++ return (+ f"Module '{module}' not found. Use 'agentscope' to view the "+ f"top-level modules to ensure the given module is valid."+ )+++if __name__ == "__main__":+ import argparse++ parser = argparse.ArgumentParser()+ parser.add_argument(+ "--module",+ type=str,+ default="agentscope",+ help="The module name to view, e.g. 'agentscope'",+ )+ args = parser.parse_args()++ res = view_agentscope_library(module=args.module)+ print(res)diff --git a/pyproject.toml b/pyproject.tomlindex 671ff8b32..ce5485ab5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -37,6 +37,7 @@ dependencies = ["shortuuid","tiktoken","sounddevice",+ "python-frontmatter",][project.optional-dependencies]diff --git a/src/agentscope/agent/_react_agent.py b/src/agentscope/agent/_react_agent.pyindex 8ddc0e162..47afd745f 100644--- a/src/agentscope/agent/_react_agent.py+++ b/src/agentscope/agent/_react_agent.py@@ -231,7 +231,11 @@ class ReActAgent(ReActAgentBase):@propertydef sys_prompt(self) -> str:"""The dynamic system prompt of the agent."""- return self._sys_prompt+ agent_skill_prompt = self.toolkit.get_agent_skill_prompt()+ if agent_skill_prompt:+ return self._sys_prompt + "\n\n" + agent_skill_prompt+ else:+ return self._sys_prompt@trace_replyasync def reply( # pylint: disable=too-many-branches@@ -574,9 +578,17 @@ class ReActAgent(ReActAgentBase):async def handle_interrupt(self,_msg: Msg | list[Msg] | None = None,+ _structured_model: Type[BaseModel] | None = None,) -> Msg:"""The post-processing logic when the reply is interrupted by the- user or something else."""+ user or something else.++ Args:+ _msg (`Msg | list[Msg] | None`, optional):+ The input message(s) to the agent.+ _structured_model (`Type[BaseModel] | None`, optional):+ The required structured output model.+ """response_msg = Msg(self.name,@@ -585,7 +597,7 @@ class ReActAgent(ReActAgentBase):"assistant",metadata={# Expose this field to indicate the interruption- "is_interrupted": True,+ "_is_interrupted": True,},)diff --git a/src/agentscope/tool/_toolkit.py b/src/agentscope/tool/_toolkit.pyindex a2c2b5f26..42eec3bd2 100644--- a/src/agentscope/tool/_toolkit.py+++ b/src/agentscope/tool/_toolkit.py@@ -1,10 +1,13 @@# -*- coding: utf-8 -*--"""The toolkit class for tool calls in agentscope."""+"""The toolkit class for tool calls in agentscope.+TODO: We should consider to split this `Toolkit` class in the future.+"""+# pylint: disable=too-many-linesimport asyncioimport inspect+import osfrom copy import deepcopy-from dataclasses import dataclassfrom functools import partialfrom typing import (AsyncGenerator,@@ -28,8 +31,8 @@ from ._async_wrapper import (_object_wrapper,_sync_generator_wrapper,)-from ._registered_tool_function import RegisteredToolFunctionfrom ._response import ToolResponse+from ._types import ToolGroup, AgentSkill, RegisteredToolFunctionfrom .._utils._common import _parse_tool_functionfrom ..mcp import (MCPToolFunction,@@ -49,55 +52,69 @@ from ..tracing._trace import trace_toolkitfrom .._logging import logger-@dataclass-class ToolGroup:- """The tool group class"""-- name: str- """The group name, which will be used in the reset function as the group- identifier."""- active: bool- """If the tool group is active, meaning the tool functions in this group- is included in the JSON schema"""- description: str- """The description of the tool group to tell the agent what the tool- group is about."""- notes: str | None = None- """The using notes of the tool group, to remind the agent how to use"""--class Toolkit(StateModule):- """The class that supports both function- and group-level tool management.+ """Toolkit is the core module to register, manage and delete tool+ functions, MCP clients, Agent skills in AgentScope.- Use the following methods to manage the tool functions:+ About tool functions:- - `register_tool_function`- - `remove_tool_function`+ - Register and parse JSON schemas from their docstrings automatically.+ - Group-wise tools management, and agentic tools activation/deactivation.+ - Extend the tool function JSON schema dynamically with Pydantic BaseModel.+ - Tool function execution with unified streaming interface.- For group-level management:+ About MCP clients:- - `create_tool_group`- - `update_tool_groups`- - `remove_tool_groups`+ - Register tool functions from MCP clients directly.+ - Client-level tool functions removal.- MCP related methods:+ About Agent skills:- - `register_mcp_server`- - `remove_mcp_servers`+ - Register agent skills from the given directory.+ - Provide prompt for the registered skills to the agent.+ """- To run the tool functions or get the data from the activated tools:+ _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."+ )- - `call_tool_function`- - `get_json_schemas`- - `get_tool_group_notes`- """+ _DEFAULT_AGENT_SKILL_TEMPLATE = """## {name}+{description}+Check "{dir}/SKILL.md" for how to use this skill"""++ def __init__(+ self,+ agent_skill_instruction: str | None = None,+ agent_skill_template: str | None = None,+ ) -> None:+ """Initialize the toolkit.- def __init__(self) -> None:- """Initialize the toolkit."""+ Args:+ 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.+ """super().__init__()self.tools: dict[str, RegisteredToolFunction] = {}self.groups: dict[str, ToolGroup] = {}+ self.skills: dict[str, AgentSkill] = {}++ 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+ )def create_tool_group(self,@@ -950,3 +967,116 @@ class Toolkit(StateModule):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.+ """+ 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:+ """Get the prompt for all registered agent skills, which can be+ attached to the system prompt for the agent.++ The prompt is consisted of an overall instruction and the detailed+ descriptions of each skill, including its name, description, and+ directory.++ .. note:: If no skill is registered, None will be returned.++ Returns:+ `str | None`:+ The combined prompt for all registered agent skills, or None+ if no skill is registered.+ """+ 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)diff --git a/src/agentscope/tool/_registered_tool_function.py b/src/agentscope/tool/_types.pysimilarity index 84%rename from src/agentscope/tool/_registered_tool_function.pyrename to src/agentscope/tool/_types.pyindex be2535f40..4c7cef8a8 100644--- a/src/agentscope/tool/_registered_tool_function.py+++ b/src/agentscope/tool/_types.py@@ -1,12 +1,12 @@# -*- coding: utf-8 -*--"""The data model for registered tool functions in AgentScope."""+"""The types for the tool module in AgentScope."""from copy import deepcopy-from dataclasses import field, dataclass-from typing import Callable, Literal, Type, Awaitable+from dataclasses import dataclass, field+from typing import TypedDict, Literal, Type, Callable, Awaitablefrom pydantic import BaseModel-from ._response import ToolResponse+from . import ToolResponsefrom .._utils._common import _remove_title_fieldfrom ..message import ToolUseBlockfrom ..types import ToolFunction, JSONSerializableObject@@ -124,3 +124,31 @@ class RegisteredToolFunction:merged_params["$defs"][def_key] = def_value_copyreturn merged_schema+++@dataclass+class ToolGroup:+ """The tool group class"""++ name: str+ """The group name, which will be used in the reset function as the group+ identifier."""+ active: bool+ """If the tool group is active, meaning the tool functions in this group+ is included in the JSON schema"""+ description: str+ """The description of the tool group to tell the agent what the tool+ group is about."""+ notes: str | None = None+ """The using notes of the tool group, to remind the agent how to use"""+++class AgentSkill(TypedDict):+ """The agent skill typed dict class"""++ name: str+ """The name of the skill."""+ description: str+ """The description of the skill."""+ dir: str+ """The directory of the agent skill."""