Skills:自定义开发

开发自己的 Claude 技能

🌐 查看英文原文 | 源码 Notebook


为 Claude 构建自定义技能

学习如何创建、部署和管理自定义技能,以扩展 Claude 的功能,结合您组织的专业知识和工作流程。

目录

  1. 简介 & 设置
  2. 理解自定义技能架构
  3. 示例 1:财务比率计算器
  4. 示例 2:公司品牌指南
  5. 示例 3:财务建模套件
  6. 技能管理与版本控制
  7. 最佳实践与生产技巧
  8. 故障排除

1. 简介 & 设置

什么是自定义技能?

自定义技能是您创建的专门专业知识包,用于教授 Claude 您组织的独特工作流程、领域知识和最佳实践。与 Anthropic 的预构建技能(Excel、PowerPoint、PDF)不同,自定义技能允许您:

  • 编码组织知识 - 捕获团队的具体方法
  • 确保一致性 - 在所有交互中应用相同的标准
  • 自动化复杂工作流程 - 连接多步骤过程
  • 维护知识产权 - 保护专有方法的安全

主要优势

优势 描述
规模化专业知识 将专业知识部署到每个 Claude 交互
版本控制 跟踪更改,如有需要可回滚
可组合性 将多个技能组合用于复杂任务
隐私 您的技能仅限于您的组织

先决条件

在开始之前,请确保您已:

环境设置

让我们设置我们的环境并导入必要的库:

  • An Anthropic API key with Skills beta access
  • Python environment with the local SDK installed

环境设置

Let’s set up our environment and import necessary libraries:

import os
import json
import requests
from transformers import pipeline

请注意,以下代码示例假设您已经安装了所有必要的库。

# Initialize the RAG model
model = pipeline("rag", model="google/rag-token-1.3b")

# Define a function to process the prompt
def process_prompt(prompt):
    # Tokenize the prompt
    tokens = model.tokenizer.tokenize(prompt)
    # Encode the tokens
    encoded_prompt = model.tokenizer.encode(prompt, return_tensors="pt")
    # Generate the response
    response = model(encoded_prompt)
    return response

# Example usage
prompt = "What is the capital of France?"
response = process_prompt(prompt)
print(response)

确保您的Python环境中安装了所有必要的库,否则代码将无法运行。 :::```python import os import sys from pathlib import Path from typing import Any

Add parent directory for imports

sys.path.insert(0, str(Path.cwd().parent))

from anthropic import Anthropic from anthropic.lib import files_from_dir from dotenv import load_dotenv

Import our utilities

from file_utils import ( download_all_files, extract_file_ids, print_download_summary, )

We’ll create skill_utils later in this notebook

from skill_utils import (

create_skill,

list_skills,

delete_skill,

test_skill

)

Load environment variables

load_dotenv(Path.cwd().parent / “.env”)

API_KEY = os.getenv(“ANTHROPIC_API_KEY”) MODEL = os.getenv(“ANTHROPIC_MODEL”, “claude-sonnet-4-6”)

if not API_KEY: raise ValueError( “ANTHROPIC_API_KEY not found. Copy ../.env.example to ../.env and add your API key.” )

Initialize client with Skills beta

client = Anthropic(api_key=API_KEY, default_headers={“anthropic-beta”: “skills-2025-10-02”})

Setup directories

SKILLS_DIR = Path.cwd().parent / “custom_skills” OUTPUT_DIR = Path.cwd().parent / “outputs” OUTPUT_DIR.mkdir(exist_ok=True)

print(“✓ API key loaded”) print(f”✓ Using model: {MODEL}“) print(f”✓ Custom skills directory: {SKILLS_DIR}“) print(f”✓ Output directory: {OUTPUT_DIR}“) print(”📝 Skills beta header configured for skill management”) ```## 2. 理解自定义技能架构 {#architecture}

技能结构

每个自定义技能都遵循以下目录结构:skill_name/ ├── SKILL.md # REQUIRED: Instructions with YAML frontmatter ├── *.md # Optional: Any additional .md files (documentation, guides) ├── scripts/ # Optional: Executable code │ ├── process.py │ └── utils.js └── resources/ # Optional: Templates, data files └── template.xlsx重要: - SKILL.md 是唯一必需的文件 - 其他所有文件都是可选的 - 允许多个 .md 文件 - 您可以在顶级文件夹中包含任意数量的 markdown 文件 - 所有 .md 文件都会被加载 - 不仅限于 SKILL.md 和 REFERENCE.md,还包括您包含的任何 .md 文件 - 按需组织 - 使用多个 .md 文件来构建复杂的文档

