# Group API (https://inference.net/docs/api/async/group)

The Group API submits multiple inference requests together, for related tasks
that you want to track as a unit. It supports chat completions and text
completions, with up to 50 requests per group.

<Callout tone="info">

The Group API is available on `/v1/slow/group/chat/completions`,
`/v1/slow/group/completions`, `/v1/slow/group/embeddings`, and
`/v1/slow/group/responses`.

</Callout>

<Callout tone="warning">

Do not mix completion and chat-completion requests in the same group.

</Callout>

<Callout tone="warning">

With the **Zero Data Retention (ZDR)** team setting on, a group must set
`webhook_id` to an enabled webhook, or it returns `400 Bad Request`. The
results are delivered only in the `slow-group.completed` event, and are purged
once it is delivered or its retries (about 68 hours) run out; a request's own
`metadata.webhook_id` is ignored. Do not disable, delete, or change the URL of a group's webhook while the group is in flight. The `slow-group.completed` event is sent to the webhook as it is at delivery time: a disabled or deleted webhook purges the results without delivery, and a changed URL receives them. See
[Retention and groups](/docs/data-retention/#retention-and-groups).

</Callout>

## When to use it

The Group API submits multiple asynchronous inference requests as a single
unit. Unlike the [Batch API](/docs/api/async/batch/), which requires JSONL file
uploads, the Group API accepts requests directly in the request body. It's a good
fit for:

- **Small to medium batches:** process up to 50 requests at once
- **Related tasks:** group related inference requests together
- **Webhook notifications:** get notified when all requests in a group complete
- **Simpler integration:** no file uploads or JSONL formatting
- **Faster implementation:** direct JSON API calls without file management

## Group API vs Batch API

| Feature          | Group API                           | Batch API                        |
| ---------------- | ----------------------------------- | -------------------------------- |
| Maximum requests | 50                                  | 1,000,000                        |
| Input format     | JSON array in request body          | JSONL file upload                |
| File management  | Not required                        | Required                         |
| Use case         | Small batches, quick implementation | Large-scale processing           |
| Webhook support  | Yes                                 | Yes                              |
| Completion time  | 72 hours                            | 24 hours (default), up to 7 days |

## Get started

Use a credit-billing API key for all Group API requests (both submissions and
Group status/result reads): [plan keys](/docs/api-keys/#plan-keys) return `403
plan_route_not_supported`.

### Submit a group

Send multiple requests together as an array in the request body:

<CodeTabs>

```typescript
const response = await fetch(
  "https://api.inference.net/v1/slow/group/chat/completions",
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.INFERENCE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      requests: [
        {
          model: "kimi-k3-fast",
          messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: "What is the capital of France?" },
          ],
          max_tokens: 100,
        },
        {
          model: "kimi-k3-fast",
          messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: "What is the capital of Germany?" },
          ],
          max_tokens: 100,
        },
      ],
      webhook_id: "my-webhook-123", // Optional: attach a webhook for notifications
    }),
  },
);

const result = await response.json();
console.log(result); // { groupId: "group_abc123", groupSize: 2 }
```

```python
import os
import requests

response = requests.post(
    "https://api.inference.net/v1/slow/group/chat/completions",
    headers={
        "Authorization": f"Bearer {os.environ['INFERENCE_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "requests": [
            {
                "model": "kimi-k3-fast",
                "messages": [
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": "What is the capital of France?"},
                ],
                "max_tokens": 100,
            },
            {
                "model": "kimi-k3-fast",
                "messages": [
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": "What is the capital of Germany?"},
                ],
                "max_tokens": 100,
            },
        ],
        "webhook_id": "my-webhook-123",  # Optional: attach a webhook for notifications
    },
)

result = response.json()
print(result)  # {"groupId": "group_abc123", "groupSize": 2}
```

```bash
curl https://api.inference.net/v1/slow/group/chat/completions \
  -H "Authorization: Bearer $INFERENCE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "requests": [
      {
        "model": "kimi-k3-fast",
        "messages": [
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "What is the capital of France?"}
        ],
        "max_tokens": 100
      },
      {
        "model": "kimi-k3-fast",
        "messages": [
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "What is the capital of Germany?"}
        ],
        "max_tokens": 100
      }
    ],
    "webhook_id": "my-webhook-123"
  }'
