Skip to main content

AI and machine learning · Intermediate · 17 min

Process thousands of prompts at half price with the Message Batches API

By Padding · Updated 18 Nov 2026
Python 3.15 · anthropic SDK 2.14.0 · Claude Haiku 5.5

You will tag 2,000 product reviews with Claude Haiku 5.5 through the Message Batches API, match results by custom_id, retry only the requests that failed or expired, and finish with a script you can stop and resume.

On this page

Some jobs do not need an answer now. Tagging last month's reviews, summarising a backlog of support tickets or scoring a test set overnight can wait an hour, and for that kind of work Anthropic's Message Batches API charges half the normal price. You send up to 100,000 Messages requests in one call, Anthropic works through them in the background, and you collect the results later. Most batches finish within an hour. A batch that is still running after 24 hours expires, and any request not yet processed comes back as expired.

Batches change how you write the code. There is no reply to wait for, so you need a way to find a batch again after your script stops. Results arrive in any order, so you match them to inputs by an ID you choose. Some requests fail or expire while others succeed, so you retry only those. This tutorial builds that, step by step, in ~/batch-demo.

The example data is 2,000 reviews from an online clothes shop that sells in several countries. Some reviews are in English, some in Nigerian Pidgin, French or Swahili, and two are blank, as real exports often are. Each review gets one of six tags: delivery, quality, price, customer_service, sizing or other. The model is claude-haiku-5-5, Anthropic's cheapest current model, which suits short classification work.

Batching also suits patchy power and prepaid data. Once the batch is submitted, the work happens on Anthropic's side. Your laptop can sleep or lose its connection, and the script you write here picks up where it left off.

Step 1 · Create the project and load your key

Load the key you saved in the earlier tutorial into this terminal. set -a exports every variable the file defines, so the SDK can read ANTHROPIC_API_KEY:

Bash
set -a
. ~/.config/llm-demo/env
set +a

Create the project and add the SDK at the exact version this tutorial uses:

Bash
mkdir -p ~/batch-demo
cd ~/batch-demo
uv init --no-package
uv add "anthropic==2.14.0"

Check it worked

Bash
uv run python -c "import anthropic; print(anthropic.__version__)"

The command prints 2.14.0. If it fails with an import error, check that you are inside ~/batch-demo.

Step 2 · Make 2,000 sample reviews

You need input data. If you have your own reviews, save them as reviews.jsonl with one JSON object per line and the fields id and text, and skip to the next step. Otherwise, generate a sample. Create make_reviews.py:

Bash
cat > make_reviews.py <<'PY'
import json
import random

rng = random.Random(2026)
CITIES = ["Lagos", "Nairobi", "Accra", "Kigali", "Abidjan", "Manchester", "Johannesburg"]
TEMPLATES = [
    "The parcel arrived {d} days late and the box was crushed.",
    "Delivery to {city} took {d} days, much longer than promised.",
    "Dem deliver am {d} days late, I no happy at all.",
    "La livraison a pris {d} jours de plus que prévu.",
    "The stitching came apart after {d} washes.",
    "Good quality fabric, it still looks new after {d} months.",
    "Ubora ni mzuri sana, nimeitumia kwa miezi {d}.",
    "Fair price for what you get, cheaper than the shops in {city}.",
    "Too expensive compared with the market in {city}.",
    "Bei ni nzuri, nitanunua tena.",
    "Customer service answered my WhatsApp message in {d} minutes.",
    "Nobody from support replied for {d} days.",
    "I ordered a medium but it fits like a small.",
    "The size chart was accurate and the dress fits well.",
    "Le pantalon est trop petit, prenez une taille au-dessus.",
    "Bought it as a gift for my sister in {city}.",
    "I have not opened it yet.",
]

with open("reviews.jsonl", "w", encoding="utf-8") as f:
    for n in range(1, 2001):
        if n in (500, 1500):
            text = "   "
        else:
            text = rng.choice(TEMPLATES).format(d=rng.randint(2, 9), city=rng.choice(CITIES))
        f.write(json.dumps({"id": f"rev-{n:05d}", "text": text}, ensure_ascii=False) + "\n")
print("wrote 2000 reviews to reviews.jsonl")
PY
uv run make_reviews.py

Reviews 500 and 1500 are blank on purpose. A later step shows what a batch does with a request that cannot work.

