LLM API Pipeline Python: Retries, Streaming, Batches
This walkthrough builds an llm api pipeline python script step by step: one reliable call, a worker pool, a streaming stage and a log that lets a crashed run resume. Every snippet points at an OpenAI-compatible endpoint, so the official SDK works as is.

Key points
- Turn off the SDK's built-in retries and handle 429 yourself, so you can honor Retry-After.
- Size the worker pool to your key: 8 concurrent requests for a full key, 2 for a trial key.
- Write every finished record to a JSONL file as soon as it is done, so a crash costs one record, not the run.
- Read the X-Balance-USD header to stop a batch before the credit runs out.
What you need before you start
You need Python 3.9 or newer, the official openai package, and an API key. Install the package with pip install openai, then export the key so it never lands in your source code:
export SORA2APIS_KEY="your-key-here"
pip install openai
curl https://api.sora2apis.com/v1/models -H "Authorization: Bearer $SORA2APIS_KEY"
The curl line is a quick check. If the key and base URL are right, you get a JSON list that includes the model uncensored. New accounts can claim $0.50 of trial credit with one click on the API key page, which is plenty for everything below. The quickstart covers the same first request in other languages.
Keep in mind what this endpoint offers: POST /v1/chat/completions and GET /v1/models, text in and text out. A pipeline here is a pipeline of writing, rewriting and extraction steps. It will not render images, audio or video, so those stages belong to other tools that your script calls separately.
Stage one: a single call that survives errors
Every other part of the pipeline depends on this function, so write it carefully. The SDK retries on its own by default, but it does not know your limits and it hides the Retry-After header. Set max_retries=0 and do it yourself.
import os
import random
import time
from openai import (
OpenAI,
APIConnectionError,
APITimeoutError,
APIStatusError,
RateLimitError,
)
client = OpenAI(
base_url="https://api.sora2apis.com/v1",
api_key=os.environ["SORA2APIS_KEY"],
max_retries=0,
timeout=120,
)
def ask(messages, attempts=5, **kwargs):
for attempt in range(attempts):
try:
return client.chat.completions.create(
model="uncensored", messages=messages, **kwargs
)
except RateLimitError as err:
wait = float(err.response.headers.get("Retry-After", 5))
time.sleep(wait + random.random())
except (APIConnectionError, APITimeoutError):
time.sleep(min(2 ** attempt, 30) + random.random())
except APIStatusError as err:
if err.status_code >= 500:
time.sleep(min(2 ** attempt, 30) + random.random())
else:
raise
raise RuntimeError("gave up after %d attempts" % attempts)
Three ideas are packed in there. A 429 means "slow down", so the function waits for the number of seconds the server asked for, plus a little random jitter so parallel workers do not wake at the same instant. Network errors and 5xx responses get exponential backoff capped at 30 seconds. Any other 4xx, such as a malformed body, is your bug, and retrying would only repeat it, so it raises immediately.
Failed or refused requests are not charged, so a retry loop does not quietly drain your credit.
Stage two: parallel work inside your limits
Serial calls are slow, but unlimited parallelism gets you a wall of 429s. The service enforces two separate ceilings. Exceeding requests per minute returns the error code rate_limited. Exceeding simultaneous requests returns concurrency. A full key allows 8 at once and 300 per minute; a trial key allows 2 at once and 60 per minute.
A thread pool is the simplest way to stay under the concurrency number. Match max_workers to your key and the cap is enforced for free:
from concurrent.futures import ThreadPoolExecutor, as_completed
WORKERS = 8 # use 2 on a trial key
def summarize(doc):
resp = ask(
[
{"role": "system", "content": "Summarize in two sentences."},
{"role": "user", "content": doc["text"]},
],
temperature=0.3,
max_tokens=200,
)
return {"id": doc["id"], "summary": resp.choices[0].message.content}
def run(docs):
results = []
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
futures = [pool.submit(summarize, d) for d in docs]
for fut in as_completed(futures):
results.append(fut.result())
return results
Eight workers do not automatically mean 300 requests per minute. If each call takes two seconds, eight workers produce about 240 per minute, which is under the cap. If calls are very short, you could pass 300 and see rate_limited. The retry function above absorbs that, but a small time.sleep between submissions is cleaner if you run near the ceiling constantly.
Threads or asyncio
The examples use threads because they are the shortest path from a loop to a parallel loop, and the OpenAI SDK client is safe to share between threads. For a pipeline making a few thousand calls, threads are entirely adequate: each call spends nearly all its time waiting on the network, so the Python GIL does not get in the way.
Asyncio becomes the better choice when the pipeline already lives inside an async application, such as a web service handling user requests, or when you need to juggle many slow things at once. The SDK ships AsyncOpenAI with the same arguments. Create an asyncio.Semaphore(8) and wrap each call in async with sem so no more than eight are in flight. A semaphore that matches your key's concurrency limit does the same job as max_workers in the thread pool.
Whichever you choose, keep the retry logic in one place. A pipeline with three slightly different retry loops in three files is hard to reason about. One ask function, imported everywhere, means one place to change when your limits change.
What about a bigger worker count later?
The limits are per key: 8 concurrent and 300 per minute on a full key. Adding more threads than that does not make the run faster; it makes more requests wait behind 429 responses. If you outgrow a single key, talk to the documentation and support before you design around it, rather than guessing at limits that are not published.
Stage three: a streaming step
Streaming helps when a person is waiting, for instance a tool that shows a draft as it is written. Pass stream=True and read chunks as they arrive over server-sent events. Usage figures come at the end of the stream.
def stream_draft(prompt):
parts = []
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
piece = chunk.choices[0].delta.content
parts.append(piece)
print(piece, end="", flush=True)
print()
return "".join(parts)
One detail matters for pipelines: a streamed request holds its concurrency slot until the stream finishes. If you open a stream and stop reading, that slot stays busy and your other workers start getting concurrency errors. Always read to the end or close the stream explicitly. In a batch job with no human watching, plain non-streamed calls are simpler and just as cheap.
Making the output safe to pass on
The next stage of a pipeline is usually code, and code wants structure. JSON mode keeps the model from wrapping its answer in prose. Add response_format={"type": "json_object"} to the call and say in the prompt which keys you expect.
import json
def extract(doc):
resp = ask(
[
{
"role": "system",
"content": 'Reply with JSON: {"title": str, "tags": [str], "language": str}',
},
{"role": "user", "content": doc["text"]},
],
response_format={"type": "json_object"},
temperature=0,
)
data = json.loads(resp.choices[0].message.content)
for key in ("title", "tags", "language"):
if key not in data:
raise ValueError("missing key: " + key)
return {"id": doc["id"], **data}
JSON mode guarantees parseable JSON, not your schema, so the key check stays. If a record fails it, log it and move on rather than killing the whole batch. If the pipeline needs the model to trigger actions, the endpoint also supports tool calling with tools and tool_choice, with results returned as messages that have the role tool.
Checkpointing so a crash costs one record
Batch jobs die: a laptop sleeps, a connection drops, you press Ctrl-C. Append each finished record to a JSONL file immediately and skip those IDs on the next start.
import json
import os
import threading
DONE_FILE = "done.jsonl"
lock = threading.Lock()
def load_done():
if not os.path.exists(DONE_FILE):
return set()
with open(DONE_FILE) as fh:
return {json.loads(line)["id"] for line in fh if line.strip()}
def save(record):
with lock:
with open(DONE_FILE, "a") as fh:
fh.write(json.dumps(record) + "\n")
def run_resumable(docs):
done = load_done()
todo = [d for d in docs if d["id"] not in done]
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
for fut in as_completed([pool.submit(extract, d) for d in todo]):
try:
save(fut.result())
except Exception as err:
print("failed:", err)
The lock matters because several threads write to the same file. Without it, two lines can interleave and corrupt the log.
Testing a pipeline without wasting credit
A pipeline has more moving parts than a single call, so test it in layers and keep the first layers free.
Start with the glue code. Replace the ask function with a stub that returns a fixed string and run your whole script on five fake records. This checks your file handling, your checkpointing and your validation without touching the network. If the stub run resumes correctly after you kill it halfway, the plumbing works.
Next, run five real records. At the prices on the pricing page this costs a fraction of a cent for short inputs, and the trial credit covers hundreds of such runs. Open the output file and read every line. People skip this and then discover on record 1,800 that the model has been adding a polite preamble to every summary. A one-line change to the system prompt fixes that, but only if you notice it early.
Then try to break it on purpose. Unplug the network in the middle of a run and check that it recovers. Set the worker count above your limit and confirm the 429 handling works instead of crashing. Feed it an empty document and a document that is ten times longer than usual. The 100,000 token window is large, but a single huge input will still be slower and costlier than the others, and you want to know how your script behaves before it happens at scale.
Watching the cost while it runs
Every response includes X-Balance-USD, X-Request-Id and the rate-limit headers. To read them with the SDK, use the raw-response wrapper:
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[{"role": "user", "content": "ping"}],
max_tokens=5,
)
print(raw.headers.get("X-Balance-USD"), raw.headers.get("X-Request-Id"))
resp = raw.parse()
A simple guard is to check the balance every few dozen calls and stop the run if it drops below a number you choose. Log the request ID with each record so you can trace any odd output.
Estimate the bill before you start. At $0.15 per 1M input tokens and $0.50 per 1M output tokens, 2,000 documents of about 3,000 tokens each, summarized into about 300 tokens, cost:
- Input: 2,000 x 3,000 = 6,000,000 tokens = 6M x $0.15 = $0.90.
- Output: 2,000 x 300 = 600,000 tokens = 0.6M x $0.50 = $0.30.
- Total: $1.20.
Pay as you go means that is the whole cost, with no subscription on top. See the pricing page for top-up amounts from $20 and the bonus tiers.
More guides
Questions and answers
Why set max_retries to 0 in the OpenAI SDK?
The built-in retries do not know your concurrency limit and keep the Retry-After value to themselves. Handling 429 in your own function lets you wait exactly as long as the server asks.
How many workers should I use?
Use 8 on a full key and 2 on a trial key, which match the concurrency limits. Fewer is fine if your downstream stages are the bottleneck.
Does a failed request cost money?
No. Failed or refused requests are not charged, so retrying after an error does not add to the bill.
Can I use async instead of threads?
Yes. The SDK has an AsyncOpenAI client with the same arguments. Cap the number of in-flight requests with an asyncio semaphore set to your concurrency limit.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.
Get API key