OpenAI API 最佳實踐整理
OpenAI API 是當今最廣泛使用的 AI 服務之一。以下從多個面向整理實務上必須注意的最佳實踐。
Function Calling 正確姿勢
Function Calling(現稱 Tool Use)是讓模型與外部系統互動的關鍵機制:
{
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "取得指定城市的天氣資訊",
"parameters": {
"type": "object",
"properties": { "city": { "type": "string", "description": "城市名稱" } },
"required": ["city"]
}
}
}]
}
注意事項:
description要具體明確,這是模型決定是否呼叫的關鍵- 一個 Request 最多可定義 128 個 functions
- 回傳結果必須是字串(JSON.stringify)
Streaming 實作
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: prompt }],
stream: true,
});
for await (const chunk of response) {
const text = chunk.choices[0]?.delta?.content || "";
process.stdout.write(text);
}
錯誤處理與重試
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
def call_openai(messages):
return openai.ChatCompletion.create(model="gpt-4o", messages=messages)
成本控制
- 使用 Prompt Caching 降低重複前綴的費用(最高省 50%)
- 批次處理使用 Batch API,費用再省 50%
- 監控 token 使用量,設定每日/每月限額