使用 OpenAI 的 Batch API,您可以成批提交异步请求,费用比同步请求低 50%。排队 Token 的上限独立于每分钟的速率限制,每个批次在 24 小时内完成。这项服务适合处理无需立即获得响应的作业。您也可以直接查阅 API 参考文档。
在 OpenAI 平台上,有些场景需要发送同步请求,但很多请求无需立即获得响应。有时,速率限制也会让您无法在短时间内执行大量查询。批处理作业通常适用于以下场景:
- 运行评估
- 对大型数据集进行分类
- 为内容库中的内容生成嵌入向量
Batch API 提供了一组易于使用的端点。您可以将多个请求写入同一个文件,然后启动批处理作业来执行这些请求。在请求执行期间,您可以查询批次状态,并在批次完成后获取汇总结果。
与直接使用标准端点相比,Batch API 具有以下优势:
- 成本更低:费用比同步 API 低 50%。
- 速率限制更高:相比同步 API,可用配额大幅增加。
- 完成速度快:每个批次都会在 24 小时内完成,通常用时更短。
首先准备一个 .jsonl 文件,每行包含一个 API 请求的详细信息。目前可用的端点如下:
输入文件中每行 body 字段的参数与对应端点的参数相同。每个请求必须包含唯一的 custom_id 值,您可以在批次完成后用它查找对应的结果。下面的输入文件示例包含 2 个请求。同一个输入文件中的所有请求必须使用同一个模型。
向 /v1/moderations 发送请求时,每个请求体都必须包含 input 字段。使用 omni-moderation-latest 时,批处理支持纯文本输入,也支持包含文本或图像输入的内容数组。与同步审核端点一样,批处理服务会拒绝设置了 stream=true 的请求。
Batch API 不支持 omni-moderation-csam-latest。获批的组织可以通过同步请求调用 CSAM 分类器。
{"custom_id": "request-1", "method": "POST", "url": "/v1/responses", "body": {"model": "gpt-6-luna", "input": "请回复单词 blue。", "reasoning": {"effort": "none"}, "max_output_tokens": 64}}
{"custom_id": "request-2", "method": "POST", "url": "/v1/responses", "body": {"model": "gpt-6-luna", "input": "请回复单词 green。", "reasoning": {"effort": "none"}, "max_output_tokens": 64}}
以下输入文件的第一行是纯文本请求,第二行是同时包含文本和图像输入的请求:
{"custom_id": "moderation-text-1", "method": "POST", "url": "/v1/moderations", "body": {"model": "omni-moderation-latest", "input": "这是一句无害的测试文本。"}}
{"custom_id": "moderation-mm-1", "method": "POST", "url": "/v1/moderations", "body": {"model": "omni-moderation-latest", "input": [{"type": "text", "text": "请描述这张图像"}, {"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.2 Astra 和 GPT-6.2 Sol 在 Batch 处理模式下支持美国和欧盟的数据驻留。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 有三类限制:
- 单个批次的限制:每个批次最多可包含 50,000 个请求,批次输入文件最大为 200 MB。对于
/v1/embeddings 批次,所有请求合计最多可包含 50,000 个嵌入输入项。
- 每个模型的排队输入 Token 上限:Batch API 作业与完成时限为
2h 或 8h 的后台模式请求共用批处理和后台模式的速率限制。API 在提交时统计输入 Token 数。您可以在 Settings > Organization > Limits 中查看限额。
- 批次创建速率限制:每小时最多可创建 2,000 个批次。如果需要提交更多请求,请增加每个批次中的请求数。
Batch API 目前对输出 Token 数没有限制。Batch 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."}}