Communitygithub.com

David-Li0406/meta-skill-evloving

使用OpenAI的无状态API构建应用 - 聊天补全(GPT-5、GPT-4o)、嵌入、图像(DALL-E 3)、音频(Whisper + TTS)和内容审核。包含Node.js SDK和适用于Cloudflare Workers的基于fetch的方法。

meta-skill-evloving 是什么?

该技能是OpenAI API的完整指南,涵盖了从GPT-5、GPT-4o聊天补全到嵌入、图像生成(DALL-E 3)和编辑、音频转录(Whisper)与合成(TTS)、以及内容审核的所有核心功能。它详细解释了如何通过Node.js SDK或原生fetch请求(例如在Cloudflare Workers中)使用这些无状态API。技能文档强调了GPT-5模型独有的推理努力(reasoning_effort)和详细程度(verbosity)参数,并提供了流式传输(SSE)、函数调用(工具)、结构化输出(JSON Schema)以及视觉(Vision)能力的具体实现模式。此外,它还包含了错误处理、速率限制以及生产环境最佳实践的指南,对于任何希望系统集成OpenAI最新模型的开发者来说,这是一份宝贵的参考资料。

兼容平台~Claude Code✓Codex CLI~Cursor✓Antigravity
npx skills add https://github.com/David-Li0406/meta-skill-evloving/tree/HEAD/AgentSkillOS/data/skill_seeds/openai-api

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

OpenAI API - 完整指南

版本:生产就绪 ✅ 包名:[email protected] 最后更新:2025-11-26


状态

✅ 生产就绪:

  • ✅ 聊天补全 API(GPT-5、GPT-4o、GPT-4 Turbo)
  • ✅ 嵌入 API(text-embedding-3-small、text-embedding-3-large)
  • ✅ 图像 API(DALL-E 3 生成 + GPT-Image-1 编辑)
  • ✅ 音频 API(Whisper 转录 + 包含11种语音的TTS)
  • ✅ 内容审核 API(11个安全类别)
  • ✅ 流式传输模式(SSE)
  • ✅ 函数调用 / 工具
  • ✅ 结构化输出(JSON 模式)
  • ✅ 视觉(GPT-4o)
  • ✅ 同时支持 Node.js SDK 和 fetch 方法

目录

  1. 快速开始
  2. 聊天补全 API
  3. GPT-5 系列模型
  4. 流式传输模式
  5. 函数调用
  6. 结构化输出
  7. 视觉(GPT-4o)
  8. 嵌入 API
  9. 图像 API
  10. 音频 API
  11. 内容审核 API
  12. 错误处理
  13. 速率限制
  14. 生产环境最佳实践
  15. 与 openai-responses 的关系

快速开始

安装

npm install [email protected]

环境设置

export OPENAI_API_KEY="sk-..."

或创建 .env 文件:

OPENAI_API_KEY=sk-...

首次聊天补全(Node.js SDK)

import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const completion = await openai.chat.completions.create({
  model: 'gpt-5',
  messages: [
    { role: 'user', content: '机器人三定律是什么?' }
  ],
});

console.log(completion.choices[0].message.content);

首次聊天补全(Fetch - Cloudflare Workers)

const response = await fetch('https://api.openai.com/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${env.OPENAI_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'gpt-5',
    messages: [
      { role: 'user', content: '机器人三定律是什么?' }
    ],
  }),
});

const data = await response.json();
console.log(data.choices[0].message.content);

聊天补全 API

端点:POST /v1/chat/completions

聊天补全 API 是与 OpenAI 语言模型交互的核心接口。它支持对话式 AI、文本生成、函数调用、结构化输出和视觉能力。

支持的模型

GPT-5 系列(2025年8月发布)

  • gpt-5:具备高级功能的完整推理模型
  • gpt-5-mini:性能良好的高性价比替代品
  • gpt-5-nano:适用于简单任务的最小/最快变体

GPT-4o 系列

  • gpt-4o:具有视觉能力的多模态模型
  • gpt-4-turbo:快速的 GPT-4 变体

GPT-4 系列

  • gpt-4:原始 GPT-4 模型

基本请求结构

{
  model: string,              // 使用的模型(例如 "gpt-5")
  messages: Message[],        // 对话历史
  reasoning_effort?: string,  // 仅 GPT-5:"minimal" | "low" | "medium" | "high"
  verbosity?: string,         // 仅 GPT-5:"low" | "medium" | "high"
  temperature?: number,       // GPT-5 不支持
  max_tokens?: number,        // 生成的最大令牌数
  stream?: boolean,           // 启用流式传输
  tools?: Tool[],             // 函数调用工具
}

响应结构

