Prompt caching
Maximizing cache hits
Set prompt_cache_key
The 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.
import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';
const { text, usage } = await generateText({
model: xai.responses('grok-4.7'),
prompt: 'What is prompt caching?',
providerOptions: {
xai: {
promptCacheKey: 'b79ad29b-b3f9-463c-bca6-041d5058d366',
},
},
});
console.log(text);
console.log(`Total tokens: ${usage.totalTokens}`);
Set x-grok-conv-id
The 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:
Bash
curl https://api.x.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $XAI_API_KEY" \
-H "x-grok-conv-id: conv_abc123" \
-d '{
"model": "grok-4.7",
"messages": [
{"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by SpaceXSI."},
{"role": "user", "content": "What is prompt caching?"}
]
}'
Set x-grok-conv-id metadata (gRPC API)
For the gRPC API using the xAI SDK, pass x-grok-conv-id as gRPC metadata to enable sticky routing for cache reuse.
Python
from xai_sdk import Client
from xai_sdk.chat import system, user
client = Client(
api_key="YOUR_API_KEY",
metadata=(("x-grok-conv-id", "conv_abc123"),),
)
chat = client.chat.create(model="grok-4.7")
chat.append(system("You are Grok, a helpful and truthful AI assistant built by SpaceXSI."))
chat.append(user("What is prompt caching?"))
response = chat.sample()
print(f"Response: {response.content}")
print(f"Cached tokens: {response.usage.cached_prompt_text_tokens}")
Next
Last updated: November 24, 2026