Prompt Caching
最大化 Cache Hit
设置 x-grok-conv-id(Chat Completions API)
该 x-grok-conv-id HTTP header 会将具有相同 conversation ID 的请求路由到同一个 Server。由于 cache entry 按 Server 存储,这可以最大限度提高 cache hit rate。
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.5",
"messages": [
{"role": "system", "content": "You are Grok, a helpful and truthful AI assistant built by xAI."},
{"role": "user", "content": "What is prompt caching?"}
]
}'设置 prompt_cache_key(Responses API)
对于 Responses API,请直接在 request body 中使用 prompt_cache_key 字段。它与设置 x-grok-conv-id 的作用相同,会将请求路由到同一个 Server 以复用 cache。
curl https://api.x.ai/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $XAI_API_KEY" \
-d '{
"model": "grok-4.5",
"input": "What is prompt caching?",
"prompt_cache_key": "b79ad29b-b3f9-463c-bca6-041d5058d366"
}'设置 x-grok-conv-id metadata(gRPC API)
通过 xAI SDK 使用 gRPC API 时,请将 x-grok-conv-id 作为 gRPC metadata 传入,启用 sticky routing 以复用 cache。
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.5")
chat.append(system("You are Grok, a helpful and truthful AI assistant built by xAI."))
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}")