{
  id: string,                 // 唯一的补全 ID
  object: "chat.completion",
  created: number,            // Unix 时间戳
  model: string,              // 使用的模型
  choices: [{
    index: number,
    message: {
      role: "assistant",
      content: string,        // 生成的文本
      tool_calls?: ToolCall[] // 如果使用了函数调用
    },
    finish_reason: string     // "stop" | "length" | "tool_calls"
  }],
  usage: {
    prompt_tokens: number,
    completion_tokens: number,
    total_tokens: number
  }
}

消息角色与多轮对话

三种角色:system(行为设定)、user(输入)、assistant(模型响应)。

重要提示:API 是无状态的 - 每次请求都需要发送完整的对话历史。如需有状态对话,请使用 openai-responses 技能。


GPT-5 系列模型

GPT-5 模型(2025年8月发布)引入了推理和详细程度控制:

GPT-5.1(2025年11月13日发布)

具有重大改进的最新模型:

  • gpt-5.1:自适应推理,动态变化思考时间
  • 24小时扩展提示缓存:更快的后续查询,成本更低
  • 新的开发者工具:apply_patch(代码编辑)、shell(命令执行)

重大变更:GPT-5.1 默认 reasoning_effort: 'none'(而 GPT-5 默认是 'medium')。迁移时请更新代码!

reasoning_effort 参数

控制思考深度(适用于 GPT-5 和 GPT-5.1):

  • "none":无推理(最快,最低延迟) - GPT-5.1 默认值
  • "minimal":快速响应,极少思考
  • "low":基本推理
  • "medium":平衡推理 - GPT-5 默认值
  • "high":深度推理,用于复杂问题
// GPT-5.1 无推理(快速)
const completion = await openai.chat.completions.create({
  model: 'gpt-5.1',
  messages: [{ role: 'user', content: '简单查询' }],
  // reasoning_effort: 'none' 是 GPT-5.1 的隐式默认值
});

// GPT-5.1 高推理(复杂任务)
const completion = await openai.chat.completions.create({
  model: 'gpt-5.1',
  messages: [{ role: 'user', content: '解决这个复杂的数学问题...' }],
  reasoning_effort: 'high',
});

verbosity 参数

控制输出详细程度(GPT-5/GPT-5.1):

  • "low":简洁
  • "medium":平衡(默认)
  • "high":详细

GPT-5 限制

不支持:

  • ❌ temperature、top_p、logprobs 参数
  • ❌ 轮次间的有状态思维链

替代方案:使用 GPT-4o 获取 temperature/top_p 支持,或使用 openai-responses 技能进行有状态推理


流式传输模式

通过 stream: true 启用逐令牌交付。

Node.js SDK

const stream = await openai.chat.completions.create({
  model: 'gpt-5.1',
  messages: [{ role: 'user', content: '写一首诗' }],
  stream: true,
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content || '';
  process.stdout.write(content);
}

Fetch(Cloudflare Workers)

const response = await fetch('https://api.openai.com/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${env.OPENAI_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'gpt-5.1',
    messages: [{ role: 'user', content: '写一首诗' }],
    stream: true,
  }),
});

const reader = response.body?.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader!.read();
  if (done) break;

  const chunk = decoder.decode(value);
  const lines = chunk.split('\n').filter(line => line.trim() !== '');

  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const data = line.slice(6);
      if (data === '[DONE]') break;

      try {
        const json = JSON.parse(data);
        const content = json.choices[0]?.delta?.content || '';
        console.log(content);
      } catch (e) {
        // 跳过无效的 JSON
      }
    }
  }
}

服务器发送事件(SSE)格式:

data: {"id":"chatcmpl-xyz","choices":[{"delta":{"content":"Hello"}}]}
data: [DONE]

关键点:优雅地处理不完整块、[DONE] 信号和无效 JSON。


函数调用

使用 JSON Schema 定义工具,模型根据上下文调用它们。

工具定义与请求

const tools = [{
  type: 'function',
  function: {
    name: 'get_weather',
    description: '获取某个位置的当前天气',
    parameters: {
      type: 'object',
      properties: {
        location: { type: 'string', description: '城市名称' },
        unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }
      },
      required: ['location']
    }
  }
}];

const completion = await openai.chat.completions.create({
  model: 'gpt-5.1',
  messages: [{ role: 'user', content: '旧金山天气如何?' }],
  tools: tools,
});

处理工具调用

const message = completion.choices[0].message;

if (message.tool_calls) {
  for (const toolCall of message.tool_calls) {
    const args = JSON.parse(toolCall.function.arguments);
    const result = await executeFunction(toolCall.function.name, args);

    // 将结果发送回模型
    await openai.chat.completions.create({
      model: 'gpt-5.1',
      messages: [
        ...messages,
        message,
        {
          role: 'tool',
          tool_call_id: toolCall.id,
          content: JSON.stringify(result)
        }
      ],
      tools: tools,
    });
  }
}

循环模式:持续调用 API,直到响应中没有 tool_calls。