📖 阅读我们关于 使用技能为代理装备真实世界能力 的工程博客文章

技能不仅仅是 Markdown

技能可以包含脚本和文件

技能可以捆绑各种文件类型: - Markdown 文件:指令和文档(SKILL.md、REFERENCE.md 等) - 脚本:Python、JavaScript 或其他用于复杂操作的可执行代码 - 模板:可定制的预构建文件(Excel 模板、文档模板) - 资源:支持数据文件、配置或资产

SKILL.md 要求

SKILL.md 文件必须包含:

  1. YAML 前置信息(名称:64 个字符,描述:1024 个字符)
    • name:小写字母数字和连字符(必需)
    • description:对技能功能的简要描述(必需)
  2. 指令(markdown 格式)
    • 清晰的 Claude 指引
    • 使用示例
    • 任何约束或规则
    • 推荐:保持低于 5,000 个 token

其他文档文件

您可以包含多个 markdown 文件以获得更好的组织:

请注意,以上翻译保留了原文的Markdown格式、技术术语、代码引用、变量名、函数名、HTML标签和callout语法,并保持了原文的段落结构和换行。 :::skill_name/ ├── SKILL.md # Main instructions (required) ├── REFERENCE.md # API reference (optional) ├── EXAMPLES.md # Usage examples (optional) ├── TROUBLESHOOTING.md # Common issues (optional) └── CHANGELOG.md # Version history (optional)根目录下的所有 .md 文件在技能加载时都将对 Claude 可用。

打包文件示例

技能中的打包文件

此示例展示了技能如何打包多个文件: - SKILL.md:包含带有颜色、字体和部分的主体指令 - slide-decks.md:特定用例的附加文档 - 脚本和资源:可以在技能执行期间引用和使用

渐进式披露

技能分三个阶段加载以优化token使用:

阶段 内容 Token 成本 加载时
1. 元数据 名称 & 描述 name: 64 个字符,description: 1024 个字符 总是可见
2. 指令 所有 .md 文件 建议使用 <5,000 个token 相关时
3. 资源 脚本 & 文件 需要时 执行期间

API 工作流程```python

1. Create skill

skill = client.beta.skills.create( display_title=“My Skill”, files=files_from_dir(“path/to/skill”) )

2. Use in messages

response = client.beta.messages.create( container={ “skills”: [{ “type”: “custom”, “skill_id”: skill.id, “version”: “latest” }] }, # … rest of message parameters ) ```### 最佳实践

有关技能创建和最佳实践的详细指南,请参阅: - Claude Skills Best Practices - Skills Documentation

创建技能实用函数

