🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
feat: Chatagent skills (#3732)
Tao Sun813ed0b5863c
diff --git a/.camel/skills/skill-creator/LICENSE.txt b/.camel/skills/skill-creator/LICENSE.txtnew file mode 100644index 000000000..c46213dce--- /dev/null+++ b/.camel/skills/skill-creator/LICENSE.txt@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2023 @ CAMEL-AI.org++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/.camel/skills/skill-creator/SKILL.md b/.camel/skills/skill-creator/SKILL.mdnew file mode 100644index 000000000..ad44c052f--- /dev/null+++ b/.camel/skills/skill-creator/SKILL.md@@ -0,0 +1,190 @@+---+name: skill-creator+description: Guide for creating effective skills. Use when you need to create or update a skill that adds specialized knowledge, workflows, or tool integrations.+license: Complete terms in LICENSE.txt+---++# Skill Creator++This skill provides guidance for creating effective skills.++## About Skills++Skills are modular, self-contained packages that extend your capabilities by providing+specialized knowledge, workflows, and tools. Think of them as onboarding guides for specific+domains or tasks.++### What Skills Provide++1. Specialized workflows - Multi-step procedures for specific domains+2. Tool integrations - Instructions for working with specific file formats or APIs+3. Domain expertise - Company-specific knowledge, schemas, business logic+4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks++## Core Principles++### Concise is Key++The context window is shared across system prompts, conversation history, and other skills.+Only add context that is truly needed. Challenge each piece of information:+"Is this needed to complete the task reliably?" Prefer concise examples over long prose.++### Set Appropriate Degrees of Freedom++Match the level of specificity to the task's fragility and variability:++- High freedom (text-based instructions): Multiple approaches are valid.+- Medium freedom (pseudocode or scripts with parameters): A preferred pattern exists.+- Low freedom (specific scripts, few parameters): Consistency is critical.++Think of exploration: a narrow bridge needs guardrails, an open field allows many routes.++### Anatomy of a Skill++Every skill consists of a required SKILL.md file and optional bundled resources:++```+skill-name/+├── SKILL.md (required)+│ ├── YAML frontmatter metadata (required)+│ │ ├── name: (required)+│ │ └── description: (required)+│ └── Markdown instructions (required)+└── Bundled Resources (optional)+ ├── scripts/ - Executable code (Python/Bash/etc.)+ ├── references/ - Documentation intended to be loaded as needed+ └── assets/ - Files used in output (templates, icons, fonts)+```++#### SKILL.md (required)++Every SKILL.md consists of:++- Frontmatter (YAML): `name` and `description`. These are the only fields used to+ determine when the skill should be used. Be explicit about triggers and contexts.+- Body (Markdown): Instructions and guidance for using the skill. Read only when needed.++#### Bundled Resources (optional)++##### Scripts (`scripts/`)++Executable code for tasks that require deterministic reliability or are repeatedly rewritten.++- When to include: Repeated code or fragile operations+- Example: `scripts/rotate_pdf.py` for PDF rotation tasks+- Benefits: Token efficient, deterministic, can be executed without reading into context+- Note: You may still need to read scripts for patching or environment-specific changes++##### References (`references/`)++Documentation intended to be loaded into context as needed.++- When to include: Detailed docs, schemas, policies, API specs+- Examples: `references/schema.md`, `references/policies.md`, `references/api.md`+- Best practice: Keep SKILL.md lean and point to references for details+- Avoid duplication: Details live in references, not in SKILL.md++##### Assets (`assets/`)++Files not intended for context, but used in outputs.++- When to include: Templates, images, icons, boilerplate code, fonts+- Examples: `assets/logo.png`, `assets/slides.pptx`, `assets/frontend-template/`++#### What to Not Include in a Skill++Do not create extra docs like README.md, INSTALLATION_GUIDE.md, QUICK_REFERENCE.md,+CHANGELOG.md. Keep only files needed for the skill to do its job.++### Progressive Disclosure Design Principle++Skills use a three-level loading system to manage context efficiently:++1. Metadata (name + description) - Always in context+2. SKILL.md body - Read when the skill is relevant+3. Bundled resources - Read or run only as needed++Keep SKILL.md under ~500 lines. Split detailed or variant-specific content into references.++#### Progressive Disclosure Patterns++**Pattern 1: High-level guide with references**++```markdown+# PDF Processing++## Quick start++Extract text with pdfplumber:+[code example]++## Advanced features++- Form filling: See references/FORM_FILLING.md+- API reference: See references/REFERENCE.md+- Examples: See references/EXAMPLES.md+```++**Pattern 2: Domain-specific organization**++```+bigquery-skill/+├── SKILL.md (overview and navigation)+└── references/+ ├── finance.md+ ├── sales.md+ ├── product.md+ └── marketing.md+```++**Pattern 3: Conditional details**++```markdown+# DOCX Processing++## Creating documents++Use docx-js for new documents. See references/DOCX-JS.md.++## Editing documents++For simple edits, modify the XML directly.++For tracked changes: See references/REDLINING.md+For OOXML details: See references/OOXML.md+```++**Guidelines:**++- Avoid deeply nested references; keep references one level deep from SKILL.md.+- For reference files longer than 100 lines, add a table of contents.++## Skill Creation Process++1. Understand the skill with concrete examples+2. Plan reusable skill contents (scripts, references, assets)+3. Initialize the skill (create folder + SKILL.md)+4. Edit the skill (implement resources and write SKILL.md)+5. Iterate based on real usage++### Step 1: Understanding the Skill with Concrete Examples++Ask for concrete examples and likely triggers. Start with a few questions and+follow up as needed.++### Step 2: Planning the Reusable Skill Contents++For each example, identify what should be captured in scripts, references, or assets.++### Step 3: Initializing the Skill++Create the skill folder with a SKILL.md template and only the resource folders you need.++### Step 4: Edit the Skill++Write in imperative form. Keep the body focused on workflows and decisions. Point to+references for detailed content.++### Step 5: Iterate++After real usage, refine the skill based on observed failures or friction.diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex 8b17aa99a..5a05e1c82 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -100,6 +100,7 @@ from .minimax_mcp_toolkit import MinimaxMCPToolkitfrom .imap_mail_toolkit import IMAPMailToolkitfrom .microsoft_outlook_mail_toolkit import OutlookMailToolkitfrom .earth_science_toolkit import EarthScienceToolkit+from .skill_toolkit import SkillToolkit__all__ = ['BaseToolkit',@@ -191,4 +192,5 @@ __all__ = ['IMAPMailToolkit',"OutlookMailToolkit",'EarthScienceToolkit',+ 'SkillToolkit',]diff --git a/camel/toolkits/skill_toolkit.py b/camel/toolkits/skill_toolkit.pynew file mode 100644index 000000000..0944fe1be--- /dev/null+++ b/camel/toolkits/skill_toolkit.py@@ -0,0 +1,389 @@+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========++from pathlib import Path+from typing import Dict, List, Optional, Tuple, Union++import yaml++from camel.logger import get_logger+from camel.toolkits.base import BaseToolkit+from camel.toolkits.function_tool import FunctionTool++logger = get_logger(__name__)+++class SkillToolkit(BaseToolkit):+ r"""Toolkit for loading SKILL.md content.++ Skills are discovered from filesystem roots and loaded on-demand.+ """++ def __init__(+ self,+ working_directory: Optional[str] = None,+ timeout: Optional[float] = None,+ ) -> None:+ super().__init__(timeout=timeout)+ self.working_directory = (+ Path(working_directory).resolve()+ if working_directory+ else Path.cwd().resolve()+ )+ self._skills_cache: Optional[Dict[str, Dict[str, str]]] = None++ def _build_description(self) -> str:+ skills = self._get_skills()+ if not skills:+ return (+ "Load a skill to get detailed instructions for a specific "+ "task. No skills are currently available."+ )+ # Build skill summary lines+ summary_lines = [+ "Load a skill to get detailed instructions for a specific task.",+ "Skills provide specialized knowledge and step-by-step guidance.",+ "Use this when a task matches an available skill's description.",+ "Only the skills listed here are available:",+ "<available_skills>",+ ]+ for skill in skills.values():+ summary_lines.extend(+ [+ " <skill>",+ f" <name>{skill['name']}</name>",+ f" <description>{skill['description']}</description>",+ f" <path>{skill['path']}</path>",+ " </skill>",+ ]+ )+ summary_lines.append("</available_skills>")+ # Build markdown list for display+ available = ""+ for skill in skills.values():+ available += (+ f"- {skill['name']}: {skill['description']} "+ f"({skill['path']})\n"+ )+ return (+ "## Skills\n"+ "A skill is a set of local instructions to follow that is stored "+ "in a `SKILL.md` file. Below is the list of skills that can be "+ "used. Each entry includes a name, description, and file path so "+ "you can open the source for full instructions when using a "+ "specific skill.\n"+ "### Available skills\n"+ f"{available}\n"+ "### How to use skills\n"+ "- Discovery: The list above is the skills available in this "+ "session (name + description + file path). Skill bodies live on "+ "disk at the listed paths.\n"+ "- Trigger rules: If the user names a skill or the task clearly "+ "matches a skill's description shown above, you should use that "+ "skill for this turn.\n"+ "- Missing/blocked: If a named skill isn't in the list or the "+ "path can't be read, say so briefly and continue with the best "+ "fallback.\n"+ "- How to use a skill (progressive disclosure):\n"+ " 1) After deciding to use a skill, open its `SKILL.md` from the "+ "filesystem. Read only enough to follow the workflow.\n"+ " 2) If `SKILL.md` points to extra folders such as `references/` "+ ", load only the specific files needed for the request; don't "+ "bulk-load everything.\n"+ " 3) If `scripts/` exist, use available execution tools "+ "(terminal, code runner) to run them instead of rewriting code.\n"+ " 4) If `assets/` or templates exist, reuse them instead of "+ "recreating from scratch.\n"+ "- Coordination and sequencing:\n"+ " - If multiple skills apply, choose the minimal set that covers "+ "the request and state the order you'll use them.\n"+ " - Announce which skill(s) you're using and why "+ "(one short line). If you skip an obvious skill, say why.\n"+ "- Context hygiene:\n"+ " - Keep context small: summarize long sections instead of "+ "pasting them; only load extra files when needed.\n"+ " - Avoid deep reference-chasing: prefer opening only files "+ "directly linked from `SKILL.md` unless you're blocked.\n"+ " - When variants exist (frameworks, providers, domains), pick "+ "only the relevant reference file(s) and note that choice.\n"+ "- Safety and fallback: If a skill can't be applied cleanly "+ "(missing files, unclear instructions), state the issue, pick the "+ "next-best approach, and continue.\n"+ "\n" + "\n".join(summary_lines)+ )++ def _get_skills(self) -> Dict[str, Dict[str, str]]:+ if self._skills_cache is None:+ self._skills_cache = self._scan_skills()+ return self._skills_cache++ def clear_cache(self) -> None:+ r"""Clear the cached skills to force rescanning on next access."""+ self._skills_cache = None++ def _scan_skills(self) -> Dict[str, Dict[str, str]]:+ r"""Scan all skill roots and collect skill metadata.++ Skills are discovered from roots in priority order:+ repo > user > system. If multiple skills have the same name,+ the first one found takes priority.++ Returns:+ Dict[str, Dict[str, str]]: Mapping of skill name to metadata.+ """+ skills: Dict[str, Dict[str, str]] = {}+ for scope, root in self._skill_roots():+ if not root.is_dir():+ continue+ for path in root.rglob("SKILL.md"):+ if self._is_hidden_path(path, root):+ continue+ skill = self._parse_skill(path)+ if not skill:+ continue+ name = skill["name"]+ # First skill with this name wins (earlier scope has priority)+ if name in skills:+ continue+ skills[name] = {+ "name": name,+ "description": skill["description"],+ "path": str(path),+ "scope": scope,+ }+ return skills++ def _skill_roots(self) -> List[Tuple[str, Path]]:+ r"""Return skill root directories with their scope.++ Scopes are checked in order: repo -> user -> system.+ Earlier scopes take priority when skills have the same name.++ Returns:+ List[Tuple[str, Path]]: List of (scope, path) tuples.+ """+ # Skills are discovered in priority order:+ # 1. repo scope: project-specific skills in working directory+ # 2. user scope: user-level skills in home directory+ # 3. system scope: system-wide skills in /etc+ roots: List[Tuple[str, Path]] = [+ # Repo scope - project-specific skills+ ("repo", self.working_directory / ".camel" / "skills"),+ ("repo", self.working_directory / ".agents" / "skills"),+ # User scope - user-level skills+ ("user", Path.home() / ".camel" / "skills"),+ ("user", Path.home() / ".config" / "camel" / "skills"),+ # System scope - system-wide skills+ ("system", Path("/etc/camel/skills")),+ ]+ return roots++ def _is_hidden_path(self, path: Path, root: Path) -> bool:+ r"""Check if a path contains hidden directories (starting with dot).++ Args:+ path (Path): The path to check.+ root (Path): The root directory to compute relative path from.++ Returns:+ bool: True if the path contains hidden directories.+ """+ try:+ rel = path.relative_to(root)+ except ValueError:+ rel = path+ return any(part.startswith(".") for part in rel.parts)++ def _parse_skill(self, path: Path) -> Optional[Dict[str, str]]:+ r"""Parse a SKILL.md file and extract metadata.++ Args:+ path (Path): Path to the SKILL.md file.++ Returns:+ Optional[Dict[str, str]]: Parsed skill data with name,+ description, and body. Returns None if parsing fails.+ """+ try:+ contents = path.read_text(encoding="utf-8")+ except OSError as exc:+ logger.warning("Failed to read skill %s: %s", path, exc)+ return None++ frontmatter_text, body = self._split_frontmatter(contents)+ if frontmatter_text is None:+ logger.warning("Missing YAML frontmatter in %s", path)+ return None++ try:+ data = yaml.safe_load(frontmatter_text) or {}+ except yaml.YAMLError as exc:+ logger.warning("Invalid YAML frontmatter in %s: %s", path, exc)+ return None++ if not isinstance(data, dict):+ logger.warning("Frontmatter must be a mapping in %s", path)+ return None++ name = data.get("name")+ description = data.get("description")+ if not isinstance(name, str) or not isinstance(description, str):+ logger.warning("Skill missing name/description in %s", path)+ return None++ return {+ "name": name.strip(),+ "description": description.strip(),+ "body": body,+ }++ def _split_frontmatter(self, contents: str) -> Tuple[Optional[str], str]:+ r"""Split YAML frontmatter from the body of a SKILL.md file.++ Args:+ contents (str): The full contents of the file.++ Returns:+ Tuple[Optional[str], str]: A tuple of (frontmatter, body).+ frontmatter is None if no valid frontmatter delimiter is found.+ """+ lines = contents.splitlines()+ if not lines or lines[0].strip() != "---":+ return None, contents+ for i in range(1, len(lines)):+ if lines[i].strip() == "---":+ frontmatter = "\n".join(lines[1:i])+ body = "\n".join(lines[i + 1 :])+ return frontmatter, body+ return None, contents++ def list_skills(self) -> List[Dict[str, str]]:+ r"""List available skills without loading their full content.++ Returns:+ List[Dict[str, str]]: Skill metadata entries including name,+ description, path, and scope.+ """+ skills = self._get_skills()+ return [+ {+ "name": skill["name"],+ "description": skill["description"],+ "path": skill["path"],+ "scope": skill["scope"],+ }+ for skill in skills.values()+ ]++ def list_skill_files(self, name: str) -> str:+ r"""List files and directories in a skill folder.++ Args:+ name (str): The skill identifier.++ Returns:+ str: Formatted list of files/directories, or error message.+ """+ skills = self._get_skills()+ skill = skills.get(name)+ if not skill:+ available = ", ".join(sorted(skills.keys())) or "none"+ return f"Error: Skill \"{name}\" not found. Available: {available}"++ skill_dir = Path(skill["path"]).parent+ lines = [f"Files in {name}:"]+ for item in sorted(skill_dir.iterdir()):+ if item.is_dir():+ lines.append(f" - {item.name}/")+ else:+ lines.append(f" - {item.name}")+ return "\n".join(lines)++ def _load_single_skill(self, name: str) -> str:+ r"""Load a single skill by name.++ Args:+ name (str): The skill identifier.++ Returns:+ str: The skill content, or error message if not found.+ """+ skills = self._get_skills()+ skill = skills.get(name)+ if not skill:+ available = ", ".join(sorted(skills.keys())) or "none"+ return f"Error: Skill \"{name}\" not found. Available: {available}"++ path = Path(skill["path"])+ parsed = self._parse_skill(path)+ if not parsed:+ return f"Error: Failed to load skill from {path}"++ base_dir = path.parent+ body = parsed.get("body", "").strip()++ # List files in skill directory+ files_info = []+ for item in sorted(base_dir.iterdir()):+ if item.name == "SKILL.md":+ continue+ files_info.append(+ f" - {item.name}/ (dir)"+ if item.is_dir()+ else f" - {item.name}"+ )++ output_lines = [+ f"## Skill: {parsed['name']}",+ "",+ f"**Base directory**: {base_dir}",+ ]++ if files_info:+ output_lines.append("")+ output_lines.append("**Available files**:")+ output_lines.extend(files_info)++ output_lines.append("")+ output_lines.append(body)++ return "\n".join(output_lines).strip()++ def get_skill(self, name: Union[str, List[str]]) -> str:+ r"""Load one or more skills by name.++ Args:+ name (Union[str, List[str]]): A single skill name or list of names.++ Returns:+ str: The skill content(s), or error message if not found.+ """+ if isinstance(name, str):+ return self._load_single_skill(name)++ # Load multiple skills+ results = []+ for skill_name in name:+ results.append(self._load_single_skill(skill_name))++ return "\n\n---\n\n".join(results)++ def get_tools(self) -> List[FunctionTool]:+ r"""Return the skill tools with injected available skills."""+ list_tool = FunctionTool(self.list_skills)+ get_tool = FunctionTool(self.get_skill)+ schema = get_tool.get_openai_tool_schema()+ schema["function"]["description"] = self._build_description()+ get_tool.set_openai_tool_schema(schema)+ return [list_tool, get_tool]diff --git a/examples/toolkits/skill_toolkit.py b/examples/toolkits/skill_toolkit.pynew file mode 100644index 000000000..f10dc3c20--- /dev/null+++ b/examples/toolkits/skill_toolkit.py@@ -0,0 +1,46 @@+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+"""+Basic SkillToolkit Example++This example shows basic usage of SkillToolkit.+For a more complete example with multiple skills, see:+ examples/toolkits/skill_toolkit_example/++Skills are SKILL.md files discovered from:+ - .camel/skills/ (repo scope)+ - ~/.camel/skills/ (user scope)+"""++from camel.toolkits import SkillToolkit++# Create toolkit - discovers skills from standard locations+skill_toolkit = SkillToolkit()++# List available skills+skills = skill_toolkit.list_skills()+print(f"Found {len(skills)} skills:")+for skill in skills:+ print(f" - {skill['name']}: {skill['description']}")++# Get tools for use with ChatAgent+tools = skill_toolkit.get_tools()+print(f"\nTools available: {[t.func.__name__ for t in tools]}")++# Load a specific skill (if available)+if skills:+ skill_name = skills[0]["name"]+ content = skill_toolkit.get_skill(skill_name)+ print(f"\nLoaded skill '{skill_name}':")+ print(content[:200] + "...")diff --git a/examples/toolkits/skill_toolkit_example/.camel/skills/code-reviewer/SKILL.md b/examples/toolkits/skill_toolkit_example/.camel/skills/code-reviewer/SKILL.mdnew file mode 100644index 000000000..9ae90faca--- /dev/null+++ b/examples/toolkits/skill_toolkit_example/.camel/skills/code-reviewer/SKILL.md@@ -0,0 +1,43 @@+---+name: code-reviewer+description: Review code for quality, bugs, and improvements. Use when user wants code review or quality assessment.+---++# Code Reviewer++Perform thorough code reviews focusing on quality and correctness.++## Review Checklist++1. **Correctness** - Does the code do what it's supposed to?+2. **Readability** - Is the code easy to understand?+3. **Performance** - Are there any obvious inefficiencies?+4. **Security** - Are there potential vulnerabilities?+5. **Best Practices** - Does it follow language conventions?++## Output Format++```markdown+## Code Review Summary++**Overall Assessment**: [Good/Needs Work/Critical Issues]++### Issues Found+| Severity | Line | Issue | Suggestion |+|----------|------|-------|------------|+| High | 42 | ... | ... |++### Positive Aspects+- [What's done well]++### Recommendations+1. [Priority fix 1]+2. [Priority fix 2]+```++## Severity Levels++- **Critical**: Security issues, data loss risks+- **High**: Bugs, incorrect logic+- **Medium**: Performance issues, code smells+- **Low**: Style issues, minor improvementsdiff --git a/examples/toolkits/skill_toolkit_example/.camel/skills/data-analyzer/SKILL.md b/examples/toolkits/skill_toolkit_example/.camel/skills/data-analyzer/SKILL.mdnew file mode 100644index 000000000..9e0eb6dd2--- /dev/null+++ b/examples/toolkits/skill_toolkit_example/.camel/skills/data-analyzer/SKILL.md@@ -0,0 +1,40 @@+---+name: data-analyzer+description: Analyze datasets and extract insights. Use when user needs to understand data patterns, statistics, or trends.+---++# Data Analyzer++Analyze data and provide statistical insights.++## Workflow++1. Load and inspect the data structure+2. Compute basic statistics (mean, median, std, min, max)+3. Identify patterns and anomalies+4. Summarize key findings++## Output Format++Provide analysis in this structure:++```+## Data Overview+- Total records: X+- Columns: [list]++## Key Statistics+| Metric | Value |+|--------|-------|+| ... | ... |++## Insights+- Finding 1+- Finding 2+```++## Guidelines++- Always validate data types before analysis+- Handle missing values explicitly+- Report confidence levels for statistical claimsdiff --git a/examples/toolkits/skill_toolkit_example/.camel/skills/data-analyzer/scripts/analyze.py b/examples/toolkits/skill_toolkit_example/.camel/skills/data-analyzer/scripts/analyze.pynew file mode 100644index 000000000..6b9006425--- /dev/null+++ b/examples/toolkits/skill_toolkit_example/.camel/skills/data-analyzer/scripts/analyze.py@@ -0,0 +1,21 @@+"""Sample analysis script for data-analyzer skill."""+++def analyze(data):+ """Analyze data and return statistics."""+ if not data:+ return {"error": "No data provided"}+ return {+ "count": len(data),+ "sum": sum(data),+ "mean": sum(data) / len(data),+ "min": min(data),+ "max": max(data),+ }+++if __name__ == "__main__":+ # Example usage+ sample_data = [10, 20, 30, 40, 50]+ result = analyze(sample_data)+ print(f"Analysis result: {result}")diff --git a/examples/toolkits/skill_toolkit_example/.camel/skills/report-writer/SKILL.md b/examples/toolkits/skill_toolkit_example/.camel/skills/report-writer/SKILL.mdnew file mode 100644index 000000000..50535bee2--- /dev/null+++ b/examples/toolkits/skill_toolkit_example/.camel/skills/report-writer/SKILL.md@@ -0,0 +1,46 @@+---+name: report-writer+description: Generate professional reports from analysis results. Use when user needs to create formatted documents summarizing findings.+---++# Report Writer++Transform analysis results into professional reports.++## Report Structure++1. **Executive Summary** - Key findings in 2-3 sentences+2. **Methodology** - How the analysis was performed+3. **Results** - Detailed findings with visualizations+4. **Recommendations** - Actionable next steps+5. **Appendix** - Raw data and technical details++## Formatting Guidelines++- Use clear headings and subheadings+- Include tables for numerical data+- Add bullet points for lists+- Keep paragraphs concise (3-4 sentences max)++## Tone++- Professional but accessible+- Data-driven claims with evidence+- Avoid jargon unless necessary++## Example Output++```markdown+# Analysis Report: [Title]++## Executive Summary+[2-3 sentence overview of key findings]++## Results+### Finding 1+[Description with supporting data]++## Recommendations+1. [Action item 1]+2. [Action item 2]+```diff --git a/examples/toolkits/skill_toolkit_example/example.py b/examples/toolkits/skill_toolkit_example/example.pynew file mode 100644index 000000000..816a22548--- /dev/null+++ b/examples/toolkits/skill_toolkit_example/example.py@@ -0,0 +1,118 @@+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+"""+Skill Toolkit Example++This example demonstrates how to use SkillToolkit with an agent.+The agent uses tool calls to interact with skills.++Skills are defined in .camel/skills/ directory:+ - data-analyzer: For analyzing datasets+ - report-writer: For generating reports+ - code-reviewer: For reviewing code++Run this example from the skill_toolkit_example directory:+ cd examples/toolkits/skill_toolkit_example+ python example.py+"""++import os+from pathlib import Path++from camel.agents import ChatAgent+from camel.models import ModelFactory+from camel.toolkits import SkillToolkit, TerminalToolkit+from camel.types import ModelPlatformType, ModelType++# Set working directory to this example folder so skills are discovered+EXAMPLE_DIR = Path(__file__).parent.resolve()+os.chdir(EXAMPLE_DIR)++# Create model (change platform/type as needed)+model = ModelFactory.create(+ model_platform=ModelPlatformType.OPENAI,+ model_type=ModelType.GPT_5_2,+)++# Create skill toolkit - discovers skills from .camel/skills/+skill_toolkit = SkillToolkit(working_directory=str(EXAMPLE_DIR))++# Create terminal toolkit - enables script execution from skills+terminal_toolkit = TerminalToolkit(working_directory=str(EXAMPLE_DIR))++# Create agent with both skill and terminal tools+agent = ChatAgent(+ system_message="You are a helpful assistant that uses skills and "+ "can execute scripts.",+ model=model,+ tools=[*skill_toolkit.get_tools(), *terminal_toolkit.get_tools()],+)+++def main():+ # Example 1: Agent lists available skills via tool call+ print("=" * 60)+ print("Example 1: Agent lists available skills")+ print("=" * 60)+ agent.reset()+ response = agent.step("What skills are available? ")+ print(f"\n{response.msgs[0].content}")++ # Example 2: Agent loads a specific skill via tool call+ print("\n" + "=" * 60)+ print("Example 2: Agent loads the data-analyzer skill")+ print("=" * 60)++ agent.reset()+ response = agent.step("Load the data-analyzer skill")+ print(f"\n{response.msgs[0].content[:500]}...")++ # Example 3: Agent executes a script from a skill+ print("\n" + "=" * 60)+ print("Example 3: Agent executes script from data-analyzer skill")+ print("=" * 60)++ task = """+ Load the data-analyzer skill and run its analysis script+ with sample data [10, 20, 30, 40, 50].+ """++ print(f"\nTask: {task.strip()}")+ print("\nAgent response:")+ agent.reset()+ response = agent.step(task)+ print(response.msgs[0].content)++ # Example 4: Agent uses skills to complete a complex task+ print("\n" + "=" * 60)+ print("Example 4: Agent uses skills for analysis task")+ print("=" * 60)++ task = """+ I have sales data showing monthly revenue:+ Jan: $10,000, Feb: $12,000, Mar: $9,500, Apr: $15,000++ Please analyze this data and write a brief report.+ Use the appropriate skills to help with this task.+ """++ print(f"\nTask: {task.strip()}")+ print("\nAgent response:")+ agent.reset()+ response = agent.step(task)+ print(response.msgs[0].content)+++if __name__ == "__main__":+ main()diff --git a/pyproject.toml b/pyproject.tomlindex 47583dcf3..07dc607ac 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -34,6 +34,7 @@ dependencies = ["astor>=0.8.1","pillow>=10.0.0","google-search-results>=2.4.2",+ "pyyaml>=6.0.3",][tool.uv]diff --git a/test/toolkits/test_skill_toolkit.py b/test/toolkits/test_skill_toolkit.pynew file mode 100644index 000000000..54f83ea1f--- /dev/null+++ b/test/toolkits/test_skill_toolkit.py@@ -0,0 +1,140 @@+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========++import tempfile+from pathlib import Path++import pytest++from camel.toolkits import SkillToolkit+++def temp_skill_dir():+ r"""Create a temporary directory with skills for testing."""+ with tempfile.TemporaryDirectory() as temp_dir:+ # Create first skill+ skill_dir = Path(temp_dir) / ".camel" / "skills" / "test-skill"+ skill_dir.mkdir(parents=True)+ skill_file = skill_dir / "SKILL.md"+ skill_file.write_text(+ """---+name: test-skill+description: A test skill for unit testing.+---++# Test Skill++This is a test skill body content.+"""+ )++ # Create second skill for multi-skill testing+ skill_dir2 = Path(temp_dir) / ".camel" / "skills" / "another-skill"+ skill_dir2.mkdir(parents=True)+ skill_file2 = skill_dir2 / "SKILL.md"+ skill_file2.write_text(+ """---+name: another-skill+description: Another test skill.+---++# Another Skill++This is another skill body.+"""+ )+ yield temp_dir+++def skill_toolkit(temp_skill_dir):+ r"""Create a SkillToolkit instance for testing."""+ return SkillToolkit(working_directory=temp_skill_dir)+++def test_initialization():+ r"""Test the initialization of SkillToolkit."""+ toolkit = SkillToolkit()+ assert toolkit.working_directory == Path.cwd().resolve()+ assert toolkit._skills_cache is None+++def test_list_skills(skill_toolkit):+ r"""Test listing available skills."""+ skills = skill_toolkit.list_skills()+ assert len(skills) == 2+ names = {s["name"] for s in skills}+ assert "test-skill" in names+ assert "another-skill" in names+++def test_get_skill(skill_toolkit):+ r"""Test getting a skill by name."""+ skill_content = skill_toolkit.get_skill("test-skill")+ assert "## Skill: test-skill" in skill_content+ assert "**Base directory**:" in skill_content+ assert "This is a test skill body content." in skill_content+++def test_get_skill_not_found(skill_toolkit):+ r"""Test getting a non-existent skill returns error message."""+ result = skill_toolkit.get_skill("non-existent-skill")+ assert "Error:" in result+ assert "not found" in result+++def test_get_multiple_skills(skill_toolkit):+ r"""Test getting multiple skills at once."""+ result = skill_toolkit.get_skill(["test-skill", "another-skill"])+ assert "## Skill: test-skill" in result+ assert "## Skill: another-skill" in result+ assert "This is a test skill body content." in result+ assert "This is another skill body." in result+ # Check separator between skills+ assert "---" in result+++def test_get_tools(skill_toolkit):+ r"""Test getting the tools from the toolkit."""+ tools = skill_toolkit.get_tools()+ assert len(tools) == 2+ tool_names = [t.func.__name__ for t in tools]+ assert "list_skills" in tool_names+ assert "get_skill" in tool_names+++def test_caching(skill_toolkit):+ r"""Test that skills are cached after first access."""+ assert skill_toolkit._skills_cache is None+ skill_toolkit.list_skills()+ assert skill_toolkit._skills_cache is not None+ cached_skills = skill_toolkit._skills_cache+ skill_toolkit.list_skills()+ assert skill_toolkit._skills_cache is cached_skills+++def test_clear_cache(skill_toolkit):+ r"""Test that clear_cache resets the skills cache."""+ # Populate the cache+ skill_toolkit.list_skills()+ assert skill_toolkit._skills_cache is not None++ # Clear the cache+ skill_toolkit.clear_cache()+ assert skill_toolkit._skills_cache is None++ # Cache should be repopulated on next access+ skill_toolkit.list_skills()+ assert skill_toolkit._skills_cache is not Nonediff --git a/uv.lock b/uv.lockindex 3b480d32b..41a1106d4 100644--- a/uv.lock+++ b/uv.lock@@ -900,6 +900,7 @@ dependencies = [{ name = "pillow" },{ name = "psutil" },{ name = "pydantic" },+ { name = "pyyaml" },{ name = "tiktoken" },{ name = "websockets" },]@@ -1631,6 +1632,7 @@ requires-dist = [{ name = "pytidb", marker = "extra == 'all'", specifier = ">=0.0.13" },{ name = "pytidb", marker = "extra == 'rag'", specifier = ">=0.0.13" },{ name = "pytidb", marker = "extra == 'storage'", specifier = ">=0.0.13" },+ { name = "pyyaml", specifier = ">=6.0.3" },{ name = "qdrant-client", marker = "extra == 'all'", specifier = ">=1.9.0,<2" },{ name = "qdrant-client", marker = "extra == 'rag'", specifier = ">=1.9.0,<2" },{ name = "qdrant-client", marker = "extra == 'storage'", specifier = ">=1.9.0,<2" },@@ -7293,7 +7295,7 @@ name = "pexpect"version = "4.9.0"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "ptyprocess" },+ { name = "ptyprocess", marker = "sys_platform != 'win32'" },]sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" }wheels = [@@ -8265,7 +8267,7 @@ name = "pyobjc-framework-cocoa"version = "12.1"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "pyobjc-core", marker = "python_full_version >= '3.13' or sys_platform == 'darwin'" },+ { name = "pyobjc-core", marker = "(python_full_version >= '3.13' and sys_platform != 'win32') or sys_platform == 'darwin'" },]sdist = { url = "https://files.pythonhosted.org/packages/02/a3/16ca9a15e77c061a9250afbae2eae26f2e1579eb8ca9462ae2d2c71e1169/pyobjc_framework_cocoa-12.1.tar.gz", hash = "sha256:5556c87db95711b985d5efdaaf01c917ddd41d148b1e52a0c66b1a2e2c5c1640", size = 2772191, upload-time = "2025-11-14T10:13:02.069Z" }wheels = [@@ -8283,8 +8285,8 @@ name = "pyobjc-framework-quartz"version = "12.1"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "pyobjc-core", marker = "python_full_version >= '3.13' or sys_platform == 'darwin'" },- { name = "pyobjc-framework-cocoa", marker = "python_full_version >= '3.13' or sys_platform == 'darwin'" },+ { name = "pyobjc-core", marker = "(python_full_version >= '3.13' and sys_platform != 'win32') or sys_platform == 'darwin'" },+ { name = "pyobjc-framework-cocoa", marker = "(python_full_version >= '3.13' and sys_platform != 'win32') or sys_platform == 'darwin'" },]sdist = { url = "https://files.pythonhosted.org/packages/94/18/cc59f3d4355c9456fc945eae7fe8797003c4da99212dd531ad1b0de8a0c6/pyobjc_framework_quartz-12.1.tar.gz", hash = "sha256:27f782f3513ac88ec9b6c82d9767eef95a5cf4175ce88a1e5a65875fee799608", size = 3159099, upload-time = "2025-11-14T10:21:24.31Z" }wheels = [