2 2
3# What Breaks Caching3# What Breaks Caching
4 4
5Any change to earlier messages breaks the cache. Only append new messages at the end.5A 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.
6 6
7> [!WARNING]7> [!WARNING]
8>8>
9> **Keep messages unchanged.** For cache hits in multi-turn conversations, never edit, remove, or reorder earlier messages — only append new ones. For reasoning models, you **must** include `reasoning_content` from previous responses; omitting it is the top cause of cache misses.9> **Keep messages unchanged.** For cache hits in multi-turn conversations, never edit, remove, or reorder earlier messages — only append new ones.
10 10
11For reasoning models, you can maintain cache hits by either:11For 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:
12 12
13* **Sending back the encrypted reasoning content** — Include the `reasoning_content` from the previous response. See [Encrypted Reasoning Content](/developers/model-capabilities/text/reasoning#encrypted-reasoning-content) for details.13* **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.
14* **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.14* **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.
15 15
16When 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.
17
16##  Cache hit — appending a new message18##  Cache hit — appending a new message
17 19
18The prompt prefix is identical to the previous request, with only a new user message appended:20The prompt prefix is identical to the previous request, with only a new user message appended:
26)28)
27 29
28conversation_id = "conv_abc123"30conversation_id = "conv_abc123"
29messages = [31history = [
30 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},32 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
31 {"role": "user", "content": "What is prompt caching?"},33 {"role": "user", "content": "What is prompt caching?"},
32]34]
33 35
34# Turn 1: Initial request (establishes the cache)36# Turn 1: Initial request (establishes the cache)
35response = client.chat.completions.create(37response = client.responses.create(
36 model="grok-4.7",38 model="grok-4.7",
37 messages=messages,39 input=history,
38 extra_headers={"x-grok-conv-id": conversation_id},40 include=["reasoning.encrypted_content"],
41 extra_body={"prompt_cache_key": conversation_id},
39)42)
40print(f"Turn 1 — Cached tokens: {response.usage.prompt_tokens_details.cached_tokens}")43print(f"Turn 1 — Cached tokens: {response.usage.input_tokens_details.cached_tokens}")
41 44
42# Append the assistant's reply and the next user message45history.extend(response.output)
43messages.append({"role": "assistant", "content": response.choices[0].message.content})46history.append({"role": "user", "content": "Show me a code example."})
44messages.append({"role": "user", "content": "Show me a code example."})
45 47
46# Turn 2: Cache HIT — prefix is unchanged, only new messages appended48# Turn 2: Cache HIT — prefix is unchanged, only new items appended
47response = client.chat.completions.create(49response = client.responses.create(
48 model="grok-4.7",50 model="grok-4.7",
49 messages=messages,51 input=history,
50 extra_headers={"x-grok-conv-id": conversation_id},52 include=["reasoning.encrypted_content"],
53 extra_body={"prompt_cache_key": conversation_id},
51)54)
52print(f"Turn 2 — Cached tokens: {response.usage.prompt_tokens_details.cached_tokens}")55print(f"Turn 2 — Cached tokens: {response.usage.input_tokens_details.cached_tokens}")
53```56```
54 57
55```bash customLanguage="bash" addedLines="26"58```bash customLanguage="bash" addedLines="26"
56# Turn 1: Initial request (establishes the cache)59# Turn 1: Initial request (establishes the cache)
57curl https://api.x.ai/v1/chat/completions \60curl https://api.x.ai/v1/responses \
58 -H "Content-Type: application/json" \61 -H "Content-Type: application/json" \
59 -H "Authorization: Bearer $XAI_API_KEY" \62 -H "Authorization: Bearer $XAI_API_KEY" \
60 -H "x-grok-conv-id: conv_abc123" \
61 -d '{63 -d '{
62 "model": "grok-4.7",64 "model": "grok-4.7",
63 "messages": [65 "prompt_cache_key": "conv_abc123",
66 "input": [
64 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},67 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
65 {"role": "user", "content": "What is prompt caching?"},68 {"role": "user", "content": "What is prompt caching?"},
66 {"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."}69 {"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."}
68 }'71 }'
69 72
70# Turn 2: Cache HIT — exact prefix preserved, new message appended73# Turn 2: Cache HIT — exact prefix preserved, new message appended
71curl https://api.x.ai/v1/chat/completions \74curl https://api.x.ai/v1/responses \
72 -H "Content-Type: application/json" \75 -H "Content-Type: application/json" \
73 -H "Authorization: Bearer $XAI_API_KEY" \76 -H "Authorization: Bearer $XAI_API_KEY" \
74 -H "x-grok-conv-id: conv_abc123" \
75 -d '{77 -d '{
76 "model": "grok-4.7",78 "model": "grok-4.7",
77 "messages": [79 "prompt_cache_key": "conv_abc123",
80 "input": [
78 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},81 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
79 {"role": "user", "content": "What is prompt caching?"},82 {"role": "user", "content": "What is prompt caching?"},
80 {"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."},83 {"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."},
92});95});
93 96
94const conversationId = 'conv_abc123';97const conversationId = 'conv_abc123';
95const messages = [98const history = [
96 {99 {
97 role: 'system',100 role: 'system',
98 content:101 content:
102];105];
103 106
104// Turn 1: Initial request (establishes the cache)107// Turn 1: Initial request (establishes the cache)
105const turn1 = await client.chat.completions.create(108const turn1 = await client.responses.create({
106 { model: 'grok-4.7', messages },109 model: 'grok-4.7',
107 { headers: { 'x-grok-conv-id': conversationId } },110 input: history,
108);111 include: ['reasoning.encrypted_content'],
112 prompt_cache_key: conversationId,
113});
109console.log(114console.log(
110 `Turn 1 — Cached tokens: ${turn1.usage.prompt_tokens_details.cached_tokens}`,115 `Turn 1 — Cached tokens: ${turn1.usage.input_tokens_details.cached_tokens}`,
111);116);
112 117
113// Append the assistant reply and next user message118history.push(...turn1.output);
114messages.push({ role: 'assistant', content: turn1.choices[0].message.content });119history.push({ role: 'user', content: 'Show me a code example.' });
115 120
116messages.push({ role: 'user', content: 'Show me a code example.' });121// Turn 2: Cache HIT — prefix unchanged, new items appended
117 122const turn2 = await client.responses.create({
118// Turn 2: Cache HIT — prefix unchanged, new message appended123 model: 'grok-4.7',
119const turn2 = await client.chat.completions.create(124 input: history,
120 { model: 'grok-4.7', messages },125 include: ['reasoning.encrypted_content'],
121 { headers: { 'x-grok-conv-id': conversationId } },126 prompt_cache_key: conversationId,
122);127});
123console.log(128console.log(
124 `Turn 2 — Cached tokens: ${turn2.usage.prompt_tokens_details.cached_tokens}`,129 `Turn 2 — Cached tokens: ${turn2.usage.input_tokens_details.cached_tokens}`,
125);130);
126```131```
127 132
128##  Cache miss — editing an earlier message133##  Cache miss — editing an earlier message
129 134
130Changing the content of any earlier message breaks the prefix match:135Changing the content of any earlier message breaks the prefix match from that message onward:
131 136
132```bash customLanguage="bash" deletedLines="11" addedLines="12"137```bash customLanguage="bash" deletedLines="11" addedLines="12"
133# Cache MISS — editing the assistant message content138# The cache breaks at the edited assistant message
134curl https://api.x.ai/v1/chat/completions \139curl https://api.x.ai/v1/responses \
135 -H "Content-Type: application/json" \140 -H "Content-Type: application/json" \
136 -H "Authorization: Bearer $XAI_API_KEY" \141 -H "Authorization: Bearer $XAI_API_KEY" \
137 -H "x-grok-conv-id: conv_abc123" \
138 -d '{142 -d '{
139 "model": "grok-4.7",143 "model": "grok-4.7",
140 "messages": [144 "prompt_cache_key": "conv_abc123",
145 "input": [
141 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},146 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
142 {"role": "user", "content": "What is prompt caching?"},147 {"role": "user", "content": "What is prompt caching?"},
143 {"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."},148 {"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."},
151 156
152##  Cache miss — removing a message157##  Cache miss — removing a message
153 158
154Removing any message from the conversation breaks the prefix:159Removing any message from the conversation breaks the prefix from that point onward:
155 160
156```bash customLanguage="bash" deletedLines="11"161```bash customLanguage="bash" deletedLines="11"
157# Cache MISS — the assistant message was removed162# The cache breaks where the assistant message was removed
158curl https://api.x.ai/v1/chat/completions \163curl https://api.x.ai/v1/responses \
159 -H "Content-Type: application/json" \164 -H "Content-Type: application/json" \
160 -H "Authorization: Bearer $XAI_API_KEY" \165 -H "Authorization: Bearer $XAI_API_KEY" \
161 -H "x-grok-conv-id: conv_abc123" \
162 -d '{166 -d '{
163 "model": "grok-4.7",167 "model": "grok-4.7",
164 "messages": [168 "prompt_cache_key": "conv_abc123",
169 "input": [
165 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},170 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
166 {"role": "user", "content": "What is prompt caching?"},171 {"role": "user", "content": "What is prompt caching?"},
167 {"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."},172 {"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."},
178 183
179```bash customLanguage="bash" deletedLines="9,10" addedLines="9,10"184```bash customLanguage="bash" deletedLines="9,10" addedLines="9,10"
180# Cache MISS — user and system messages are swapped185# Cache MISS — user and system messages are swapped
181curl https://api.x.ai/v1/chat/completions \186curl https://api.x.ai/v1/responses \
182 -H "Content-Type: application/json" \187 -H "Content-Type: application/json" \
183 -H "Authorization: Bearer $XAI_API_KEY" \188 -H "Authorization: Bearer $XAI_API_KEY" \
184 -H "x-grok-conv-id: conv_abc123" \
185 -d '{189 -d '{
186 "model": "grok-4.7",190 "model": "grok-4.7",
187 "messages": [191 "prompt_cache_key": "conv_abc123",
192 "input": [
188 {"role": "user", "content": "What is prompt caching?"},193 {"role": "user", "content": "What is prompt caching?"},
189 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},194 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
190 {"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."},195 {"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."},