详情

首页手游攻略 Codex Skills操作步骤完全指南

Codex Skills操作步骤完全指南

佚名 2026-07-31 12:24:09

Codex Skills操作步骤完全指南需要先看清适用场景和关键步骤,避免只记结论却忽略实际限制。

1. 什么是 Skill

Skill 是一个自包含的文件夹,作用是把 Codex 从通用型 Agent 转变成某个领域的专家。

Codex Skills教程完全指南

Skill 能提供什么

能力说明
专项工作流针对特定领域的多步骤流程
工具集成如何使用特定文件格式或 API 的指令
领域知识公司专有知识、Schema、业务逻辑
捆绑资源可直接运行的脚本、参考文档、模板资产

什么不是 Skill

  1. Skill 不是安装包管理器
  2. Skill 不是 README 或用户文档
  3. Skill 不是 CHANGELOG 或安装指南

Skill 是给另一个 Codex 实例看的上岗培训手册

2. 理解 Skill 的运行原理

这是最重要的概念,理解了这个才能写出好 Skill。

上下文窗口就是公共资源

Codex 的上下文窗口是有限的,它同时要容纳:系统提示词、对话历史、其他 Skill 的元数据、以及用户当前的请求。你的 Skill 在和所有这些东西竞争空间

三级加载机制

Level 1: 元数据(name + description)  → 始终在上下文中(~100 词)Level 2: SKILL.md 正文                → Skill 被触发时才加载(<5k 词)Level 3: Bundled Resources            → 按需加载(无上限,因为脚本可直接执行)

这意味着:

  1. Description 写得好不好,直接决定 Skill 能不能被正确触发
  2. SKILL.md 要尽量精简,超过 500 行就应该拆分到 references/
  3. 脚本是最省 token 的,执行时不需要读进上下文

3. Skill 的文件结构

my-skill/├── SKILL.md              ← 必须:核心指令文件├── agents/│   └── openai.yaml       ← 推荐:UI 展示元数据├── scripts/              ← 可选:可执行脚本│   ├── rotate_pdf.py│   └── extract_text.py├── references/           ← 可选:按需加载的参考文档│   ├── api_docs.md│   └── schema.md└── assets/               ← 可选:输出用的模板/图片/字体    ├── template.pptx    └── logo.png

各目录职责

SKILL.md(必须)

  1. YAML 前置元数据(name + description)→ 决定触发条件
  2. Markdown 正文 → 触发后读取的具体指令

scripts/ — 可执行代码

  1. 适合:需要确定性可靠执行、或每次都在重写同样逻辑的代码
  2. 优势:Token 高效,可以直接执行不需要读进上下文
  3. 例如:PDF 旋转脚本、数据转换脚本

references/ — 参考文档

  1. 适合:Codex 需要查阅但不需要始终加载的详细信息
  2. 例如:API 文档、数据库 Schema、公司政策、领域知识
  3. 最佳实践:超过 1 万词的文件,在 SKILL.md 里加 grep 搜索指引

assets/ — 输出资源

  1. 适合:最终输出里要用的文件,不需要读进上下文
  2. 例如:PPT 模板、logo 图片、字体文件、项目脚手架

什么不该放进 Skill

❌ README.md❌ INSTALLATION_GUIDE.md❌ QUICK_REFERENCE.md❌ CHANGELOG.md❌ 测试说明❌ 用户可见文档

Skill 是给 AI 看的,不是给人看的。

4. 第一个 Skill:手把手入门

4.1 使用 init 脚本创建

# 运行初始化脚本python3 ~/.codex/skills/.system/skill-creator/scripts/init_skill.py   hello-world   --path ~/.codex/skills   --resources scripts,references

这会创建:

~/.codex/skills/hello-world/├── SKILL.md├── agents/│   └── openai.yaml├── scripts/└── references/

4.2 编写 SKILL.md

把生成的模板替换为以下内容:

---name: hello-worlddescription: "Use when user asks to create a hello-world project in any language. Supports Python, JavaScript, Go, and Rust. Handles project setup, basic file structure, and a runnable entry point."---# Hello World Skill## Supported Languages| Language | Entry File | Run Command ||----------|-----------|-------------|| Python   | main.py   | python3 main.py || JavaScript | index.js | node index.js || Go       | main.go   | go run main.go || Rust     | main.rs   | cargo run |## Workflow1. Detect language from user request (default: Python if unspecified).2. Create entry file with print/hello-world logic.3. If Go or Rust, also create go.mod / Cargo.toml.4. Print the run command for the user.## Scripts- `scripts/validate_project.py ` — Checks that the generated project has correct structure.

4.3 创建脚本

# scripts/validate_project.py#!/usr/bin/env python3"""Validate that a hello-world project has the expected structure."""import sysfrom pathlib import PathREQUIRED_FILES = {    "python": ["main.py"],    "javascript": ["index.js"],    "go": ["main.go", "go.mod"],    "rust": ["main.rs", "Cargo.toml"],}def validate(lang: str, project_dir: str) -> bool:    files = REQUIRED_FILES.get(lang)    if not files:        print(f"Unknown language: {lang}")        return False    base = Path(project_dir)    ok = True    for f in files:        if not (base / f).exists():            print(f"Missing: {f}")            ok = False    if ok:        print(f"Project structure OK for {lang}")    return okif __name__ == "__main__":    if len(sys.argv) != 3:        print("Usage: validate_project.py ")        sys.exit(1)    success = validate(sys.argv[1], sys.argv[2])    sys.exit(0 if success else 1)

4.4 验证

python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py   ~/.codex/skills/hello-world

输出 Skill is valid! 就说明结构正确。

5. SKILL.md 编写指南

5.1 Frontmatter(必须)

---name: my-skill-namedescription: "完整描述,告诉 Codex 什么时候该用这个 Skill。"---

规则:

  1. name:全小写 + 连字符,不超过 64 字符,只用 [a-z0-9-]
  2. description:不超过 1024 字符,不能包含 <>
  3. description唯一的触发机制,必须写清楚:做什么 + 什么时候用

Description 范例:

# ❌ 太模糊description: "A skill for working with documents"# ❌ 缺少触发条件description: "Create and edit DOCX files"# ✅ 完整description: "Comprehensive document creation, editing, and analysis with support fortracked changes, comments, formatting preservation, and text extraction. Use whenCodex needs to work with professional documents (.docx files) for: (1) Creating newdocuments, (2) Modifying or editing content, (3) Working with tracked changes,(4) Adding comments, or any other document tasks"

5.2 Body 编写原则

用祈使句

# ❌ 描述式This skill allows you to rotate PDF pages.# ✅ 指令式Rotate PDF pages using the rotation script.

只写 Codex 不知道的东西

# ❌ 废话连篇(Codex 知道 Python 怎么写)## Python BasicsPython is a programming language created by Guido van Rossum...Use `def` to define functions. Use `for` to iterate...# ✅ 只写领域特定知识## Internal SchemaThe `orders` table has a `status` column with values:`pending`, `shipped`, `delivered`, `returned`.Join with `customers` on `customer_id`.

结构清晰,按需组织

根据 Skill 的性质选择合适的结构:

结构类型适用场景示例
工作流型顺序步骤流程PDF 处理:渲染 → 检查 → 输出
任务型多种独立操作PDF Skill:合并 / 拆分 / 提取文本
指南型规范或标准品牌规范:颜色 / 字体 / 间距
能力型一体化多功能系统产品管理:多维度能力

6. Bundled Resources 详解

6.1 scripts/ — 确定性执行

什么时候放脚本:

  1. 同样的代码每次都在重写
  2. 操作容易出错,需要确定性可靠执行
  3. 可以参数化复用的逻辑

脚本的优势:

  1. Token 高效:直接 exec_command 执行,不需要读进上下文
  2. 确定性:不像 LLM 生成的代码可能有变体
  3. 可测试:可以像普通代码一样写测试
# 执行脚本(推荐方式)python3 scripts/rotate_pdf.py input.pdf 90 output.pdf# 或者 bash 脚本bash scripts/deploy.sh staging

