OpenAI Batch API 常見技術問題排除

「OpenAI 的 Batch API 是非同步批量請求 (指一次可以同時處理多項任務) 的工具,可以降低 50% 的成本、更彈性的速率限制以及 24 小時內的完成時間。這項 API 服務適合處理不需要即時回應的需求。」 (資料來源:OpenAI) 使用 Batch API 常會遇到認證、檔案太大等錯誤,本文列出建議解決方式。

Inspired by Mpho Mojapelo on StockSnap


修正使用 Batch API 遇到的錯誤

1. 認證錯誤類型

錯誤狀況:

傳送 API 請求時,遇到錯誤訊息「Incorrect API key provided: ''. You can find your API key at https://platform.openai.com/account/api-keys.」或「Invalid authorization header」

解決方式:

依照錯誤訊息中提到請到 https://platform.openai.com/account/api-keys 設定有效的 API key,並將 API 加入請求的標頭。例如:

curl https://api.openai.com/v1/batches?limit=10 \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json"

2. 檔案太大錯誤類型

錯誤狀況:

依照 OpenAI 文件提到使用 File API 上傳 jsonl 檔案,每個檔案最多 512MB,遇到的第一個錯誤訊息「File is too large」

Individual files can be up to 512 MB, and the size of all files uploaded by one organization can be up to 100 GB.

將檔案切割到 500 MB以下,跑 Batch API 時則遇到第二個錯誤訊息「The batch input file is larger than the 209715200 maximum for the gpt-4o model. Please try again with a smaller batch.」

解決方式:

依據錯誤訊息提到 GPT-4o 模型的限制 209715200 bytes 約 200MB,因此需要將原本準備的 jsonl 檔案切割到 200MB 以下。因為 jsonl 是每行一筆資料,所以切割時不可以依照檔案大小切割,而是依照行數切割

可以使用 split 命令處理檔案 (雖然是 Linux 指令,Windows 使用 CygWin 也可以安裝使用)

split [-l 行數] 輸入檔名 輸出檔名前置詞

例如:約 8 萬筆資料的檔案大小是 800 MB,如果要切割到 200 MB 以下,需要將每份檔案切割到 8萬/4 = 2萬行。 split 命令將是

split -l 20000 input.jsonl batch_file

分割後檔案是以英文方式命名 aa, ab, ac ... 依此類推。

3. token 長度限制類型錯誤

錯誤狀況:

在 OpenAI 開發者論壇可以看到的錯誤 “This model’s maximum context length is 128000 tokens. However, you requested 141226 tokens (41226 in the messages, 100000 in the completion). Please reduce the length of the messages or completion.”

解決方式:

模型本身有 token 長度限制。請先閱讀模型本身 context window (上下文) 的 token 長度限制。再到 OpenAI API playground 先初步測試,依照任務需求調整輸入文章長度與 Maximum Tokens 後,才使用 Batch API。


參考資料

  1. Batch - OpenAI API
  2. File API Reference - OpenAI API
  3. Split large files into a number of smaller files in Unix
  4. BATCH Api errors max_tokens is too large - API - OpenAI Developer Forum
  5. Models - OpenAI API
  6. Batch API FAQ | OpenAI Help Center

留言