结构化输出

结构化输出允许你在模型响应上强制执行 JSON Schema 验证。

使用 JSON Schema

const completion = await openai.chat.completions.create({
  model: 'gpt-4o', // 注意:结构化输出在 GPT-4o 上支持最好
  messages: [
    { role: 'user', content: '生成一个人物简介' }
  ],
  response_format: {
    type: 'json_schema',
    json_schema: {
      name: 'person_profile',
      strict: true,
      schema: {
        type: 'object',
        properties: {
          name: { type: 'string' },
          age: { type: 'number' },
          skills: {
            type: 'array',
            items: { type: 'string' }
          }
        },
        required: ['name', 'age', 'skills'],
        additionalProperties: false
      }
    }
  }
});

const person = JSON.parse(completion.choices[0].message.content);
// { name: "Alice", age: 28, skills: ["TypeScript", "React"] }

JSON 模式(简单)

适用于无需严格模式验证的简单用例:

const completion = await openai.chat.completions.create({
  model: 'gpt-5',
  messages: [
    { role: 'user', content: '以 JSON 格式列出3种编程语言' }
  ],
  response_format: { type: 'json_object' }
});

const data = JSON.parse(completion.choices[0].message.content);

重要提示:使用 response_format 时,请在提示中包含"JSON"以引导模型。


视觉(GPT-4o)

GPT-4o 支持文本以外的图像理解。

通过 URL 提供图像

const completion = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: '这张图片里有什么?' },
        {
          type: 'image_url',
          image_url: {
            url: 'https://example.com/image.jpg'
          }
        }
      ]
    }
  ]
});

通过 Base64 提供图像

import fs from 'fs';

const imageBuffer = fs.readFileSync('./image.jpg');
const base64Image = imageBuffer.toString('base64');

const completion = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: '详细描述这张图片' },
        {
          type: 'image_url',
          image_url: {
            url: `data:image/jpeg;base64,${base64Image}`
          }
        }
      ]
    }
  ]
});

多张图像

const completion = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: '比较这两张图片' },
        { type: 'image_url', image_url: { url: 'https://example.com/image1.jpg' } },
        { type: 'image_url', image_url: { url: 'https://example.com/image2.jpg' } }
      ]
    }
  ]
});

嵌入 API

端点:POST /v1/embeddings

将文本转换为向量,用于语义搜索和 RAG。

模型

  • text-embedding-3-large:3072 维(可自定义:256-3072),最高质量
  • text-embedding-3-small:1536 维(可自定义:256-1536),高性价比,推荐使用

基本请求

const embedding = await openai.embeddings.create({
  model: 'text-embedding-3-small',
  input: '食物很美味。',
});
// 返回:{ data: [{ embedding: [0.002, -0.009, ...] }] }

自定义维度(OpenAI 特有)

const embedding = await openai.embeddings.create({
  model: 'text-embedding-3-small',
  input: '示例文本',
  dimensions: 256, // 从默认的1536减少
});

优势:存储减少4-12倍,搜索更快,质量损失极小。

批量处理

const embeddings = await openai.embeddings.create({
  model: 'text-embedding-3-small',
  input: ['第一篇文档', '第二篇文档', '第三篇文档'],
});

限制:每个输入最多 8192 个令牌,批次总令牌数不超过 300k,数组最大长度 2048。

关键点:使用自定义维度提高效率,批量最多 2048 个文档,缓存嵌入(确定性)。


图像 API

图像生成(DALL-E 3)

端点:POST /v1/images/generations

const image = await openai.images.generate({
  model: 'dall-e-3',
  prompt: '一只白色暹罗猫,有着引人注目的蓝眼睛',
  size: '1024x1024', // 其他尺寸:1024x1536, 1536x1024, 1024x1792, 1792x1024
  quality: 'standard', // 或 'hd'
  style: 'vivid', // 或 'natural'
});

console.log(image.data[0].url);
console.log(image.data[0].revised_prompt); // DALL-E 3 可能会出于安全考虑修改提示

DALL-E 3 特性:

  • 仅支持 n: 1(每次请求生成一张图像)
  • 可能出于安全/质量原因修改提示(请检查 revised_prompt)
  • URL 在1小时后过期(如果使用 response_format: 'b64_json' 则不会)

生成后处理:

  • revised_prompt:OpenAI 用于安全/质量的提示重写
  • 1小时 URL 过期时间:如果部署到生产环境,请务必下载、存储或转换为 base64

图像编辑(GPT-Image-1)

端点:...


注意:由于原始内容被截断,翻译在此截止。如需完整翻译,请提供完整的原始 SKILL.md 内容。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

David-Li0406/meta-skill-evloving

