夜間 LLM 任務使用批次 API,可節省 50% 成本
Your nightly LLM jobs don't need real-time prices: run them through the Batch API for 50% off (Monday AI Insight)
文章比較 OpenAI、Anthropic 和 Google 的批次 API,指出三者都以標準 API 價格的 50% 處理非即時 LLM 工作。文中以 OpenAI 示範建立 JSONL 批次請求,並提醒結果可能亂序,須按 custom_id 配對,只重試失敗項目。評測、回填、嵌入向量和大型數據集分類適合批次處理;即時對話及需要串流或即時前置結果的工作則不適用,各平台亦有不同配額與逾期規則。
Monday AI Insight. One practical cost lesson: if nobody is waiting for the answer, don't pay real-time prices for it. Eval runs, backfills, re-embedding a corpus, classifying a big dataset, nightly summaries: these jobs usually go through the same synchronous endpoint your chat UI uses, one request at a time, fighting your per-minute rate limits. OpenAI, Anthropic and Google all offer a batch mode for exactly this work, and all three price it at half the standard rate.
What the docs actually promise
OpenAI Batch API. OpenAI's guide lists a 50% cost discount compared to synchronous APIs, substantially more rate-limit headroom, and a 24-hour completion window ("and often more quickly"). completion_window can currently only be set to 24h. Supported endpoints include /v1/responses, /v1/chat/completions, /v1/embeddings, /v1/completions and /v1/moderations. The guide's own example use cases: running evaluations, classifying large datasets, and embedding content repositories.
Anthropic Message Batches API. All usage is charged at 50 percent of standard API prices. Most batches finish in less than 1 hour; batches that don't finish processing within 24 hours expire. Almost any Messages API request can go in a batch (vision, tool use, system messages, multi-turn, extended thinking), and you can mix request types in one batch. stream: true is not supported.
Google Gemini Batch API. Also 50% of the standard interactive cost, with a target turnaround of 24 hours ("in majority of cases, it is much quicker"). You can send inline requests (total request size under 20MB) or a JSONL input file of up to 2GB.
How it works (OpenAI flavour)
- Write a
.jsonlfile: one request per line, each with a uniquecustom_id,method,urlandbody. Thebodyis the same as the parameters for the normal endpoint. One input file can only contain requests to a single model. - Upload it with the Files API using
purpose="batch". - Create the batch with the file ID, endpoint and
completion_window="24h". - Poll the status:
validating,in_progress,finalizing,completed(orfailed,expired,cancelling,cancelled). - Download
output_file_idfor successes anderror_file_idfor failures.
Anthropic uses the same idea with a slightly different shape: you send a list of requests, each with a custom_id (1 to 64 characters, letters, digits, hyphens and underscores) and normal Messages params. Gemini uses a user-defined key per line instead of custom_id.
The rule that bites everyone: results are not in order
OpenAI: "the output line order may not match the input line order." Anthropic: batch results "can be returned in any order." Never zip inputs and outputs by position. Match on custom_id, and make it something meaningful, like eval-42 or doc-8812-chunk-3, so a result points straight back to its source row.
A short Python example
import json
from openai import OpenAI
client = OpenAI()
MODEL = "gpt-6-luna" # any Batch-supported model; one model per input file
tickets = {"t-101": "App crashes on login", "t-102": "Refund not received"}
# 1) Build the JSONL: one request per line, unique custom_id
with open("batch_input.jsonl", "w") as f:
for tid, text in tickets.items():
f.write(json.dumps({
"custom_id": tid,
"method": "POST",
"url": "/v1/responses",
"body": {"model": MODEL,
"input": f"Label as bug, billing or other: {text}",
"max_output_tokens": 16},
}) + "\n")
# 2) Upload + create the batch
f = client.files.create(file=open("batch_input.jsonl", "rb"), purpose="batch")
batch = client.batches.create(input_file_id=f.id, endpoint="/v1/responses",
completion_window="24h",
metadata={"job": "nightly-ticket-labels"})
# 3) Later, after polling client.batches.retrieve(batch.id) until a final status:
def read_jsonl(file_id):
if not file_id:
return []
return [json.loads(l) for l in client.files.content(file_id).text.splitlines() if l]
batch = client.batches.retrieve(batch.id)
results, failed = {}, []
for row in read_jsonl(batch.output_file_id) + read_jsonl(batch.error_file_id):
resp = row.get("response")
if row.get("error") or not resp or resp["status_code"] != 200:
failed.append(row["custom_id"])
continue
body = resp["body"]
text = "".join(c["text"] for o in body["output"] if o["type"] == "message"
for c in o["content"] if c["type"] == "output_text")
results[row["custom_id"]] = text # matched by custom_id, not by position
# Anything we sent but never got back also needs a retry
failed += [tid for tid in tickets if tid not in results and tid not in failed]
print(results, "retry:", failed)
Partial failures and expiry: retry only what failed
A batch is not all-or-nothing:
-
OpenAI: the output file has one line per successful request; failures go to the error file. If a batch doesn't finish in the window it moves to
expired: unfinished requests are cancelled, completed responses are still in the output file, and you are charged for tokens from completed requests. Expired requests appear in the error file with codebatch_expired, and you can use theircustom_idto find the original request. -
Anthropic: each result is
succeeded,errored,canceledorexpired. You aren't billed for errored, canceled or expired requests. The docs' own example draws a useful line: aninvalid_request_errormeans the request body must be fixed before re-sending; other errors can be retried directly. -
Gemini: check
batchStatsforfailedRequestCount, and parse each output line to see whether it's a response or an error status. Batch creation is not idempotent: sending the same create request twice creates two jobs. A job pending or running for more than 48 hours expires with no results.
So the retry loop is simple: collect the custom_ids that didn't succeed, rebuild a smaller JSONL from your source rows, and submit only that.
Limits to plan around
-
OpenAI: up to 50,000 requests per batch and a 200 MB input file (
/v1/embeddingsbatches are also capped at 50,000 embedding inputs). Queued input tokens per model are limited separately, and you can create up to 2,000 batches per hour. Batch jobs don't count toward your standard per-model request or token rate limits. Output and error files expire 30 days after creation by default. - Anthropic: up to 100,000 requests or 256 MB per batch, whichever comes first. Results are downloadable for 29 days. Rate limits apply both to batch API calls and to requests waiting to be processed, and under heavy demand more requests may expire after 24 hours.
- Gemini: 2GB per input file; inline requests must stay under 20MB total.
Stack it with prompt caching
Anthropic says prompt caching discounts and batch discounts stack, but cache hits in a batch are best-effort because requests run concurrently and in any order. Their tips: put identical cache_control blocks in every request, share as much prefix as possible, and since batches can take longer than 5 minutes, consider the 1-hour cache duration. Gemini supports context caching in batch requests via cached_content; cache hits are billed at standard context caching rates. For an eval set where every request shares the same long system prompt and rubric, that's a big chunk of input you stop paying full price for.
When NOT to use batch
- Anything a user is waiting on. Chat replies, autocomplete, agent steps in a live session. The contract is "within 24 hours", not seconds.
-
Streaming. Anthropic rejects
stream: truein a batch because results come back as a single file, not a stream; OpenAI's batch worker rejects it for moderations too. - Chains where step 2 needs step 1 right now. Every hop becomes a potential day-long wait. Batch each stage separately, or keep the chain synchronous.
- Tiny jobs you need in minutes. "Most batches finish in less than 1 hour" (Anthropic) is a typical case, not a guarantee.
- Zero data retention requirements on Anthropic. Anthropic lists batch processing as not eligible for ZDR; inputs and outputs are stored for up to 29 days.
Checklist
- List your jobs where nobody is waiting: evals, backfills, embeddings, classification, nightly reports.
- Give every request a meaningful, unique
custom_id(orkeyon Gemini). - Match results by ID, never by line order.
- Read the error file too, then resubmit only failed and expired IDs.
- Keep shared prefixes identical so prompt caching can help (Anthropic, Gemini).
- Keep user-facing and latency-sensitive calls on the real-time API.
Takeaway: the same model, the same prompt, half the price, as long as you can wait. Most teams have more "can wait" traffic than they think.
Which of your LLM jobs could move to batch tomorrow: evals, embeddings, or nightly summaries?
References
- OpenAI docs, Batch API guide: https://platform.openai.com/docs/guides/batch
- Anthropic docs, Batch processing (Message Batches API, pricing, prompt caching with batches): https://docs.claude.com/en/docs/build-with-claude/batch-processing
- Google AI for Developers, Gemini Batch API: https://ai.google.dev/gemini-api/docs/batch-mode
- My earlier post in this series:
- Your embedding model is a schema decision: https://dev.to/m_t_ramkrushna/your-embedding-model-is-a-schema-decision-how-to-choose-it-and-plan-the-re-embed-23mo
來源:DEV Community · dev.to