Hosted Batch API
Send text requests as a JSONL file for work that can run asynchronously, such as model evaluations, classification, extraction, or dataset enrichment. Submit the file, keep the batch ID, and download the results when they’re ready.
Hosted input rows use request_id. Submit them with client.submit() from the hosted Python client.
Use the Python client, API URL, and key provided with your preview workspace. Request preview access.
Models and limits
Choose one model per text batch. Check client.models() for the models available to your workspace.
| Limit | Hosted preview |
|---|---|
| Requests per batch | 1 to 250,000 |
| JSONL file size | 2 GB (2,000,000,000 bytes) |
| Single JSONL record | 1 MiB by default, including the JSON fields. Check the model entry for any override. |
| Context per request | See the model entry. The limit counts the prompt and requested output. |
| Completion time | Varies with workload size and available capacity. Check the batch status for progress and any wait reason. |
| Result retention | 48 hours after results are published, unless you delete them sooner. Check results.expires_at for your batch’s deadline. |
Request count, file size, line size, and context are checked independently. If the file hits the count or size cap, split it into smaller batches. Read client.limits() or GET /v1/api/limits for batch-wide limits, and client.model(model_id) for the limits of your chosen model.
Prepare requests
Save one UTF-8 JSON object per line in requests.jsonl. Use the two fields below for each line and leave out blank lines.
| Field | What to send |
|---|---|
request_id | Unique within the file. Use 1–128 ASCII letters, digits, periods, underscores, colons, or hyphens. Start with a letter or digit. |
body | A chat request with a messages array and an explicit max_tokens output cap. Select the model when you submit the batch. |
{"request_id":"review-001","body":{"messages":[{"role":"user","content":"Reply with positive or negative. Review: The team resolved my issue."}],"temperature":0,"max_tokens":8}}
{"request_id":"review-002","body":{"messages":[{"role":"user","content":"Reply with positive or negative. Review: The item arrived broken."}],"temperature":0,"max_tokens":8}}
This preview accepts text messages. Results are written to JSONL files. Omit streaming options and request one completion per row.
Submit a batch
Set FIRMBATCH_API_BASE_URL and FIRMBATCH_API_KEY in your environment. Set FIRMBATCH_MODEL_ID to a model listed for your workspace. The client checks and uploads the file before handing it over for processing.
from os import environ
from firmbatch_client import Client
client = Client(
environ["FIRMBATCH_API_BASE_URL"],
environ["FIRMBATCH_API_KEY"],
)
batch = client.submit(
environ["FIRMBATCH_MODEL_ID"],
file="requests.jsonl",
journal="review-run",
)
batch_id = batch["id"]
print("Batch ID", batch_id)
Save the batch ID and keep the review-run journal directory. Once submission returns, you can close your notebook while FirmBatch processes the batch.
Check status and progress
client.get(batch_id) returns the current status, progress, and any wait reason or error. client.list() lists batches in your workspace. Use client.wait(batch_id) to poll every 20 seconds for up to about an hour by default. When that local wait ends, any active batch keeps running.
| Batch status | What it means |
|---|---|
awaiting_upload | The upload is incomplete. If submission was interrupted, resume it with the same journal. |
verifying or queued | FirmBatch is checking the input or waiting to start. Check the wait reason before retrying. |
awaiting_credits | The batch is waiting for sufficient workspace credits. |
running or finalizing | FirmBatch is processing the requests or preparing the results. |
cancelling | Cancellation was requested. Check back for the final status and available results. |
completed | The batch ended. Check each downloaded row for its outcome. |
rejected | The input was refused. Inspect the error and correct the input before creating a new batch. |
failed or cancelled | Processing ended early. Check whether partial results are available. |
Download and read results
Check results.available on the batch. When results are available, download them to a directory for that batch. If the download is interrupted, rerun it in the same directory to keep the parts already verified.
import json
from pathlib import Path
batch = client.wait(batch_id)
if (batch.get("results") or {}).get("available"):
target = Path("results") / batch_id
summary = client.results(batch_id, target)
print("Download expires at", summary["expires_at"])
for part in sorted(target.glob("part-*.jsonl")):
with part.open(encoding="utf-8") as source:
for line in source:
row = json.loads(line)
if row["status"] == "completed":
print(row["custom_id"], row["response"]["body"])
else:
print(row["custom_id"], row["status"], row["error"])
else:
print(batch["status"], batch.get("error"))
Match each result’s custom_id to the request_id you sent. A row is completed, failed, cancelled, or unfinished. Read the error for rows without a completed response. An unfinished row had no recorded outcome when the batch ended.
Retry, cancel, or delete
- Interrupted submission. Call
client.submit()again with the same file, model, and journal to resume the same submission. Useclient.resume("review-run")to look up the batch recorded in the journal. - Invalid input. The returned error can identify the code, line, and limit. Correct the input and submit it with a new journal. To rerun part of a finished batch, build a new file with just the requests you want to repeat.
- Cancellation. Call
client.cancel(batch_id)to stop the remaining work. Checkclient.get(batch_id)afterward and download any results already available. - Deletion. Download any results you need before calling
client.delete(batch_id)to remove the stored input and results.
| Error code | How to resolve it |
|---|---|
too_many_records or file_too_large | Split the JSONL file across batches. |
record_too_large | Reduce the size in bytes of the indicated JSONL record. |
context_length_exceeded | Shorten the prompt or lower its output cap. |
duplicate_request_id | Give each line a distinct ID within the file. |
results_not_ready or results_not_available | Check the batch status and results.available again. Reuse the batch ID. |
results_expired (HTTP 410) | The stored results have expired or were deleted. Use your saved local copy if you downloaded one. |
Pricing and data
Check your workspace’s model entry for the rates that apply to your jobs. Ask about pricing for your workload.
Batches and downloads are scoped to your workspace. Processing is available in the EU and US. Read the data protection notice.
Local SDK
For operator-configured local runs, use LocalClient. Local input rows use custom_id and you submit them with client.batches.create().
You need access to the Firmbatch code, a Python environment prepared for the pilot, and an operator-configured execution profile. That profile defines the available models and cloud resources. Run these examples where from firmbatch import LocalClient can be imported.
LocalClient() loads the default local profile, or the profile named by FIRMBATCH_PROFILE. Execution can incur cloud charges under that configuration. The coordinating machine must remain on while work runs.
Contact us to arrange setup, agree on the model and discuss your workload.
1. Prepare requests
Save one JSON object per line in requests.jsonl. Each request needs a unique custom_id and a body containing chat messages.
{"custom_id":"review-001","body":{"messages":[{"role":"user","content":"Classify as positive, negative, or neutral. Reply with one word: Support took weeks and never solved the problem."}],"temperature":0,"max_tokens":8}}
{"custom_id":"review-002","body":{"messages":[{"role":"user","content":"Classify as positive, negative, or neutral. Reply with one word: The team was helpful and resolved my issue."}],"temperature":0,"max_tokens":8}}
The body uses an OpenAI-style chat-completion shape. This does not imply compatibility with the hosted OpenAI Batch API. The model is chosen when creating the batch; a model field inside the body does not select it.
| Field | Rule |
|---|---|
custom_id | Required and unique. 1–128 ASCII characters: A–Z, a–z, 0–9, periods, underscores, colons, or hyphens; start with an ASCII letter or digit. |
body.messages | Required, non-empty list. Every message needs a string role and a content field. |
method | Optional. If supplied, it must be POST. |
url | Optional. If supplied, it must be /v1/chat/completions. |
2. Run a batch
The example model name is an alias in the example operator profile. Check client.models for the aliases actually configured for your pilot.
from firmbatch import LocalClient
client = LocalClient()
print("Configured models:", client.models)
batch = client.batches.create(
model="llama-3.1-8b-instruct",
input_file="requests.jsonl",
name="review-classification",
)
print("Batch ID:", batch.id)
batch.wait()
print("Status:", batch.status)
if batch.error:
print("Batch error:", batch.error)
if batch.output_file is not None:
batch.download("results.jsonl")
For this small-file workflow, create() validates and stores the input. wait() drives execution and prints progress. Keep that process running. Finishing the wait does not by itself mean every request succeeded: inspect the batch status and output records.
3. Track progress
Keep the batch ID to retrieve it from the same local profile and state directory. Status and progress are read from durable local state.
batch = client.batches.retrieve("YOUR_BATCH_ID")
print(batch.status)
print(batch.progress.summary())
print(batch.error)
# Resume or wait for the batch using its existing state.
batch.wait()
A batch can wait for capacity, start its model, process requests, and finalize results. Its terminal status is completed, failed, or cancelled. A capacity wait is not a guaranteed completion time.
Use batch.cancel() to request cancellation. Completed responses are kept. The small-file and manifest workflows handle an interrupted wait differently; see the larger-dataset section before leaving a job unattended.
4. Read results
For a small-file batch, download() saves a JSONL file and results() returns the parsed records. Match results to inputs using custom_id.
if batch.output_file is not None:
for result in batch.results():
if result["status"] == "completed":
response = result["response"]["body"]
print(result["custom_id"], response)
else:
print(result["custom_id"], result["status"], result["error"])
Each output record contains custom_id, status, response, and error. A completed response includes status_code: 200 and the model response in body. Other record statuses are failed, cancelled, and unfinished.
A completed request means inference returned successfully. It does not certify that its answer meets your quality criteria; evaluate a representative sample before scaling up.
Larger datasets
The manifest workflow accepts pre-sharded JSONL in object storage. An operator prepares and validates the manifest, including checksums and unique request IDs. Supply input_manifest instead of input_file.
batch = client.batches.create(
model="llama-3.1-8b-instruct",
input_manifest="s3://YOUR_BUCKET/YOUR_PREFIX/manifest.json",
)
batch.wait()
print(batch.status, batch.error)
batch.download("result-shards")
for result in batch.iter_results():
print(result["custom_id"], result["status"])
Here create() starts a background coordinator on the local machine and returns. wait() only watches; interrupting it leaves the batch running. Use batch.cancel() to stop it. The local machine still needs to stay on.
For manifest batches, download() takes a directory and writes result shards. iter_results() reads one shard at a time; results() is not available. Partial results may exist even when a batch fails or is cancelled.
SDK reference
| Call or property | Purpose |
|---|---|
client.models | List model aliases in the current operator profile. |
client.files.upload(path) | Validate and store a small JSONL file. Pass the returned file to input_file. |
client.batches.create(...) | Create a batch with exactly one of input_file or input_manifest. |
client.batches.retrieve(id) | Open a batch in the same profile's local state. |
client.batches.list() | List batches recorded in that state. |
batch.wait() | Drive a small-file batch, or watch a manifest batch. |
batch.status, batch.error | Read the batch state and failure explanation, when present. |
batch.download(destination) | Save a result file, or a directory of shards for a manifest batch. |
batch.cancel() | Request cancellation while keeping completed output. |
Local SDK limits and errors
The small-file parser accepts UTF-8 JSONL up to 200 MiB, at most 50,000 requests, and at most 1 MiB per line. Use the operator-prepared manifest workflow for larger input.
Streaming responses and multiple completions per request are not supported. Omit stream, stream_options, and n. Small-file records accept only the four envelope fields listed above; optional metadata belongs to the manifest workflow.
Invalid input raises InputValidationError. An unconfigured model raises UnknownModelError. Reading a small-file result before output exists raises OutputNotAvailable. Execution failures are also reported through batch.status and batch.error.
Model availability, deployment locations, pricing, and service terms are agreed separately for each pilot.
Request access