6.2 references/ — 按需加载

什么时候放参考文档:

  1. 详细 API 文档
  2. 数据库 Schema
  3. 公司内部政策
  4. 复杂领域知识
  5. 超过 500 行的详细内容

大文件技巧:

## API ReferenceFor detailed endpoint documentation, see `references/api_docs.md`.To find a specific endpoint: `grep -n "endpoint_name" references/api_docs.md`

6.3 assets/ — 输出用资源

什么时候放资产文件:

  1. PPT/Word 模板
  2. Logo、图片
  3. 字体文件
  4. 项目脚手架/模板目录
  5. 不需要读进上下文,直接复制或修改使用的文件
assets/├── template.pptx        ← PowerPoint 模板├── brand-logo.png       ← 公司 logo├── hello-world/         ← 前端项目脚手架│   ├── index.html│   ├── style.css│   └── app.js└── fonts/    └── custom.ttf

7. agents/openai.yaml 元数据

这个文件是给 UI 展示用的,不是给 Codex 逻辑用的。

interface:  display_name: "My Skill Name"         # UI 列表显示名  short_description: "Help with X tasks" # 25-64 字符的简短描述  icon_small: "./assets/small.png"       # 小图标(可选)  icon_large: "./assets/large.svg"       # 大图标(可选)  brand_color: "#3B82F6"                 # UI 强调色(可选)  default_prompt: "Use $my-skill to help with ..." # 默认提示(可选)dependencies:  tools:    - type: "mcp"      value: "github"      description: "GitHub MCP server"      transport: "streamable_http"      url: "https://api.githubcopilot.com/mcp/"policy:  allow_implicit_invocation: true   # false 则只允许 $skill 手动触发

用脚本自动生成

python3 ~/.codex/skills/.system/skill-creator/scripts/generate_openai_yaml.py   ~/.codex/skills/my-skill   --interface display_name="My Skill"   --interface short_description="Help with my skill tasks"

8. 中级技巧:渐进式披露设计

这是写出高效 Skill 的核心设计模式。

模式一:高层指南 + 引用文件

# PDF Processing## Quick startExtract text with pdfplumber:[code example]## Advanced features- **Form filling**: See references/forms.md for complete guide- **API reference**: See references/api_docs.md for all methods- **Examples**: See references/examples.md for common patterns

Codex 只在用户需要表单填写时才加载 forms.md。

模式二:按领域拆分

bigquery-skill/├── SKILL.md               ← 概览和导航└── references/    ├── finance.md          ← 收入、计费指标    ├── sales.md            ← 机会、管道    ├── product.md          ← API 使用、功能    └── marketing.md        ← 活动、归因

用户问销售指标时,只加载 sales.md。

模式三:按框架/变体拆分

cloud-deploy/├── SKILL.md               ← 工作流 + 选择指南└── references/    ├── aws.md    ├── gcp.md    └── azure.md

用户选 AWS,只加载 aws.md。

模式四:条件详情

# DOCX Processing## Creating documentsUse docx-js for new documents. See references/docx-js.md.## Editing documentsFor simple edits, modify the XML directly.**For tracked changes**: See references/redlining.md**For OOXML details**: See references/ooxml.md

关键原则

  1. 引用文件从 SKILL.md 出发只跳一层,不要深层嵌套
  2. 超过 100 行的引用文件,顶部加目录(Table of Contents)
  3. SKILL.md 不超过 500 行,超过就拆

9. 中级技巧:自由度控制

根据任务的脆弱性和可变性,匹配不同的自由度:

高自由度(文本指令)

适用场景: 多种方法都可行,决策依赖上下文,启发式引导即可。

## Code Review GuidelinesFocus on security, performance, and maintainability.Use your judgment for severity levels.Suggest improvements when patterns are suboptimal.

中自由度(伪代码/带参数脚本)

适用场景: 有推荐模式,允许一定变体,配置影响行为。

