SpyBara
Go Premium

Documentation 2026-11-22 23:59 UTC to 2026-11-23 23:59 UTC

10 files changed +318 −163. View all changes and history on the product overview
2026
Tue 24 23:59 Mon 23 23:59 Fri 20 23:59 Thu 19 22:57 Wed 18 23:57 Tue 17 23:59 Mon 16 23:59 Sun 15 22:59 Fri 13 23:57 Thu 12 22:57 Wed 11 23:00 Tue 10 23:57 Mon 9 23:00 Sun 8 23:57 Sat 7 22:59 Fri 6 23:59 Thu 5 23:58 Wed 4 23:01 Tue 3 23:00 Mon 2 23:57 Sun 1 23:02
Details

2 2 

3# Prompt Caching3# Prompt Caching

4 4 

5We recommend the [Responses API](/developers/model-capabilities/text/generate-text) for Grok models, and the examples in this section use it. It carries the model's reasoning from one request to the next, either in the `reasoning` items you send back or through `previous_response_id`; Chat Completions has no field for encrypted reasoning. Prompt caching itself works the same way on both APIs.

6 

5When consecutive requests share the same starting messages, the xAI API automatically caches them. On the next request, messages at the beginning that match exactly are served from cache:7When consecutive requests share the same starting messages, the xAI API automatically caches them. On the next request, messages at the beginning that match exactly are served from cache:

6 8 

7* **Faster time-to-first-token** — the model skips re-computing cached messages9* **Faster time-to-first-token** — the model skips re-computing cached messages


9 11 

10> [!NOTE]12> [!NOTE]

11>13>

12> The xAI API performs prompt caching **automatically**. However, we recommend setting the `x-grok-conv-id` HTTP header to maximize your cache hit rate.14> The xAI API performs prompt caching **automatically**. However, we recommend setting `prompt_cache_key` (or the `x-grok-conv-id` HTTP header) to maximize your cache hit rate.

13 15 

14## In this section16## In this section

15 17 

16* [How It Works](/developers/advanced-api-usage/prompt-caching/how-it-works) — Understand how caching works from the start of your messages array18* [How It Works](/developers/advanced-api-usage/prompt-caching/how-it-works) — Understand how caching works from the start of your messages array

17* [Maximizing Cache Hits](/developers/advanced-api-usage/prompt-caching/maximizing-cache-hits) — Set up `x-grok-conv-id` and `prompt_cache_key` for optimal caching19* [Maximizing Cache Hits](/developers/advanced-api-usage/prompt-caching/maximizing-cache-hits) — Set up `prompt_cache_key` or `x-grok-conv-id` for optimal caching

18* [What Breaks Caching](/developers/advanced-api-usage/prompt-caching/multi-turn) — Common mistakes that cause cache misses20* [What Breaks Caching](/developers/advanced-api-usage/prompt-caching/multi-turn) — Common mistakes that cause cache misses

19* [Usage & Pricing](/developers/advanced-api-usage/prompt-caching/usage-and-pricing) — Read cached token counts and understand billing21* [Usage & Pricing](/developers/advanced-api-usage/prompt-caching/usage-and-pricing) — Read cached token counts and understand billing

20* [Best Practices & FAQ](/developers/advanced-api-usage/prompt-caching/best-practices) — Tips, supported models, and common questions22* [Best Practices & FAQ](/developers/advanced-api-usage/prompt-caching/best-practices) — Tips, supported models, and common questions

Details

4 4 

5## Best practices5## Best practices

6 6 

71. **Always set `x-grok-conv-id`** (or `prompt_cache_key` for Responses API) — Routes requests to the same server, maximizing cache hits.71. **Always set `prompt_cache_key`** (or the `x-grok-conv-id` header) — Routes requests to the same server, maximizing cache hits.

8 8 

92. **Use a stable conversation ID** — A UUID or your application's session ID works well.92. **Use a stable conversation ID** — A UUID or your application's session ID works well.

10 10 

113. **Never modify earlier messages** — Only append new ones. Any edit, removal, or reorder breaks the cache.113. **Never modify earlier messages** — Only append new ones. Any edit, removal, or reorder breaks the cache from that point onward.

12 12 