```

</CodeTabs>

The response includes a group ID and the number of requests:

```json
{
  "groupId": "group_xY3kL9mN2pQ",
  "groupSize": 2
}
```

### Retrieve group results

Once the group is processed, retrieve all generation results with the group ID.
The results are kept only until the group's `slow-group.completed` event is
delivered or dropped, or, without a webhook, for a short time after the group
finishes. See [Data retention](/docs/data-retention/#asynchronous-results-are-kept-until-delivery-finishes).

<Callout tone="info">
  Once a generation finishes, each image URL in its `request` (a chat `image_url` part or an image embedding input) reads `"REDACTED"`, unless that request sets its own `metadata.webhook_id`. The `slow-group.completed` webhook always sends the request with image URLs as `"REDACTED"`.
</Callout>

<CodeTabs>

```typescript
const response = await fetch(
  `https://api.inference.net/v1/slow/group/${groupId}/generations`,
  {
    headers: {
      Authorization: `Bearer ${process.env.INFERENCE_API_KEY}`,
    },
  },
);

const result = await response.json();
console.log(result.generations); // Array of all completed generations
```

```python
import os
import requests

response = requests.get(
    f"https://api.inference.net/v1/slow/group/{group_id}/generations",
    headers={"Authorization": f"Bearer {os.environ['INFERENCE_API_KEY']}"},
)

result = response.json()
print(result["generations"])  # Array of all completed generations
```

```bash
curl https://api.inference.net/v1/slow/group/group_xY3kL9mN2pQ/generations \
  -H "Authorization: Bearer $INFERENCE_API_KEY"
```

</CodeTabs>

The response includes every generation in the group:

```json
{
  "generations": [
    {
      "id": "gen_abc123",
      "state": "Success",
      "request": {
        "model": "kimi-k3-fast",
        "messages": [
          { "role": "system", "content": "You are a helpful assistant." },
          { "role": "user", "content": "What is the capital of France?" }
        ],
        "max_tokens": 100
      },
      "response": {
        "id": "gen_abc123",
        "object": "chat.completion",
        "choices": [
          {
            "message": {
              "role": "assistant",
              "content": "The capital of France is Paris."
            },
            "finish_reason": "stop"
          }
        ],
        "usage": {
          "prompt_tokens": 25,
          "completion_tokens": 8,
          "total_tokens": 33
        }
      }
    },
    {
      "id": "gen_def456",
      "state": "Success",
      "request": {
        "model": "kimi-k3-fast",
        "messages": [
          { "role": "system", "content": "You are a helpful assistant." },
          { "role": "user", "content": "What is the capital of Germany?" }
        ],
        "max_tokens": 100
      },
      "response": {
        "id": "gen_def456",
        "object": "chat.completion",
        "choices": [
          {
            "message": {
              "role": "assistant",
              "content": "The capital of Germany is Berlin."
            },
            "finish_reason": "stop"
          }
        ],
        "usage": {
          "prompt_tokens": 25,
          "completion_tokens": 8,
          "total_tokens": 33
        }
      }
    }
  ]
}
```

### List groups

List your team's groups, newest first. Use it to find groups in a time window, for example to check that every completed group's webhook was delivered.

<CodeTabs>

```bash
curl "https://api.inference.net/v1/slow/groups?limit=1000&since=2026-11-01T00:00:00Z&until=2026-11-02T00:00:00Z" \
  -H "Authorization: Bearer $INFERENCE_API_KEY"
