A long document pasted into every prompt is reprocessed on every call, which is slow. mlx-lm has prompt caching: mlx_lm.cache_prompt processes the long prompt once and saves it to a file, and later generations reuse that file as a prefix.
Cache the prompt, then generate from it
Pipe the long prompt into the cache command: cat prompt.txt | mlx_lm.cache_prompt --model mistralai/Mistral-7B-Instruct-v0.3 --prompt - --prompt-cache-file mistral_prompt.safetensors. Then generate with the cached file: mlx_lm.generate --prompt-cache-file mistral_prompt.safetensors --prompt "\nSummarize the above text.". The cached prompt is treated as a prefix to the supplied prompt, and the model is read from the cache — you do not need to supply it again.
cat prompt.txt | mlx_lm.cache_prompt \
--model mistralai/Mistral-7B-Instruct-v0.3 \
--prompt - \
--prompt-cache-file mistral_prompt.safetensors
mlx_lm.generate \
--prompt-cache-file mistral_prompt.safetensors \
--prompt "\nSummarize the above text."
The cache belongs to one model and one prompt: change the model or the document and the cached file is wrong, not just stale. Keep the cache file next to the prompt it came from, and re-cache whenever the document changes.
Try it: four checks
| Check | What you should see | If you do not see it |
|---|---|---|
| Prompt cached | mlx_lm.cache_prompt writes the .safetensors file | Check the prompt file is not empty |
| Generate uses cache | mlx_lm.generate accepts –prompt-cache-file | The model is read from the cache |
| Faster second run | The second query starts sooner | Compare with a cold prompt |
| Prefix correct | The answer uses the cached document | Check the reply refers to the document |
Expected result. We checked the mlx-lm README, which documents mlx_lm.cache_prompt, the –prompt-cache-file flag, and that the cached prompt is treated as a prefix and the model is read from the cache. We did not cache a prompt on this machine.
Limits
This guide covers prompt caching only. A cache file is only valid for the model and prompt that made it. We did not test any caching ourselves.
