Skip to main content
When you are asking multiple questions against the same background material — a system prompt, a long document, a set of tools — resending that material with every request wastes tokens and increases latency. Polyglot’s withCachedContext() method lets you separate the stable parts of a conversation from the per-call messages, so the provider can cache and reuse them across requests.

How Context Caching Works

Without caching, every request includes the full conversation history, system prompt, and any reference material. As conversations grow, this can lead to significant token overhead. Context caching solves this by marking a portion of the request as a reusable prefix. The provider stores this prefix server-side and references it on subsequent requests, reducing both the number of tokens processed and the time to first token.

Using Cached Context

The withCachedContext() method accepts the same kinds of data you would normally pass through with(), but treats them as a persistent prefix for subsequent requests:
The first request populates the provider’s cache (you may see cacheWriteTokens reported). Every subsequent request that shares the same prefix benefits from a cache hit, reflected in cacheReadTokens.

What Can Be Cached

The cached context can include any combination of:
  • messages — system prompts, conversation history, or reference material
  • tools — tool/function definitions that remain constant across calls
  • toolChoice — the tool selection strategy
  • responseFormat — a fixed response schema

Processing Large Documents

Context caching is particularly valuable when working with large documents. Instead of resending the full document with every question, you cache it once and issue lightweight follow-up queries:
After the first request populates the provider’s cache, subsequent questions benefit from reduced input token processing, which lowers both cost and latency.

Inspecting Cache Usage

If a provider reports cache usage, you can inspect it through response()->usage(). The InferenceUsage object exposes the following cache-related fields when available:

Provider Support

Different providers handle context caching differently: Polyglot sends the appropriate cache control markers to providers that support them. For providers without native caching support, withCachedContext() still works correctly — the context is prepended to each request — but you will not see cache-related usage metrics in the response.
Tip: To maximize cache hit rates with Anthropic, keep your cached context stable across requests. Even small changes to the cached portion will invalidate the cache and trigger a new cache write.