让我们为技能管理创建辅助函数:```python def create_skill(client: Anthropic, skill_path: str, display_title: str) -> dict[str, Any]: ““” Create a new custom skill from a directory.

Args:
    client: Anthropic client instance
    skill_path: Path to skill directory
    display_title: Human-readable skill name

Returns:
    Dictionary with skill_id, version, and metadata
"""
try:
    # Create skill using files_from_dir
    skill = client.beta.skills.create(
        display_title=display_title, files=files_from_dir(skill_path)
    )

    return {
        "success": True,
        "skill_id": skill.id,
        "display_title": skill.display_title,
        "latest_version": skill.latest_version,
        "created_at": skill.created_at,
        "source": skill.source,
    }
except Exception as e:
    return {"success": False, "error": str(e)}

def list_custom_skills(client: Anthropic) -> list[dict[str, Any]]: ““” List all custom skills in the workspace.

Returns:
    List of skill dictionaries
"""
try:
    skills_response = client.beta.skills.list(source="custom")

    skills = []
    for skill in skills_response.data:
        skills.append(
            {
                "skill_id": skill.id,
                "display_title": skill.display_title,
                "latest_version": skill.latest_version,
                "created_at": skill.created_at,
                "updated_at": skill.updated_at,
            }
        )

    return skills
except Exception as e:
    print(f"Error listing skills: {e}")
    return []

def delete_skill(client: Anthropic, skill_id: str) -> bool: ““” Delete a custom skill and all its versions.

Args:
    client: Anthropic client
    skill_id: ID of skill to delete

Returns:
    True if successful, False otherwise
"""
try:
    # First delete all versions
    versions = client.beta.skills.versions.list(skill_id=skill_id)

    for version in versions.data:
        client.beta.skills.versions.delete(skill_id=skill_id, version=version.version)

    # Then delete the skill itself
    client.beta.skills.delete(skill_id)
    return True

except Exception as e:
    print(f"Error deleting skill: {e}")
    return False

def test_skill( client: Anthropic, skill_id: str, test_prompt: str, model: str = “claude-sonnet-4-6”, ) -> Any: ““” Test a custom skill with a prompt.

Args:
    client: Anthropic client
    skill_id: ID of skill to test
    test_prompt: Prompt to test the skill
    model: Model to use for testing

Returns:
    Response from Claude
"""
response = client.beta.messages.create(
    model=model,
    max_tokens=4096,
    container={"skills": [{"type": "custom", "skill_id": skill_id, "version": "latest"}]},
    tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
    messages=[{"role": "user", "content": test_prompt}],
    betas=[
        "code-execution-2025-08-25",
        "files-api-2025-04-14",
        "skills-2025-10-02",
    ],
)

return response

print(“✓ Skill utility functions defined”) print(” - create_skill()“) print(” - list_custom_skills()“) print(” - delete_skill()“) print(” - test_skill()“) ```### 检查现有自定义技能

让我们看看您的工区内是否已存在自定义技能:

⚠️ 重要:开始前请清理现有技能

如果您正在重新运行此笔记本,您可能有一个之前的会话中的技能。技能不能有重复的显示标题,因此您有三个选择:

  1. 删除现有技能(推荐用于测试)- 从头开始
  2. 使用不同的显示标题 - 在名称中添加时间戳或版本号
  3. 更新现有技能为新版本 - 请参阅技能管理与版本控制部分

让我们检查并可选地清理现有技能:```python # Check for existing skills that might conflict existing_skills = list_custom_skills(client) skill_titles_to_create = [ “Financial Ratio Analyzer”, “Corporate Brand Guidelines”, “Financial Modeling Suite”,] conflicting_skills = []

if existing_skills: print(f”Found {len(existing_skills)} existing custom skill(s):“) for skill in existing_skills: print(f” - {skill[‘display_title’]} (ID: {skill[‘skill_id’]})“) if skill[“display_title”] in skill_titles_to_create: conflicting_skills.append(skill)

if conflicting_skills:
    print(
        f"\n⚠️ Found {len(conflicting_skills)} skill(s) that will conflict with this notebook:"
    )
    for skill in conflicting_skills:
        print(f"  - {skill['display_title']} (ID: {skill['skill_id']})")

    print("\n" + "=" * 70)
    print("To clean up these skills and start fresh, uncomment and run:")
    print("=" * 70)
    print("\n# UNCOMMENT THE LINES BELOW TO DELETE CONFLICTING SKILLS:")
    print("# for skill in conflicting_skills:")
    print("#     if delete_skill(client, skill['skill_id']):")
    print("#         print(f\"✅ Deleted: {skill['display_title']}\")")
    print("#     else:")
    print("#         print(f\"❌ Failed to delete: {skill['display_title']}\")")

    # for skill in conflicting_skills:
    #     if delete_skill(client, skill['skill_id']):
    #         print(f"✅ Deleted: {skill['display_title']}")
    #     else:
    #         print(f"❌ Failed to delete: {skill['display_title']}")
else:
    print("\n✅ No conflicting skills found. Ready to proceed!")

else: print(“✅ No existing custom skills found. Ready to create new ones!”) ```## 3. 示例 1:财务比率计算器 {#financial-ratio}

让我们创建我们的第一个自定义技能——一个可以分析公司财务状况的财务比率计算器。

技能概述

财务比率计算器技能将: - 计算关键财务比率(ROE、市盈率、流动比率等) - 结合行业背景解释比率 - 生成格式化报告 - 与各种数据格式(CSV、JSON、文本)协同工作

上传财务分析器技能

