#### Prompt caching

# What breaks caching

A change to an earlier message breaks the cache from that message onward; everything before it is still served from cache. To keep the whole conversation cached, only append new messages at the end. The same rules apply to the `messages` array of Chat Completions requests.

> [!WARNING]
>
> **Keep messages unchanged.** For cache hits in multi-turn conversations, never edit, remove, or reorder earlier messages — only append new ones.

For reasoning models, the reasoning of earlier turns is part of the cached prefix. On the Responses API, you can keep it in place by either:

* **Sending back the reasoning items** — Append every item of each response's `output` array, including the `reasoning` items, unchanged to the next request's `input`, and set `include: ["reasoning.encrypted_content"]` on every request. See [Encrypted Reasoning Content](/developers/model-capabilities/text/reasoning#encrypted-reasoning-content) for details.
* **Using stateful responses** — Use `previous_response_id` to automatically continue the conversation. See [Chaining the Conversation](/developers/model-capabilities/text/generate-text#chaining-the-conversation) for details.

When a follow-up request loses a turn's reasoning, the cache can match only up to that turn. [Troubleshooting Reasoning](/developers/advanced-api-usage/troubleshooting-reasoning) lists the mistakes that lose it.

## Cache hit — appending a new message

The prompt prefix is identical to the previous request, with only a new user message appended:

```python customLanguage="pythonOpenAISDK"
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_XAI_API_KEY",
    base_url="https://api.x.ai/v1",
)

conversation_id = "conv_abc123"
history = [
    {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
    {"role": "user", "content": "What is prompt caching?"},
]

# Turn 1: Initial request (establishes the cache)
response = client.responses.create(
    model="grok-4.7",
    input=history,
    include=["reasoning.encrypted_content"],
    extra_body={"prompt_cache_key": conversation_id},
)
print(f"Turn 1 — Cached tokens: {response.usage.input_tokens_details.cached_tokens}")

history.extend(response.output)
history.append({"role": "user", "content": "Show me a code example."})

# Turn 2: Cache HIT — prefix is unchanged, only new items appended
response = client.responses.create(
    model="grok-4.7",
    input=history,
    include=["reasoning.encrypted_content"],
    extra_body={"prompt_cache_key": conversation_id},
)
print(f"Turn 2 — Cached tokens: {response.usage.input_tokens_details.cached_tokens}")
```

```bash customLanguage="bash" addedLines="26"
# Turn 1: Initial request (establishes the cache)
curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-4.7",
    "prompt_cache_key": "conv_abc123",
    "input": [
      {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
      {"role": "user", "content": "What is prompt caching?"},
      {"role": "assistant", "content": "Prompt caching stores KV pairs from unchanged prompt prefixes so they can be reused on subsequent requests. This makes responses faster and cheaper."}
    ]
  }'

# Turn 2: Cache HIT — exact prefix preserved, new message appended
curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-4.7",
    "prompt_cache_key": "conv_abc123",
    "input": [
      {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
      {"role": "user", "content": "What is prompt caching?"},
      {"role": "assistant", "content": "Prompt caching stores KV pairs from unchanged prompt prefixes so they can be reused on subsequent requests. This makes responses faster and cheaper."},
      {"role": "user", "content": "Show me a code example."}
    ]
  }'
```

```javascript customLanguage="javascriptOpenAISDK"
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'YOUR_XAI_API_KEY',
  baseURL: 'https://api.x.ai/v1',
});

const conversationId = 'conv_abc123';
const history = [
  {
    role: 'system',
    content:
      'You are Grok, a helpful and truthful AI assistant built by SpaceXSI.',
  },
  { role: 'user', content: 'What is prompt caching?' },
];

// Turn 1: Initial request (establishes the cache)
const turn1 = await client.responses.create({
  model: 'grok-4.7',
  input: history,
  include: ['reasoning.encrypted_content'],
  prompt_cache_key: conversationId,
});
console.log(
  `Turn 1 — Cached tokens: ${turn1.usage.input_tokens_details.cached_tokens}`,
);

history.push(...turn1.output);
history.push({ role: 'user', content: 'Show me a code example.' });

// Turn 2: Cache HIT — prefix unchanged, new items appended
const turn2 = await client.responses.create({
  model: 'grok-4.7',
  input: history,
  include: ['reasoning.encrypted_content'],
  prompt_cache_key: conversationId,
});
console.log(
  `Turn 2 — Cached tokens: ${turn2.usage.input_tokens_details.cached_tokens}`,
);
```

## Cache miss — editing an earlier message

Changing the content of any earlier message breaks the prefix match from that message onward:

```bash customLanguage="bash" deletedLines="11" addedLines="12"
# The cache breaks at the edited assistant message
curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-4.7",
    "prompt_cache_key": "conv_abc123",
    "input": [
      {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
      {"role": "user", "content": "What is prompt caching?"},
      {"role": "assistant", "content": "Prompt caching stores KV pairs from unchanged prompt prefixes so they can be reused on subsequent requests. This makes responses faster and cheaper."},
      {"role": "assistant", "content": "It stores KV pairs."},
      {"role": "user", "content": "Show me a code example."}
    ]
  }'
```

**What changed:** The assistant response on line 11 was shortened to `"It stores KV pairs."` (line 12).

## Cache miss — removing a message

Removing any message from the conversation breaks the prefix from that point onward:

```bash customLanguage="bash" deletedLines="11"
# The cache breaks where the assistant message was removed
curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-4.7",
    "prompt_cache_key": "conv_abc123",
    "input": [
      {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
      {"role": "user", "content": "What is prompt caching?"},
      {"role": "assistant", "content": "Prompt caching stores KV pairs from unchanged prompt prefixes so they can be reused on subsequent requests. This makes responses faster and cheaper."},
      {"role": "user", "content": "Show me a code example."}
    ]
  }'
```

**What changed:** The assistant message on line 11 was removed entirely.

## Cache miss — reordering messages

Changing the order of messages also breaks the prefix:

```bash customLanguage="bash" deletedLines="9,10" addedLines="9,10"
# Cache MISS — user and system messages are swapped
curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-4.7",
    "prompt_cache_key": "conv_abc123",
    "input": [
      {"role": "user", "content": "What is prompt caching?"},
      {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
      {"role": "assistant", "content": "Prompt caching stores KV pairs from unchanged prompt prefixes so they can be reused on subsequent requests. This makes responses faster and cheaper."},
      {"role": "user", "content": "Show me a code example."}
    ]
  }'
```

**What changed:** Lines 9 and 10 were swapped — the user message now comes before the system message.

## Next

* [Usage & Pricing](/developers/advanced-api-usage/prompt-caching/usage-and-pricing)
