codecamp

OpenAI 技能

Agent Skills为智能体提供可复用的任务指令和配套文件。可以配合Responses API的Shell工具使用,也可放入Agents API沙箱。以下上传、挂载和版本管理步骤针对Responses Shell;Agents API从沙箱目录发现技能。

Responses支持本地执行与托管容器执行两种形式。要在自己的机器上运行代码,使用Shell工具的本地执行模式。

什么是技能

技能是包含 SKILL.md 清单的文件目录,清单由front matter和指令组成。它可以把公司风格规范、多步骤流程等知识封装成模块。上传的技能以带版本的包管理,并兼容开放的Agent Skills标准。

SKILL.md 示例:

来源示例1(markdown)

---
name: basic-math
description: 对数字进行加法或乘法。
---

需要快速计算数字之和或乘积时使用本技能。

发现技能时,模型先看到名称和描述。描述应同时说明技能做什么、何时使用。例如“使用备用条款审核并修订供应商协议”比“帮助处理法律工作”提供更多有效上下文。

将主要指令保留在 SKILL.md,按需链接支持文件:

来源示例2(text):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

review-pr/
├── SKILL.md
├── references/
│   └── review-guidelines.md
├── scripts/
│   └── check-changes.sh
└── assets/
    └── review-template.md

references/ 存背景资料,scripts/ 存可重复执行的操作,assets/ 存可复用模板。

创建技能

可用multipart表单上传目录,或上传只包含一个顶层目录的 .zip。

方式1:目录上传(multipart)

提交多个 files[] 部分,每部分包含同一个顶层目录中的文件路径。

来源示例3(bash)

## [中文] 通过multipart文件或ZIP上传技能,保留单顶层目录结构。
curl -X POST 'https://api.openai.com/v1/skills' \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F 'files[]=@./basic_math/SKILL.md;filename=basic_math/SKILL.md;type=text/markdown' \
  -F 'files[]=@./basic_math/calculate.py;filename=basic_math/calculate.py;type=text/plain'

方式2:ZIP上传

压缩顶层目录并上传ZIP。

来源示例4(bash)

## [中文] 通过multipart文件或ZIP上传技能,保留单顶层目录结构。
curl -X POST 'https://api.openai.com/v1/skills' \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F 'files=@./basic_math.zip;type=application/zip'

等待上传版本就绪

新上传版本可能短暂返回404。挂载到容器或Live会话前,用 GET /v1/skills/{skill_id}/versions/{version} 检索。若刚上传成功后立刻检索得到404,可短暂退避重试并设置超时;成功后使用返回的版本字符串构造技能引用。

在托管Shell中使用技能

调用Shell时,通过 tools[].environment.skills 挂载技能。

来源示例5(bash)

程序中的自然语言译释90:

使用技能计算144与377之和,再计算底为9、高为13的三角形面积。

## [中文] 在托管Shell环境挂载skill_reference,并提交加法和三角形面积任务。
curl -L 'https://api.openai.com/v1/responses' \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-6-astra",
    "tools": [
      {
        "type": "shell",
        "environment": {
          "type": "container_auto",
          "skills": [
            { "type": "skill_reference", "skill_id": "<skill_id>" },
            { "type": "skill_reference", "skill_id": "<skill_id>", "version": "2" }
          ]
        }
      }
    ],
    "input": "Use the skills to add 144 and 377, then compute triangle area with base 9 height 13."
  }'

来源示例6(javascript)

本段复用的中文释义:译释90。

// [中文] 在托管Shell环境挂载skill_reference,并提交加法和三角形面积任务。
import OpenAI from "openai";

const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  tools: [
    {
      type: "shell",
      environment: {
        type: "container_auto",
        skills: [
          { type: "skill_reference", skill_id: "<skill_id>" },
          { type: "skill_reference", skill_id: "<skill_id>", version: "2" },
        ],
      },
    },
  ],
  input:
    "Use the skills to add 144 and 377, then compute triangle area with base 9 height 13.",
});

console.log(response.output_text);

来源示例7(python)

本段复用的中文释义:译释90。

## [中文] 在托管Shell环境挂载skill_reference,并提交加法和三角形面积任务。
response = client.responses.create(
    model="gpt-6-astra",
    tools=[
        {
            "type": "shell",
            "environment": {
                "type": "container_auto",
                "skills": [
                    {"type": "skill_reference", "skill_id": "<skill_id>"},
                    {
                        "type": "skill_reference",
                        "skill_id": "<skill_id>",
                        "version": "2",
                    },
                ],
            },
        }
    ],
    input="Use the skills to add 144 and 377, then compute triangle area with base 9 height 13.",
)

print(response.output_text)

来源示例8(go)

本段复用的中文释义:译释90。

// [中文] 在托管Shell环境挂载skill_reference,并提交加法和三角形面积任务。
package main

