#### Advanced API usage

# Deferred Chat Completions

> [!NOTE]
>
> Deferred Chat Completions are currently available only via REST requests or xAI SDK.

Deferred Chat Completions allow you to create a chat completion, get a `request_id`, and retrieve the response at a later time. The result would be available to be requested exactly once within 24 hours, after which it would be discarded.

> [!TIP]
>
> Your deferred completion rate limit is the same as your chat completions rate limit. To view your rate limit, please visit [Grok Console](https://console.x.ai?utm_source=docs\&utm_medium=referral\&utm_campaign=developers-advanced-api-usage-deferred-chat-completions\&utm_content=console-home).

After sending the request to the Grok API, the chat completion result will be available at `https://api.x.ai/v1/chat/deferred-completion/{request_id}`. The response body will contain `{'request_id': 'f15c114e-f47d-40ca-8d5c-8c23d656eeb6'}`, and the `request_id` value can be inserted into the `deferred-completion` endpoint path. Then, we send this GET request to retrieve the deferred completion result.

When the completion result is not ready, the request will return `202 Accepted` with an empty response body.

> [!TIP]
>
> Reasoning models return a summary of their thinking in `message.reasoning_content` on the chat completion response. It is a short summary written for the reader, not the model's raw thinking trace, and it is much shorter than `usage.completion_tokens_details.reasoning_tokens` suggests.

> [!NOTE]
>
> `deferred` works on [Chat Completions](/developers/rest-api-reference/inference/chat-completions) only. The [Responses API](/developers/rest-api-reference/inference/responses) ignores `deferred: true`: the request runs synchronously and returns a normal completed response with no `request_id`.

## Example

A code example is provided below, where we retry retrieving the result until it has been processed. The examples use third-party packages for the HTTP request and the retry loop: `requests` and `tenacity` for Python without the xAI SDK (`pip install requests tenacity`), `axios` and `retry` for JavaScript (`npm install axios retry`), and `jq` for the shell example. The JavaScript example uses ESM `import`, so run it as `.mjs` or set `"type": "module"` in your `package.json`.

```pythonRequests
import json
import os
import requests

from tenacity import retry, wait_exponential

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"
}

payload = {
    "messages": [
        {"role": "system", "content": "You are Zaphod Beeblebrox."},
        {"role": "user", "content": "126/3=?"}
    ],
    "model": "grok-4.7",
    "deferred": True
}

response = requests.post(
    "https://api.x.ai/v1/chat/completions",
    headers=headers,
    json=payload
)
request_id = response.json()["request_id"]
print(f"Request ID: {request_id}")

@retry(wait=wait_exponential(multiplier=1, min=1, max=60),)
def get_deferred_completion():
    response = requests.get(f"https://api.x.ai/v1/chat/deferred-completion/{request_id}", headers=headers)
    if response.status_code == 200:
        return response.json()
    elif response.status_code == 202:
        raise Exception("Response not ready yet")
    else:
        raise Exception(f"{response.status_code} Error: {response.text}")

completion_data = get_deferred_completion()
print(json.dumps(completion_data, indent=4))
```

```javascriptWithoutSDK
import axios from 'axios';
import retry from 'retry';

const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.XAI_API_KEY}`
};

const payload = {
    messages: [
        { role: 'system', content: 'You are Zaphod Beeblebrox.' },
        { role: 'user', content: '126/3=?' }
    ],
    model: 'grok-4.7',
    deferred: true
};

async function main() {
    const requestId = (await axios.post('https://api.x.ai/v1/chat/completions', payload, { headers })).data.request_id;
    console.log(`Request ID: ${requestId}`);

    const operation = retry.operation({
        minTimeout: 1000,
        maxTimeout: 60000,
        factor: 2
    });

    const completion = await new Promise((resolve, reject) => {
        operation.attempt(async () => {
            const res = await axios.get(`https://api.x.ai/v1/chat/deferred-completion/${requestId}`, { headers });

            if (res.status === 200) resolve(res.data);
            else if (res.status === 202) operation.retry(new Error('Not ready'));
            else reject(new Error(`${res.status}: ${res.statusText}`));
        });

    });

    console.log(JSON.stringify(completion, null, 4));
}

main().catch(console.error);
```

```bash
RESPONSE=$(curl -s https://api.x.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $XAI_API_KEY" \
-d '{
    "messages": [
        {"role": "system", "content": "You are Zaphod Beeblebrox."},
        {"role": "user", "content": "126/3=?"}
    ],
    "model": "grok-4.7",
    "deferred": true
}')

REQUEST_ID=$(echo "$RESPONSE" | jq -r '.request_id')
echo "Request ID: $REQUEST_ID"

sleep 10

curl -s https://api.x.ai/v1/chat/deferred-completion/$REQUEST_ID \
-H "Authorization: Bearer $XAI_API_KEY"
```

```pythonXAI
import os
from datetime import timedelta

from xai_sdk import Client
from xai_sdk.chat import user, system

client = Client(api_key=os.getenv('XAI_API_KEY'))

chat = client.chat.create(
    model="grok-4.7",
    messages=[system("You are Zaphod Beeblebrox.")]
)
chat.append(user("126/3=?"))

# Poll the result every 10 seconds for a maximum of 10 minutes

response = chat.defer(
    timeout=timedelta(minutes=10), interval=timedelta(seconds=10)
)

# Print the result when it is ready

print(response.content)
```

The response body will be the same as what you would expect with non-deferred chat completions:

```json
{
  "id": "d98419d2-b389-4d3c-b281-2be770e551e9",
  "object": "chat.completion",
  "created": 1795495585,
  "model": "grok-4.7",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "42.\n\nEven I, Zaphod Beeblebrox, former President of the Galaxy and owner of two heads and zero patience for arithmetic, can see that 126 divided by 3 is 42. The universe keeps insisting on that number. Rude, really.",
        "reasoning_content": "The user is asking for the result of 126 divided by 3.",
        "refusal": null
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1259,
    "completion_tokens": 55,
    "total_tokens": 1479,
    "prompt_tokens_details": {
      "text_tokens": 1259,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 1152
    },
    "completion_tokens_details": {
      "reasoning_tokens": 165,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "num_sources_used": 0,
    "cost_in_usd_ticks": 21100000
  },
  "system_fingerprint": "fp_b507827d1c19f448",
  "service_tier": "default"
}
```

For more details, refer to [Chat completions](/developers/rest-api-reference/inference/chat-completions#chat-completions) and [Get deferred chat completions](/developers/rest-api-reference/inference/chat-completions#get-deferred-chat-completions) in our REST API Reference.