## Data Pipeline1. Read source data with `scripts/ingest.py --source  --format `2. Validate schema against `references/schema.md`3. Transform using the patterns in `references/transform_guide.md`4. Load to target with `scripts/load.py --target  --mode `

低自由度(特定脚本,少量参数)

适用场景: 操作脆弱易错,一致性关键,必须按特定顺序执行。

## PDF Rotation (MUST follow this exact sequence)1. Run: `python3 scripts/rotate_pdf.py `2. Render output: `pdftoppm -png `3. Visually inspect ALL pages for alignment issues4. If any page has issues, re-run from step 1 with corrected input

类比: 窄桥+悬崖需要明确护栏(低自由度),开阔草地可以自由探索(高自由度)。

10. 进阶:Forward-Testing

Forward-testing 是验证 Skill 是否真正有效的关键手段。

什么是 Forward-Testing

让子代&理(subagent)假装是普通用户,用你的 Skill 完成真实任务,从而测试:

  1. Skill 能否被正确触发
  2. 指令是否足够清晰
  3. 输出是否符合预期

怎么做

正确方式:

Use $skill-name at /path/to/skill-name to solve problem y

错误方式:

Review the skill at /path/to/skill-name; pretend a user asks you to...

Forward-Testing 原则

  1. 用新线程,保持独立
  2. 只传 Skill 路径和任务描述,不要泄露你的诊断或预期答案
  3. 每次迭代后清理子代&理产生的文件,避免污染
  4. 只在子代&理泄露上下文才能成功时才信任结果 — 如果结果依赖泄露的上下文,说明 Skill 还需要改进
  5. 如果测试可能涉及生产系统或需要额外审批,先向用户确认

决策规则

  1. 倾向于做 forward-testing
  2. 如果以下任一条件成立,先问用户:
    1. 测试耗时较长
    2. 需要额外用户审批
    3. 可能修改线上生产系统

11. 进阶:Production 级 Skill 设计模式

模式一:带有质量检查的工作流

---name: chart-generatordescription: "Generate publication-quality charts. Use when user asks to create any data visualization, chart, or graph from data."---# Chart Generator## Workflow1. Determine chart type from user request (bar, line, scatter, heatmap, etc.)2. Generate chart with matplotlib/plotly using `scripts/generate_chart.py`3. Render to PNG and visually verify4. If verification fails, fix and re-render5. Deliver final PNG## Quality Checks (Mandatory)After EVERY chart generation:- Verify no overlapping labels- Confirm axis labels are readable at target size- Check color contrast meets WCAG AA- Ensure title and legend are visible## Scripts- `scripts/generate_chart.py --type  --data  --output `- `scripts/verify_chart.py ` — Automated quality check

模式二:环境感知 Skill

---name: deploy-helperdescription: "Deploy applications to cloud providers. Use when user asks to deploy, ship, or release an application. Supports AWS, GCP, Azure."---# Deploy Helper## Pre-flight ChecksBefore any deployment:1. Verify target environment credentials exist2. Check that build artifacts are up to date3. Confirm deployment target matches user's intent (staging vs production)## Provider Selection| Provider | Config File | Credentials ||----------|------------|-------------|| AWS      | aws-config.yaml | AWS_PROFILE env || GCP      | gcp-config.yaml | GOOGLE_APPLICATION_CREDENTIALS || Azure    | azure-config.yaml | AZURE credentials |Load provider-specific details from `references/.md`.## Safety Rules- NEVER deploy to production without explicit user confirmation- ALWAYS preview changes before executing- If deployment fails, rollback and explain what went wrong

模式三:带上下文积累的长流程

---name: code-migrationdescription: "Migrate codebases between frameworks or languages. Use when user asks to migrate, convert, or transform an existing codebase."---# Code Migration Skill## Phase 1: AnalysisScan the source codebase and produce `migration-report.md`:- File count and structure- Dependencies inventory- Complexity estimate## Phase 2: PlanningBased on the report, create a migration plan in `migration-plan.md`:- Ordered list of files to convert- Dependency graph- Risk assessment per file## Phase 3: ExecutionConvert files following the plan. After each batch:- Run available tests- Update migration-plan.md with progress- If error rate > 10%, pause and reassess## Phase 4: Verification- Run full test suite- Compare coverage metrics before/after- Generate final migration summary