现在让我们将我们的财务分析器技能上传到Claude:```python # Upload the Financial Analyzer skill financial_skill_path = SKILLS_DIR / “analyzing-financial-statements”

if financial_skill_path.exists(): print(“Uploading Financial Analyzer skill…”) result = create_skill(client, str(financial_skill_path), “Financial Ratio Analyzer”)

if result["success"]:
    financial_skill_id = result["skill_id"]
    print("✅ Skill uploaded successfully!")
    print(f"   Skill ID: {financial_skill_id}")
    print(f"   Version: {result['latest_version']}")
    print(f"   Created: {result['created_at']}")
else:
    print(f"❌ Upload failed: {result['error']}")
    if "cannot reuse an existing display_title" in str(result["error"]):
        print("\n💡 Solution: A skill with this name already exists.")
        print("   Run the 'Clean Up Existing Skills' cell above to delete it first,")
        print("   or change the display_title to something unique.")

else: print(f”⚠️ Skill directory not found: {financial_skill_path}“) print(”Please ensure the custom_skills directory contains the analyzing-financial-statements folder.” ) ```### 测试财务分析技能

让我们使用示例财务数据来测试这个技能:```python # Test the Financial Analyzer skill if “financial_skill_id” in locals(): test_prompt = ““” Calculate financial ratios for this company:

Income Statement:
- Revenue: $1,000M
- EBITDA: $200M
- Net Income: $120M

Balance Sheet:
- Total Assets: $2,000M
- Current Assets: $500M
- Current Liabilities: $300M
- Total Debt: $400M
- Shareholders Equity: $1,200M

Market Data:
- Share Price: $50
- Shares Outstanding: 100M

Please calculate key ratios and provide analysis.
"""

print("Testing Financial Analyzer skill...")
response = test_skill(client, financial_skill_id, test_prompt)

# Print response
for content in response.content:
    if content.type == "text":
        print(content.text)

else: print(“⚠️ Please upload the Financial Analyzer skill first (run the previous cell)”) ```## 4. 示例 2:公司品牌指南 {#brand-guidelines}

现在让我们创建一个技能,以确保所有文档都遵循公司品牌标准。

技能概述

Brand Guidelines 技能将: - 应用一致的色彩、字体和布局 - 确保标志的位置和使用 - 保持专业语气和信息 - 在所有文档类型(Excel、PowerPoint、PDF)中工作```python # Upload the Brand Guidelines skill brand_skill_path = SKILLS_DIR / “applying-brand-guidelines”

if brand_skill_path.exists(): print(“Uploading Brand Guidelines skill…”) result = create_skill(client, str(brand_skill_path), “Corporate Brand Guidelines”)

if result["success"]:
    brand_skill_id = result["skill_id"]
    print("✅ Skill uploaded successfully!")
    print(f"   Skill ID: {brand_skill_id}")
    print(f"   Version: {result['latest_version']}")
else:
    print(f"❌ Upload failed: {result['error']}")
    if "cannot reuse an existing display_title" in str(result["error"]):
        print("\n💡 Solution: A skill with this name already exists.")
        print("   Run the 'Clean Up Existing Skills' cell above to delete it first,")
        print("   or change the display_title to something unique.")

else: print(f”⚠️ Skill directory not found: {brand_skill_path}“) ```### 使用文档创建测试品牌指南

让我们通过创建一个品牌化的PowerPoint演示文稿来测试品牌技能:```python # Test Brand Guidelines skill with PowerPoint creation if “brand_skill_id” in locals(): # Combine brand skill with Anthropic’s pptx skill response = client.beta.messages.create( model=MODEL, max_tokens=4096, container={ “skills”: [ {“type”: “custom”, “skill_id”: brand_skill_id, “version”: “latest”}, {“type”: “anthropic”, “skill_id”: “pptx”, “version”: “latest”}, ] }, tools=[{“type”: “code_execution_20250825”, “name”: “code_execution”}], messages=[ { “role”: “user”, “content”: “““Create a 3-slide PowerPoint presentation following Acme Corporation brand guidelines:

        Slide 1: Title slide for "Q4 2025 Results"
        Slide 2: Revenue Overview with a chart showing Q1-Q4 growth
        Slide 3: Key Achievements (3 bullet points)

        Apply all brand colors, fonts, and formatting standards.
        """,
        }
    ],
    betas=[
        "code-execution-2025-08-25",
        "files-api-2025-04-14",
        "skills-2025-10-02",
    ],
)

print("Response from Claude:")
for content in response.content:
    if content.type == "text":
        print(content.text[:500] + "..." if len(content.text) > 500 else content.text)

# Download generated file
file_ids = extract_file_ids(response)
if file_ids:
    results = download_all_files(
        client, response, output_dir=str(OUTPUT_DIR), prefix="branded_"
    )
    print_download_summary(results)

else: print(“⚠️ Please upload the Brand Guidelines skill first”) ```## 5. 示例 3:财务建模套件 {#financial-modeling}

