使用 OpenAI 的 Batch API 即可整批傳送非同步請求,成本降低 50%,並享有獨立且大幅提高的速率限制。每個批次的處理時限為 24 小時,適合無須立即取得回應的作業。你也可以直接查閱 API 參考文件。
在 OpenAI 平台上,有些用途需要傳送同步請求,但許多作業無須立即取得回應。有時,速率限制也會讓你無法在短時間內執行大量查詢。批次處理常用於下列情境:
- 執行評估
- 將大型資料集中的資料分類
- 為內容庫中的資料產生嵌入向量
Batch API 提供一組易於使用的端點。你可以將多個請求整理成單一檔案,再啟動批次處理作業來執行這些請求。執行期間可以查詢批次狀態,批次完成後即可取得彙整的結果。
相較於直接使用標準端點,Batch API 有以下優點:
- 成本更低: 費用比同步 API 低 50%。
- 速率限制更高: 相較於同步 API,可用額度大幅提高。
- 完成時間短: 每個批次都會在 24 小時內完成,通常所需時間更短。
首先準備一個 .jsonl 檔案,每一行都包含一個 API 請求的詳細資料。目前可使用下列端點:
輸入檔案中每一行的 body 欄位都使用與對應端點相同的參數。每個請求都必須包含唯一的 custom_id 值,方便你在批次完成後找出對應的結果。以下輸入檔案範例包含兩個請求。同一個輸入檔案中的所有請求都必須使用同一個模型。
使用 /v1/moderations 時,每個請求主體都必須包含 input 欄位。使用 omni-moderation-latest 模型時,Batch API 支援純文字輸入,也支援包含文字或圖像輸入的內容陣列。批次處理程式會拒絕設定 stream=true 的請求,這與同步內容審核端點的行為一致。
{"custom_id": "request-1", "method": "POST", "url": "/v1/responses", "body": {"model": "gpt-6-luna", "input": "Reply with the word blue.", "reasoning": {"effort": "none"}, "max_output_tokens": 64}}
{"custom_id": "request-2", "method": "POST", "url": "/v1/responses", "body": {"model": "gpt-6-luna", "input": "Reply with the word green.", "reasoning": {"effort": "none"}, "max_output_tokens": 64}}
以下輸入檔案包含兩個請求:第一行的請求僅含文字,第二行的請求同時包含文字和圖像輸入。
{"custom_id": "moderation-text-1", "method": "POST", "url": "/v1/moderations", "body": {"model": "omni-moderation-latest", "input": "This is a harmless test sentence."}}
{"custom_id": "moderation-mm-1", "method": "POST", "url": "/v1/moderations", "body": {"model": "omni-moderation-latest", "input": [{"type": "text", "text": "Describe this image"}, {"type": "image_url", "image_url": {"url": "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg"}}]}}
建議使用 image_url 引用遠端資源,避免直接嵌入 base64 資料,讓 .jsonl 檔案大小遠低於批次上傳的 200 MB 上限。處理多模態內容審核請求時尤其建議這麼做。
與使用微調 API 一樣,你必須先上傳輸入檔案,才能在啟動批次時正確引用該檔案。請將 .jsonl 檔案透過 Files API 上傳。
1
2
3
4
5
6
7
8
9
10import fs from "fs";
import OpenAI from "openai";
const openai = new OpenAI();
const file = await openai.files.create({
file: fs.createReadStream("fixtures/batchinput.jsonl"),
purpose: "batch",
});
console.log(file);
1
2
3
4
5
6
7
8
9from openai import OpenAI
client = OpenAI()
batch_input_file = client.files.create(
file=open("batchinput.jsonl", "rb"), purpose="batch"
)
print(batch_input_file)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27package main
import (
"context"
"fmt"
"os"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
file, err := os.Open("batchinput.jsonl")
if err != nil {
panic(err)
}
defer file.Close()
uploaded, err := client.Files.New(context.Background(), openai.FileNewParams{
File: file,
Purpose: openai.FilePurposeBatch,
})
if err != nil {
panic(err)
}
fmt.Println(uploaded.ID)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.files.FileCreateParams;
import com.openai.models.files.FilePurpose;
import java.nio.file.Path;
var file =
client
.files()
.create(
FileCreateParams.builder()
.file(Path.of(System.getenv("OPENAI_EXAMPLE_FILE_PATH")))
.purpose(FilePurpose.BATCH)
.build());
System.out.println(file.id());
1
2
3
4
5
6
7require "openai"
require "pathname"
client = OpenAI::Client.new
file = Pathname("batchinput.jsonl")
uploaded = client.files.create(file: file, purpose: :batch)
puts(uploaded.id)
1
2
3
4curl https://api.openai.com/v1/files \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-F purpose="batch" \
-F file="@batchinput.jsonl"
1
2
3openai files create \
--file batchinput.jsonl \
--purpose batch
成功上傳輸入檔案後,即可使用該檔案的 File 物件 ID 建立批次。在此範例中,假設檔案 ID 為 file-abc123。目前完成時限只能設為 24h。你也可以透過選用的 metadata 參數提供自訂中繼資料。
1
2
3
4
5
6
7
8
9
10import OpenAI from "openai";
const openai = new OpenAI();
const batch = await openai.batches.create({
input_file_id: "file-abc123",
endpoint: "/v1/responses",
completion_window: "24h",
});
console.log(batch);
1
2
3
4
5
6
7batch = client.batches.create(
input_file_id=batch_input_file.id,
endpoint="/v1/responses",
completion_window="24h",
metadata={"description": "nightly eval job"},
)
print(batch)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
batch, err := client.Batches.New(context.Background(), openai.BatchNewParams{
InputFileID: "file-abc123",
Endpoint: openai.BatchNewParamsEndpointV1Responses,
CompletionWindow: openai.BatchNewParamsCompletionWindow24h,
})
if err != nil {
panic(err)
}
fmt.Println(batch.ID)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.batches.BatchCreateParams;
String fileId = "file-abc123";
var batch =
client
.batches()
.create(
BatchCreateParams.builder()
.inputFileId(fileId)
.endpoint(BatchCreateParams.Endpoint.V1_RESPONSES)
.completionWindow(BatchCreateParams.CompletionWindow._24H)
.build());
System.out.println(batch.id());
1
2
3
4
5require "openai"
client = OpenAI::Client.new
batch = client.batches.create(input_file_id: "file-abc123", endpoint: "/v1/responses", completion_window: "24h")
puts(batch.id)
1
2
3
4
5
6
7
8curl https://api.openai.com/v1/batches \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"input_file_id": "file-abc123",
"endpoint": "/v1/responses",
"completion_window": "24h"
}'
1
2
3
4openai batches create \
--input-file-id file-abc123 \
--endpoint /v1/responses \
--completion-window 24h
這個請求會傳回一個 Batch 物件,其中包含批次的中繼資料:
1234567891011121314151617181920212223{
"id": "batch_abc123",
"object": "batch",
"endpoint": "/v1/responses",
"errors": null,
"input_file_id": "file-abc123",
"completion_window": "24h",
"status": "validating",
"output_file_id": null,
"error_file_id": null,
"created_at": 1714508499,
"in_progress_at": null,
"expires_at": 1714536634,
"completed_at": null,
"failed_at": null,
"expired_at": null,
"request_counts": {
"total": 0,
"completed": 0,
"failed": 0
},
"metadata": null
}
你可以隨時查詢批次狀態。這項查詢也會傳回一個 Batch 物件。
1
2
3
4
5import OpenAI from "openai";
const openai = new OpenAI();
const batch = await openai.batches.retrieve("batch_abc123");
console.log(batch);
1
2batch = client.batches.retrieve(batch.id)
print(batch)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
batch, err := client.Batches.Get(context.Background(), "batch_abc123")
if err != nil {
panic(err)
}
fmt.Println(batch.Status)
}
1
2
3
4
5
6
7
8import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
String batchId = "batch_abc123";
var batch = client.batches().retrieve(batchId);
System.out.println(batch.status());
1
2
3
4
5require "openai"
client = OpenAI::Client.new
batch = client.batches.retrieve("batch_abc123")
puts(batch.status)
1
2
3curl https://api.openai.com/v1/batches/batch_abc123 \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json"
1
2openai batches retrieve \
--batch-id batch_abc123
Batch 物件可能處於下列任一狀態:
| 狀態 |
說明 |
validating |
正在驗證輸入檔案,通過驗證後才能開始執行批次 |
failed |
輸入檔案未通過驗證 |
in_progress |
輸入檔案已通過驗證,批次正在執行 |
finalizing |
批次已執行完畢,正在整理結果 |
completed |
批次已完成,可以取得結果 |
expired |
批次未能在 24 小時內完成 |
cancelling |
正在取消批次(最多可能需要 10 分鐘) |
cancelled |
批次已取消 |
批次完成後,即可向 Files API 發出請求,使用 Batch 物件的 output_file_id 欄位下載輸出,再將輸出寫入本機檔案。本例使用的檔名為 batch_output.jsonl。
1
2
3
4
5
6
7import OpenAI from "openai";
const openai = new OpenAI();
const fileResponse = await openai.files.content("file-xyz123");
const fileContents = await fileResponse.text();
console.log(fileContents);
1
2
3
4
5
6
7
8
9# Replace the illustrative IDs and URLs below with your own resource values.
from openai import OpenAI
output_file_id = "file_123"
client = OpenAI()
file_response = client.files.content(output_file_id)
print(file_response.text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23package main
import (
"context"
"fmt"
"io"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
response, err := client.Files.Content(context.Background(), "file-xyz123")
if err != nil {
panic(err)
}
defer response.Body.Close()
contents, err := io.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println(string(contents))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.HttpResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
String fileId = "file-xyz123";
try (HttpResponse content = client.files().content(fileId)) {
Files.copy(
content.body(), Path.of("batch_output.jsonl"), StandardCopyOption.REPLACE_EXISTING);
}
1
2
3
4
5require "openai"
client = OpenAI::Client.new
content = client.files.content("file-xyz123")
puts(content.read)
1
2curl https://api.openai.com/v1/files/file-xyz123/content \
-H "Authorization: Bearer $OPENAI_API_KEY" > batch_output.jsonl
1
2
3openai files content \
--file-id file-xyz123 \
--output batch_output.jsonl
輸入檔案中每一個成功的請求,在輸出的 .jsonl 檔案中都有一行對應的回應。批次中所有失敗請求的錯誤資訊都會寫入錯誤檔案,你可以透過批次的 error_file_id 找到該檔案。
請注意,輸出檔案的行序可能與輸入檔案不同。處理結果時,請使用輸出檔案每一行都有的 custom_id 欄位,將輸入請求與輸出結果配對,避免依賴行序。
以下是簡化後的輸出,顯示各請求的 ID 與結果如何對應,以及模型生成的文字。若要讀取每則訊息的 output_text 內容,請從 response.body.output 中取得。
{"id": "batch_req_2", "custom_id": "request-2", "response": {"status_code": 200, "request_id": "req_2", "body": {"id": "resp_2", "object": "response", "status": "completed", "output": [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "green"}]}]}}, "error": null}
{"id": "batch_req_1", "custom_id": "request-1", "response": {"status_code": 200, "request_id": "req_1", "body": {"id": "resp_1", "object": "response", "status": "completed", "output": [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "blue"}]}]}}, "error": null}
依預設,批次的輸出檔案和錯誤檔案都會在各自建立後 30 天到期。若要調整保留期限,請將 output_expires_after 加入建立批次的請求。期限可設為 1 小時至 30 天,自各檔案建立時起算。
如有需要,你可以取消正在執行的批次。批次狀態會先變更為 cancelling,等候執行中的請求完成(最多 10 分鐘),之後再變更為 cancelled。
1
2
3
4
5import OpenAI from "openai";
const openai = new OpenAI();
const batch = await openai.batches.cancel("batch_abc123");
console.log(batch);
1
2
3
4
5
6
7
8# Replace the illustrative IDs and URLs below with your own resource values.
from openai import OpenAI
batch_id = "batch_123"
client = OpenAI()
client.batches.cancel(batch_id)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
batch, err := client.Batches.Cancel(context.Background(), "batch_abc123")
if err != nil {
panic(err)
}
fmt.Println(batch.Status)
}
1
2
3
4
5
6import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
String batchId = "batch_abc123";
System.out.println(client.batches().cancel(batchId).status());
1
2
3
4
5require "openai"
client = OpenAI::Client.new
batch = client.batches.cancel("batch_abc123")
puts(batch.status)
1
2
3
4curl https://api.openai.com/v1/batches/batch_abc123/cancel \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-X POST
1
2openai batches cancel \
--batch-id batch_abc123
你可以隨時查看自己的所有批次。如果批次很多,可以使用 limit 和 after 參數分頁取得結果。
1
2
3
4
5
6
7
8import OpenAI from "openai";
const openai = new OpenAI();
const list = await openai.batches.list();
for await (const batch of list) {
console.log(batch);
}
1
2
3
4
5from openai import OpenAI
client = OpenAI()
client.batches.list(limit=10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
list := client.Batches.ListAutoPaging(context.Background(), openai.BatchListParams{Limit: openai.Int(10)})
for list.Next() {
fmt.Println(list.Current().ID)
}
if err := list.Err(); err != nil {
panic(err)
}
}
1
2
3
4
5
6
7
8
9import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.batches.BatchListParams;
client
.batches()
.list(BatchListParams.builder().limit(10).build())
.autoPager()
.forEach(batch -> System.out.println(batch.id()));
1
2
3
4
5
6require "openai"
client = OpenAI::Client.new
client.batches.list(limit: 10).auto_paging_each do |batch|
puts(batch.id)
end
1
2
3curl https://api.openai.com/v1/batches?limit=10 \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json"
1
2openai batches list \
--limit 10
大多數模型都支援 Batch API。請查閱模型參考文件,確認你使用的模型是否支援。GPT-6 Sol 和 Luna 在 Standard、Flex 和 Batch 處理模式下皆支援歐盟資料駐留。詳情請參閱資料駐留適用條件。
GPT-Image-2.5 的 gpt-image-2.5-flare 和 gpt-image-2.5-sunburst 模型及其 2026-09-08 快照皆支援批次圖像生成與編輯。請使用 /v1/images/generations 或 /v1/images/edits 端點,並參閱圖像生成價格以瞭解批次費率。
Batch API 的速率限制獨立於各模型既有的速率限制。Batch API 有三種速率限制:
- 每個批次的上限: 單一批次最多可包含 50,000 個請求,批次輸入檔案大小上限為 200 MB。使用
/v1/embeddings 時,同一批次所有請求的嵌入輸入項目合計也不得超過 50,000 個。
- 各模型佇列中的提示詞 Token 上限: 每個模型可排入批次處理佇列的提示詞 Token 數量都有上限。你可以在平台設定頁面查看各模型的上限。
- 批次建立速率限制: 每小時最多可建立 2,000 個批次。如果需要提交更多請求,請增加每個批次中的請求數量。
Batch API 目前沒有輸出 Token 數量上限。由於 Batch API 使用獨立的新額度,使用 Batch API 不會占用各模型標準速率限制下的 Token 額度。因此,透過批次處理,你可以向 API 發出更多請求,也能處理更多 Token。
未能如期完成的批次最終會進入 expired 狀態。系統會取消該批次中尚未完成的請求,你仍可從批次輸出檔案取得已完成請求的回應。系統會依已完成請求耗用的 Token 數量計費。
系統會將逾時的請求寫入錯誤檔案,訊息如下所示。你可以使用 custom_id 取得逾時請求的資料。
{"id": "batch_req_123", "custom_id": "request-3", "response": null, "error": {"code": "batch_expired", "message": "This request could not be executed before the completion window expired."}}
{"id": "batch_req_123", "custom_id": "request-7", "response": null, "error": {"code": "batch_expired", "message": "This request could not be executed before the completion window expired."}}