134. **Front-load static content** — Place system prompts, few-shot examples, and reference documents at the beginning where they form a stable prefix.134. **Front-load static content** — Place system prompts, few-shot examples, and reference documents at the beginning where they form a stable prefix.

14 14 


28 28 

29### How long do cache entries persist?29### How long do cache entries persist?

30 30 

31Cache entries can be evicted at any time due to server load or restarts. Use `x-grok-conv-id` to maximize retention by routing to the same server.31Cache entries can be evicted at any time due to server load or restarts. Set `prompt_cache_key` (or `x-grok-conv-id`) to maximize retention by routing to the same server.

32 32 

33### Can I force a cache miss?33### Can I force a cache miss?

34 34 

35Yes — use a different `x-grok-conv-id` or omit the header entirely. This will route your request to a potentially different server where no cache exists for your prompt.35Not reliably. A different `prompt_cache_key` or `x-grok-conv-id`, or none at all, can route your request to a server where no cache exists for your prompt, but it can also reach one that has it. To keep a prompt from matching earlier requests, change the start of the prompt (`instructions` if you set it, otherwise the first message), since matching begins there.

36 36 

37### Does caching work with streaming?37### Does caching work with streaming?

38 38 

39Yes. Prompt caching works with both streaming and non-streaming requests. The first empty token in a stream corresponds to the cache lookup and prefill phase.39Yes. Prompt caching works with both streaming and non-streaming requests.

40 40 

41### Does caching work with tool calls and function calling?41### Does caching work with tool calls and function calling?

42 42 

Details

10 10 

11> [!WARNING]11> [!WARNING]

12>12>

13> Prompt caching is not 100% guaranteed. Cache entries can be evicted due to memory pressure, and requests may be routed to different servers. Use `x-grok-conv-id` to maximize cache hit rates.13> Prompt caching is not 100% guaranteed. Cache entries can be evicted due to memory pressure, and requests may be routed to different servers. Set `prompt_cache_key` (or `x-grok-conv-id`) to maximize cache hit rates.

14 14 

15## Example15## Example

16 16 

Details

2 2 

3# Maximizing Cache Hits3# Maximizing Cache Hits

4 4 

5## Set `x-grok-conv-id` (Chat Completions API)5## Set `prompt_cache_key`

6 6 

7The `x-grok-conv-id` HTTP header routes requests with the same conversation ID to the same server. Since cache entries are stored per-server, this maximizes your cache hit rate.7The `prompt_cache_key` field in the request body routes requests with the same key to the same server. Since cache entries are stored per-server, this maximizes your cache hit rate.

8 

9```python customLanguage="pythonOpenAISDK"

10from openai import OpenAI

11 

12client = OpenAI(

13 api_key="YOUR_XAI_API_KEY",

14 base_url="https://api.x.ai/v1",

15)

16 

17response = client.chat.completions.create(

18 model="grok-4.7",

19 messages=[

20 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},

21 {"role": "user", "content": "What is prompt caching?"},

22 ],

23 extra_headers={

24 "x-grok-conv-id": "conv_abc123",

25 },

26)

27 

28print(response.choices[0].message.content)

29print(f"Cached tokens: {response.usage.prompt_tokens_details.cached_tokens}")

30```

31 

32```bash customLanguage="bash"

33curl https://api.x.ai/v1/chat/completions \

34 -H "Content-Type: application/json" \

35 -H "Authorization: Bearer $XAI_API_KEY" \

36 -H "x-grok-conv-id: conv_abc123" \

37 -d '{

38 "model": "grok-4.7",

39 "messages": [

40 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},

41 {"role": "user", "content": "What is prompt caching?"}

42 ]

43 }'

44```

45 

46```javascript customLanguage="javascriptOpenAISDK"

47import OpenAI from 'openai';

48 

49const client = new OpenAI({

50 apiKey: 'YOUR_XAI_API_KEY',

51 baseURL: 'https://api.x.ai/v1',

52});

53 

54const response = await client.chat.completions.create(

55 {

56 model: 'grok-4.7',

57 messages: [

58 {

59 role: 'system',

60 content:

61 'You are Grok, a helpful and truthful AI assistant built by SpaceXSI.',

62 },

63 { role: 'user', content: 'What is prompt caching?' },

64 ],

65 },

66 {

67 headers: {

68 'x-grok-conv-id': 'conv_abc123',

69 },

70 },

71);

72 

73console.log(response.choices[0].message.content);

74console.log(

75 `Cached tokens: ${response.usage.prompt_tokens_details.cached_tokens}`,

76);

77```

