Repository navigation
Prompt caching — Anthropic cache_control + OpenAI prompt_cache_key, on by default - #118
Conversation
…n by default
Cache hit reads we already parsed but never actually emitted the
breakpoints to earn. Two providers, ~200 LOC, default-on.
Anthropic
- System prompt switches to block form (array of text blocks)
when caching is on, with cache_control:{type:ephemeral} on
the trailing block. This caches every byte up to the tools
array on the next turn — the largest single-breakpoint win
for multi-turn chats.
- Last tool entry gets the second cache_control breakpoint,
so the entire tools array is cached as part of the prefix.
Two of Anthropic's 4-breakpoint budget used; remaining two
reserved for higher layers (compaction summary, steering).
- Optional ttl:"1h" extended-TTL hint when CacheTTL="1h";
omitted (5m default) otherwise.
OpenAI
- Emits prompt_cache_key derived from the persistent session id
(auto-allocated by PR #117). Anchors OpenAI's automatic
prefix cache to a stable per-conversation bucket instead of
relying on content-hash bucketing, which thrashes when two
parallel sessions happen to share a prefix.
- ParseOAIResponse now reads cached_tokens from
prompt_tokens_details into Usage.CacheReadTokens — we were
ignoring the field entirely.
Plumbing
- TChatOptions gets CacheEnabled / CacheTTL / CacheKey
(defaults: True / "" / ""); DefaultChatOptions flips
CacheEnabled on so the legacy field-by-field option construction
paths in channels / gateway / embedders pick it up automatically.
- TConfig gets PromptCache:{Enabled,TTL} with ToJSON/FromJSON
roundtrip. Default state stays out of ToJSON so stock configs
remain clean.
- Cmd.Agent BuildLoopConfig threads Cfg.PromptCache through;
RunInteractive sets CacheKey := Session.Meta.Id per turn.
- /status grows a "cache:" line showing cumulative read/write
tokens + hit % on input so far. Per-turn token summary
(FormatTokenLine) adds cache_r= and cache_w= when non-zero.
Builder exports
- Promoted Anthropic.BuildRequest, OpenAI.BuildOAIRequest and
OpenAI.ParseOAIResponse to the interface section. Pure
functions; same code path Chat() executes. Lets embedders
inspect the wire body for audit/logging, and lets test
harnesses verify the JSON shape without standing up a mock
HTTP server.
Verified with a focused test (built, ran, removed) covering all
eleven wire-format and config-roundtrip assertions: cache_control
emission on system + last tool, TTL pass-through, off-path stays
clean, OpenAI prompt_cache_key gating on Enabled+Key, cached_tokens
parse, config roundtrip, defaults-out-of-ToJSON.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5950abf408
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| flipping this on costs nothing for short prompts and saves ~10x | ||
| on long ones. Disable per-call via TPromptCacheConfig.Enabled | ||
| (config.json) when you want to A/B without it. } | ||
| Result.CacheEnabled := True; |
There was a problem hiding this comment.
Honor prompt_cache.enabled outside the CLI agent
When prompt_cache.enabled is set to false, only BuildLoopConfig in PasClaw.Cmd.Agent.pas copies that value into TChatOptions; the new default here remains True everywhere else. I checked the config-backed gateway (PasClaw.Gateway.Server.pas:991), Telegram channel (PasClaw.Channels.Telegram.pas:162), email channel (PasClaw.Channels.Email.pas:402), and embedded-agent path (PasClaw.Agent.pas:683): each uses DefaultChatOptions without overriding CacheEnabled. Anthropic requests from those paths therefore still emit cache_control even after the operator disables caching, which can retain prompt KV state and incur cache-write pricing. Thread Cfg.PromptCache through every config-backed path or opt in centrally rather than enabling the provider option unconditionally.
Useful? React with 👍 / 👎.
| if TotalIn > 0 then | ||
| WriteLn(Format(' cache: on, %d read / %d written (%d%% hit on input so far)', | ||
| [TotalCacheRead, TotalCacheWrite, | ||
| (TotalCacheRead * 100) div TotalIn])) |
There was a problem hiding this comment.
Include Anthropic cached tokens in the hit-rate denominator
For Anthropic sessions with cache hits, this percentage divides cache reads by only usage.input_tokens, because TotalIn is incremented from Loop.LastResp.Usage.InputTokens below. Anthropic documents that input_tokens contains only tokens after the final breakpoint and that total input is cache_read_input_tokens + cache_creation_input_tokens + input_tokens (Claude prompt-caching docs). A request with 100,000 cached tokens and 50 uncached tokens will therefore display a 200,000% hit rate instead of approximately 100%. Use the provider's total-input formula for the denominator.
Useful? React with 👍 / 👎.
| Inc(TotalCacheRead, Loop.LastResp.Usage.CacheReadTokens); | ||
| Inc(TotalCacheWrite, Loop.LastResp.Usage.CacheCreatedTokens); |
There was a problem hiding this comment.
Roll up cache usage from every tool-loop request
When an interactive turn invokes tools, RunToolLoop performs multiple provider calls and overwrites Loop.LastResp after each iteration (PasClaw.Tools.ToolLoop.pas:603). These new counters add only the final response's cache metrics, so cache writes and reads from the initial and intermediate requests disappear from /status; the displayed cumulative totals can substantially under-report usage for the agentic flows where caching matters most. Accumulate usage inside the loop or return an aggregate alongside LastResp.
Useful? React with 👍 / 👎.
…hit rate, roll up usage across tool loop Three legit Codex P2 findings on the prompt-caching PR — all addressed in place on PR #118. P2 — Honor prompt_cache.enabled outside the CLI agent. The DefaultChatOptions default of CacheEnabled=True was correct for library embedders, but the operator's `prompt_cache.enabled: false` only landed in TChatOptions when Cmd.Agent.BuildLoopConfig ran — every other path (gateway endpoints, TUI, all 7 channels, subagents, the embedder TPasClawAgent, the /compact summariser) kept caching on regardless of config, incurring write costs the operator thought they'd disabled. Added ApplyPromptCacheConfig helper in PasClaw.Config that folds TPromptCacheConfig into TChatOptions; called it at every config-aware DefaultChatOptions site. TSubagentContext gained a PromptCache field so spawned child loops inherit the same operator policy. Compact inherits the caller's CacheEnabled/CacheTTL since it can't see TConfig directly. TUI gained PromptCacheEnabled / PromptCacheTTL public fields that Cmd.TUI.Run copies from Cfg.PromptCache after construction. P2 — Hit rate denominator includes Anthropic cached tokens. The /status line "(X% hit on input so far)" divided cache reads by input_tokens. Anthropic reports input_tokens EXCLUDING the cached portion (those live in cache_read_input_tokens) — 100k cached + 50 fresh would report 200,000% hit. New TotalPromptTokens helper branches on provider name: Anthropic sums Input + CacheRead + CacheCreated; OpenAI returns InputTokens directly (cached_tokens is a subset of prompt_tokens there). The /status label now reads "% hit on prompt so far" to match the corrected denominator. P2 — Roll up cache usage from every tool-loop request. /status was reading Loop.LastResp.Usage, which only holds the FINAL provider call's tokens; intermediate tool-using turns vanished. TToolLoopResult gained a TotalUsage field that RunToolLoop accumulates after every Resp assignment (incl. successful fallbacks). Cmd.Agent's per-turn token line and the cumulative /status counters both switch to Loop.TotalUsage so multi-tool rounds count fully. Verified with a focused test (created, built, ran, removed) covering all six assertions: ApplyPromptCacheConfig disabled suppresses cache_control emission, enabled+1h preserves the TTL hint, Anthropic hit-rate denominator computes 99% instead of 200000% on Codex's example, OpenAI denominator stays input_tokens, TotalUsage accumulates across multiple Inc calls, and TSubagentContext.PromptCache compiles (real cross-path propagation is compile-checked). https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Summary
We already parsed cache hit/write tokens from the Anthropic response but never emitted the breakpoints to earn them — and OpenAI's
cached_tokensfield was ignored entirely. This wires both up, default-on, ~200 LOC.Inspired by OnlyTerp/prompt-cache-skills — same lessons (cache stable prefix content; never on volatile recent user messages; anchor OpenAI's bucket with a session id), implemented in-place rather than as a patch over a broken default.
Anthropic
cache_control: { type: "ephemeral" }on the trailing block. Caches every byte up to the tools array on the next turn — biggest single-breakpoint win for multi-turn chats.cache_controlbreakpoint, so the entire tools array becomes part of the cached prefix. Uses 2 of Anthropic's 4-breakpoint budget; the other two are reserved for higher layers (compaction summary, steering).ttl: "1h"extended-TTL hint whenCacheTTL="1h"; omitted (default 5m) otherwise.OpenAI
prompt_cache_keyderived from the persistent session id (auto-allocated by PR Persistent session management — durable conversations across restarts #117). Anchors the automatic prefix cache to a stable per-conversation bucket instead of relying on content-hash bucketing.ParseOAIResponsenow readscached_tokensfromprompt_tokens_detailsintoUsage.CacheReadTokens— we were ignoring it entirely.Plumbing
TChatOptionsgrowsCacheEnabled / CacheTTL / CacheKey(defaults: True / "" / "");DefaultChatOptionsflipsCacheEnabledon so the field-by-field construction paths in channels / gateway / embedders pick it up automatically.TConfig.PromptCache:{Enabled,TTL}with JSON roundtrip. Default state stays out ofToJSONso stock configs remain clean.Cmd.Agent.BuildLoopConfigthreadsCfg.PromptCachethrough;RunInteractivesetsOptions.CacheKey := Session.Meta.Idper turn./statusgrows acache:line showing cumulative read/write tokens + hit % on input so far. Per-turn token summary (FormatTokenLine) addscache_r=andcache_w=when non-zero.Builder exports
Promoted
Anthropic.BuildRequest,OpenAI.BuildOAIRequestandOpenAI.ParseOAIResponseto the interface section. Pure functions; same code pathChat()executes. Useful for embedders inspecting the wire body for audit / logging, and for test harnesses verifying JSON shape without standing up a mock HTTP server.Gemini
Skipped for v1. Implicit caching is automatic on supported Gemini models; the explicit
cachedContentresource API has a lifecycle (create / refresh / delete) that's annoying to manage and doesn't fit the same plumbing pattern.Test plan
make clean && makecleanmake smoke11/11 OKcache_controlemission on system + last tool, TTL pass-through, off-path stays clean, OpenAIprompt_cache_keygating onEnabled+Key,cached_tokensparse, config roundtrip, defaults-out-of-ToJSONpasclaw agent/statusshowscache: on, no turns yetin offline modepasclaw agentagainst Anthropic — confirmcache_w=Non first turn,cache_r=Non second+ turns of the same conversationpasclaw agentagainst OpenAI — confirmcache_r=Nappears once the prefix has been served onceGenerated by Claude Code