```

</CodeTabs>

| Query parameter | Description |
| --- | --- |
| `limit` | Groups per page. Default `100`. Values above `1000` are clamped to `1000`. |
| `after` | A group ID. Returns the groups created before it. Pass the previous page's `last_id`. |
| `since` | ISO 8601 timestamp. Returns groups created at or after this time. |
| `until` | ISO 8601 timestamp. Returns groups created before this time. |

```json
{
  "object": "list",
  "data": [
    {
      "id": "group_xY3kL9mN2pQ",
      "object": "group",
      "status": "completed",
      "created_at": 1761955200,
      "completed_at": 1761955320,
      "request_counts": { "total": 2, "completed": 2, "failed": 0 }
    }
  ],
  "first_id": "group_xY3kL9mN2pQ",
  "last_id": "group_xY3kL9mN2pQ",
  "has_more": false
}
```

Timestamps are Unix seconds. `status` is one of `validating`, `in_progress`, `finalizing`, `completed`, `failed`, `expired`, `cancelling`, or `cancelled`. `request_counts` is final once the group reaches a terminal status. While `has_more` is `true`, request the next page with `after` set to `last_id`. Groups created while you page do not shift the pages. The same route is available at `/v1/async/groups`.

## Use webhooks

Attach a webhook to be notified when the group finishes processing. Include the
`webhook_id` when you submit the group:

<CodeTabs>

```typescript
const response = await fetch(
  "https://api.inference.net/v1/slow/group/chat/completions",
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.INFERENCE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      requests: [
        /* your requests */
      ],
      webhook_id: "my-webhook-123",
    }),
  },
);
```

```python
import os
import requests

response = requests.post(
    "https://api.inference.net/v1/slow/group/chat/completions",
    headers={
        "Authorization": f"Bearer {os.environ['INFERENCE_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "requests": [
            # your requests
        ],
        "webhook_id": "my-webhook-123",
    },
)
```

```bash
curl https://api.inference.net/v1/slow/group/chat/completions \
  -H "Authorization: Bearer $INFERENCE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "requests": [ ... ],
    "webhook_id": "my-webhook-123"
  }'
```

</CodeTabs>

When the group finishes, your webhook receives a `slow-group.completed`
notification. Its `data.status` is `completed` when all requests in the group
finished, or `failed` when the group could not finish: processing failed, or
the group passed its 72-hour completion window. In a failed group, check each
entry's `state` in `generations` to see which requests finished.

The notification includes:

- Group ID
- Completion status
- Summary of successful and failed requests
- Custom IDs for each request (if provided)

See [Webhooks](/docs/api/async/webhooks/) for setup and the
[webhooks reference](/docs/api/async/webhooks-reference/#slow-groupcompleted) for
the payload.

## Text completions

The Group API also supports text completions:

<CodeTabs>

```typescript
const response = await fetch(
  "https://api.inference.net/v1/slow/group/completions",
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.INFERENCE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      requests: [
        {
          model: "kimi-k3-fast",
          prompt: "The capital of France is",
          max_tokens: 10,
        },
        {
          model: "kimi-k3-fast",
          prompt: "The capital of Germany is",
          max_tokens: 10,
        },
      ],
    }),
  },
);
```

```python
import os
import requests

response = requests.post(
    "https://api.inference.net/v1/slow/group/completions",
    headers={
        "Authorization": f"Bearer {os.environ['INFERENCE_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "requests": [
            {
                "model": "kimi-k3-fast",
                "prompt": "The capital of France is",
                "max_tokens": 10,
            },
            {
                "model": "kimi-k3-fast",
                "prompt": "The capital of Germany is",
                "max_tokens": 10,
            },
        ],
    },
)
```

```bash
curl https://api.inference.net/v1/slow/group/completions \
  -H "Authorization: Bearer $INFERENCE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "requests": [
      {
        "model": "kimi-k3-fast",
        "prompt": "The capital of France is",
        "max_tokens": 10
      },
      {
        "model": "kimi-k3-fast",
        "prompt": "The capital of Germany is",
        "max_tokens": 10
      }
    ]
  }'
```

</CodeTabs>

## Embeddings

A group of embeddings requests sends one `slow-group.completed` webhook that
holds every vector of the group.

With `"encoding_format": "base64"`, set `"embed_dtype"` to choose the value
type of each vector:

| `embed_dtype` | Bytes per value | 768-dimension vector in base64 |
| --- | --- | --- |
| `float32` (default) | 4 | 4,096 characters |
| `float16` | 2 | 2,048 characters |

- Values are little-endian.
- `float16` halves the webhook body and your storage. Values keep about 3
  significant digits.
- `embed_dtype` has no effect with `"encoding_format": "float"`.

To decode a `float16` vector in Python:

```python
import base64
import numpy as np

