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, // 要產生的最大 token 數
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參數 - ❌ 回合間的有狀態思維鏈
替代方案:對於 temperature/top_p 使用 GPT-4o,或使用 openai-responses 技能進行有狀態推理
串流模式
設定 stream: true 以啟用逐個 token 的傳遞。
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 個 token,整個批次總計 300k 個 token,陣列最大長度 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'取得永久基底64數據)
圖片編輯 (GPT-Image-1)
const response = await openai.images.edit({
model: 'gpt-image-1',
image: fs.createReadStream('original.png'),
prompt: '將背景改為巴黎艾菲爾鐵塔的夜景',
mask: fs.createReadStream('mask.png'), // 可選遮罩
});
注意:圖片編輯需要 gpt-image-1 模型,並以 FORM 編碼送出。
音訊 API
語音轉文字 (Whisper)
端點:POST /v1/audio/transcriptions
import fs from 'fs';
const transcription = await openai.audio.transcriptions.create({
model: 'whisper-1',
file: fs.createReadStream('audio.mp3'),
language: 'en', // 或 'zh' (中文)
response_format: 'text', // 'text', 'json', 'srt', 'vtt'
});
console.log(transcription);
支援的輸入格式:flac, m4a, mp3, mp4, mpeg, mpga, oga, ogg, wav, webm 最大檔案大小:25 MB
文字轉語音 (TTS)
端點:POST /v1/audio/speech
const speech = await openai.audio.speech.create({
model: 'tts-1', // 或 'tts-1-hd' (更高品質)
voice: 'alloy', // nova, echo, fable, onyx, shimmer, ash, ballad, coral, sage, verse
input: '今天天氣真好!',
speed: 1.0, // 0.25 到 4.0
response_format: 'mp3', // mp3, opus, aac, flac, wav, pcm
});
const buffer = Buffer.from(await speech.arrayBuffer());
語音選項 (11 種):alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, shimmer, verse
TTS 模型:
tts-1:較低延遲,適合即時tts-1-hd:更高品質,但延遲較高
內容審核 API
端點:POST /v1/moderations
用於安全檢查的分類器,識別不當內容。
const moderation = await openai.moderations.create({
model: 'omni-moderation-latest',
input: '這是一個測試文字',
});
console.log(moderation.results[0]);
// { flagged: false, categories: {...}, scores: {...} }
審核類別 (11 種)
| 類別 ID | 描述 |
|---|---|
harassment | 騷擾 |
harassment/threatening | 具威脅性的騷擾 |
hate | 仇恨言論 |
hate/threatening | 具威脅性的仇恨言論 |
illicit/controlled_substance | 違禁藥物 |
illicit/violent | 非法暴力內容 |
self-harm | 自殘 |
self-harm/instructions | 自殘指導 |
self-harm/intent | 自殘意圖 |
sexual | 性內容 |
violence | 暴力 |
violence/graphic | 血腥暴力 |
分類強度等級:
none:未偵測到low:可能medium:很可能high:非常確定
重要:
- 在顯示使用者生成內容之前,始終進行審核
- 對於繁體中文內容,可以正常使用;API 會自動處理語言
- 審核不是特別針對繁體中文進行最佳化,但對大多數內容仍應合理準確
錯誤處理
常見錯誤代碼
| HTTP 狀態碼 | 類型 | 含義 | 修復 |
|---|---|---|---|
400 | BadRequestError | 無效的請求 (例如模型參數錯誤) | 檢查請求格式 |
401 | AuthenticationError | API 金鑰無效 | 檢查環境變數中的 OPENAI_API_KEY |
403 | PermissionDeniedError | 權限不足 | 檢查 API 金鑰權限 |
404 | NotFoundError | 端點/模型不存在 | 確認端點和模型名稱 |
409 | ConflictError | 資源衝突 | 重試或檢查狀態 |
422 | UnprocessableEntityError | 語意錯誤 (例如 JSON Schema 無效) | 檢查請求結構 |
429 | RateLimitError | 速率限制超過 | 實作指數退避 |
500 | InternalServerError | OpenAI 伺服器錯誤 | 重試 |
502-504 | 閘道錯誤 | 網路/伺服器問題 | 重試 |
重試模式
async function chatWithRetry(params, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await openai.chat.completions.create(params);
} catch (error) {
if (error instanceof OpenAI.APIError) {
if (error.status === 429 || error.status >= 500) {
const delay = Math.pow(2, attempt) * 1000;
await new Promise(r => setTimeout(r, delay));
continue;
}
}
throw error;
}
}
throw new Error('超過最大重試次數');
}
串流解析錯誤
try {
for await (const chunk of stream) {
// 處理區塊
}
} catch (error) {
if (error.message.includes('JSON')) {
console.error('串流 JSON 解析錯誤,跳過無效區塊');
} else {
throw error;
}
}
速率限制
限制類型
- RPM (每分鐘請求數):基於組織/Tier
- TPM (每分鐘 token 數):基於組織/Tier
- IPM (每分鐘圖片數):適用於圖片 API
處理 429 錯誤
if (error instanceof OpenAI.RateLimitError) {
const retryAfter = error.headers['retry-after-ms'] || 5000;
await new Promise(r => setTimeout(r, retryAfter));
return await retry();
}
最佳實踐
- 實作指數退避 (如錯誤處理所示)
- 使用串流以減少延遲感
- 快取常見查詢的結果
- 監控儀表板中的使用情況:https://platform.openai.com/usage
生產環境最佳實踐
API 金鑰安全
- 使用環境變數,永遠不要寫死在程式碼中
- 為不同環境使用不同的金鑰
- 定期輪換金鑰
錯誤處理
- 始終實現重試邏輯 (指數退避)
- 區分可重試錯誤 (429, 5xx) 和客戶端錯誤 (4xx)
- 加入全面性的日誌記錄
快取策略
- 快取嵌入結果 (確定性)
- 快取常見的聊天完成結果
max_tokens感應 - 使用 ESI/CDN 快取審核結果
監控
- 在 https://platform.openai.com/usage 追蹤使用情況
- 監控延遲和錯誤率
- 設定用量警報
成本最佳化
- 對簡單任務使用
gpt-5-mini或gpt-5-nano - 為嵌入減少維度
- 實施提示壓縮
- 批次非急迫請求
與 openai-responses 的關係
這個技能提供無狀態 API 的完整指南。對於有狀態 / 持久性對話 (內建思維鏈),請參閱「openai-responses」技能。
區別:
- 這個技能 (chat completions):無狀態,每次請求都需發送完整歷史
- openai-responses:管理對話狀態,支援持久性會話
在無狀態設定中使用這個技能,或將其與 openai-responses 結合以實現進階用例。