12. 完整实战案例

案例:Notion 知识管理 Skill

notion-knowledge-capture/├── SKILL.md├── agents/│   └── openai.yaml├── references/│   ├── page_types.md        ← 各种页面类型的 Schema│   └── linking_rules.md     ← 链接和关联规则└── assets/    └── templates/        ├── decision.md      ← 决策记录模板        └── faq.md           ← FAQ 模板

SKILL.md:

---name: notion-knowledge-capturedescription: "Capture conversations and decisions into structured Notion pages. Use when turning chats/notes into wiki entries, how-tos, decisions, or FAQs with proper linking."---# Notion Knowledge Capture## When to CaptureCapture knowledge when the conversation contains:- A decision that should be持久化- A how-to that will be repeated- An FAQ that multiple people ask- A meeting outcome that affects others## Workflow1. Identify the type of knowledge (decision / how-to / FAQ / meeting-notes)2. Load the appropriate template from `assets/templates/`3. Fill in the template with conversation content4. Determine where it belongs in the Notion hierarchy (see `references/linking_rules.md`)5. Create the page via Notion MCP## Quality Standards- Title must be specific and searchable (not "Meeting Notes" but "Q3 Planning: API Rate Limiting Decision")- Every entry must have: author, date, status, related pages- Decisions must include: context, options considered, rationale, follow-ups

13. 调试与排错

Skill 没有被触发

检查清单:

  1. description 是否清晰描述了使用场景?
  2. 用户的请求是否匹配 description 中提到的场景?
  3. 是否有其他 Skill 的 description 更匹配?
  4. Skill 文件夹是否放在 $CODEX_HOME/skills/ 下?

Skill 触发了但行为不对

  1. SKILL.md 正文是否在 frontmatter 之后?
  2. 指令是否足够具体?(用祈使句,给出明确步骤)
  3. 引用的脚本/文件路径是否正确?

验证命令

# 检查结构是否正确python3 ~/.codex/skills/.system/skill-creator/scripts/quick_validate.py ~/.codex/skills/my-skill# 检查 YAML 格式cat ~/.codex/skills/my-skill/agents/openai.yaml# 列出所有已安装的 Skillls ~/.codex/skills/

14. 最佳实践速查表

Description 写法

原则说明
写清楚做什么 + 什么时候用两者缺一不可
包含所有触发场景触发信息只能放 description,不能放 body
不超过 1024 字符避免 <> 符号
包含文件类型/任务类型帮助 Codex 精确匹配

SKILL.md 写法

原则说明
用祈使句“Run the script” 而不是 “The script can be run”
只写 Codex 不知道的不解释基础概念
不超过 500 行超过就拆到 references/
引用文件只跳一层不要深层嵌套引用
大文件加 grep 指引方便 Codex 搜索定位

资源管理

原则说明
脚本优先确定性任务用脚本,不重写代码
references 只放按需内容不要污染主文件
assets 只放输出资源不读进上下文的文件
不放 README/CHANGELOGSkill 是给 AI 看的

Production 级要求

原则说明
质量检查内嵌到流程每个关键步骤后验证
错误恢复明确写出来失败时该怎么做
Forward-test 复杂 Skill用子代&理模拟真实使用
多环境感知明确区分 staging/production
安全操作确认破坏性操作前确认

附录:关键路径

路径用途
~/.codex/skills/个人 Skill 安装目录
~/.codex/skills/.system/skill-creator/Skill 创建工具
scripts/init_skill.py初始化新 Skill
scripts/quick_validate.py验证 Skill 结构
scripts/generate_openai_yaml.py生成 UI 元数据
$CODEX_HOME/skills/.system/系统预装 Skill(不可修改)

本教程基于 Codex Skill Creator 系统文档编写,覆盖从零基础到生产级的完整路径。

点击查看更多
推荐专题
热门阅读