让我们创建我们最先进的技能——一个全面的财务建模套件,用于估值和风险评估。

技能概述

财务建模套件技能提供以下功能: - DCF 估值:完整的折现现金流模型 - 敏感性分析:测试变量对估值的影响 - 蒙特卡洛模拟:使用概率分布的风险建模 - 情景规划:最佳/基准/最坏情况分析

这展示了具有复杂计算和专业级财务建模的多文件技能。

上传财务建模套件

首先,上传财务建模技能:```python # Upload the Financial Modeling Suite skill modeling_skill_path = SKILLS_DIR / “creating-financial-models”

if modeling_skill_path.exists(): print(“Uploading Financial Modeling Suite skill…”) result = create_skill(client, str(modeling_skill_path), “Financial Modeling Suite”)

if result["success"]:
    modeling_skill_id = result["skill_id"]
    print("✅ Skill uploaded successfully!")
    print(f"   Skill ID: {modeling_skill_id}")
    print(f"   Version: {result['latest_version']}")
    print("\nThis skill includes:")
    print("   - DCF valuation model (dcf_model.py)")
    print("   - Sensitivity analysis framework (sensitivity_analysis.py)")
    print("   - Monte Carlo simulation capabilities")
    print("   - Scenario planning tools")
else:
    print(f"❌ Upload failed: {result['error']}")

else: print(f”⚠️ Skill directory not found: {modeling_skill_path}“) print(”Please ensure the custom_skills directory contains the creating-financial-models folder.” ) ```### 测试财务建模套件

让我们通过一个DCF估值请求来测试高级建模功能:```python # Test the Financial Modeling Suite with a DCF valuation if “modeling_skill_id” in locals(): dcf_test_prompt = ““” Perform a DCF valuation for TechCorp with the following data:

Historical Financials (Last 3 Years):
- Revenue: $500M, $600M, $750M
- EBITDA Margin: 25%, 27%, 30%
- CapEx: $50M, $55M, $60M
- Working Capital: 15% of revenue

Projections:
- Revenue growth: 20% for years 1-3, then declining to 5% by year 5
- EBITDA margin expanding to 35% by year 5
- Terminal growth rate: 3%

Market Assumptions:
- WACC: 10%
- Tax rate: 25%
- Current net debt: $200M
- Shares outstanding: 100M

Please create a complete DCF model with sensitivity analysis on WACC and terminal growth.
Generate an Excel file with the full model including:
1. Revenue projections
2. Free cash flow calculations
3. Terminal value
4. Enterprise value to equity value bridge
5. Sensitivity table
"""

print("Testing Financial Modeling Suite with DCF valuation...")
print("=" * 70)
print("\n⏱️ Note: Complex financial model generation may take 1-2 minutes.\n")

response = client.beta.messages.create(
    model=MODEL,
    max_tokens=4096,
    container={
        "skills": [
            {"type": "custom", "skill_id": modeling_skill_id, "version": "latest"},
            {"type": "anthropic", "skill_id": "xlsx", "version": "latest"},
        ]
    },
    tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
    messages=[{"role": "user", "content": dcf_test_prompt}],
    betas=[
        "code-execution-2025-08-25",
        "files-api-2025-04-14",
        "skills-2025-10-02",
    ],
)

# Print Claude's response
for content in response.content:
    if content.type == "text":
        # Print first 800 characters to keep output manageable
        text = content.text
        if len(text) > 800:
            print(text[:800] + "\n\n[... Output truncated for brevity ...]")
        else:
            print(text)

# Download the DCF model if generated
file_ids = extract_file_ids(response)
if file_ids:
    print("\n" + "=" * 70)
    print("Downloading generated DCF model...")
    results = download_all_files(
        client, response, output_dir=str(OUTPUT_DIR), prefix="dcf_model_"
    )
    print_download_summary(results)
    print("\n💡 Open the Excel file to explore the complete DCF valuation model!")

else: print(“⚠️ Please upload the Financial Modeling Suite skill first (run the previous cell)”) ```## 6. 技能管理与版本控制 {#management}