import (
    "context"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

func main() {
    client := openai.NewClient()
    tool := responses.ToolUnionParam{OfShell: &responses.FunctionShellToolParam{
        Environment: responses.FunctionShellToolEnvironmentUnionParam{OfContainerAuto: &responses.ContainerAutoParam{
            Skills: []responses.ContainerAutoSkillUnionParam{
                {OfSkillReference: &responses.SkillReferenceParam{SkillID: "<skill_id>"}},
                {OfSkillReference: &responses.SkillReferenceParam{SkillID: "<skill_id>", Version: openai.String("2")}},
            },
        }},
    }}
    response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
        Model: "gpt-6-astra",
        Tools: []responses.ToolUnionParam{tool},
        Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the skills to add 144 and 377, then compute triangle area with base 9 height 13.")},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.OutputText())
}

来源示例9(java)

程序中的自然语言译释137:

使用技能计算144加377,再计算底9、高13的三角形面积。

// [中文] 在托管Shell环境挂载skill_reference,并提交加法和三角形面积任务。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.ResponseCreateParams;
import java.util.List;
import java.util.Map;

String skillId = "<skill_id>";

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input(
            "Use the skills to add 144 and 377, then compute a triangle area with base 9 and height 13.")
        .putAdditionalBodyProperty(
            "tools",
            JsonValue.from(
                List.of(
                    Map.of(
                        "type",
                        "shell",
                        "environment",
                        Map.of(
                            "type",
                            "container_auto",
                            "skills",
                            List.of(
                                Map.of("type", "skill_reference", "skill_id", skillId),
                                Map.of(
                                    "type", "skill_reference",
                                    "skill_id", skillId,
                                    "version", "2")))))))
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例10(ruby)

本段复用的中文释义:译释137。

## [中文] 在托管Shell环境挂载skill_reference,并提交加法和三角形面积任务。
require "openai"

client = OpenAI::Client.new
response = client.responses.create(
  model: "gpt-6-astra",
  input: "Use the skills to add 144 and 377, then compute a triangle area with base 9 and height 13.",
  tools: [
    {
      type: :shell,
      environment: {
        type: :container_auto,
        skills: [
          {
            type: :skill_reference,
            skill_id: "<skill_id>"
          },
          {
            type: :skill_reference,
            skill_id: "<skill_id>",
            version: "2"
          }
        ]
      }
    }
  ]
)

puts(response.output_text)

提示词行为

挂载后模型可以自行判断何时使用。需要更明确的行为时,可显式要求“使用 <技能名称> 技能”。

在本地Shell模式中使用技能

本地与托管模式接受的技能挂载格式不同:

  • 托管Shell支持已上传的 skill_reference,包括官方维护技能和显式版本。
  • 本地Shell不支持 skill_reference,应从自己控制的运行时提供本地技能文件路径。

本地执行方式参见Shell。

来源示例11(bash)

程序中的自然语言译释82:

汇总CSV文件并生成Markdown报告。

程序中的自然语言译释91:

使用csv-insights技能,在本地汇总该仓库今天的CSV报告。

程序中的自然语言译释108:

技能描述:汇总CSV文件。技能正文:读取CSV并生成包含总计的Markdown报告。name等技能标识保持不变。

## [中文] 本地模式提供本地技能路径,不使用托管skill_reference挂载。
curl -L 'https://api.openai.com/v1/responses' \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-6-astra",
    "tools": [
      {
        "type": "shell",
        "environment": {
          "type": "local",
          "skills": [
            {
              "name": "csv-insights",
              "description": "Summarize CSV files and produce a markdown report.",
              "path": "<path-to-skill-folder>"
            }
          ]
        }
      }
    ],
    "input": "Use the csv-insights skill and run locally to summarize today\'s CSV reports in this repo."
  }'

来源示例12(javascript)

本段复用的中文释义:译释82、译释91、译释108。

// [中文] 本地模式提供本地技能路径,不使用托管skill_reference挂载。
import OpenAI from "openai";

const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-astra",
  tools: [
    {
      type: "shell",
      environment: {
        type: "local",
        skills: [
          {
            name: "csv-insights",
            description: "Summarize CSV files and produce a markdown report.",
            path: "<path-to-skill-folder>",
          },
        ],
      },
    },
  ],
  input:
    "Use the csv-insights skill and run locally to summarize today's CSV reports in this repo.",
});

console.log(response.output_text);

来源示例13(python)

本段复用的中文释义:译释82、译释91、译释108。

