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

# Cancel Batch

> Cancel a batch that is in progress

## POST /v1/batches/:id/cancel

Cancel a batch that is currently being processed. Once cancelled, the batch cannot be resumed.

<Warning>
  Cancelling a batch is permanent. Any requests that have already been processed will be included in the output file, but no new requests will be processed.
</Warning>

## Authentication

Requires provider authentication headers:

```bash theme={null}
x-portkey-provider: openai
Authorization: Bearer YOUR_OPENAI_API_KEY
```

## Request

### Headers

<ParamField header="x-portkey-provider" type="string" required>
  The provider to route the request to (e.g., `openai`)
</ParamField>

<ParamField header="Authorization" type="string" required>
  Bearer token for the provider API
</ParamField>

### Path Parameters

<ParamField path="id" type="string" required>
  The ID of the batch to cancel
</ParamField>

## Response

<ResponseField name="id" type="string">
  The batch identifier
</ResponseField>

<ResponseField name="object" type="string">
  The object type, always "batch"
</ResponseField>

<ResponseField name="status" type="string">
  The status of the batch, which will be `cancelling` or `cancelled`
</ResponseField>

<ResponseField name="cancelled_at" type="integer">
  Unix timestamp of when the batch was cancelled
</ResponseField>

All other fields from the batch object are also returned.

## Example

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://localhost:8787/v1/batches/batch_abc123/cancel \
    -H "x-portkey-provider: openai" \
    -H "Authorization: Bearer $OPENAI_API_KEY"
  ```

  ```python Python theme={null}
  from portkey_ai import Portkey

  client = Portkey(
      provider="openai",
      Authorization="sk-***"
  )

  # Cancel a batch
  batch = client.batches.cancel("batch_abc123")
  print(f"Batch {batch.id} status: {batch.status}")

  # Check final status
  import time
  time.sleep(5)
  batch = client.batches.retrieve("batch_abc123")
  if batch.status == "cancelled":
      print("Batch successfully cancelled")
      if batch.output_file_id:
          print(f"Partial results available: {batch.output_file_id}")
  ```

  ```javascript JavaScript theme={null}
  import Portkey from 'portkey-ai';

  const client = new Portkey({
      provider: "openai",
      Authorization: "sk-***"
  });

  // Cancel a batch
  const batch = await client.batches.cancel("batch_abc123");
  console.log(`Batch ${batch.id} status: ${batch.status}`);

  // Check final status after a delay
  setTimeout(async () => {
      const updatedBatch = await client.batches.retrieve("batch_abc123");
      if (updatedBatch.status === "cancelled") {
          console.log("Batch successfully cancelled");
          if (updatedBatch.output_file_id) {
              console.log(`Partial results available: ${updatedBatch.output_file_id}`);
          }
      }
  }, 5000);
  ```
</CodeGroup>

### Response Example

```json theme={null}
{
  "id": "batch_abc123",
  "object": "batch",
  "endpoint": "/v1/chat/completions",
  "errors": null,
  "input_file_id": "file-abc123",
  "completion_window": "24h",
  "status": "cancelling",
  "output_file_id": null,
  "error_file_id": null,
  "created_at": 1713894800,
  "in_progress_at": 1713894900,
  "cancelled_at": 1713895200,
  "completed_at": null,
  "request_counts": {
    "total": 100,
    "completed": 45,
    "failed": 0
  },
  "metadata": {
    "description": "Daily batch job"
  }
}
```

## Cancellation Behavior

### What Happens When You Cancel

1. **In Progress Requests**: Requests currently being processed may complete
2. **Queued Requests**: Requests that haven't started processing are cancelled
3. **Output File**: An output file is generated with all completed requests
4. **Billing**: You're only charged for completed requests

### When Cancellation is Not Allowed

You cannot cancel a batch if its status is:

* `completed` - Batch has already finished
* `failed` - Batch has already failed
* `cancelled` - Batch is already cancelled

## Use Cases

<AccordionGroup>
  <Accordion title="Long Running Batches">
    Cancel batches that are taking longer than expected, allowing you to debug and resubmit with optimizations.
  </Accordion>

  <Accordion title="Changed Requirements">
    If requirements change mid-processing, cancel the batch and submit a new one with updated parameters.
  </Accordion>

  <Accordion title="Error Detection">
    If you detect an error in your input file after submission, cancel the batch to avoid wasting resources.
  </Accordion>
</AccordionGroup>

## Best Practices

<Note>
  After cancelling a batch, wait a few seconds before retrieving it again to ensure the cancellation has been processed.
</Note>

<Tip>
  Always check if an `output_file_id` is available after cancellation - you may have partial results that are still useful.
</Tip>

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Create Batch" icon="plus" href="/api/batches/create">
    Create a new batch
  </Card>

  <Card title="Retrieve Batch" icon="search" href="/api/batches/retrieve">
    Check batch status
  </Card>

  <Card title="List Batches" icon="list" href="/api/batches/list">
    View all batches
  </Card>
</CardGroup>
