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 方法
目录
- 快速开始
- 聊天补全 API
- GPT-5 系列模型
- 流式传输模式
- 函数调用
- 结构化输出
- 视觉(GPT-4o)
- 嵌入 API
- 图像 API
- 音频 API
- 内容审核 API
- 错误处理
- 速率限制
- 生产环境最佳实践
- 与 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 内容。