## [中文] 本地模式提供本地技能路径,不使用托管skill_reference挂载。
response = client.responses.create(
    model="gpt-6-astra",
    tools=[
        {
            "type": "shell",
            "environment": {
                "type": "local",
                "skills": [
                    {
                        "name": "csv-insights",
                        "description": "Summarize CSV files and produce a markdown report.",
                        "path": "<path-to-skill-folder>",
                    }
                ],
            },
        }
    ],
    input="Use the csv-insights skill and run locally to summarize today's CSV reports in this repo.",
)

print(response.output_text)

来源示例14(go)

程序中的自然语言译释109:

使用csv-insights技能,在本地汇总/workspace/reports.csv。先阅读技能指令,写出/workspace/report.md,并在最终回答中包含总计。

本段复用的中文释义:译释82、译释108。

// [中文] 本地模式提供本地技能路径,不使用托管skill_reference挂载。
// [中文] 外层程序需准备带技能文件的隔离沙箱。
// 外部程序会准备包含技能文件的隔离沙盒。
client := openai.NewClient()
tool := responses.ToolUnionParam{OfShell: &responses.FunctionShellToolParam{Environment: responses.FunctionShellToolEnvironmentUnionParam{OfLocal: &responses.LocalEnvironmentParam{Skills: []responses.LocalSkillParam{{Name: "csv-insights", Description: "Summarize CSV files and produce a markdown report.", Path: "/workspace/skills/csv-insights"}}}}}}
params := responses.ResponseNewParams{Model: "gpt-6-astra", Tools: []responses.ToolUnionParam{tool}, Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Use the csv-insights skill and run locally to summarize /workspace/reports.csv. Read the skill instructions, write /workspace/report.md, and include the total in your final answer.")}}
for turn := 0; turn <= 8; turn++ {
    response, err := client.Responses.New(ctx, params)
    if err != nil {
        return err
    }
    if response.Status != responses.ResponseStatusCompleted {
        return fmt.Errorf("response ended with status %s", response.Status)
    }
    results := responses.ResponseInputParam{}
    for _, item := range response.Output {
        if item.Type != "shell_call" {
            continue
        }
        if turn == 8 {
            return fmt.Errorf("shell workflow exceeded eight tool turns")
        }
        result, err := executeShellCall(ctx, name, item.AsShellCall())
        if err != nil {
            return err
        }
        results = append(results, result)
    }
    if len(results) == 0 {
        fmt.Println(response.OutputText())
        // [中文] 读取制品,不在容器以外执行生成的代码。
        // 读取生成的文件,避免在容器外执行生成的代码。
        report, err := readReport(ctx, name)
        if err != nil {
            return fmt.Errorf("read generated report: %w", err)
        }
        fmt.Printf("Report:\n%s\n", report)
        return nil
    }
    params.PreviousResponseID = openai.String(response.ID)
    params.Input = responses.ResponseNewParamsInputUnion{OfInputItemList: results}
}
return fmt.Errorf("shell workflow exceeded eight turns")

来源示例15(java)

程序中的自然语言译释138:

使用csv-insights技能汇总今天的CSV报告,具体目录与本地执行要求按本段完整input。

本段复用的中文释义:译释82、译释108。

// [中文] 本地模式提供本地技能路径,不使用托管skill_reference挂载。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.ResponseCreateParams;
import java.util.List;
import java.util.Map;

String skillPath = "<path-to-skill-folder>";

ResponseCreateParams params =
    ResponseCreateParams.builder()
        .model("gpt-6-astra")
        .input("Use the csv-insights skill to summarize today's CSV reports.")
        .putAdditionalBodyProperty(
            "tools",
            JsonValue.from(
                List.of(
                    Map.of(
                        "type",
                        "shell",
                        "environment",
                        Map.of(
                            "type",
                            "local",
                            "skills",
                            List.of(
                                Map.of(
                                    "name", "csv-insights",
                                    "description",
                                        "Summarize CSV files and produce a Markdown report.",
                                    "path", skillPath)))))))
        .build();

client.responses().create(params).output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例16(ruby)

本段复用的中文释义:译释82、译释108、译释138。

## [中文] 本地模式提供本地技能路径,不使用托管skill_reference挂载。
require "openai"

client = OpenAI::Client.new
response = client.responses.create(
  model: "gpt-6-astra",
  input: "Use the csv-insights skill to summarize today's CSV reports.",
  tools: [
    {
      type: :shell,
      environment: {
        type: :local,
        skills: [
          {
            name: "csv-insights",
            description: "Summarize CSV files and produce a Markdown report.",
            path: "<path-to-skill-folder>"
          }
        ]
      }
    }
  ]
)

puts(response.output_text)

Agents API

先把技能目录放到沙箱中,创建会话时在 environment.capability_directories 登记它们的父目录。这些目录称为能力目录,执行框架从中发现技能,不使用托管Shell的 skill_reference 挂载格式。

例如放置合同审核与拉取请求审核技能:

来源示例17(text):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

/workspace/capabilities/
├── legal/
│   └── contract-redline/
│       ├── SKILL.md
│       └── references/
│           └── fallback-clauses.md
└── engineering/
    └── review-pr/
        ├── SKILL.md
        └── references/
            └── review-guidelines.md

创建会话时使用以下环境配置:

来源示例18(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

{
  "environment": {
    "type": "self_hosted",
    "workspace_directory": "/workspace",
    "capability_directories": [
      "/workspace/capabilities/legal",
      "/workspace/capabilities/engineering"
    ]
  }
}

能力目录必须满足:位于沙箱内;路径为绝对路径且彼此唯一;不含 . 或 .. 路径段;会话最多登记32个;目录必须已存在。

沙箱可用后,执行框架在这些目录查找 SKILL.md,将名称和描述加入上下文。模型选择相关技能后,再读取完整指令及支持文件。

会话设置参见智能体配置,执行环境参见连接沙箱。提供给智能体前审核技能及支持文件,并遵守沙箱安全指导。

用户提示词中的技能

对于Responses Shell工具,平台把可用技能的 name、description、path 加入用户提示词上下文。模型据此判断是否调用;选择技能后,通过路径读取 SKILL.md 的完整Markdown指令。

技能属于用户提示词输入,不属于系统提示词,与其他用户指令按相同优先级处理。需要显式控制时仍可要求使用指定技能。

限制与验证

  • SKILL.md 文件名匹配不区分大小写。
  • 一个技能包恰好允许一个 skill.md 或 SKILL.md。
  • front matter按技能规范验证。
  • ZIP上传最大50MB。
  • 每个技能版本最多500个文件。
  • 未压缩文件大小上限25MB。

联网时的安全性

应审查每个用于Responses API的技能。技能可能引入提示注入导致的数据外传等风险;使用前仔细阅读风险与安全。

版本与管理

版本指针

  • 不指定版本时使用 default_version。
  • latest_version 跟踪最新上传版本。
  • skill_reference.version 接受字符串,例如 "2" 或 "latest"。
  • 更新 default_version 时也必须提供字符串。

创建新版本

来源示例19(bash)

## [中文] 分别创建技能新版本或更新默认版本;版本值使用字符串。
curl -X POST 'https://api.openai.com/v1/skills/<skill_id>/versions' \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F 'files=@./geometry.zip;type=application/zip'

设置默认版本

来源示例20(bash)

## [中文] 分别创建技能新版本或更新默认版本;版本值使用字符串。
curl -X POST 'https://api.openai.com/v1/skills/<skill_id>' \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{"default_version": "2"}'

删除规则

不能直接删除默认版本,应先指定另一个默认版本。删除最后一个版本会删除整个技能;删除技能则级联删除全部版本。

官方维护技能

OpenAI维护一组第一方技能,可通过ID引用,例如 openai-spreadsheets。

来源示例21(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

{ "type": "skill_reference", "skill_id": "openai-spreadsheets", "version": "latest" }

内联技能

不想创建托管技能时,可把ZIP包以Base64形式内联放进环境的 skills 数组。

来源示例22(bash)

## [中文] 把ZIP技能包以Base64内联挂载。
INLINE_ZIP=$(base64 -i ./basic_math.zip)

curl -L 'https://api.openai.com/v1/containers' \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "name": "inline-skill-container",
    "skills": [
      {
        "type": "inline",
        "name": "basic_math",
        "description": "Add or multiply numbers.",
        "source": {
          "type": "base64",
          "media_type": "application/zip",
          "data": "'"$INLINE_ZIP"'"
        }
      }
    ]
  }'

风险与安全

审查每个技能,防范提示注入和数据外传。联网使用还应阅读Shell网络风险。

将技能视为具有权限的代码和指令

技能会影响规划、工具使用和命令执行;在开发者验证前,应按潜在不可信输入审查。

不向终端用户暴露开放技能仓库

避免让消费者从开放目录任意浏览、选择或挂载技能。恶意 SKILL.md 可能导致提示注入、规则绕过,未经审查的自动化也可能触发数据外传或破坏性操作。

在开发者层面集成技能

开发者审核并集成后,通过有明确边界的产品流程向终端用户提供:将技能映射到具体用例;限制用户任意选择技能;对写入和高影响操作设置明确批准及规则检查。

敏感操作要求批准

工作流能够执行写入或高影响操作时,执行前应取得明确批准。

验证数据驻留与保留要求

托管技能遵循托管Shell容器生命周期:挂载技能和容器文件在容器活动期间可用,容器过期或删除后丢弃。需要完全在自己管理的基础设施上执行时,使用本地Shell。Agents API沙箱参见生命周期,数据要求参见数据控制。

OpenAI Shell
OpenAI 工具搜索
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

其他能力与进阶指南

Embeddings 接口参考

审计日志接口参考

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }