
Get Batch API cost breakdown
Read how much a finished (or in-flight) Batch API job spent so finance and ops can attribute overnight evals, bulk classification, and Imagine batch runs without guessing from real-time rates. Official Batch API documents cost_breakdown on the batch object from client.batch.get, with totals in ticks (1e-10 USD) for precision, and per-result usage fields on chat completions. Reduced Batch pricing is on the models / pricing pages; create a key and load credits at console.x.ai.
What you need
An XAI_API_KEY, a batch_id from create or from List batches via the xAI API, and enough completed requests that cost fields are populated. Neighboring jobs include Get Batch API results when you need content plus usage, Run a Batch API job for the create–add–poll loop, and Cancel a Batch API job when you stop spend mid-queue. More API jobs live on the API hub.
Read total cost from the batch
- Export the key:
export XAI_API_KEY="your_api_key"
- Fetch the batch (replace
{batch_id}):
curl "https://api.x.ai/v1/batches/{batch_id}" \
-H "Authorization: Bearer $XAI_API_KEY"
- In the xAI Python SDK, convert ticks to USD:
import os
from xai_sdk import Client
client = Client(api_key=os.getenv("XAI_API_KEY"))
batch = client.batch.get(batch_id="your_batch_id")
total_cost_usd = batch.cost_breakdown.total_cost_usd_ticks / 1e10
print("Total cost: $%.4f" % total_cost_usd)
- Optionally sum per-result chat costs while paging results. Official docs show
cost_in_usd_ticksunder chat completion usage on each result; divide by1e10the same way. Image and video lines use their own response shapes — still download signed media URLs promptly (about one hour after completion).
When to check cost
After num_pending reaches zero for a final invoice number, or mid-run if you need an early signal before cancel. Pair the dollar figure with num_success / num_error so a cheap batch that mostly failed does not look like a win. For pricing tables, see Batch API Pricing on the official pricing page linked from the Batch guide.
Pitfalls
Treating ticks as dollars overstates spend by ten orders of magnitude. Reading cost before any request finishes can show zero or incomplete totals. Logging full result payloads into tickets leaks prompts and answers. Mixing Console Batch spend with SuperGrok consumer quotas on grok.com merges two meters. Leaving Imagine result URLs undownloaded loses the paid media even when the cost line looks correct.