对技能进行时间管理需要理解版本控制、更新和生命周期管理。

列出您的技能

了解您工作空间中所有自定义技能的概览:```python # List all your custom skills my_skills = list_custom_skills(client)

if my_skills: print(f”You have {len(my_skills)} custom skill(s):“) print(”=” * 70) for i, skill in enumerate(my_skills, 1): print(f”. {skill[‘display_title’]}“) print(f” Skill ID: {skill[‘skill_id’]}“) print(f” Current Version: {skill[‘latest_version’]}“) print(f” Created: {skill[‘created_at’]}“) if skill.get(”updated_at”): print(f” Last Updated: {skill[‘updated_at’]}“) print(”” + “=” * 70) else: print(“No custom skills found in your workspace.”) ```### 创建新版本

技能支持版本控制以维护历史记录并启用回滚。让我们增强我们的财务分析器技能并创建一个新版本。

第1步:增强财务分析器

我们将添加医疗行业基准,使我们的技能更加通用。这是一个现实场景,您会根据用户需求扩展技能的功能。

  • healthcare industry:医疗行业
  • versatile:通用的
  • real-world scenario:现实场景
  • expand a skill’s capabilities:扩展技能的功能```python # Add healthcare industry benchmarks to the Financial Analyzer # This demonstrates a realistic skill enhancement scenario

if “financial_skill_id” in locals(): # Read the current interpret_ratios.py file interpret_file_path = SKILLS_DIR / “analyzing-financial-statements” / “interpret_ratios.py”

with open(interpret_file_path) as f:
    content = f.read()

# Add healthcare benchmarks after the 'manufacturing' section
healthcare_benchmarks = """        },
    'healthcare': {
        'current_ratio': {'excellent': 2.3, 'good': 1.8, 'acceptable': 1.4, 'poor': 1.0},
        'debt_to_equity': {'excellent': 0.3, 'good': 0.6, 'acceptable': 1.0, 'poor': 1.8},
        'roe': {'excellent': 0.22, 'good': 0.16, 'acceptable': 0.11, 'poor': 0.07},
        'gross_margin': {'excellent': 0.65, 'good': 0.45, 'acceptable': 0.30, 'poor': 0.20},
        'pe_ratio': {'undervalued': 18, 'fair': 28, 'growth': 40, 'expensive': 55}
    """

# Find the position after manufacturing section and before the closing brace
insert_pos = content.find("        }\n    }")  # Find the end of the BENCHMARKS dict

if insert_pos != -1:
    # Insert the healthcare benchmarks
    new_content = content[:insert_pos] + healthcare_benchmarks + content[insert_pos:]

    # Save the enhanced file
    with open(interpret_file_path, "w") as f:
        f.write(new_content)

    print("✅ Enhanced Financial Analyzer with healthcare industry benchmarks")
    print("\nChanges made:")
    print("  - Added healthcare industry to BENCHMARKS")
    print("  - Includes specific thresholds for:")
    print("    • Current ratio (liquidity)")
    print("    • Debt-to-equity (leverage)")
    print("    • ROE (profitability)")
    print("    • Gross margin")
    print("    • P/E ratio (valuation)")
    print("\n📝 Now we can create a new version of the skill with this enhancement!")
else:
    print("⚠️ Could not find the correct position to insert healthcare benchmarks")
    print("The file structure may have changed.")

else: print(“⚠️ Please upload the Financial Analyzer skill first (run cells in Section 3)”) ```#### 第2步:创建新版本

现在我们已经提升了我们的技能,让我们创建一个新版本来追踪这个变化:

