> ## Documentation Index
> Fetch the complete documentation index at: https://www.truefoundry.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Batch API (/batches)

> Process jobs asynchronously using TrueFoundry's batch prediction API.

**API Reference:** [`POST /batches`](https://www.truefoundry.com/docs/api-reference/batch/create-batch)

## Provider capabilities

The table below summarizes gateway support for this endpoint by provider.

> [!NOTE]
>
> Legend:
>
> * **✅** Supported by provider and TrueFoundry
> * &#x20;Provided by provider, but not by TrueFoundry
> * &#x20;Provider does not support this feature

| Provider | Batch |
| - | - |
| OpenAI | ✅ |
| Azure OpenAI | ✅ |
| Microsoft Foundry | ✅ |
| Anthropic | ✅ |
| Bedrock | ✅ |
| Vertex | ✅ |
| Cohere | |
| Gemini | |
| Groq | |
| Cerebras | |
| Together-AI | |
| xAI | |
| DeepInfra | |

Anthropic batches use Anthropic's native `/v1/messages/batches` API; see [Anthropic Message Batches](https://www.truefoundry.com/docs/ai-gateway/batch-predictions-with-truefoundry-llm-gateway.md#anthropic-message-batches).

For every gateway endpoint and provider, see [Supported APIs](https://www.truefoundry.com/docs/ai-gateway/intro-to-llm-gateway.md#supported-apis).

> [!NOTE]
>
> The Batch API does **not** support [Virtual Models](https://www.truefoundry.com/docs/ai-gateway/virtual-model.md). Batch jobs run asynchronously on a single provider, so the AI Gateway cannot apply virtual model routing, retries, or fallbacks to requests inside a batch. Always pass a real catalog model identifier (for example `openai-main/gpt-4o`) as the `model` when creating a batch job — passing a virtual model name will be rejected.

This guide explains how to perform batch predictions using TrueFoundry's AI Gateway with OpenAI, Microsoft Foundry, Azure OpenAI, Vertex AI, or AWS Bedrock providers. Anthropic batches use Anthropic's native Message Batches API instead; see [Anthropic Message Batches](#anthropic-message-batches). For how the gateway prices OpenAI and Anthropic batches, see [Batch cost tracking](#batch-cost-tracking).

## Client Setup

All providers use the OpenAI SDK with provider-specific headers. Choose your provider to get started:

```python OpenAI Provider lines theme={"dark"}
from openai import OpenAI

client = OpenAI(
    api_key="your-truefoundry-api-key",
    base_url="{GATEWAY_BASE_URL}",
    default_headers={
        "x-tfy-provider-name": "openai-main"  # truefoundry provider integration name
    }
)
```

```python Azure OpenAI Provider lines theme={"dark"}
from openai import OpenAI

client = OpenAI(
    api_key="your-truefoundry-api-key",
    base_url="{GATEWAY_BASE_URL}",
    default_headers={
        "x-tfy-provider-name": "azure-batch",  # truefoundry provider integration name
        "x-tfy-azure-api-version": "2024-12-01-preview"  # api version for the model being used
    }
)
```

```python Microsoft Foundry Provider lines theme={"dark"}
from openai import OpenAI

client = OpenAI(
    api_key="your-truefoundry-api-key",
    base_url="{GATEWAY_BASE_URL}",
    default_headers={
        "x-tfy-provider-name": "my-foundry",
    }
)
```

```python Vertex AI Provider lines theme={"dark"}
from openai import OpenAI

client = OpenAI(
    api_key="your-truefoundry-api-key",
    base_url="{GATEWAY_BASE_URL}",
    default_headers={
        "x-tfy-provider-name": "vertex-main",  # truefoundry provider integration name
        "x-tfy-vertex-storage-bucket-name": "your-bucket-name",
        "x-tfy-vertex-region": "your-region",  # e.g., "europe-west4"
        "x-tfy-provider-model": "gemini-2-0-flash"
    }
)
```

```python AWS Bedrock Provider lines theme={"dark"}
from openai import OpenAI

client = OpenAI(
    api_key="your-truefoundry-api-key",
    base_url="{GATEWAY_BASE_URL}",
    default_headers={
        "x-tfy-provider-name": "bedrock-main",  # truefoundry provider integration name
        "x-tfy-aws-s3-bucket": "your-s3-bucket-name",
        "x-tfy-aws-bedrock-model": "amazon.nova-lite-v1:0"
    }
)
```

## Input File Format

Create a JSONL file with one JSON object per line. Each line represents a single request:

```json request.jsonl lines theme={"dark"}
{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-3.5-turbo-0125", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 1000}}
{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-3.5-turbo-0125", "messages": [{"role": "system", "content": "You are an unhelpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 1000}}
{"custom_id": "request-3", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4-vision-preview", "messages": [{"role": "user", "content": [{"type": "text", "text": "What's in this image?"}, {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}]}], "max_tokens": 1000}}
```

**Requirements:** Valid JSON per line, meaningful `custom_id` values. See provider notes below for any provider-specific limits (e.g. minimum records, URL/body format).

> [!NOTE]
>
> Before using AWS Bedrock batch processing, ensure you have:
>
> * **S3 Bucket**: For storing input and output files.
> * **IAM Execution Role**: With permissions for S3 access and Bedrock model invocation.
> * **User Permissions**: Including `iam:PassRole` to pass the execution role to Bedrock.

> [!NOTE]
>
> Before using Vertex AI batch processing, ensure you have:
>
> * **Cloud Storage Bucket**: The bucket must be in the same region as the model, and the service account must have read/write access to the bucket.
> * **Batch Prediction Permissions**: The service account must have permission to create batch prediction jobs.

> [!NOTE]
>
> Before using Azure OpenAI batch processing, ensure you have:
>
> * **Deployment type**: A model deployed as **Global Batch** or **Data Zone Batch** (standard/online deployments cannot be used for batch).
> * **Headers**: Set `x-tfy-azure-api-version` (e.g. `2024-12-01-preview`) to match the API version used by your batch deployment.
> * **Endpoint**: When creating the job, use `endpoint="/chat/completions"` for chat (Azure API uses this form). For the Responses API, use `url: "/v1/responses"` and `body.input` in each JSONL line.
>
> See [Azure OpenAI batch documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/batch) for details.

> [!NOTE]
>
> Before using Microsoft Foundry batch processing, ensure you have a deployment that supports batch processing and an integration for the deployment in your Microsoft Foundry account. Microsoft Foundry v1 uses implicit API versioning; do not add a dated Azure API version header unless the integration uses the legacy `api_version` fallback.

## Workflow Steps

The batch process follows these steps for all providers:

1. **Upload**: Upload JSONL file → Get file ID
2. **Create**: Create batch job → Get batch ID
3. **Monitor**: Check status until complete
4. **Fetch**: Download results

### Step-by-Step Examples

> [accordion] 1. Upload Input File
>
> ```python OpenAI Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "openai-main"  # truefoundry provider integration name
>     }
> )
>
> # Upload the input file
> file = client.files.create(
>     file=open("request.jsonl", "rb"),
>     purpose="batch"
> )
>
> print(file.id)  # Example: file-PnFGrFLN5LjjcWr4eFsStK
> ```
>
> ```python Azure OpenAI Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "azure-batch",
>         "x-tfy-azure-api-version": "2024-12-01-preview"
>     }
> )
>
> # Upload the input file (purpose must be "batch")
> file = client.files.create(
>     file=open("request.jsonl", "rb"),
>     purpose="batch"
> )
>
> print(file.id)  # Example: file-xxxxx
> ```
>
> ```python Vertex AI Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "vertex-main",  # truefoundry provider integration name
>         "x-tfy-vertex-storage-bucket-name": "your-bucket-name",
>         "x-tfy-vertex-region": "your-region",
>         "x-tfy-provider-model": "gemini-2-0-flash"
>     }
> )
>
> # Upload the input file
> file = client.files.create(
>     file=open("request.jsonl", "rb"),
>     purpose="batch"
> )
>
> print(file.id)  # Example: file-PnFGrFLN5LjjcWr4eFsStK
> ```
>
> ```python AWS Bedrock Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "bedrock-main",  # truefoundry provider integration name
>         "x-tfy-aws-s3-bucket": "your-s3-bucket-name",
>         "x-tfy-aws-bedrock-model": "amazon.nova-lite-v1:0"
>     }
> )
>
> # Upload the input file
> file = client.files.create(
>     file=open("bedrock-requests.jsonl", "rb"),
>     purpose="batch"
> )
>
> print(file.id)  # Example: s3://bucket/uuid.jsonl
> ```

> [accordion] 2. Create Batch Job
>
> ```python OpenAI Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "openai-main"  # truefoundry provider integration name
>     }
> )
>
> batch_job = client.batches.create(
>     input_file_id=file.id,
>     endpoint="/v1/chat/completions",
>     completion_window="24h"
> )
>
> print(batch_job.id)  # Example: batch_67f7bfc50b288190893f242d9fa47c52
> ```
>
> ```python Azure OpenAI Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "azure-batch",
>         "x-tfy-azure-api-version": "2024-12-01-preview"
>     }
> )
>
> # Azure uses endpoint="/chat/completions"; completion_window must be "24h"
> batch_job = client.batches.create(
>     input_file_id=file.id,
>     endpoint="/chat/completions",
>     completion_window="24h"
> )
>
> print(batch_job.id)  # Example: batch_xxxxx
> ```
>
> ```python Vertex AI Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "vertex-main",  # truefoundry provider integration name
>         "x-tfy-vertex-storage-bucket-name": "your-bucket-name",
>         "x-tfy-vertex-region": "your-region",
>         "x-tfy-provider-model": "gemini-2-0-flash"
>     }
> )
>
> batch_job = client.batches.create(
>     input_file_id=file.id,
>     endpoint="/v1/chat/completions",
>     completion_window="24h"
> )
>
> print(batch_job.id)  # Example: batch_67f7bfc50b288190893f242d9fa47c52
> ```
>
> ```python AWS Bedrock Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "bedrock-main",  # truefoundry provider integration name
>         "x-tfy-aws-s3-bucket": "your-s3-bucket-name",
>         "x-tfy-aws-bedrock-model": "amazon.nova-lite-v1:0"
>     }
> )
>
> # Bedrock requires extra_body with additional parameters
> role_arn = "arn:aws:iam::YOUR_ACCOUNT_ID:role/BedrockBatchExecutionRole"
>
> batch_job = client.batches.create(
>     input_file_id=file.id,  # S3 URL from file upload
>     endpoint="/v1/chat/completions",
>     completion_window="24h",
>     extra_body={
>         "model": "bedrock-main/amazon-nova-lite-v1-0",
>         "role_arn": role_arn,
>         "job_name": "my-custom-batch-job"  # Optional
>     }
> )
>
> print(batch_job.id)  # Example: arn:aws:bedrock:us-east-1:ACCOUNT:model-invocation-job/JOB_ID
> ```

> [accordion] 3. Check Batch Status
>
> ```python OpenAI Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "openai-main"  # truefoundry provider integration name
>     }
> )
>
> batch_status = client.batches.retrieve(batch_job.id)
> print(batch_status.status)  # Example: completed, validating, in_progress, etc.
> ```
>
> ```python Azure OpenAI Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "azure-batch",
>         "x-tfy-azure-api-version": "2024-12-01-preview"
>     }
> )
>
> batch_status = client.batches.retrieve(batch_job.id)
> print(batch_status.status)  # Example: completed, validating, in_progress, finalizing, etc.
> ```
>
> ```python Vertex AI Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "vertex-main",  # truefoundry provider integration name
>         "x-tfy-vertex-storage-bucket-name": "your-bucket-name",
>         "x-tfy-vertex-region": "your-region",
>         "x-tfy-provider-model": "gemini-2-0-flash"
>     }
> )
>
> batch_status = client.batches.retrieve(batch_job.id)
> print(batch_status.status)  # Example: completed, validating, in_progress, etc.
> ```
>
> ```python AWS Bedrock Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "bedrock-main",  # truefoundry provider integration name
>         "x-tfy-aws-s3-bucket": "your-s3-bucket-name",
>         "x-tfy-aws-bedrock-model": "amazon.nova-lite-v1:0"
>     }
> )
>
> batch_status = client.batches.retrieve(batch_job.id)
> print(batch_status.status)  # Example: completed, validating, in_progress, etc.
> ```

> [accordion] 4. Fetch Results
>
> ```python OpenAI Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "openai-main"  # truefoundry provider integration name
>     }
> )
>
> if batch_status.status == "completed":
>     output_content = client.files.content(batch_status.output_file_id)
>     print(output_content.content.decode('utf-8'))
> ```
>
> ```python Azure OpenAI Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "azure-batch",
>         "x-tfy-azure-api-version": "2024-12-01-preview"
>     }
> )
>
> if batch_status.status == "completed":
>     output_content = client.files.content(batch_status.output_file_id)
>     print(output_content.content.decode('utf-8'))
> ```
>
> ```python Vertex AI Provider lines theme={"dark"}
> from openai import OpenAI
>
> client = OpenAI(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "vertex-main",  # truefoundry provider integration name
>         "x-tfy-vertex-storage-bucket-name": "your-bucket-name",
>         "x-tfy-vertex-region": "your-region",
>         "x-tfy-provider-model": "gemini-2-0-flash"
>     }
> )
>
> if batch_status.status == "completed":
>     output_content = client.files.content(batch_status.output_file_id)
>     print(output_content.content.decode('utf-8'))
> ```
>
> ```python AWS Bedrock Provider lines theme={"dark"}
> import requests
>
> # For Bedrock, use REST API to fetch results
> if batch_status.status == "completed":
>
> response = requests.get(
>     f"{{GATEWAY_BASE_URL}}/batches/{batch_job.id}/output",
>     headers={
>         "Authorization": "Bearer your-truefoundry-api-key",
>         "x-tfy-provider-name": "bedrock-main"
>     }
> )
>
> print("Batch results:")
> print(response.json())
> ```

## Anthropic Message Batches

Anthropic batches go through Anthropic's native [Message Batches API](https://docs.anthropic.com/en/docs/build-with-claude/batch-processing) at `/v1/messages/batches`, not `/batches`. There is no input file to upload: the requests are sent in the create call. Use the Anthropic SDK with the gateway as its base URL, and set `x-tfy-provider-name` to your Anthropic provider account.

| Operation | Endpoint |
| - | - |
| Create | `POST /v1/messages/batches` |
| Retrieve | `GET /v1/messages/batches/{id}` |
| List | `GET /v1/messages/batches` |
| Cancel | `POST /v1/messages/batches/{id}/cancel` |
| Delete | `DELETE /v1/messages/batches/{id}` |
| Results | `GET /v1/messages/batches/{id}/results` |

> [!NOTE]
>
> Every request in a batch must use the same model. Set it in each request's `params.model`, either as the TrueFoundry model name (for example `anthropic-main/claude-sonnet-4-5`) or as the Anthropic model id (`claude-sonnet-4-5`). A TrueFoundry model name must belong to the provider account in `x-tfy-provider-name`; the gateway replaces it with the Anthropic model id before sending the batch. A batch that mixes models is rejected with **400**.

> [accordion] 1. Create Message Batch
>
> ```python Anthropic Provider lines theme={"dark"}
> from anthropic import Anthropic
>
> client = Anthropic(
>     api_key="your-truefoundry-api-key",
>     base_url="{GATEWAY_BASE_URL}",
>     default_headers={
>         "x-tfy-provider-name": "anthropic-main"  # truefoundry provider integration name
>     }
> )
>
> batch = client.messages.batches.create(
>     requests=[
>         {
>             "custom_id": "request-1",
>             "params": {
>                 "model": "anthropic-main/claude-sonnet-4-5",
>                 "max_tokens": 1024,
>                 "messages": [{"role": "user", "content": "Hello world!"}],
>             },
>         },
>         {
>             "custom_id": "request-2",
>             "params": {
>                 "model": "anthropic-main/claude-sonnet-4-5",
>                 "max_tokens": 1024,
>                 "messages": [{"role": "user", "content": "Summarize TrueFoundry in one line."}],
>             },
>         },
>     ]
> )
>
> print(batch.id)  # Example: msgbatch_01HkcTjaV5uDC8jWR4ZsDV8d
> ```

> [accordion] 2. Check Batch Status
>
> ```python Anthropic Provider lines theme={"dark"}
> batch = client.messages.batches.retrieve(batch.id)
> print(batch.processing_status)  # in_progress, canceling, or ended
> print(batch.request_counts)     # succeeded, errored, canceled, expired
> ```

> [accordion] 3. Fetch Results
>
> Fetch results from the gateway's results endpoint. The SDK's `client.messages.batches.results()` downloads from the `results_url` in the batch, which points at Anthropic directly and does not go through the gateway.
>
> ```python Anthropic Provider lines theme={"dark"}
> import json
> import requests
>
> GATEWAY_BASE_URL = "{GATEWAY_BASE_URL}"
>
> if batch.processing_status == "ended":
>     response = requests.get(
>         f"{GATEWAY_BASE_URL}/v1/messages/batches/{batch.id}/results",
>         headers={
>             "Authorization": "Bearer your-truefoundry-api-key",
>             "x-tfy-provider-name": "anthropic-main",
>         },
>     )
>     for line in response.text.splitlines():
>         result = json.loads(line)
>         print(result["custom_id"], result["result"]["type"])  # succeeded, errored, canceled, or expired
> ```

## Batch Status Reference

* `validating`: Initial validation of the batch
* `in_progress`: Processing the requests
* `completed`: All requests processed successfully
* `failed`: Batch processing failed (use `error_file_id` from the batch response to fetch error details)
* `finalizing`: Results being prepared (OpenAI / Azure OpenAI)
* `expired`: Did not complete within the time window (OpenAI / Azure OpenAI)
* `cancelling` / `cancelled`: Batch cancelled; partial results may be available via `output_file_id`

Anthropic batches report `processing_status` instead: `in_progress`, `canceling`, then `ended`. Once a batch has `ended`, each request's outcome (`succeeded`, `errored`, `canceled`, or `expired`) is in its result line and in `request_counts`.

## Batch cost tracking

The AI Gateway records the cost of OpenAI and Anthropic batches after the provider finishes them. Batch spend then shows up in [Metrics](https://www.truefoundry.com/docs/ai-gateway/cost-tracking.md#view-costs), counts against [budget limits](https://www.truefoundry.com/docs/ai-gateway/budget-limiting-v2.md), and appears on the trace of the request that created the batch.

### How a batch is costed

1. **When you create a batch that will be costed** (see [Which batches are costed](#which-batches-are-costed)), the gateway checks your budgets. If an enforced budget for that model is already used up, the request is rejected with **429** and nothing is sent to the provider. Otherwise the gateway records who submitted the batch (user, team, virtual account), the model, and the budgets that matched.
2. **While the provider runs it**, the gateway checks each unfinished batch with the provider about every 30 minutes.
3. **When the provider finishes**, the gateway reads the batch results, prices each successful request, and records one cost entry for the whole batch. On the trace of the create request, it appears as a `Model: <model> (batch)` span with the batch's token counts and cost.

### Which batches are costed

| Provider | Costed when |
| - | - |
| OpenAI | Created with `POST /batches`, `endpoint` set to `/v1/chat/completions` or `/v1/responses`, and the `x-tfy-provider-model` header set |
| Anthropic | Created with `POST /v1/messages/batches`; the model comes from `params.model` |
| Azure OpenAI, Microsoft Foundry, Vertex AI, AWS Bedrock | Not costed. The batch runs, but its cost is not recorded |

For OpenAI, the gateway does not read the input file, so it takes the model from the `x-tfy-provider-model` header on the create request. Set it to the model name in your provider account (for example `gpt-4.1` for `openai-main/gpt-4.1`) or to the OpenAI model id. Without the header, the batch still runs but its cost is not recorded.

```python OpenAI Provider lines theme={"dark"}
batch_job = client.batches.create(
    input_file_id=file.id,
    endpoint="/v1/chat/completions",
    completion_window="24h",
    extra_headers={"x-tfy-provider-model": "gpt-4.1"},
)
```

### How batch prices are calculated

Batch requests are priced from the public [pricing catalog](https://www.truefoundry.com/docs/ai-gateway/cost-tracking.md#how-cost-is-calculated) at the provider's batch rates:

* **Input and output tokens** use the catalog's `input_cost_per_token_batches` and `output_cost_per_token_batches` rates. When a model has no batch rate, the gateway uses half the standard rate, which is the discount OpenAI and Anthropic give batch jobs.
* **Cache read and cache write tokens** are priced at half the standard cache rates.
* **Tiered pricing**, such as long-context rates, is halved tier by tier.
* **The provider account's discount %**, if set, still applies.
* **Only successful requests are charged.** Failed, errored, cancelled, and expired requests cost nothing; requests that finished before a batch was cancelled or expired are still charged.

Private (custom) pricing on a model and [service-tier overlays](https://www.truefoundry.com/docs/ai-gateway/cost-tracking.md#service-tiers) are not applied to batches.

For example, `openai-main/gpt-4.1` costs $2 per 1M input tokens and $8 per 1M output tokens normally, and $1 and $4 in a batch. A batch of 1,000 successful requests with 500 input and 100 output tokens each is billed as 500,000 × $1/1M + 100,000 × $4/1M = \*\*$0.90**, half the $1.80 the same requests cost one at a time.

### Timing and limits

* **Cost is recorded when the batch is priced, not when it was created.** A batch created on the last day of a month and finished the next day counts toward the new month's budget.
* **The gateway stops checking a batch 3 days after it was created.** A batch the provider has not finished by then is not costed.
* **Result files larger than 200 MB are not costed.**

> [!WARNING]
>
> On self-hosted gateways, batch cost tracking needs gateway tracing to be enabled. If tracing is off, creating an OpenAI or Anthropic batch that would be costed returns **503**.

## Best Practices

1. **File Format**: Use meaningful `custom_id` values and valid JSONL format
2. **Error Handling**: Implement proper error handling and status monitoring
3. **Security**: Store API keys securely, use minimal IAM permissions
4. **Provider-specific**: Check the prerequisites above (e.g. Azure: batch deployment type and endpoint; Bedrock: minimum 100 records, IAM and S3)

## Vertex AI Permissions

The following permissions are required for Vertex AI batch prediction:

> [accordion] Storage and service account requirements
>
> **Cloud Storage bucket**
>
> * The Cloud Storage bucket used for batch input and output must be in the **same region** as the Vertex AI model you are using.
> * The service account that runs the batch job must have **read and write** access to this bucket (e.g. `roles/storage.objectAdmin` or equivalent object-level read/write permissions on the bucket).

> [accordion] Batch prediction job permissions
>
> **Create batch prediction jobs**
>
> * The service account must have permission to **create and manage batch prediction jobs** in Vertex AI (e.g. `roles/aiplatform.user` or the `aiplatform.batchPredictionJobs.create` permission).

## AWS Bedrock Permissions

> [accordion] User Permissions (for API calls)
>
> These are the minimum permissions required to use the Bedrock Batch APIs. For complete official guidance, see [AWS Bedrock Batch Inference Permissions](https://docs.aws.amazon.com/bedrock/latest/userguide/batch-inference-permissions.html).
>
> ```json User Policy lines theme={"dark"}
> {
>   "Version": "2012-10-17",
>   "Statement": [
>     {
>       "Effect": "Allow",
>       "Action": [
>         "bedrock:ListFoundationModels",
>         "bedrock:GetFoundationModel",
>         "bedrock:ListInferenceProfiles",
>         "bedrock:GetInferenceProfile",
>         "bedrock:ListCustomModels",
>         "bedrock:GetCustomModel",
>         "bedrock:TagResource",
>         "bedrock:UntagResource",
>         "bedrock:ListTagsForResource",
>         "bedrock:CreateModelInvocationJob",
>         "bedrock:GetModelInvocationJob",
>         "bedrock:ListModelInvocationJobs",
>         "bedrock:StopModelInvocationJob"
>       ],
>       "Resource": [
>         "arn:aws:bedrock:<region>:<account_id>:model-customization-job/*",
>         "arn:aws:bedrock:<region>:<account_id>:custom-model/*",
>         "arn:aws:bedrock:<region>::foundation-model/*"
>       ]
>     },
>     {
>       "Effect": "Allow",
>       "Action": ["s3:ListBucket", "s3:PutObject", "s3:GetObject", "s3:GetObjectAttributes"],
>       "Resource": ["arn:aws:s3:::<bucket>", "arn:aws:s3:::<bucket>/*"]
>     },
>     {
>       "Action": ["iam:PassRole"],
>       "Effect": "Allow",
>       "Resource": "arn:aws:iam::<account_id>:role/<service_role_name>",
>       "Condition": {
>         "StringEquals": {
>           "iam:PassedToService": ["bedrock.amazonaws.com"]
>         }
>       }
>     }
>   ]
> }
> ```

> [accordion] Service Role Permissions (for batch execution)
>
> The service role (role\_arn) used for creating and executing the batch job requires:
>
> **Trust Relationship:**
>
> ```json Trust Policy lines theme={"dark"}
> {
>   "Version": "2012-10-17",
>   "Statement": [
>     {
>       "Effect": "Allow",
>       "Principal": {
>         "Service": "bedrock.amazonaws.com"
>       },
>       "Action": "sts:AssumeRole",
>       "Condition": {
>         "StringEquals": {
>           "aws:SourceAccount": "<account_id>"
>         },
>         "ArnEquals": {
>           "aws:SourceArn": "arn:aws:bedrock:<region>:<account_id>:model-invocation-job/*"
>         }
>       }
>     }
>   ]
> }
> ```
>
> **Permission Policy:**
>
> ```json Permission Policy lines theme={"dark"}
> {
>   "Version": "2012-10-17",
>   "Statement": [
>     {
>       "Effect": "Allow",
>       "Action": ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
>       "Resource": ["arn:aws:s3:::<bucket>", "arn:aws:s3:::<bucket>/*"]
>     }
>   ]
> }
> ```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.