78 

79## Set `prompt_cache_key` (Responses API)

80 

81For the Responses API, use the `prompt_cache_key` field directly in the request body. It functions identically to setting `x-grok-conv-id` — it routes requests to the same server for cache reuse.

82 8 

83```javascript customLanguage="javascriptAISDK"9```javascript customLanguage="javascriptAISDK"

84import { xai } from '@ai-sdk/xai';10import { xai } from '@ai-sdk/xai';


140const response = await client.responses.create({66const response = await client.responses.create({

141 model: 'grok-4.7',67 model: 'grok-4.7',

142 input: 'What is prompt caching?',68 input: 'What is prompt caching?',

143 // @ts-expect-error -- SpaceXSI-specific field

144 prompt_cache_key: 'b79ad29b-b3f9-463c-bca6-041d5058d366',69 prompt_cache_key: 'b79ad29b-b3f9-463c-bca6-041d5058d366',

145});70});

146 71 


150);75);

151```76```

152 77 

78## Set `x-grok-conv-id`

79 

80The `x-grok-conv-id` HTTP header functions identically to `prompt_cache_key`. Both the Responses API and the Chat Completions API accept either one; when a request sets both, `prompt_cache_key` takes priority. For example, on Chat Completions:

81 

82```bash customLanguage="bash"

83curl https://api.x.ai/v1/chat/completions \

84 -H "Content-Type: application/json" \

85 -H "Authorization: Bearer $XAI_API_KEY" \

86 -H "x-grok-conv-id: conv_abc123" \

87 -d '{

88 "model": "grok-4.7",

89 "messages": [

90 {"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},

91 {"role": "user", "content": "What is prompt caching?"}

92 ]

93 }'

94```

95 

153## Set `x-grok-conv-id` metadata (gRPC API)96## Set `x-grok-conv-id` metadata (gRPC API)

154 97 

155For the gRPC API using the xAI SDK, pass `x-grok-conv-id` as gRPC metadata to enable sticky routing for cache reuse.98For the gRPC API using the xAI SDK, pass `x-grok-conv-id` as gRPC metadata to enable sticky routing for cache reuse.

Details

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."},

Details

2 2 

3# Usage & Pricing3# Usage & Pricing

4 4 

5## Chat Completions API5## Responses API

6 6 

7Cached tokens appear in `usage.prompt_tokens_details.cached_tokens`:7Cached tokens appear in `usage.input_tokens_details.cached_tokens`:

8 8 

9```json customLanguage="json"9```json customLanguage="json"

10{10{

11 "usage": {11 "usage": {

12 "prompt_tokens": 125,12 "input_tokens": 125,

13 "completion_tokens": 48,13 "output_tokens": 48,

14 "total_tokens": 173,14 "total_tokens": 173,

15 "prompt_tokens_details": {15 "input_tokens_details": {

16 "text_tokens": 125,

17 "audio_tokens": 0,

18 "image_tokens": 0,

19 "cached_tokens": 9816 "cached_tokens": 98

20 },17 },

21 "completion_tokens_details": {18 "output_tokens_details": {

22 "reasoning_tokens": 0,19 "reasoning_tokens": 0

23 "audio_tokens": 0,

24 "accepted_prediction_tokens": 0,

25 "rejected_prediction_tokens": 0

26 }20 }

27 }21 }

28}22}

29```23```

30 24 

31## Responses API25## Chat Completions API

32 26 

33Cached tokens appear in `usage.input_tokens_details.cached_tokens`:27Cached tokens appear in `usage.prompt_tokens_details.cached_tokens`:

34 28 

35```json customLanguage="json"29```json customLanguage="json"