```markdown Now that we’ve enhanced our skill, let’s create a new version to track this change: ``````python # Create a new version of the enhanced Financial Analyzer skill def create_skill_version(client: Anthropic, skill_id: str, skill_path: str): “““Create a new version of an existing skill.”“” try: version = client.beta.skills.versions.create( skill_id=skill_id, files=files_from_dir(skill_path) ) return { “success”: True, “version”: version.version, “created_at”: version.created_at, } except Exception as e: return {“success”: False, “error”: str(e)}

Create the new version with our healthcare enhancement

if “financial_skill_id” in locals(): print(“Creating new version of Financial Analyzer with healthcare benchmarks…”)

result = create_skill_version(
    client, financial_skill_id, str(SKILLS_DIR / "analyzing-financial-statements")
)

if result["success"]:
    print("✅ New version created successfully!")
    print(f"   Version: {result['version']}")
    print(f"   Created: {result['created_at']}")
    print("\n📊 Version History:")
    print("   v1: Original skill with tech, retail, financial, manufacturing")
    print(f"   v{result['version']}: Enhanced with healthcare industry benchmarks")
else:
    print(f"❌ Version creation failed: {result['error']}")

else: print(“⚠️ Please run the previous cells to upload the skill and make enhancements first”) ```#### 第3步:测试新版本

让我们通过分析一家医疗保健公司来验证我们的增强功能是否有效:```python # Test the enhanced skill with healthcare industry data if “financial_skill_id” in locals(): healthcare_test_prompt = ““” Analyze this healthcare company using the healthcare industry benchmarks:

Company: MedTech Solutions (Healthcare Industry)

Income Statement:
- Revenue: $800M
- EBITDA: $320M
- Net Income: $160M

Balance Sheet:
- Total Assets: $1,200M
- Current Assets: $400M
- Current Liabilities: $200M
- Total Debt: $300M
- Shareholders Equity: $700M

Market Data:
- Share Price: $75
- Shares Outstanding: 50M

Please calculate key ratios and provide healthcare-specific analysis.
"""

print("Testing enhanced Financial Analyzer with healthcare company...")
print("=" * 70)

response = test_skill(client, financial_skill_id, healthcare_test_prompt, MODEL)

# Print Claude's analysis
for content in response.content:
    if content.type == "text":
        # Print first 1000 characters to keep output manageable
        text = content.text
        if len(text) > 1000:
            print(text[:1000] + "\n\n[... Output truncated for brevity ...]")
        else:
            print(text)

print(
    "\n✅ The skill now recognizes 'healthcare' as an industry and applies specific benchmarks!"
)

else: print(“⚠️ Please run the previous cells to create the enhanced version first”) ```### 清理:管理您的技能

当您完成测试或需要清理工作区时,您可以有选择地删除技能。让我们回顾一下我们创建的内容,并提供清理选项:

When you’re done testing or need to clean up your workspace, you can selectively remove skills. Let’s review what we’ve created and provide options for cleanup:

  • Args: client: Anthropic client dry_run: If True, only show what would be deleted without actually deleting ““” # Get all current skills all_skills = list_custom_skills(client)

    # Skills we created in this notebook notebook_skill_names = [ “Financial Ratio Analyzer”, “Corporate Brand Guidelines”, “Financial Modeling Suite”, ]

    # Track skills created by this notebook notebook_skills = [] other_skills = []

    for skill in all_skills: if skill[“display_title”] in notebook_skill_names: notebook_skills.append(skill) else: other_skills.append(skill)

    print(“=” * 70) print(“SKILL INVENTORY REPORT”) print(“=” * 70)

    print(f”custom skills in workspace: {len(all_skills)}“)

    if notebook_skills: print(f”📚 Skills created by this notebook ({len(notebook_skills)}):“) for skill in notebook_skills: print(f” • {skill[‘display_title’]}“) print(f” ID: {skill[‘skill_id’]}“) print(f” Version: {skill[‘latest_version’]}“) print(f” Created: {skill[‘created_at’]}“) else: print(”✅ No skills from this notebook found”)

    if other_skills: print(f”🔧 Other skills in workspace ({len(other_skills)}):“) for skill in other_skills: print(f” • {skill[‘display_title’]} (v{skill[‘latest_version’]})“)

    # Cleanup options if notebook_skills: print(“” + “=” * 70) print(“CLEANUP OPTIONS”) print(“=” * 70)

      if dry_run:
          print("\n🔍 DRY RUN MODE - No skills will be deleted")
          print("\nTo delete the notebook skills, uncomment and run:")
          print("-" * 40)
          print("# review_and_cleanup_skills(client, dry_run=False)")
          print("-" * 40)
    
          print("\nThis would delete:")
          for skill in notebook_skills:
              print(f"   • {skill['display_title']}")
      else:
          print("\n⚠️ DELETION MODE - Skills will be permanently removed")
          print("\nDeleting notebook skills...")
    
          success_count = 0
          for skill in notebook_skills:
              if delete_skill(client, skill["skill_id"]):
                  print(f"   ✅ Deleted: {skill['display_title']}")
                  success_count += 1
              else:
                  print(f"   ❌ Failed to delete: {skill['display_title']}")
    
          print(f"\n📊 Cleanup complete: {success_count}/{len(notebook_skills)} skills deleted")

    return { “total_skills”: len(all_skills), “notebook_skills”: len(notebook_skills), “other_skills”: len(other_skills), “notebook_skill_ids”: [s[“skill_id”] for s in notebook_skills], }