vector = np.frombuffer(base64.b64decode(item["embedding"]), dtype="<f2").astype(np.float32)
```

### Image inputs

An image embedding request takes each image as a user message with one
`image_url` part. Send up to 50 images in one request:

```json
{
  "input": [
    [{ "role": "user", "content": [{ "type": "image_url", "image_url": { "url": "https://my-bucket.s3.amazonaws.com/cat.jpg?X-Amz-Expires=259200&..." } }] }],
    [{ "role": "user", "content": [{ "type": "image_url", "image_url": { "url": "data:image/jpeg;base64,/9j/4AAQ..." } }] }]
  ]
}
```

`image_url.url` is one of:

- A base64 data URI (`data:image/png`, `image/jpeg`, `image/gif` or
  `image/webp`) of at most 524,288 characters.
- An `https://` URL of at most 4,096 characters, for example a presigned S3
  GET URL. A URL is about 2 KB in the request body, where the same image as a
  data URI is its full size plus a third.

An `https://` URL must:

- Use a public host name: no IP address, `localhost` or internal name, and no
  `user:password@`. The host must resolve to public addresses.
- Return a PNG, JPEG, GIF or WebP image of at most 384 KiB within 10 seconds.
  Up to 4 redirects are followed, and redirects from `https://` must stay on
  `https://`.

A fetch that fails with HTTP 408, 429 or 5xx, a dropped connection or a
timeout is tried twice more on the worker. If a request still hits HTTP 408,
429, 5xx or a timeout, async dispatch retries it with backoff across the
completion window before failing.

S3 serves at least 5,500 GET requests per second per key prefix and answers
`503 SlowDown` while it scales past that. Above that rate, spread your keys
across prefixes (for example, start each key with a short hash).

We fetch the URL when the request runs, not when you submit it. A group can
wait up to its 72-hour completion window, so:

- Presign URLs for at least 72 hours (`X-Amz-Expires=259200`).
- A SigV4 presigned URL lasts at most 7 days, and only when you sign it with
  long-term IAM user credentials. A URL signed with temporary credentials (an
  IAM role, STS or SSO session) stops working when that session expires,
  whatever expiry you set.

Once a request finishes, its stored copy keeps `"REDACTED"` in place of each
image URL, unless the request sets its own `metadata.webhook_id`. The results
endpoints return the stored copy, and the group webhook always sends
`"REDACTED"`, so keep your own copy of the images if you need them.

Errors:

- A URL that breaks the rules above gets a `400` when you submit it.
- A URL we cannot fetch fails only its request: that generation's `state` is
  `Failed` and its `stateMessage` names the input (from 0) and the reason. The
  other requests in the group still run. Submit the failed request again with
  a fresh URL.

```text
Could not fetch the image URL of input 3: the server answered HTTP 403 (an expired presigned URL answers 403).
```

## Retry safely with Idempotency-Key

A group request can time out after the server accepted it. If you retry it
without a key, you can create the same group twice. To prevent this, send an
`Idempotency-Key` header, and send the same key and the same body on each retry.

- **Header:** `Idempotency-Key`, 1 to 255 printable ASCII characters.
- **Endpoints:** every async create endpoint under `/v1/slow/` and `/v1/async/`,
  for groups and for single requests.
- **Scope:** your team. Keys from other teams never match yours.
- **Lifetime:** 1 hour after the first request with the key succeeds.

| Request                                                | Response                                                                                                     |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
| First request with a key                               | The normal response.                                                                                         |
| Same key and body, after the first request succeeded   | `200` with the original body (the same `groupId`) and the header `Idempotent-Replayed: true`. No new group.  |
| Same key and body, while the first request is running  | `409` with type `IdempotencyKeyInProgress`. Wait, then retry with the same key.                              |
| Same key, different body or endpoint                   | `422` with type `IdempotencyKeyReused`.                                                                      |
| Key that is empty, too long, or not printable ASCII    | `400` with type `InvalidIdempotencyKey`.                                                                     |

Only successful responses are stored. If the first request fails, a retry with
the same key runs again. If the first request was interrupted before it
finished, retries can get `409` for up to 10 minutes. After that, a retry with
the same key runs again.

A key replays the original group for 1 hour. To submit the same requests
again as new work, use a new key. After 1 hour, the same key creates a new
group, so finish your retries for a group within that hour.

Idempotency is best effort. If the key check is briefly unavailable, the
request runs without it, so in rare cases a retry can still create a second
group. Make your pipeline tolerate an occasional duplicate group.