36{30{

37 "usage": {31 "usage": {

38 "input_tokens": 125,32 "prompt_tokens": 125,

39 "output_tokens": 48,33 "completion_tokens": 48,

40 "total_tokens": 173,34 "total_tokens": 173,

41 "input_tokens_details": {35 "prompt_tokens_details": {

36 "text_tokens": 125,

37 "audio_tokens": 0,

38 "image_tokens": 0,

42 "cached_tokens": 9839 "cached_tokens": 98

43 },40 },

44 "output_tokens_details": {41 "completion_tokens_details": {

45 "reasoning_tokens": 042 "reasoning_tokens": 0,

43 "audio_tokens": 0,

44 "accepted_prediction_tokens": 0,

45 "rejected_prediction_tokens": 0

46 }46 }

47 }47 }

48}48}


56|---|---|56|---|---|

57| `0` | **Cache miss** — the entire prompt was computed from scratch. This is expected on the first request or after cache eviction. |57| `0` | **Cache miss** — the entire prompt was computed from scratch. This is expected on the first request or after cache eviction. |

58| `> 0` | **Cache hit** — some or all of your prompt prefix was served from cache. The number indicates how many tokens were reused. |58| `> 0` | **Cache hit** — some or all of your prompt prefix was served from cache. The number indicates how many tokens were reused. |

59| Equal to `prompt_tokens` | **Full cache hit** — your entire prompt was served from cache (rare, typically happens when resending the exact same request). |59| Close to the input token count | **Near-full cache hit** — almost your entire prompt was served from cache, as when you resend the exact same request. |

60 60 

61A typical multi-turn conversation shows increasing `cached_tokens` over time:61A typical multi-turn conversation shows increasing `cached_tokens` over time:

62 62 

63```text63```text

64Turn 1: prompt_tokens=50, cached_tokens=0 # First request, cache established64Turn 1: input_tokens=50, cached_tokens=0 # First request, cache established

65Turn 2: prompt_tokens=120, cached_tokens=50 # Previous 50 tokens cached65Turn 2: input_tokens=120, cached_tokens=50 # Previous 50 tokens cached

66Turn 3: prompt_tokens=200, cached_tokens=120 # Previous 120 tokens cached66Turn 3: input_tokens=200, cached_tokens=120 # Previous 120 tokens cached

67```67```

68 68 

69> [!NOTE]69> [!NOTE]

70>70>

71> If `cached_tokens` is consistently 0 across multiple requests in the same conversation, verify that you're setting `x-grok-conv-id` (or `prompt_cache_key`) and that you're not modifying earlier messages between requests.71> If `cached_tokens` is consistently 0 across multiple requests in the same conversation, verify that you're setting `prompt_cache_key` (or `x-grok-conv-id`) and that you're not modifying earlier messages between requests.

72 72 

73## Pricing73## Pricing

74 74 

Details

1#### Advanced API Usage

2 

3# Troubleshooting Reasoning

4 

5Grok reasoning models think before they answer or call a tool, and they work best when each later request gives that reasoning back. When a multi-turn or tool-calling integration loses it, nothing fails: the API returns `200`, and results can get worse.

6 

7## Dropping the reasoning items

8 

9The `input` of your follow-up requests has `function_call` items or assistant messages with no `reasoning` item before them. This happens when code keeps only the answer text or the function calls from a response, reads only the text of a stream, or rebuilds the history from its own records.

10 

11To fix it, keep every item of each response's `output` array exactly as it arrived and append all of them, in order, to the history, then add your tool results. When you stream, take the items from the final `response.completed` or `response.incomplete` event:

12 

13```json addedLines="3"

14[

15 {"role": "user", "content": "What is the temperature in Paris?"},

16 {"type": "reasoning", "summary": [], "encrypted_content": "Hfq+g7jQ...4QfQnY"},

17 {"type": "function_call", "call_id": "call-5faadddf-0", "name": "get_temperature", "arguments": "{\"location\":\"Paris\"}"},

18 {"type": "function_call_output", "call_id": "call-5faadddf-0", "output": "{\"temperature\":15}"}

19]

20```

21 

