In short.
This is a guide from xAI's cookbook for developers building multi-turn chats on the Grok API, and its main catch is that every number is xAI's own single-run or in-house result, so you would need to run the demo yourself to confirm them. It explains that Grok reads a repeated prompt prefix from a cache at a quarter of the input price, and it demonstrates with a TypeScript app that three chats of 30 messages behave very differently. In one reported run, the chat with the current time at the top of the latest message cost $0.117 and had 87% of its input read from the cache. The chat with the time at the top of the system prompt cost $0.270 with 3% cached, and xAI reports a 2.2 to 2.9 times gap across its runs. The chat that compacted its history cost $0.167. The page also covers the usage fields that report cached tokens, prompt_cache_key, carrying encrypted reasoning with toInput(), responses.compact() and the onRequest timing hook. The results are xAI's own. Independent reproduction remains unverified. The repository code is described but not shown, and the page states no licence, reuse terms or publication date.
Researched and written by an AI model and checked by a second AI model. How it works
The selected scope is the complete documentation page at [https://docs.x.ai/cookbook/examples/prompt-caching.md]; linked pages are excluded. The cookbook repository files the page names (src/chat.ts, src/compare.ts, src/server.ts, src/index.ts, public/index.html, handbook.md, script.txt) are described but not included, so the repository implementation remains unverified. The page states no licence, copyright notice or reuse terms, so copying and redistribution rights are unknown. The demo's behaviour remains unverified: all results, costs and timings are xAI's reported figures from the page, and independent reproduction remains unverified. The page's publication date, the repository address and the code itself are unknown.
The overview
What this resource is
This is a single documentation page titled Prompt Caching, from the xAI cookbook at [https://docs.x.ai/cookbook/examples/prompt-caching.md]. It is a written walkthrough of a runnable example, not a library or a hosted tool. The example lives in a repository folder named examples/prompt-caching/typescript and talks to the Grok API through the xAI SDK. The page does not give the repository address, an author name, a version number or a publication date.
Overall assessment
The page is a focused, specific and practical guide. It leads with a concrete, checkable claim: a line of text placed at the top of a system prompt can quietly turn cheap cached reads into full-price input. It backs the claim with a table, per-turn cost ranges, token counts and the arithmetic used to price a turn. It is also frank about its own results: it says compaction cost more than it saved in the demo, that the cache key makes a hit likelier but not certain, and that summaries can lose facts.
The main weakness is that the evidence is the vendor's own, from one reported run plus unspecified other runs. Independent reproduction remains unverified, so treat the figures as xAI's reported results for its own demo, not as measurements for your workload.
Who it is for
The guide suits developers who call the Grok API from an app that resends a growing conversation on every turn, such as a support bot that sends its help docs with each request. It is readable by a beginner because it starts from the plain idea that each turn resends the whole chat, then adds the technical detail. The code walkthrough assumes comfort with TypeScript, Node.js, streaming responses and reading API usage objects.
It is less useful for someone who only uses Grok through a chat interface, or who builds on another provider's API. The page says nothing about other providers' caching behaviour.
What it teaches and demonstrates
The page lists what a reader will learn: that caching needs a prompt starting the same way as the last one; what breaks it, such as the current time at the top of the system prompt, and where to put the time instead; where cached tokens appear in usage and how to price a turn from token counts; how to send every turn of a chat to the server that has it cached with prompt_cache_key; how to carry Grok's encrypted reasoning between turns with toInput(); how to compact a chat with responses.compact() and why the turn after it misses the cache; and how to time each turn using the SDK's onRequest hook.
The demo plays the same 30 messages from script.txt in three chats at once, against a roughly 2,100-token handbook (handbook.md) for a made-up Mars research station. A browser page at [http://localhost:3000] charts each turn's cost split into cached input, new input, output and compacting. A terminal mode prints each turn and saves results to output/comparison-<time>.json. You can edit handbook.md and script.txt to try your own content.
Using it
Requirements
The page states that you need Node.js 22.13 or later and an xAI API key, supplied either in a .env file at the root of the repository or as the XAI_API_KEY environment variable. The demo uses the grok-4.7 model and a low reasoning effort. Whether the model or API is available to every account, and any account tier or credit needed, is not stated. A checkout of the cookbook repository is implied by the commands, but the page does not link to it.
How it works
Grok caches a prompt prefix. If a new request starts the same way as an earlier one, the matching part is read from the cache at a quarter of the input price. The page reports that cached counts were always multiples of 128 tokens, so the last partial block of a prompt is always new.
In the demo, sendMessage() in src/chat.ts streams one turn. The input order is the chat's latest compaction item (if any), then the system prompt with the handbook, then the turns since, then the new message. The first and third chats put Current time: and the time at the start of the latest message. The second chat, Time on top, puts it at the very start of the system prompt, which changes the whole prompt on every turn and so defeats the cache. The request sets prompt_cache_key to chat: plus the chat ID, to steer turns to the server that has the chat cached.
After each turn the code adds the message and response.toInput() to the chat. toInput() includes Grok's reasoning items with encrypted content. Without them, the page says the next turn's cache hit stops where Grok's last answer begins, and Grok loses the reasoning behind earlier answers.
For pricing a regular response, the SDK usage fields are usage.input_tokens, usage.input_tokens_details.cached_tokens for the part read from the cache, and usage.output_tokens, which for a regular response already includes usage.output_tokens_details.reasoning_tokens. The API also reports usage.cost_usd, but only as a total, and a compaction reports no cost at all. So a price() function works out each part from token counts and the rates read from client.models.language.get().
compactChat() sends the turns and any previous compaction item to client.responses.compact() and keeps the single encrypted item it returns. compacted.usage reports the tokens it used and dropped_message_count, but unlike a regular response, its output_tokens do not include its reasoning tokens. The page reports that compaction summaries and their reasoning tokens are all billed at the output price, so pricing a compaction means adding its reasoning tokens to its output_tokens before applying the output rate. A compaction item has to come first because the API drops anything before it, including instructions. So the demo keeps the system prompt out of the compaction and places it right after the item, which keeps the handbook word for word. The compacting chat compacts once the turns since its last compaction pass COMPACT_AFTER, set to 1,500 tokens.
Every request goes through the client's onRequest hook, which records when each attempt starts, so a rate-limit retry is not counted as a slow first token. The client allows up to seven retries instead of the default two, with waits up to 30 seconds, and sets retryBeforeOutput so a failed request does not stop a chat halfway. src/compare.ts defines the three chats and runs them, src/server.ts is a small node:http server that streams results to the page as server-sent events, public/index.html is the page, and src/index.ts is the terminal runner.
Setup and running
The page gives these steps. Put the API key in .env at the repository root or export XAI_API_KEY. Run cd examples/prompt-caching/typescript, then npm install, then npm run web. Open [http://localhost:3000] and click Play the chat three ways. The page offers Stop to cancel a run, and Results to download every turn as JSON when finished. Hovering a bar shows that turn's tokens, cost by part and why it did or did not hit the cache. Clicking a bar scrolls every chat to that turn.
For the terminal, run npm start. It prints each turn and compaction as it finishes, then a summary, and saves to output/comparison-<time>.json. Passing a number, as in npm start -- 10, plays only that many turns. The page says the server serves only the results files its own runs wrote. Install size, dependency list and any other setup detail are not on the page. Whether these steps work as described remains unverified.
Worked example and reported results
All three chats send the same 30 messages. In the one run the page tabulates: Time in the message cost $0.117, had 87% of input read from cache, median time to first token 0.6 s and 0 compactions. Time on top cost $0.270, 3% cached, 0.7 s, 0 compactions. With compaction cost $0.167, 86% cached, 0.7 s, 3 compactions. The run took 3 minutes 13 seconds and cost 56 cents at list price, 27 cents of it for the time-on-top chat.
For the time-on-top chat, the page says it read only 128 tokens per turn from the cache, a preamble every request shares. Its cost per turn climbed from 0.6 cents to 1.2 cents as the chat grew from 2,400 to 5,900 tokens, while the first chat mostly stayed between 0.2 and 0.5 cents. It cost 2.3 times as much as the first chat in the tabulated run and 2.2 to 2.9 times across xAI's runs. The gap grows with chat length because each turn resends everything before it.
On compaction, the three compactions cost 1.4, 1.7 and 3.3 cents and took 19, 29 and 53 seconds. They produced summaries of 600 to 1,800 tokens, plus up to 2,600 reasoning tokens, all at the output price, while removing only 600 to 900 tokens from the prompt. The turn after each compaction read only 128 tokens from the cache and cost about three times a normal turn. In that run all three chats answered the last question correctly (bunk 9, suit 6, three peanut dinners).
Assessment & evidence
Limitations and risks
The numbers are from xAI's own demo: a single tabulated run and unspecified additional runs. The handbook is about 2,100 tokens and the chats reach about 2,400 to 6,900 tokens, so results for much larger prompts, different models or other workloads are not established. The page's own comparisons are limited to one model, grok-4.7, with low reasoning effort.
The cache is not guaranteed. The first chat missed the cache on three turns besides its first while the API was busy. In a test without prompt_cache_key, the API still cached most turns, between 64% and 95% of input with or without a key, so the key's benefit is a likelier hit, not a measured large gain.
Compaction carries quality risk. Summaries came back anywhere from 15 to 2,350 tokens in xAI's tests, and the 15-token one forgot the user's suit number. If the system prompt was compacted with the turns, the second compaction summarized it, so Grok worked from a summary of the handbook. With the system prompt before the compaction item or in instructions, the API dropped the handbook entirely and Grok made up menu details.
Time to first token barely changed with caching. Reading a 2,400 to 6,900 token prompt is a small part of the wait, and turns took up to 80 seconds to start when the API was busy, cached or not. So the guide supports a cost argument, not a latency one.
Also unknown from the page: the source code itself (only described), test coverage, behaviour on Node versions below 22.13, and the page's date or revision history. Independent reproduction of the reported results, and the repository implementation itself, remain unverified.
Why the guide's conclusions follow
The core claim is straightforward: a cache can only reuse a prefix, so anything that changes at the front of every prompt invalidates the whole prefix. The page's figures fit that: the time-on-top chat read just 128 cached tokens per turn (3% of input), while the time-in-message chat read 87%. The direction of the cost gap follows from the stated rates, since cached input is billed at $0.50 per million tokens against $2.00 for new input. The page does not give full token totals for each chat, so independent reconciliation of the reported costs against those rates is unknown. The three table costs add up to $0.554 (55.4 cents), while the text reports that the run cost 56 cents; the page does not explain the difference.
The compaction conclusion is also argued from numbers: the compaction cost and the lost cache hit on the next turn outweighed the 600 to 900 tokens removed. The page is careful to say this depends on the demo's low COMPACT_AFTER setting, which was chosen to force a few compactions, and on how large turns are compared with a summary. The caveat that the cache key helps likelihood rather than guaranteeing a hit is stated plainly, and the page tells you how to test it yourself by removing prompt_cache_key from sendMessage().
Alternatives and related options
The evidence does not compare this guide with other resources, other providers' caching features, or other cookbook pages, so no ranking can be given. Within the page, the choices are the three chat variants: put changing text in the latest message, put it at the top of the system prompt, or compact as the chat grows. For compaction there are three placements of the system prompt: after the compaction item (recommended by the page), compacted together with the turns, or in instructions or before the item, which the page says lost the handbook. Alternatives such as xAI's main API documentation, or other providers' caching guides, are outside this page, and how they compare is unknown.
Evidence base
The evidence is the full text of one documentation page, [https://docs.x.ai/cookbook/examples/prompt-caching.md], about 9.9 kilobytes. It covers the introduction, the learning goals, the run instructions, the code walkthrough, and the comparison table and findings. The example code, handbook.md, script.txt, output files and any linked pages are not part of it. Its figures are xAI's own reported results; independent measurement and reproduction remain unverified.
Access & freshness
Costs
The guide itself is a documentation page, and no charge for reading it is stated. Running the demo calls the paid Grok API. The page says the example reads rates from client.models.language.get(): $2.00 per million input tokens, $0.50 per million cached input tokens and $6.00 per million output tokens. By xAI's account, the reported 30-turn, three-chat run cost 56 cents at list price. Whether the rates apply to your account, any free credits, current prices, and what your own chats would cost are unknown from this evidence and may differ.
The page's cost advice is: keep the front of the prompt stable so more input is billed at the cached rate; a changing line like the time belongs in the newest message. On compaction, it says each 10,000 tokens removed saves half a cent per turn with caching, so it pays off for long chats whose turns are many times the size of a summary, or for staying inside the context window. In the demo it did not pay off. Compaction itself is billed on tokens, including reasoning tokens, and the API reports no cost for it, so the code has to price it from token counts.
Rights and licence
The page states no licence, copyright notice or terms of use for its text or for the example code. The reuse terms of the cookbook repository, and the xAI terms that govern API use, are not stated on the page and are unknown, so copying and redistribution rights are unknown. Anyone wanting to copy the example code should check the licence in the cookbook repository and xAI's API terms first.
Freshness
The page was captured on 2026-11-15. It carries no visible publication or update date, so how current it is cannot be judged from the evidence. Details that may change include the grok-4.7 model name, the per-token rates, the SDK method names (toInput, responses.compact, onRequest, retryBeforeOutput), the Node.js requirement and the reported cache behaviour. Check the live page and the current xAI API documentation before relying on any of them.
What to do next
If you run a chat on the Grok API, check your prompt order: keep the system prompt and handbook-like context identical across turns, and move anything that changes every turn, such as the time, into the newest message. Log usage.input_tokens and usage.input_tokens_details.cached_tokens on your own traffic to see your real cache rate, and expect cached counts in multiples of 128.
Before adding compaction, estimate whether your turns are many times larger than a summary, or whether you need it only to stay inside the context window. If you do compact, keep the system prompt after the compaction item and check the summary against facts the user gave. To try the demo, get the cookbook repository (the page does not give its address) and confirm the licence and current pricing first. For a short, low-cost trial, npm start -- 10 plays only ten turns; this is a shorter trial, not a reproduction of the reported comparison. To reproduce the reported 30-message comparison, run npm start with no number, or the full browser run with npm run web and Play the chat three ways. To test the cache key, remove prompt_cache_key from sendMessage() and run the comparison again.