Check it worked

Bash
wc -l reviews.jsonl
head -n 3 reviews.jsonl

wc reports 2000 reviews.jsonl, and the first lines look like {"id": "rev-00001", "text": "..."}. French and Swahili text keeps its accents and letters because the script writes UTF-8 with ensure_ascii=False.

Step 3 · Build the batch requests

Each item in a batch has two parts. custom_id is your own label for the request, and it is the only reliable way to match a result to its input. It must be 1 to 64 characters of letters, digits, hyphens and underscores, and unique within the batch. params is exactly what you would pass to messages.create().

Create build.py, which turns reviews into requests and checks them against the documented batch limits of 100,000 requests and 256 MB:

Bash
cat > build.py <<'PY'
import json
import re

MODEL = "claude-haiku-5-5"
TAGS = ["delivery", "quality", "price", "customer_service", "sizing", "other"]
SYSTEM = (
    "You tag customer reviews for an online clothes shop. Reviews can be in any language, "
    "including English, Nigerian Pidgin, French and Swahili. Reply with exactly one tag "
    "from this list and nothing else: " + ", ".join(TAGS) + "."
)
CUSTOM_ID = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")
MAX_REQUESTS = 100_000
MAX_BYTES = 256_000_000


def load_reviews(path="reviews.jsonl"):
    with open(path, encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def build_request(review):
    custom_id = review["id"]
    if not CUSTOM_ID.match(custom_id):
        raise ValueError(f"{custom_id!r} cannot be a custom_id: use 1-64 letters, digits, - or _")
    return {
        "custom_id": custom_id,
        "params": {
            "model": MODEL,
            "max_tokens": 1024,
            "output_config": {"effort": "low"},
            "system": SYSTEM,
            "messages": [{"role": "user", "content": review["text"]}],
        },
    }


def check_limits(requests):
    ids = [r["custom_id"] for r in requests]
    if len(set(ids)) != len(ids):
        raise ValueError("custom_id values must be unique within a batch")
    if len(requests) > MAX_REQUESTS:
        raise ValueError(f"{len(requests)} requests: split them into batches of {MAX_REQUESTS} or fewer")
    size = len(json.dumps({"requests": requests}).encode())
    if size > MAX_BYTES:
        raise ValueError(f"{size} bytes: split the requests into smaller batches")
    return size


if __name__ == "__main__":
    requests = [build_request(r) for r in load_reviews()]
    size = check_limits(requests)
    print(json.dumps(requests[0], indent=2, ensure_ascii=False))
    print(f"{len(requests)} requests, {size / 1_000_000:.1f} MB, within the batch limits")
PY
uv run build.py

A few choices in params matter:

  • Claude Haiku 5.5 thinks before it answers by default, and thinking tokens count towards max_tokens and are billed as output. output_config={"effort": "low"} keeps that short for a simple task, and max_tokens=1024 leaves room for thinking plus a one-word answer.
  • The system prompt is the same in every request, so you can add prompt caching to it once your prompts are long enough to cache. The tutorial on prompt caching covers that.
  • Your own review IDs may contain characters custom_id does not allow, such as # or /. In that case give each review a safe ID, such as its line number, and keep a map back to the original.

Some parameters are refused inside a batch: stream, fast mode's speed, fallbacks and max_tokens: 0.

Check it worked

The script prints the first request as JSON, with "custom_id": "rev-00001" and the review text in messages, then a line like 2000 requests, 1.0 MB, within the batch limits.

Step 4 · Submit a 20-review trial batch

Before you send 2,000 requests, send 20. A trial batch costs almost nothing and shows whether the prompt and your code work. Create jobs.py with two functions, one that submits a batch and one that waits for it to end:

Bash
cat > jobs.py <<'PY'
import os
import time

POLL_SECONDS = float(os.environ.get("POLL_SECONDS", "60"))


def submit(client, requests):
    batch = client.messages.batches.create(requests=requests)
    print(f"submitted {batch.id}: {len(requests)} requests, {batch.processing_status}, expires {batch.expires_at}")
    return batch


def wait_for_end(client, batch_id):
    while True:
        batch = client.messages.batches.retrieve(batch_id)
        c = batch.request_counts
        print(
            f"  {batch.processing_status}: {c.processing} processing, {c.succeeded} succeeded, "
            f"{c.errored} errored, {c.expired} expired, {c.canceled} canceled",
            flush=True,
        )
        if batch.processing_status == "ended":
            return batch
        time.sleep(POLL_SECONDS)
PY

processing_status starts as in_progress and becomes ended once every request has a result. (It shows canceling for a while if you cancel a batch.) request_counts tells you how many requests are still processing and how many have each result. Checking once a minute is plenty: each check is a small request, and the batch will not finish faster if you ask more often.

Now create trial.py, which submits the first 20 reviews, saves the batch ID to a file and waits:

Bash
cat > trial.py <<'PY'
import anthropic

from build import build_request, check_limits, load_reviews
from jobs import submit, wait_for_end

client = anthropic.Anthropic()
requests = [build_request(r) for r in load_reviews()[:20]]
check_limits(requests)
batch = submit(client, requests)
with open("trial-batch-id.txt", "w") as f:
    f.write(batch.id + "\n")
wait_for_end(client, batch.id)
PY

Run it:

Bash
uv run trial.py

The batch ID is written to disk straight away, before the wait. If the script stops, the batch carries on without it, and the ID is how you find it again.

Check it worked

You see a submitted msgbatch_... line, then one in_progress line a minute, then a final line such as ended: 0 processing, 20 succeeded, 0 errored, 0 expired, 0 canceled. A small batch often ends within a few minutes, but it can take longer when the API is busy. trial-batch-id.txt holds the ID.

Step 5 · Read the results and match them by custom_id

client.messages.batches.results() streams the results file one line at a time, so even a large batch never has to fit in memory. Each item has a custom_id and a result whose type is one of four values:

  • succeeded: result.message is a normal Message, the same as messages.create() returns.
  • errored: no message was made. result.error.error.type says why. invalid_request_error means the request itself is wrong, and sending it again will fail again. Other types, such as api_error, are worth retrying.
  • expired: the batch reached its 24 hours before this request was processed.
  • canceled: you cancelled the batch before this request was processed.

You are not billed for errored, expired or cancelled requests. Batch requests are also validated after you submit them, so a request with a mistake is accepted at first and only reported as errored once the whole batch ends.

Create results.py. It saves each finished request to one of two JSON Lines files and leaves anything worth retrying unsaved:

Bash
cat > results.py <<'PY'
import json
from collections import Counter

from build import TAGS


def read_jsonl(path):
    try:
        f = open(path, encoding="utf-8")
    except FileNotFoundError:
        return []
    rows = []
    with f:
        for line in f:
            try:
                rows.append(json.loads(line))
            except json.JSONDecodeError:
                pass  # a last line cut short when the script was stopped
    return rows


def load_done(*paths):
    return {row["custom_id"] for path in paths for row in read_jsonl(path)}


def parse_tag(text):
    word = text.strip().strip(".").lower()
    return word if word in TAGS else None


def write(f, row):
    f.write(json.dumps(row, ensure_ascii=False) + "\n")
    f.flush()


def collect(client, batch_id, labels_path, problems_path):
    done = load_done(labels_path, problems_path)
    counts = Counter()
    with open(labels_path, "a", encoding="utf-8") as labels, open(problems_path, "a", encoding="utf-8") as problems:
        for item in client.messages.batches.results(batch_id):
            cid, outcome = item.custom_id, item.result
            if cid in done:
                counts["already saved"] += 1
            elif outcome.type == "succeeded":
                msg = outcome.message
                usage = {"input_tokens": msg.usage.input_tokens, "output_tokens": msg.usage.output_tokens}
                text = next((b.text for b in msg.content if b.type == "text"), None)
                tag = parse_tag(text) if text else None
                if tag:
                    write(labels, {"custom_id": cid, "tag": tag, **usage})
                    counts["tagged"] += 1
                else:
                    write(problems, {"custom_id": cid, "problem": "no tag", "stop_reason": msg.stop_reason, "text": text, **usage})
                    counts["no tag"] += 1
            elif outcome.type == "errored" and outcome.error.error.type == "invalid_request_error":
                write(problems, {"custom_id": cid, "problem": "invalid request", "message": outcome.error.error.message})
                counts["invalid request"] += 1
            else:
                counts[f"retry ({outcome.type})"] += 1
    return counts
PY

Two cases end up in problems. An invalid request needs you to fix the input. A message with no usable tag usually stopped at max_tokens before writing any text, because thinking used the whole allowance, or replied with something outside the tag list. Neither gets better by sending the same request again, so neither is retried. Both lines keep the token counts, because those requests were billed.

Try it on the trial batch. Create trial_results.py, which first prints the order the results arrive in, then collects them:

Bash
cat > trial_results.py <<'PY'
import anthropic

from results import collect, read_jsonl

client = anthropic.Anthropic()
batch_id = open("trial-batch-id.txt").read().strip()

order = [item.custom_id for item in client.messages.batches.results(batch_id)]
print("first five results:", ", ".join(order[:5]))

counts = collect(client, batch_id, "trial-labels.jsonl", "trial-problems.jsonl")
print(dict(sorted(counts.items())))
for row in read_jsonl("trial-labels.jsonl")[:5]:
    print(f"  {row['custom_id']}: {row['tag']}")
PY

Run it:

Bash
uv run trial_results.py

Check it worked

The first line lists five IDs that are not rev-00001 to rev-00005 in order: results come back in any order, which is why the code never relies on position. The counts look something like {'tagged': 20}. When a request errors or expires you see a retry (errored) or retry (expired) count as well. Run the script a second time and every result shows as already saved, so collecting the same batch twice writes nothing twice.

Step 6 · Write the resumable script

The full run puts the pieces in a loop. Each round submits every review that has no saved tag and no recorded problem, waits, and collects. Requests that errored for a retryable reason or expired stay unsaved, so the next round picks them up and nothing else is sent twice. After three rounds the script stops, so a problem that keeps failing cannot loop forever.

What makes it resumable is state.json. It holds the ID of the batch in progress, and it is written before the script starts waiting. If the script stops, the next run reads the ID and follows that batch instead of submitting a new one. The file is written to a temporary name and then renamed, so a stop halfway through a write cannot leave it broken.

Create tag_reviews.py:

Bash
cat > tag_reviews.py <<'PY'
import json
import os
import sys
from pathlib import Path

import anthropic

from build import build_request, check_limits, load_reviews
from jobs import submit, wait_for_end
from results import collect, load_done

STATE = Path("state.json")
LABELS, PROBLEMS = "labels.jsonl", "problems.jsonl"
MAX_ROUNDS = 3


def load_state():
    if STATE.exists():
        return json.loads(STATE.read_text())
    return {"batch_id": None, "round": 0}


def save_state(state):
    tmp = STATE.with_name("state.json.tmp")
    tmp.write_text(json.dumps(state))
    os.replace(tmp, STATE)


def main():
    client = anthropic.Anthropic()
    reviews = load_reviews()
    state = load_state()
    while True:
        if state["batch_id"]:
            print(f"round {state['round']}: following batch {state['batch_id']}")
        else:
            done = load_done(LABELS, PROBLEMS)
            pending = [r for r in reviews if r["id"] not in done]
            if not pending:
                print("finished: every review has a tag or a recorded problem")
                return
            if state["round"] >= MAX_ROUNDS:
                print(f"stopped after {MAX_ROUNDS} rounds with {len(pending)} reviews still untagged")
                return
            requests = [build_request(r) for r in pending]
            check_limits(requests)
            batch = submit(client, requests)
            state = {"batch_id": batch.id, "round": state["round"] + 1}
            save_state(state)
            print(f"round {state['round']}: saved batch {batch.id} to {STATE}")
        wait_for_end(client, state["batch_id"])
        counts = collect(client, state["batch_id"], LABELS, PROBLEMS)
        print("  results: " + ", ".join(f"{k} {v}" for k, v in sorted(counts.items())))
        state["batch_id"] = None
        save_state(state)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nstopped; run the script again to carry on where it left off")
        sys.exit(130)
PY

The script can stop at three points, and each is safe:

  • While waiting: the batch ID is in state.json, so the next run follows the same batch.
  • While collecting: tags already written are skipped next time, because collect checks custom_id against the saved files. A half-written last line is ignored when the files are read back.
  • Between create() returning and save_state() finishing: this window is a fraction of a second, but if the script dies inside it, a batch runs that state.json does not know about. If you ever see a batch you did not expect, find it in the Batches page of the Claude Console, or with client.messages.batches.list(), before running again.

Check it worked

Bash
uv run python -c "import tag_reviews; print(tag_reviews.load_state())"

The command prints {'batch_id': None, 'round': 0}, because no state.json exists yet. Importing the module does not start a run, because main() only runs when you start the file as a script.

Step 7 · Run it, stop it and resume

Start the full run. When the first in_progress line appears, press Ctrl+C:

Bash
uv run tag_reviews.py

The script prints stopped; run the script again to carry on where it left off. Look at the state file:

Bash
cat state.json

It holds the batch ID and "round": 1. The batch is still running on Anthropic's side. Run the script again:

Bash
uv run tag_reviews.py | tee run.log

Check it worked

The second run starts with round 1: following batch msgbatch_..., the same ID as in state.json, and does not submit a new batch. When the round ends, the results line looks something like results: invalid request 2, no tag 1, retry (errored) 20, retry (expired) 13, tagged 1964. Your counts differ, and most real runs show few or no retries. When nothing needs a retry, the run ends after one round. Any retries go out in round 2 as a smaller batch containing only those reviews, and the run ends with finished: every review has a tag or a recorded problem.

Step 8 · Check the tags and the cost

A finished batch is not a correct batch. Before anyone uses these tags, read some of them yourself. Create report.py, which counts the tags, lists the problems, adds up the tokens and prints ten random reviews for you to check:

Bash
cat > report.py <<'PY'
import random
from collections import Counter

from build import load_reviews
from results import read_jsonl

# Claude Haiku 5.5 batch prices in US dollars per million tokens, for prompts up to
# 100,000 tokens, from Anthropic's batch processing page on 26 November 2026.
# Check the page for current prices before you rely on these.
BATCH_INPUT, BATCH_OUTPUT = 0.05, 0.25

texts = {r["id"]: r["text"] for r in load_reviews()}
labels = read_jsonl("labels.jsonl")
problems = read_jsonl("problems.jsonl")

print("tags:", ", ".join(f"{tag} {n}" for tag, n in Counter(r["tag"] for r in labels).most_common()))
for p in problems:
    print(f"problem: {p['custom_id']}: {p['problem']} ({p.get('stop_reason') or p.get('message')})")

tokens_in = sum(r.get("input_tokens", 0) for r in labels + problems)
tokens_out = sum(r.get("output_tokens", 0) for r in labels + problems)
cost = tokens_in / 1e6 * BATCH_INPUT + tokens_out / 1e6 * BATCH_OUTPUT
print(f"{tokens_in} input and {tokens_out} output tokens: about ${cost:.4f} at batch prices, ${cost * 2:.4f} without the discount")

print("\nRead these ten and note any tag you disagree with:")
for r in random.Random(1).sample(labels, 10):
    print(f"  {r['tag']:<17} {texts[r['custom_id']]}")
PY
uv run report.py

Output tokens include thinking, so they are higher than a one-word answer suggests. Requests that errored or expired do not appear in the totals, because they were not billed.

Read the ten reviews and their tags. If you disagree with more than one, do not just rerun the batch. Change the system prompt in build.py, for example by describing each tag in a sentence, then run the 20-review trial again and read the trial results before you run the full set. For anything that feeds a decision, such as which supplier to drop, check a larger sample by hand and keep a record of how many you checked and how many were wrong.

The two blank reviews show up as invalid request problems: fix or remove them in your data. A no tag problem with stop reason max_tokens means thinking used the whole allowance. If you see many, raise max_tokens, or turn thinking off by adding thinking={"type": "disabled"} to each request in build.py, which Claude Haiku 5.5 accepts at low effort. A no tag problem whose reply is a word outside the list needs a tighter prompt instead.

Check it worked

The script prints a tags: line with counts for the six tags, two problem: lines for rev-00500 and rev-01500 (invalid request), plus a no tag line for any reply that stopped at max_tokens or used a word outside the list, a cost line such as ... about $0.0350 at batch prices, $0.0700 without the discount, and ten tagged reviews. Your token counts and cost come from your own run and will differ.

When you have finished with the example, delete the project folder. Batches and their results stay in your Claude Console workspace until their results expire after 29 days:

Bash
rm -rf ~/batch-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.