22To confirm the fix, log the `input` of a follow-up request and check that it holds every `reasoning` item of the earlier responses, each in its original place. For a complete loop in Python, see [Keep reasoning in agent loops](/developers/model-capabilities/text/best-practices#keep-reasoning-in-agent-loops).

23 

24## Not asking for encrypted reasoning

25 

26The `reasoning` items you send back have no `encrypted_content` field. `grok-4.7` returns `encrypted_content` on every response; earlier models, such as `grok-4.6` and `grok-4.5`, return it only when you ask.

27 

28To fix it, add `include` to every request of a conversation whose history you keep yourself, starting with the first. Apply this together with the first fix; asking for encrypted reasoning helps only if your requests send it back. In the xAI SDK, set `use_encrypted_content=True`.

29 

30```json addedLines="4"

31{

32 "model": "grok-4.6",

33 "store": false,

34 "include": ["reasoning.encrypted_content"],

35 "input": [{"role": "user", "content": "What is the temperature in Paris?"}]

36}

37```

38 

39## Using Chat Completions for multi-turn conversations

40 

41Your multi-turn or tool-calling requests go to `/v1/chat/completions`. That endpoint has no field for encrypted reasoning, so your requests cannot send it back.

42 

43To fix it, send these conversations to `/v1/responses` and keep the history as in the first fix. The assistant turn changes from a `messages` entry to the output items of the response. The [comparison guide](/developers/model-capabilities/text/comparison) maps each parameter and field.

44 

45```json addedLines="3,4"

46[

47 {"role": "user", "content": "What is the temperature in Paris?"},

48 {"type": "reasoning", "summary": [], "encrypted_content": "Hfq+g7jQ...4QfQnY"},

49 {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "It is 15°C."}]},

50 {"role": "user", "content": "And in Fahrenheit?"}

51]

52```

53 

54## Sending both the previous response ID and the history

55 

56A request sets `previous_response_id` and also resends the earlier turns in `input`. Nothing fails, but those turns are sent twice and `usage.input_tokens` grows much faster than the conversation.

57 

58To fix it, choose one way to continue a conversation. With `previous_response_id`, send only the new items. Without it, send the whole history. A `previous_response_id` that points at a response created with `store: false` returns `404`, so those conversations need the whole history.

59 

60> [!NOTE]

61>

62> With [Zero Data Retention (ZDR)](/developers/faq/security#what-is-zero-data-retention-zdr) enabled for your team, `previous_response_id` does not work for HTTP requests either, so send the whole history.

63 

64```json

65{

66 "model": "grok-4.7",

67 "previous_response_id": "9a1e6c0e-5c1f-4f0b-b5a5-1c2f6f6f0d11",

68 "input": [

69 {"type": "function_call_output", "call_id": "call-5faadddf-0", "output": "{\"temperature\":15}"}

70 ]

71}

72```

73 

74## Tool results that do not match their calls

75 

76A `function_call_output` has an empty `call_id` or one that matches no `function_call`, or a `function_call` has no result. The API accepts these requests, and the model cannot reliably tell which result answers which call. One cause is an unset field that serializes as `""`.

77 

78To fix it, copy the `call_id` of each `function_call` into the result that answers it, and send a result for every call:

79 

80```json addedLines="3"

81[

82 {"type": "function_call", "call_id": "call-5faadddf-0", "name": "get_temperature", "arguments": "{\"location\":\"Paris\"}"},

83 {"type": "function_call_output", "call_id": "call-5faadddf-0", "output": "{\"temperature\":15}"}

84]

85```

86 

87## Changing reasoning items

88 

89A follow-up fails with `400` and `Could not decrypt the provided encrypted_content`. Something between the response and the next request shortened or rewrote the item, for example storage that truncates long strings.

90 

91To fix it, store and send every reasoning item unchanged:

92 

93```json addedLines="2"

94[

95 {"type": "reasoning", "summary": [], "encrypted_content": "Hfq+g7jQ...4QfQnY"}

96]

97```

98 

99## Fix it with a coding agent

100 

101Paste the following into your coding agent, or save it as a skill, for example as `.grok/skills/fix-grok-reasoning/SKILL.md` for [Grok Build](/build/features/skills-plugins-marketplaces). It finds these mistakes in your code and fixes them.

102 

103```text

104---

105name: fix-grok-reasoning

106description: >-

107 Find and fix code that loses a Grok model's reasoning between requests in

108 multi-turn or tool-calling conversations on the xAI API. Use when results

109 get worse over a conversation or agent loop, or when asked to check that

110 reasoning is sent back to the model.

111---

112 

113# Fix lost reasoning in xAI API conversations

114 

115Grok reasoning models return their reasoning as "reasoning" items in the

116output array of a /v1/responses response. Each later request must give

117them back, by exactly one of two routes:

118 

119- Stored: set previous_response_id and put only the new items in input.

120 The previous response must have been created with store on (the

121 default). Over HTTP, this route does not work for teams with Zero Data

122 Retention.

123- Stateless: no previous_response_id. Put the whole conversation in input,

124 including every output item of every earlier response, unchanged and in

125 order, and send include: ["reasoning.encrypted_content"] on every

126 request.

127 

128A correct stateless follow-up after one tool call:

129 

130 {

131 "model": "<same model>",

132 "store": false,

133 "include": ["reasoning.encrypted_content"],

134 "tools": [<same tools>],

135 "input": [

136 {"role": "user", "content": "<the question>"},

137 {"type": "reasoning", "id": "rs_...", "summary": [],

138 "encrypted_content": "<as received>"},

139 {"type": "function_call", "id": "fc_...", "call_id": "call-1",

140 "name": "<tool>", "arguments": "<as received>"},

141 {"type": "function_call_output", "call_id": "call-1",

142 "output": "<your tool result>"}

143 ]

144 }

145 

146Real items carry more fields than shown here. Send all of them back.

147 

148Most of these mistakes return HTTP 200 and a plausible answer, so judge

149from the request bodies, not from the responses.

150 

1511. Work only on calls to the xAI API; leave other providers alone. Find

152 where a response's output is read and where the input of the next

153 request is built. Search for /v1/responses, /v1/chat/completions,

154 responses.create, chat.completions.create, previous_response_id, and

155 function_call_output. Then follow the history between requests: where

156 it is saved, loaded, converted, or logged. An SDK that runs the tool

157 loop for you, a wrapper, or a storage layer can drop or change items

158 after the code that builds them. Requests with no follow-up need no

159 change.

160 

1612. Check each point. Fix every failure with the smallest change that works.

162 a. Reasoning dropped. The code keeps only text or function calls,

163 filters output by type, rebuilds items from its own types, or reads

164 only the text deltas of a stream. Fix: keep each response's output

165 items as raw JSON (from the response.completed or response.incomplete

166 event when streaming) and append the whole array to the history,

167 before the tool results.

168 b. Encrypted reasoning not requested on the stateless route. Fix: send

169 include: ["reasoning.encrypted_content"] on every request, including

170 the first (use_encrypted_content=True in the xAI SDK; in the Vercel

171 AI SDK, providerOptions.xai with store: false or include).

172 c. Multi-turn or tool-calling requests sent to /v1/chat/completions,

173 which cannot carry reasoning. Fix: move them to /v1/responses, then

174 apply a and b. If the migration is too large to do safely, stop and

175 report it.

176 d. previous_response_id sent together with earlier turns. Fix: keep one

177 route. If the id fails with 404, use the stateless route.

178 e. A function_call_output with an empty call_id or one that matches no

179 function_call, or a call left without a result. Fix: copy call_id

180 from the function_call and answer every call.

181 f. Reasoning items edited or truncated (error 400 "Could not decrypt

182 the provided encrypted_content"). Look for length limits where the

183 history is saved or logged. Fix: store and send the items unchanged.

184 Keep a limit that other data relies on; exempt conversation items.

185 

1863. Verify with a test that sends two requests of one conversation (with a

187 tool call if the code uses tools) and captures the body of the second.

188 Stateless: it must hold every output item of the first response

189 unchanged, each reasoning item with a non-empty encrypted_content.

190 Stored: it must set previous_response_id and hold only new items.

191 Either way, every function_call_output.call_id must match a

192 function_call. If an API key is available, also run every multi-turn

193 flow once against the API, including the ones you judged correct, and

194 check the follow-up bodies it really sends. Some failures, such as the

195 400 above, show up only then. Existing tests must still pass.

196 

1974. Report what was wrong, with file and line, what you changed, and what

198 you could not check. Do not change models, prompts, or tools.

199```

faq/security.md +4 −0

Details

96 96 

97The default endpoint, `https://api.x.ai`, does not guarantee a processing region. To keep API request handling, model inference, moderation, and retained request data in the United States, use the US regional endpoint, `https://us.api.x.ai/v1`. It currently serves only `grok-4.7` and `grok-4.6`, with no image generation, video generation, or voice APIs, and its token prices are 10% higher than global rates. Files, Collections, server-side tools, and the network path from your systems to the endpoint are outside the guarantee. See [Regional Endpoints](/developers/advanced-api-usage/regions) for details.97The default endpoint, `https://api.x.ai`, does not guarantee a processing region. To keep API request handling, model inference, moderation, and retained request data in the United States, use the US regional endpoint, `https://us.api.x.ai/v1`. It currently serves only `grok-4.7` and `grok-4.6`, with no image generation, video generation, or voice APIs, and its token prices are 10% higher than global rates. Files, Collections, server-side tools, and the network path from your systems to the endpoint are outside the guarantee. See [Regional Endpoints](/developers/advanced-api-usage/regions) for details.

98 98 

99## Is audio from the voice APIs watermarked?

100 

101Yes. Audio generated by [Text to Speech](/developers/model-capabilities/audio/text-to-speech) and [Speech to Speech](/developers/model-capabilities/audio/speech-to-speech), including custom voices, is watermarked with [AudioSeal](https://github.com/facebookresearch/audioseal), an inaudible watermark embedded directly in the audio to help identify it as synthetic speech.

102 

99## Is the xAI API HIPAA compliant?103## Is the xAI API HIPAA compliant?

100 104 

101To inquire about a Business Associate Agreement (BAA), please complete our [BAA Questionnaire](https://x.ai/legal/baa). A member of our team will review your responses and reach out with next steps.105To inquire about a Business Associate Agreement (BAA), please complete our [BAA Questionnaire](https://x.ai/legal/baa). A member of our team will review your responses and reach out with next steps.

Details

229* It edits, reorders, or filters output items before sending them back. Pass them back exactly as received.229* It edits, reorders, or filters output items before sending them back. Pass them back exactly as received.

230* It rebuilds the conversation from a transcript in a different format, such as a Chat Completions `messages` array, between turns.230* It rebuilds the conversation from a transcript in a different format, such as a Chat Completions `messages` array, between turns.

231 231 

232[Troubleshooting Reasoning](/developers/advanced-api-usage/troubleshooting-reasoning) shows how to check your requests for each of these and how to fix them.

233 

232For long agent loops, [WebSocket mode](/developers/advanced-api-usage/websocket-mode) reduces per-turn latency, and [context compaction](/developers/advanced-api-usage/context-compaction) keeps long conversations within the context window.234For long agent loops, [WebSocket mode](/developers/advanced-api-usage/websocket-mode) reduces per-turn latency, and [context compaction](/developers/advanced-api-usage/context-compaction) keeps long conversations within the context window.

233 235 

234## Use prompt caching to lower cost236## Use prompt caching to lower cost

Details

10 10 

11### Encrypted Reasoning Content11### Encrypted Reasoning Content

12 12 

13The reasoning content is encrypted by us and can be returned if you pass `include: ["reasoning.encrypted_content"]` to the Responses API. You can send the encrypted content back to provide more context to a previous conversation. See [Adding encrypted thinking content](/developers/model-capabilities/text/generate-text#adding-encrypted-thinking-content) for more details on how to use the content.13The reasoning content is encrypted by us and can be returned if you pass `include: ["reasoning.encrypted_content"]` to the Responses API. You can send the encrypted content back to provide more context to a previous conversation. See [Adding encrypted thinking content](/developers/model-capabilities/text/generate-text#adding-encrypted-thinking-content) for more details on how to use the content, and [Troubleshooting Reasoning](/developers/advanced-api-usage/troubleshooting-reasoning) to check that your multi-turn and tool-calling requests carry it.

14 14 

15> [!NOTE]15> [!NOTE]

16> Always returned for grok-4.716> Always returned for grok-4.7