OpenAI 整合
規則
- 使用官方
openai 套件 — new OpenAI({ apiKey: process.env.OPENAI_API_KEY })
- 聊天串流:設定
stream: true 搭配非同步迭代器 — 對使用者介面的回應絕不阻塞等待完整完成
- 函式呼叫:以 JSON Schema 定義函式,處理回應中的
tool_calls,以工具訊息回傳結果
- 結構化輸出:使用
response_format: { type: "json_schema", json_schema: {...} } 或搭配 AI SDK 的 Zod
- Token 管理:發送前預估 Token(約 4 字元等於 1 個 Token),主動裁剪上下文以保持在限制內
- 模型選擇:複雜推理使用
gpt-4o,簡單任務使用 gpt-4o-mini — 建議設為可設定
- 系統提示作為第一則訊息 — 設定語氣、限制條件與輸出格式
- 溫度:確定性輸出(資料萃取)設為 0,創意任務設為 0.7-1.0
- 速率限制:遵循
x-ratelimit-* 標頭,對 429 錯誤實作指數退避
模式
const stream = await openai.chat.completions.create({
model: "gpt-4o",
messages,
stream: true,
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || "";
process.stdout.write(content);
}
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages,
tools: [{ type: "function", function: { name: "get_weather", parameters: schema } }],
});
避免
- 硬編碼 API 金鑰 — 永遠使用環境變數
- 忽略 Token 限制 — 計算 Token 並主動裁剪訊息
- 瑣碎任務使用
gpt-4o — 使用 gpt-4o-mini 節省成本
- API 呼叫缺少錯誤處理 — 妥善處理 429、500、逾時錯誤