Browser automation with persistent page state. Use when users ask to navigate websites, fill forms, take screenshots, extract web data, test web apps, or automate browser workflows. Trigger phrases include "go to [url]", "click on", "fill out the form", "take a screenshot", "scrape", "automate", "test the website", "log into", or any browser interaction request.

David-Li0406/meta-skill-evloving

Create technical diagrams using Mermaid syntax for architecture, sequences, ERDs, flowcharts, and state machines. Use for visualizing system design, data flows, and processes. Triggers: diagram, mermaid, architecture diagram, sequence diagram, flowchart, ERD, entity relationship, state diagram, C4 model, component diagram, visualize, draw.

David-Li0406/meta-skill-evloving

Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. When Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks

David-Li0406/meta-skill-evloving

Complete color manipulation and green screen effects system. PROACTIVELY activate for: (1) Green screen/chromakey removal, (2) Color grading with LUTs, (3) Color correction (levels, curves, white balance), (4) Colorkey/color removal effects, (5) Hue/saturation manipulation, (6) Color space conversions (BT.709, BT.2020, HDR), (7) Color isolation effects, (8) Teal and orange look, (9) Vintage/film looks, (10) Color keying for transparency. Provides: chromakey and colorkey filters, LUT application (lut3d), curves and levels adjustment, color balance, selective color manipulation, color space handling, HDR tone mapping, professional color grading chains.

David-Li0406/meta-skill-evloving

Convert files and office documents to Markdown. Supports PDF, DOCX, PPTX, XLSX, images (with OCR), audio (with transcription), HTML, CSV, JSON, XML, ZIP, YouTube URLs, EPubs and more.

David-Li0406/meta-skill-evloving

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

David-Li0406/meta-skill-evloving

Comprehensive PDF manipulation toolkit for extracting text and tables, creating new PDFs, merging/splitting documents, and handling forms. When Claude needs to fill in a PDF form or programmatically process, generate, or analyze PDF documents at scale.

David-Li0406/meta-skill-evloving

Presentation creation, editing, and analysis. When Claude needs to work with presentations (.pptx files) for: (1) Creating new presentations, (2) Modifying or editing content, (3) Working with layouts, (4) Adding comments or speaker notes, or any other presentation tasks

David-Li0406/meta-skill-evloving

Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Claude needs to work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets with formulas and formatting, (2) Reading or analyzing data, (3) Modify existing spreadsheets while preserving formulas, (4) Data analysis and visualization in spreadsheets, or (5) Recalculating formulas

David-Li0406/meta-skill-evloving

Download YouTube videos with customizable quality and format options. Use this skill when the user asks to download, save, or grab YouTube videos. Supports various quality settings (best, 1080p, 720p, 480p, 360p), multiple formats (mp4, webm, mkv), and audio-only downloads as MP3.

David-Li0406/meta-skill-evloving

Best practices for Remotion - Video creation in React

David-Li0406/meta-skill-evloving

Provides bidirectional translation (Chinese/English), grammar checking, and sentence polishing. Supports specific tense constraints, context-aware tone adjustment, and natural expression optimization. Outputs direct text without formatting.

David-Li0406/meta-skill-evloving

指导如何通过自定义注解(如@Unicom)标识Dubbo接口,利用BeanDefinitionRegistryPostProcessor在启动时扫描并动态注册ReferenceBean,实现RPC调用的封装。

David-Li0406/meta-skill-evloving

生成Python脚本,利用FFmpeg将图片序列按3x3布局合并,或将合并图拆分。要求使用subprocess模块执行命令,并支持用户交互式输入路径。

David-Li0406/meta-skill-evloving

SOP for extracting and analyzing promotional activity details, handling time formatting, location mapping, payment logic, and step-by-step process validation.

David-Li0406/meta-skill-evloving

Specializes in creating TikTok short video scripts using an anthropomorphic 'Chef' perspective to explain wildlife food chains and survival environments, utilizing real field footage.

David-Li0406/meta-skill-evloving

针对TikTok平台,以拟人化视角(如动物作为厨师)创作系列短视频脚本。重点介绍野生动物、食物链及生态环境,要求使用野外实拍素材,风格幽默且具有教育意义。

David-Li0406/meta-skill-evloving

Generates KWL (Know, Want to know, Learned) charts for educational videos, specifically BrainPOP, using simple 7th-grade language and short, concise bullet points.

David-Li0406/meta-skill-evloving

Develops DAX measures to calculate promo and regular volumes and generates a calculated table of dates excluding continuous promo date ranges, handling multiple periods and nulls.

David-Li0406/meta-skill-evloving

Tracks complex, multi-session work using the Beads issue tracker and dependency graphs, and provides persistent memory that survives conversation compaction. Use when work spans multiple sessions, has complex dependencies, or needs persistent context across compaction cycles. Trigger with phrases like "create task for", "what's ready to work on", "show task", "track this work", "what's blocking", or "update status".

相关技能