Run the review (in dry-run mode by default)

print(“Reviewing your custom skills workspace…”) cleanup_summary = review_and_cleanup_skills(client, dry_run=True)

Store skill IDs for potential cleanup

if cleanup_summary[“notebook_skill_ids”]: skills_to_cleanup = cleanup_summary[“notebook_skill_ids”] print(f”💡 Tip: {len(skills_to_cleanup)} skill(s) can be cleaned up when you’re done testing”)

UNCOMMENT THE LINE BELOW TO ACTUALLY DELETE THE NOTEBOOK SKILLS:

review_and_cleanup_skills(client, dry_run=False)

```## 7. 最佳实践与生产技巧 {#best-practices}

技能设计原则

  1. 单一职责:每个技能应专注于一个专业领域
  2. 清晰的文档:SKILL.md 应全面而简洁
  3. 错误处理:脚本应优雅地处理边缘情况
  4. 版本控制:使用 Git 跟踪技能变更
  5. 测试:在生产部署前始终测试技能

目录结构最佳实践custom_skills/ ├── financial_analyzer/ # Single purpose, clear naming │ ├── SKILL.md # Under 5,000 tokens │ ├── scripts/ # Modular Python/JS files │ └── tests/ # Unit tests for scripts ├── brand_guidelines/ # Organizational standards │ ├── SKILL.md │ ├── REFERENCE.md # Additional documentation │ └── assets/ # Logos, templates### 性能优化

策略 影响 实现
最小化前置信息 加快技能发现 name: 64 个字符,description: 1024 个字符
懒加载 减少token使用 仅在需要时引用参考文件
技能组合 避免重复 组合技能与mega-skill
缓存 加快响应 重复使用技能容器

安全考虑

  • API密钥:技能中切勿硬编码凭证
  • 数据隐私:不要在技能文件中包含敏感数据
  • 访问控制:技能是特定于工作区的
  • 验证:在脚本中清理输入
  • 审计跟踪:记录技能使用情况以符合规定

下一步

🎉 恭喜! 你已经学会了如何为Claude创建、部署和管理自定义技能。

你学到了什么

  • ✅ 自定义技能架构和需求
  • ✅ 使用SKILL.md和Python脚本创建技能
  • ✅ 通过API上传技能
  • ✅ 结合自定义和Anthropic技能
  • ✅ 生产部署的最佳实践
  • ✅ 解决常见问题的技巧

继续你的旅程

  1. 实验:根据你的用例修改示例技能
  2. 构建:为你的组织工作流程创建技能
  3. 优化:监控token使用和性能
  4. 分享:记录你的技能以供团队协作

资源

尝试的技能想法

  • 📊 数据管道:带有验证的ETL工作流程
  • 📝 文档模板:合同、提案、报告
  • 🔍 代码审查:风格指南和最佳实践
  • 📈 Analytics Dashboard: KPI tracking and visualization
  • 🤖 Automation Suite: Repetitive task workflows

Happy skill building! 🚀


Tip

中文读者提示:本章节的代码和输出为英文原文。如需理解具体实现细节,可参考上方中文导读和代码注释。如有疑问,欢迎在 GitHub Issues 讨论。