首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Skill 技能:把领域知识封装为可加载、可执行、可审计的能力单元

Skill 技能:把领域知识封装为可加载、可执行、可审计的能力单元

原创
作者头像
IT大佬 jzit-top
发布于 2026-11-24 14:02:19
发布于 2026-11-24 14:02:19
170
举报

定位:技能不是提示词,是能力包

把 Skill 理解为“一段更长的提示词”,会立刻撞上两个天花板:上下文装不下、技能之间互相干扰。Skill 的真正设计是渐进式披露:启动时只加载元数据(名称+描述),判断相关后才读正文,执行时才调脚本。三层加载,每层只在必要时发生。

专业定位因此是:Skill 是一个自包含能力包,由 SKILL.md(流程与约束)、scripts/(可执行工具)、references/(按需资料)组成,以文件系统为边界,以元数据为触发契约。价值在于把“领域知识、操作步骤、工具实现”打包成可版本管理、可组合、可审计的单元。

三层加载结构

元数据层:name 与 description,常驻上下文,决定是否被激活。写得含糊,整个技能形同虚设。

指令层:SKILL.md 正文,触发后才读入,描述流程、约束、何时用哪个脚本。

资源层:脚本与参考文件,执行或查阅时才加载,不占常驻上下文。

三层分离的意义:挂载几十个技能,常驻上下文只增加几十条描述,而非几十份全文。

三个工程难点

触发精度。 description 必须同时说清“做什么”和“什么时候用”。只写能力不写触发条件,Agent 不知道何时激活;写得太宽,又会误激活干扰其他任务。

文档与脚本一致性。 SKILL.md 写的流程必须与脚本实际行为严格对应。文档说“先校验再写入”、脚本却直接写,事故由此产生。

执行安全。 脚本是 Agent 实际执行的代码,必须限定输入 schema、可访问路径、超时,不能让模型自由拼命令。

代码实现

(1)SKILL.md:元数据与正文分离

代码语言:javascript
复制
---
name: csv-cleaner
description: 清洗CSV中的重复行、空值与格式错误。当用户提供CSV并要求去重、
  补全缺失值或统一日期格式时使用。不适用于Excel或JSON。
---

# CSV 清洗流程
1. 运行 `scripts/validate.py` 校验表头与编码,失败即中止。
2. 运行 `scripts/clean.py`,参数由用户需求决定。
3. 输出报告,标注每类问题处理条数。

## 约束
- 不修改原始文件,只写 `*.clean.csv`。
- 缺失值填充仅允许均值/中位数/前向填充,禁止凭空生成。

(2)技能注册与触发匹配

代码语言:javascript
复制
from dataclasses import dataclass
import re, yaml, os

@dataclass
class SkillMeta:
    name: str; description: str; path: str

def parse_skill(skill_md: str) -> SkillMeta:
    m = re.match(r"^---\n(.*?)\n---", open(skill_md).read(), re.S)
    meta = yaml.safe_load(m.group(1))
    return SkillMeta(meta["name"], meta["description"],
                     skill_md.rsplit("/", 1)[0])

def match_skills(task: str, skills: list, top_k=2) -> list:
    """名称命中 > 描述关键词命中,避免全量加载正文"""
    scored = []
    for s in skills:
        score = 3 if s.name.replace("-", " ") in task.lower() else 0
        score += min(sum(1 for w in s.description.split() if w in task), 3)
        if score > 0:
            scored.append((score, s))
    return [s for _, s in sorted(scored, key=lambda x: -x[0])[:top_k]]

(3)渐进式加载:正文按需读入

代码语言:javascript
复制
def load_skill_body(meta: SkillMeta, budget=4000) -> str:
    body = open(f"{meta.path}/SKILL.md").read().split("---", 2)[-1].strip()
    return body[:budget] + ("\n[已截断,按需读取references/]"
                            if len(body) > budget else "")