A `508` means no group was created. Any other `5xx` can arrive after the group
was created, so retry it only with the same key and body: when the group's
response was stored, the retry returns that group (`200` replay, or `409`
while it is still running) instead of creating a new one.

Derive the key from what identifies the group, for example a SHA-256 hash of
its custom IDs. Then every retry of that group uses the same key.

<CodeTabs>

```python
import hashlib
import json
import os
import time

import requests

def group_key(custom_ids):
    return hashlib.sha256("\n".join(custom_ids).encode()).hexdigest()

def submit_group(group, custom_ids):
    body = json.dumps(group).encode()  # Serialize once; resend the same bytes.
    headers = {
        "Authorization": f"Bearer {os.environ['INFERENCE_API_KEY']}",
        "Content-Type": "application/json",
        "Idempotency-Key": group_key(custom_ids),
    }
    for attempt in range(6):
        try:
            response = requests.post(
                "https://api.inference.net/v1/slow/group/embeddings",
                data=body,
                headers=headers,
                timeout=120,
            )
        except requests.RequestException:
            time.sleep(2**attempt)
            continue
        if response.status_code == 508:
            # subrequest_depth_exceeded: the request came through too many
            # Cloudflare Worker hops. A retry fails the same way; call from
            # a shallower Worker chain instead.
            response.raise_for_status()
        if response.status_code == 409 or response.status_code >= 500:
            # Another 5xx may follow a created group; the same key and body
            # replay it instead of creating a second one.
            time.sleep(2**attempt)
            continue
        response.raise_for_status()
        return response.json()  # {"groupId": "...", "groupSize": N}
    raise RuntimeError("group submit did not succeed")
```

```bash
curl https://api.inference.net/v1/slow/group/embeddings \
  -H "Authorization: Bearer $INFERENCE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 3f9a1c0e7b2d4a6f8e5c1b0a9d7e6f5c4b3a2918e7d6c5b4a3f2e1d0c9b8a7f6" \
  -d @group.json
```

</CodeTabs>

## Limits

- **Maximum requests per group:** 50
- **Request format:** direct JSON (no JSONL files)
- **Supported endpoints:**
  - `/v1/slow/group/chat/completions`
  - `/v1/slow/group/completions`
  - `/v1/slow/group/embeddings`
  - `/v1/slow/group/responses`
- **Completion time:** 72 hours
- **Request expiration:** groups expire after 72 hours if not completed
- **Stored input:** a group's requests are not a file in the Files API
  (`/v1/files`). The submitted body is deleted when the group closes; each
  request stays readable through [Retrieve group results](#retrieve-group-results)
  until the group's delivery finishes ([Data retention](/docs/data-retention/#asynchronous-results-are-kept-until-delivery-finishes)).

## Best practices

1. **Group related requests:** use groups for requests that logically belong
   together (for example, analyzing multiple documents from the same source).
2. **Use webhooks for notifications:** instead of polling, configure a webhook
   to be notified when your group completes.
3. **Handle individual failures:** some requests in a group may fail while
   others succeed. Check each generation's state.
4. **Stay under the limit:** keep groups to 50 requests or fewer. For larger
   workloads, use the [Batch API](/docs/api/async/batch/).
5. **Include metadata:** add custom IDs or metadata to your requests for easier
   tracking:

```json
{
  "model": "kimi-k3-fast",
  "messages": [{ "role": "user", "content": "..." }],
  "metadata": {
    "custom_id": "doc_123",
    "type": "summary"
  }
}
```

## Error handling

The API validates your request structure immediately. A common error:

```json
{
  "error": {
    "message": "Invalid request body.",
    "type": "BadRequestError",
    "fields": {
      "_errors": ["Unrecognized key(s) in object: 'webhook_url'"]
    }
  }
}
```

Use the correct field name:

- `webhook_id` (correct)
- `webhook_url` (incorrect — this is for the Batch API)

If the upstream provider returns an error without a JSON body, the response keeps the upstream HTTP status and its JSON body has `error.type` `upstream_error`. `error.request_id` matches the `X-Request-Id` response header.

## When to choose the Group API

Choose the Group API when you need:

- Quick implementation without file management
- To process 50 or fewer related requests
- Webhook notifications for a set of requests
- Simple JSON-based integration

For workloads of more than 50 requests, use the
[Batch API](/docs/api/async/batch/) instead.