ANALYSIS
CoPaw 技能系统详解
概述
CoPaw 的技能系统是一个可扩展的插件系统,允许你为 CoPaw 添加各种功能。技能从工作区自动加载,内置定时调度,是一等公民 —— 可发现、可组合、可独立部署。
技能系统概述
什么是技能
技能是 CoPaw 的功能扩展模块,可以为 CoPaw 添加新的能力。
技能特点:
- 可发现:可以通过 CLI 命令发现和安装
- 可组合:多个技能可以组合使用
- 可独立部署:技能可以独立开发和部署
- 无厂商锁定:完全开源,无厂商限制
技能类型
| 类型 | 说明 | 示例 |
|---|---|---|
| 内置技能 | CoPaw 自带的基本技能 | 天气查询、计算器 |
| 自定义技能 | 用户自己开发的技能 | 数据分析、报告生成 |
| 社区技能 | 社区共享的技能 | 网络爬虫、内容生成 |
技能目录结构
PRTCL // PLAINTEXT
~/.copaw/workspace/skills/├── builtin/ # 内置技能│ ├── weather/│ │ └── SKILL.md│ ├── calculator/│ │ └── SKILL.md│ └── ...├── customized/ # 自定义技能│ ├── my-skill/│ │ ├── SKILL.md│ │ ├── main.py│ │ └── config.yaml│ └── ...└── active/ # 激活的技能 ├── weather -> ../builtin/weather ├── calculator -> ../builtin/calculator └── my-skill -> ../customized/my-skill技能管理
技能 CLI 命令
查看可用技能:
PRTCL // BASH
# 列出所有可用技能copaw skills list
# 列出已安装技能copaw skills installed
# 列出激活的技能copaw skills active安装技能:
PRTCL // BASH
# 从本地安装copaw skills install path/to/skill
# 从 Git 仓库安装copaw skills install git+https://github.com/user/skill.git
# 从 PyPI 安装copaw skills install skill-name移除技能:
PRTCL // BASH
# 移除技能copaw skills remove skill-name
# 强制移除copaw skills remove skill-name --force更新技能:
PRTCL // BASH
# 更新技能copaw skills update skill-name
# 更新所有技能copaw skills update --all激活 / 停用技能:
PRTCL // BASH
# 激活技能copaw skills activate skill-name
# 停用技能copaw skills deactivate skill-name技能搜索
搜索技能:
PRTCL // BASH
# 搜索技能copaw skills search keyword
# 搜索天气相关技能copaw skills search weather
# 搜索计算相关技能copaw skills search calculator技能信息
查看技能详情:
PRTCL // BASH
# 查看技能详情copaw skills info skill-name
# 查看技能配置copaw skills config skill-name
# 查看技能依赖copaw skills dependencies skill-name技能结构
SKILL.md 文件
基础结构:
PRTCL // MARKDOWN
# 技能名称
## 描述简要描述技能的功能和用途。
## 版本1.0.0
## 作者Your Name
## 依赖- numpy >= 1.20.0- requests >= 2.25.0
## 配置```yamlparam1: value1param2: value2使用方法
说明如何使用该技能。
示例
PRTCL // PLAINTEXT
用户:查询北京的天气CoPaw:[调用天气技能] 北京今天天气晴朗,温度 25°CPRTCL // PLAINTEXT
** 高级结构 **:```markdown# 高级数据分析技能
## 描述提供强大的数据分析功能,包括统计分析、数据可视化和报告生成。
## 版本2.1.0
## 作者Data Team
## 依赖- pandas >= 1.5.0- numpy >= 1.23.0- matplotlib >= 3.5.0- plotly >= 5.0.0
## 配置```yamloutput_format: "markdown"chart_theme: "plotly"max_rows: 1000cache_enabled: truecache_ttl: 3600功能
- 数据加载和清洗
- 统计分析
- 数据可视化
- 报告生成
使用方法
PRTCL // PLAINTEXT
用户:分析销售数据CoPaw:[调用数据分析技能] 正在分析销售数据...示例
PRTCL // PLAINTEXT
用户:分析今年的销售数据并生成报告CoPaw:[调用数据分析技能]- 加载数据:sales_2024.csv- 数据清洗:完成- 统计分析: * 总销售额:¥1,234,567 * 同比增长:15.3% * 月均销售额:¥102,880- 数据可视化:生成图表- 报告生成:完成权限
- read: 读取文件
- write: 写入文件
- network: 网络访问
限制
- 最大文件大小:100MB
- 最大处理行数:10,000 行
PRTCL // PLAINTEXT
### main.py 文件
** 基础结构 **:```python# main.pyfrom typing import Dict, Anyfrom copaw.skills import Skill
class MySkill(Skill): """自定义技能"""
def __init__(self, config: Dict[str, Any]): super().__init__(config) self.param1 = config.get('param1', 'default_value')
def execute(self, input_data: Dict[str, Any]) -> Dict[str, Any]: """执行技能""" result = self.process(input_data) return { 'success': True, 'result': result }
def process(self, input_data: Dict[str, Any]) -> Any: """处理输入数据""" # 处理逻辑 return processed_result高级结构:
PRTCL // PYTHON
import pandas as pdimport matplotlib.pyplot as pltfrom typing import Dict, Any, Listfrom copaw.skills import Skill
class DataAnalysisSkill(Skill): """数据分析技能"""
def __init__(self, config: Dict[str, Any]): super().__init__(config) self.output_format = config.get('output_format', 'markdown') self.chart_theme = config.get('chart_theme', 'plotly') self.max_rows = config.get('max_rows', 1000) self.cache_enabled = config.get('cache_enabled', True) self.cache_ttl = config.get('cache_ttl', 3600)
def execute(self, input_data: Dict[str, Any]) -> Dict[str, Any]: """执行数据分析""" try: # 加载数据 data = self.load_data(input_data)
# 数据清洗 cleaned_data = self.clean_data(data)
# 统计分析 stats = self.analyze(cleaned_data)
# 数据可视化 charts = self.visualize(cleaned_data)
# 生成报告 report = self.generate_report(stats, charts)
return { 'success': True, 'result': report, 'stats': stats, 'charts': charts } except Exception as e: return { 'success': False, 'error': str(e) }
def load_data(self, input_data: Dict[str, Any]) -> pd.DataFrame: """加载数据""" file_path = input_data.get('file_path') if file_path.endswith('.csv'): return pd.read_csv(file_path) elif file_path.endswith('.xlsx'): return pd.read_excel(file_path) else: raise ValueError("不支持的文件格式")
def clean_data(self, data: pd.DataFrame) -> pd.DataFrame: """清洗数据""" # 去除重复 data = data.drop_duplicates()
# 处理缺失值 data = data.fillna(data.mean())
# 限制行数 if len(data) > self.max_rows: data = data.head(self.max_rows)
return data
def analyze(self, data: pd.DataFrame) -> Dict[str, Any]: """统计分析""" stats = { 'count': len(data), 'mean': data.mean().to_dict(), 'std': data.std().to_dict(), 'min': data.min().to_dict(), 'max': data.max().to_dict(), 'median': data.median().to_dict() } return stats
def visualize(self, data: pd.DataFrame) -> List[str]: """数据可视化""" charts = [] # 生成图表 fig, ax = plt.subplots(figsize=(10, 6)) data.plot(kind='bar', ax=ax) plt.savefig('chart.png') charts.append('chart.png') return charts
def generate_report(self, stats: Dict[str, Any], charts: List[str]) -> str: """生成报告""" report = f"# 数据分析报告\n\n" report += f"## 统计摘要\n\n" report += f"- 数据量:{stats['count']}\n" report += f"- 平均值:{stats['mean']}\n" report += f"- 标准差:{stats['std']}\n" report += f"\n## 图表\n\n" for chart in charts: report += f"\n\n" return reportconfig.yaml 文件
配置示例:
PRTCL // YAML
name: "data-analysis"version: "2.1.0"author: "Data Team"
# 功能配置features: data_loading: true data_cleaning: true statistical_analysis: true data_visualization: true report_generation: true
# 性能配置performance: max_rows: 1000 max_file_size: 104857600 # 100MB cache_enabled: true cache_ttl: 3600
# 输出配置output: format: "markdown" include_charts: true include_stats: true
# 权限配置permissions: read: true write: true network: false创建自定义技能
创建技能目录
步骤:
PRTCL // BASH
# 创建技能目录mkdir -p ~/.copaw/workspace/skills/customized/my-skill
# 进入技能目录cd ~/.copaw/workspace/skills/customized/my-skill创建 SKILL.md
示例:
PRTCL // MARKDOWN
# 我的自定义技能
## 描述这是一个示例自定义技能,用于演示如何创建 CoPaw 技能。
## 版本1.0.0
## 作者Your Name
## 依赖- requests >= 2.25.0
## 配置```yamlapi_url: "https://api.example.com"timeout: 30使用方法
PRTCL // PLAINTEXT
用户:执行我的技能CoPaw:[调用我的技能] 执行完成PRTCL // PLAINTEXT
### 创建 main.py
** 示例 **:```python# main.pyimport requestsfrom typing import Dict, Anyfrom copaw.skills import Skill
class MySkill(Skill): """我的自定义技能"""
def __init__(self, config: Dict[str, Any]): super().__init__(config) self.api_url = config.get('api_url', 'https://api.example.com') self.timeout = config.get('timeout', 30)
def execute(self, input_data: Dict[str, Any]) -> Dict[str, Any]: """执行技能""" try: # 调用 API response = requests.get( self.api_url, params=input_data, timeout=self.timeout )
# 处理响应 result = response.json()
return { 'success': True, 'result': result } except Exception as e: return { 'success': False, 'error': str(e) }创建 config.yaml
示例:
PRTCL // YAML
name: "my-skill"version: "1.0.0"author: "Your Name"
# API 配置api: url: "https://api.example.com" timeout: 30 retry: 3
# 功能配置features: feature1: true feature2: false安装和测试技能
安装技能:
PRTCL // BASH
# 安装技能copaw skills install ~/.copaw/workspace/skills/customized/my-skill
# 激活技能copaw skills activate my-skill测试技能:
PRTCL // BASH
# 测试技能copaw skills test my-skill
# 测试技能功能echo '{"param1": "value1"}' | copaw skills run my-skill技能开发最佳实践
技能设计原则
单一职责:
- 每个技能只做一件事
- 保持简单和专注
- 便于维护和测试
可组合性:
- 技能可以组合使用
- 提供清晰的接口
- 支持管道操作
可扩展性:
- 易于添加新功能
- 支持配置扩展
- 预留扩展点
错误处理
基础错误处理:
PRTCL // PYTHON
def execute(self, input_data: Dict[str, Any]) -> Dict[str, Any]: """执行技能""" try: result = self.process(input_data) return { 'success': True, 'result': result } except Exception as e: return { 'success': False, 'error': str(e), 'error_type': type(e).__name__ }高级错误处理:
PRTCL // PYTHON
import loggingfrom typing import Dict, Any
class MySkill(Skill): """我的自定义技能"""
def __init__(self, config: Dict[str, Any]): super().__init__(config) self.logger = logging.getLogger(__name__)
def execute(self, input_data: Dict[str, Any]) -> Dict[str, Any]: """执行技能""" try: # 验证输入 self.validate_input(input_data)
# 处理数据 result = self.process(input_data)
# 验证输出 self.validate_output(result)
return { 'success': True, 'result': result } except ValueError as e: self.logger.error(f"验证错误: {e}") return { 'success': False, 'error': str(e), 'error_type': 'ValidationError' } except RuntimeError as e: self.logger.error(f"运行时错误: {e}") return { 'success': False, 'error': str(e), 'error_type': 'RuntimeError' } except Exception as e: self.logger.error(f"未知错误: {e}") return { 'success': False, 'error': str(e), 'error_type': 'UnknownError' }
def validate_input(self, input_data: Dict[str, Any]) -> None: """验证输入""" if not isinstance(input_data, dict): raise ValueError("输入必须是字典") # 更多验证逻辑
def validate_output(self, output: Any) -> None: """验证输出""" if output is None: raise ValueError("输出不能为空") # 更多验证逻辑性能优化
缓存机制:
PRTCL // PYTHON
from functools import lru_cacheimport hashlibimport json
class MySkill(Skill): """我的自定义技能"""
def __init__(self, config: Dict[str, Any]): super().__init__(config) self.cache_enabled = config.get('cache_enabled', True) self.cache_ttl = config.get('cache_ttl', 3600) self.cache = {}
def execute(self, input_data: Dict[str, Any]) -> Dict[str, Any]: """执行技能""" # 生成缓存键 cache_key = self.generate_cache_key(input_data)
# 检查缓存 if self.cache_enabled and cache_key in self.cache: cached_result, cached_time = self.cache[cache_key] if time.time() - cached_time < self.cache_ttl: return cached_result
# 处理数据 result = self.process(input_data)
# 更新缓存 if self.cache_enabled: self.cache[cache_key] = (result, time.time())
return result
def generate_cache_key(self, input_data: Dict[str, Any]) -> str: """生成缓存键""" data_str = json.dumps(input_data, sort_keys=True) return hashlib.md5(data_str.encode()).hexdigest()批处理:
PRTCL // PYTHON
def process_batch(self, inputs: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """批处理""" results = [] for input_data in inputs: try: result = self.execute(input_data) results.append(result) except Exception as e: results.append({ 'success': False, 'error': str(e) }) return results技能发布和共享
打包技能
创建 setup.py:
PRTCL // PYTHON
from setuptools import setup, find_packages
setup( name="copaw-my-skill", version="1.0.0", packages=find_packages(), install_requires=[ "copaw>=1.0.0", "requests>=2.25.0", ], author="Your Name", description="My CoPaw Skill", python_requires=">=3.10",)打包技能:
PRTCL // BASH
# 构建 distributionpython setup.py sdist bdist_wheel
# 安装本地包pip install dist/copaw_my_skill-1.0.0-py3-none-any.whl发布到 PyPI
注册 PyPI 账户:
- 访问 https://pypi.org/
- 注册账户
- 创建 API Token
发布技能:
PRTCL // BASH
# 安装发布工具pip install twine
# 发布到 PyPItwine upload dist/*
# 或发布到 TestPyPItwine upload --repository testpypi dist/*共享技能
Git 仓库:
PRTCL // BASH
# 创建 Git 仓库git initgit add .git commit -m "Initial commit"
# 推送到 GitHubgit remote add origin https://github.com/yourusername/copaw-my-skill.gitgit push -u origin main通过 URL 安装:
PRTCL // BASH
# 从 Git 仓库安装copaw skills install git+https://github.com/yourusername/copaw-my-skill.git常见问题
Q1: 技能无法加载?
解决方案:
PRTCL // BASH
# 检查技能配置copaw skills validate my-skill
# 查看技能日志copaw logs | grep my-skill
# 重新加载技能copaw skills reload my-skillQ2: 技能执行失败?
解决方案:
PRTCL // BASH
# 查看技能详情copaw skills info my-skill
# 检查技能依赖copaw skills dependencies my-skill
# 测试技能copaw skills test my-skillQ3: 如何调试技能?
解决方案:
PRTCL // PYTHON
# 启用调试日志import logginglogging.basicConfig(level=logging.DEBUG)
# 添加调试信息self.logger.debug(f"输入数据: {input_data}")self.logger.debug(f"处理结果: {result}")资源链接
- CoPaw 技能文档: https://copaw.bot/docs/skills
- 技能示例: https://github.com/modelscope/agentscope/tree/main/skills
- 技能开发指南: https://copaw.bot/docs/skills/development
最后更新: 2026-03-12 作者: EchoHaoRan
R P
Rhine Lab Pioneer Division
Auth_Verified: 2026.04.08
Auth_Verified: 2026.04.08