def build_context(task: str, skills: list) -> str:
    triggered = match_skills(task, skills)
    if not triggered:
        return ""                       # 无匹配不占上下文
    parts = []
    for s in triggered:
        parts.append(f"## 技能 {s.name}\n{load_skill_body(s)}")
        d = f"{s.path}/scripts"
        parts.append(f"可用脚本: {[f for f in os.listdir(d) if f.endswith('.py')]}"
                     if os.path.isdir(d) else "无脚本")
    return "\n".join(parts)

(4)脚本执行沙箱:schema、路径、超时三重约束

代码语言:javascript
复制
import subprocess, tempfile
from pydantic import BaseModel, Field

class ScriptInput(BaseModel):
    input_file: str = Field(pattern=r"^[\w\-./]+\.csv$")
    dedup: bool = True; fill: bool = False

ALLOWED = {"validate.py", "clean.py"}

def run_skill_script(skill_path: str, script: str,
                     args: ScriptInput, timeout=30) -> dict:
    if script not in ALLOWED:
        return {"error": f"未授权脚本: {script}"}
    sp = os.path.join(skill_path, "scripts", script)
    if not os.path.realpath(sp).startswith(os.path.realpath(skill_path)):
        return {"error": "路径越界"}                  # 防目录穿越
    cmd = ["python", sp, "--input", args.input_file]
    if args.dedup: cmd.append("--dedup")
    if args.fill:  cmd.append("--fill")
    with tempfile.TemporaryDirectory() as tmp:
        try:
            r = subprocess.run(cmd, cwd=tmp, capture_output=True,
                               text=True, timeout=timeout)
        except subprocess.TimeoutExpired:
            return {"error": f"超时{timeout}s"}
    return {"rc": r.returncode, "out": r.stdout[-2000:], "err": r.stderr[-500:]}

(5)一致性校验:文档与脚本必须对得上

代码语言:javascript
复制
def check_consistency(skill_path: str) -> list:
    doc = open(f"{skill_path}/SKILL.md").read()
    referenced = set(re.findall(r"scripts/(\w+\.py)", doc))
    d = f"{skill_path}/scripts"
    actual = set(os.listdir(d)) if os.path.isdir(d) else set()
    issues = []
    if referenced - actual: issues.append(f"文档引用但不存在: {referenced - actual}")
    if actual - referenced: issues.append(f"存在但文档未提及: {actual - referenced}")
    return issues        # 空列表才允许发布

(6)验收:触发精度与上下文成本

代码语言:javascript
复制
def evaluate_skills(cases: list, skills: list) -> dict:
    hit = fp = ctx = 0
    for c in cases:
        got = {s.name for s in match_skills(c["task"], skills)}
        hit += int(c["expect_skill"] in got)
        fp  += int(bool(got - {c["expect_skill"]}))
        ctx += len(build_context(c["task"], skills))
    n = len(cases)
    return {"trigger_recall": round(hit / n, 3),
            "false_positive": round(fp / n, 3),
            "avg_context_chars": round(ctx / n)}
# 验收:recall>0.9, false_positive<0.1, 上下文不随技能数线性膨胀

验收指标

六项硬指标:触发召回率(>90%)、误触发率(<10%)、平均上下文占用(只加元数据)、文档脚本一致率(不一致=0)、越界拦截率(非法路径/未授权脚本=100%)、超时可控率(100%)。前两项决定技能是否被正确使用,中间两项决定能否规模化挂载,后两项决定敢不敢让 Agent 真执行。

结语

Skill 的工程核心,是用元数据做触发契约、用文件系统做分层加载、用脚本封装真实操作、用一致性校验与沙箱守住执行边界。价值不在“给模型更多知识”,而在把领域能力做成按需加载、可组合、可审计的单元。触发准、文档对得上、执行管得住——三件事做到,Skill 才是能力;做不到,就只是更长的提示词。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

目录
  • 定位:技能不是提示词,是能力包
    • 三层加载结构
    • 三个工程难点
    • 代码实现
    • 验收指标
    • 结语
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档