The goal
You have a file of 5,000 tickets, documents or rows to classify or summarise. A plain for loop takes hours. Firing all 5,000 requests at once gets you a wall of 429s and a half-finished run you can't restart cleanly.
What you want is a script that:
- Runs a fixed number of requests at the same time (for example 8 or 16).
- Retries 429 and 5xx errors with backoff, and gives up on bad requests.
- Writes each result to disk as soon as it arrives.
- Skips items that are already done when you start it again.
If the results aren't needed for hours, use your provider's batch API instead; it's cheaper and doesn't touch your real-time quota. This post is for jobs you need done in the next hour or so.
Input and output format
Use JSON Lines for both. Each input line has a stable id:
{"id": "INC-100231", "text": "VPN drops every 20 minutes since the client update"}
{"id": "INC-100232", "text": "Cannot open the finance share from the Leeds office"}
Each output line has the same id, plus either a result or an error. The id is what makes the run resumable: on restart the script reads the output file and skips any id that already has a result.
The script
# bulk_llm.py
import asyncio, json, os, sys, time
from openai import AsyncOpenAI, APIStatusError, APIConnectionError, APITimeoutError, RateLimitError
MODEL = os.environ.get("LLM_MODEL", "gpt-4o-mini") # Azure: your deployment name
CONCURRENCY = int(os.environ.get("LLM_CONCURRENCY", "8"))
MAX_ATTEMPTS = 6
# OpenAI: reads OPENAI_API_KEY. For Azure OpenAI or vLLM, set base_url to
# https://<resource>.openai.azure.com/openai/v1/ or http://vllm:8000/v1
client = AsyncOpenAI(
base_url=os.environ.get("LLM_BASE_URL"), # None = default OpenAI endpoint
timeout=60, # per-request timeout in seconds
max_retries=0, # we retry ourselves, so the SDK doesn't multiply attempts
)
SYSTEM = "Classify the IT ticket. Reply with one word: network, access, hardware, software or other."
def load_done(path):
done = set()
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
for line in f:
try:
rec = json.loads(line)
except json.JSONDecodeError:
continue # partial last line after a crash
if "result" in rec:
done.add(rec["id"])
return done
async def call_llm(text):
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
resp = await client.chat.completions.create(
model=MODEL,
messages=[{"role": "system", "content": SYSTEM},
{"role": "user", "content": text}],
max_tokens=10,
temperature=0,
)
return resp.choices[0].message.content.strip(), resp.usage.total_tokens
except RateLimitError as e:
retry_after = e.response.headers.get("retry-after")
wait = float(retry_after) if retry_after else min(2 ** attempt, 60)
except (APITimeoutError, APIConnectionError):
wait = min(2 ** attempt, 60)
except APIStatusError as e:
if e.status_code >= 500:
wait = min(2 ** attempt, 60)
else:
raise # 400, 401, 403, 404: retrying won't help
if attempt == MAX_ATTEMPTS:
raise RuntimeError(f"gave up after {MAX_ATTEMPTS} attempts")
await asyncio.sleep(wait + (0.5 * attempt)) # small spread so workers don't retry in lockstep
async def worker(name, queue, out, stats):
while True:
item = await queue.get()
try:
result, tokens = await call_llm(item["text"])
rec = {"id": item["id"], "result": result, "tokens": tokens}
stats["ok"] += 1
stats["tokens"] += tokens
except Exception as e:
rec = {"id": item["id"], "error": f"{type(e).__name__}: {e}"[:500]}
stats["failed"] += 1
out.write(json.dumps(rec, ensure_ascii=False) + "\n")
out.flush()
queue.task_done()
async def main(in_path, out_path):
done = load_done(out_path)
queue = asyncio.Queue(maxsize=CONCURRENCY * 4)
stats = {"ok": 0, "failed": 0, "skipped": 0, "tokens": 0}
start = time.monotonic()
with open(out_path, "a", encoding="utf-8") as out:
workers = [asyncio.create_task(worker(i, queue, out, stats)) for i in range(CONCURRENCY)]
with open(in_path, encoding="utf-8") as f:
for n, line in enumerate(f, 1):
item = json.loads(line)
if item["id"] in done:
stats["skipped"] += 1
continue
await queue.put(item) # blocks when the queue is full
if n % 200 == 0:
rate = stats["ok"] / max(time.monotonic() - start, 1) * 60
print(f"read={n} {stats} ~{rate:.0f}/min", file=sys.stderr)
await queue.join()
for w in workers:
w.cancel()
print(f"finished {stats} in {time.monotonic() - start:.0f}s", file=sys.stderr)
if __name__ == "__main__":
asyncio.run(main(sys.argv[1], sys.argv[2]))
Run it:
pip install "openai>=1.40"
export OPENAI_API_KEY=...
LLM_CONCURRENCY=8 python bulk_llm.py tickets.jsonl results.jsonl
For an OpenAI-compatible server such as vLLM, set LLM_BASE_URL=http://vllm:8000/v1, LLM_MODEL to the served model name and any non-empty OPENAI_API_KEY. For Azure OpenAI, use your resource's /openai/v1/ base URL and the deployment name as the model. Use Entra ID through a token provider if your resource has keys disabled. How URLs and authentication work differs between SDK versions, so check what your installed version supports.
Why it's built this way
A fixed pool of workers, not one task per item
Creating 5,000 tasks at once means 5,000 open requests. A fixed set of workers pulling from a bounded asyncio.Queue keeps exactly CONCURRENCY requests in flight and keeps memory flat, even for a million-line file. The maxsize on the queue stops the reader from loading the whole file ahead of the workers.
One retry layer
The SDK retries some errors by default. If your code retries too, one failing request can turn into a dozen. Setting max_retries=0 and retrying in one place makes the attempt count predictable. When a 429 includes retry-after, wait that long; otherwise back off exponentially.
Write as you go
Each result is flushed to disk as soon as it comes back. If the process is killed at item 3,400, you lose at most the requests that were in flight. On restart, load_done skips everything that already has a result, so you don't pay for those tokens again. Lines with error are retried on the next run.
Warning
Only use this pattern for calls with no side effects, such as classification, extraction and summaries. If the model output triggers actions (emails, tickets, writes), a resumed run can repeat them. Record each completed action under its
idand check that record before acting.
Choosing the concurrency
Your limits are in tokens per minute (TPM) and requests per minute (RPM), not in concurrent requests. Estimate it:
requests per minute per worker ≈ 60 / average latency in seconds
tokens per minute ≈ workers × requests per minute per worker × average tokens per request
With 2-second calls and 600 tokens each, one worker uses about 18,000 TPM. A 150,000 TPM deployment can take about 8 workers before 429s start. Start below the estimate, watch the progress line, and raise it until 429 retries begin to appear. Then step back one notch.
Caution
If this job shares a deployment or API key with production traffic, it will use up the same quota and production users will get 429s. Run bulk jobs against a separate deployment or key with its own limit, or outside business hours.
Symptoms and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
Lots of RateLimitError retries, throughput flat | Concurrency above your TPM/RPM | Lower LLM_CONCURRENCY; cut max_tokens |
Every item fails with BadRequestError | Wrong model or deployment name, or a parameter the model rejects | Test one call with curl first; read the error message |
NotFoundError on Azure OpenAI | Deployment name or base URL wrong | Use the deployment name, not the model name |
| Run is slow but no 429s | Concurrency too low or long outputs | Raise concurrency; ask for shorter answers |
| Output file has a broken last line | Process killed mid-write | Already handled; the line is ignored and the item reruns |
Same id appears twice in output | An item failed, then succeeded on rerun | Keep the last line with result per id when you load results |
Too many open files or connection errors at high concurrency | OS or proxy connection limits | Keep concurrency in the tens, not hundreds |
To get the final, clean result set:
# Last record per id, results only
python - <<'EOF'
import json
best = {}
for line in open("results.jsonl", encoding="utf-8"):
try: r = json.loads(line)
except json.JSONDecodeError: continue
if "result" in r: best[r["id"]] = r
print(len(best), "items with results")
json.dump(best, open("final.json", "w"), ensure_ascii=False)
EOF
Prevent it next time
- Try 20 items with
LLM_CONCURRENCY=2before the full run, and check both the answers and the tokens per item. - Multiply items by average tokens before you start, so you know the cost and how long the job will take.
- Give bulk jobs their own deployment, key or gateway product so they can't starve production quota.
- Keep
id,result,errorandtokensin every output line; it makes resumes, cost reports and spot checks easy. - For jobs that can wait hours, move them to the provider's batch API.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get