Add prompt-caching module: Spring AI 2.1 Anthropic cache strategies on the real request (breakpoints per strategy, hit/miss/write in Usage, one changed word, multi-block system caching, minimum length, 5-minute and 1-hour lifetimes, the 20-block lookback), OpenAI automatic caching with prompt_cache_key, and a cost table. The vendors are a local server applying their documented rules; no vendor API called. Spring Boot 4.2.0, Spring AI 2.1.0, Java 25.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4gvXXQgw1eTk5EoTT
This commit is contained in:
Claude
2026-11-24 06:07:23 +05:30
parent 45d83826da
commit 02c3cbf439
32 changed files with 1759 additions and 0 deletions
@@ -0,0 +1,134 @@
package com.ankurm.promptcaching;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import com.ankurm.promptcaching.support.Ask;
import com.ankurm.promptcaching.support.FakeProviders;
import com.ankurm.promptcaching.support.Transcript;
import com.ankurm.promptcaching.support.Wire;
import org.junit.jupiter.api.Test;
import org.springframework.ai.anthropic.AnthropicCacheOptions;
import org.springframework.ai.anthropic.AnthropicCacheStrategy;
import org.springframework.ai.anthropic.AnthropicChatOptions;
import org.springframework.ai.anthropic.AnthropicChatModel;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.metadata.Usage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.support.ToolCallbacks;
/** What does a cache hit look like in Spring AI's Usage, and what does one changed word cost? */
class HitsTest {
static final String MODEL = "claude-sonnet-5-5";
static final String POLICY = SupportPrompts.policy(24000);
static final AnthropicCacheOptions SYSTEM_AND_TOOLS = AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_AND_TOOLS).build();
@Test
void hitsAndInvalidation() throws Exception {
try (FakeProviders fake = new FakeProviders();
Transcript t = new Transcript("02-hits-and-invalidation.txt",
"A cache hit in Spring AI's Usage, and what one changed word costs (SYSTEM_AND_TOOLS, 4 tools, 24,000-character system prompt)")) {
t.line("A. The same tools and system prompt, a different question each time");
ChatModel m = Models.anthropic(fake.url(), MODEL, SYSTEM_AND_TOOLS, true);
Usage u1 = Ask.usage(m, POLICY, SupportPrompts.userTurn(List.of(1), "How do I get a refund?"));
Usage u2 = Ask.usage(m, POLICY, SupportPrompts.userTurn(List.of(2), "Can I pause my subscription?"));
line(t, "call 1", u1);
line(t, "call 2", u2);
assertThat(u1.getCacheWriteInputTokens()).isGreaterThan(5000);
assertThat(u1.getCacheReadInputTokens()).isZero();
assertThat(u2.getCacheReadInputTokens()).isEqualTo(u1.getCacheWriteInputTokens());
long all = u1.getCacheWriteInputTokens();
long uncached2 = u2.getPromptTokens() - u2.getCacheReadInputTokens() - u2.getCacheWriteInputTokens();
assertThat(uncached2).isLessThan(500);
t.line(" call 2: %d of %d prompt tokens came from the cache; %d were billed at the plain input price",
u2.getCacheReadInputTokens(), u2.getPromptTokens(), uncached2);
t.line(" (getPromptTokens() includes the cached tokens in 2.1.0)");
t.blank();
t.line("B. After a warm-up call, what does each change do? (read = served from cache, write = stored again)");
fake.reset();
Usage toolsOnly = Ask.usage(Models.anthropic(fake.url(), MODEL,
AnthropicCacheOptions.builder().strategy(AnthropicCacheStrategy.TOOLS_ONLY).build(), true), POLICY, "warm");
long toolsTokens = toolsOnly.getCacheWriteInputTokens();
t.line(" (the four tool definitions alone are %d tokens; the whole prefix is %d)", toolsTokens, all);
variant(t, fake, "nothing changed", POLICY, SupportPrompts.userTurn(List.of(3), "Gift card balance?"), true, false);
variant(t, fake, "only the retrieved context changed", POLICY, SupportPrompts.userTurn(List.of(9, 10, 11), "Gift card balance?"), true, false);
Usage sys = variant(t, fake, "one word of the system prompt changed", POLICY.replace("Rule 3:", "Rule three:"),
"Gift card balance?", true, false);
Usage tool = variant(t, fake, "one word of one tool description changed", POLICY, "Gift card balance?", true, true);
assertThat(sys.getCacheReadInputTokens()).isEqualTo(toolsTokens);
assertThat(sys.getCacheWriteInputTokens()).isBetween(all - toolsTokens, all - toolsTokens + 2);
assertThat(tool.getCacheReadInputTokens()).isZero();
assertThat(tool.getCacheWriteInputTokens()).isGreaterThan(all - 100);
}
}
@Test
void volatileTextInTheSystemPrompt() throws Exception {
try (FakeProviders fake = new FakeProviders();
Transcript t = new Transcript("03-clock-in-the-system-prompt.txt",
"A clock in the system prompt: one joined block, or the static prefix pattern (SYSTEM_ONLY)")) {
for (boolean multiBlock : new boolean[] {false, true}) {
fake.reset();
ChatModel m = Models.anthropic(fake.url(), MODEL, AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY).multiBlockSystemCaching(multiBlock).build(), false);
Usage a = call(m, "10:00:01");
var body = fake.last().body();
Usage b = call(m, "10:00:02");
t.line("multiBlockSystemCaching=%-5s system blocks sent=%d breakpoints=%s", multiBlock,
body.path("system").size(), Wire.breakpoints(body));
t.line(" call 1: cacheWrite=%-6d cacheRead=%d", a.getCacheWriteInputTokens(), a.getCacheReadInputTokens());
t.line(" call 2: cacheWrite=%-6d cacheRead=%d (the clock changed between the calls)", b.getCacheWriteInputTokens(),
b.getCacheReadInputTokens());
if (multiBlock) {
assertThat(body.path("system").size()).isEqualTo(2);
assertThat(Wire.breakpoints(body)).containsExactly("system[0]");
assertThat(b.getCacheReadInputTokens()).isEqualTo(a.getCacheWriteInputTokens());
assertThat(b.getCacheWriteInputTokens()).isZero();
}
else {
assertThat(body.path("system").size()).isEqualTo(1);
assertThat(b.getCacheReadInputTokens()).isZero();
assertThat(b.getCacheWriteInputTokens()).isEqualTo(a.getCacheWriteInputTokens());
}
}
}
}
private static Usage call(ChatModel m, String clock) {
return m.call(new Prompt(List.of(new SystemMessage(POLICY), new SystemMessage("Current time: " + clock),
new UserMessage("Where is my parcel?")))).getMetadata().getUsage();
}
/** Warm the cache with the baseline request, then send the variant and report what the vendor billed. */
private static Usage variant(Transcript t, FakeProviders fake, String label, String system, String user,
boolean tools, boolean changedTool) {
fake.reset();
ChatModel base = Models.anthropic(fake.url(), MODEL, SYSTEM_AND_TOOLS, tools);
Ask.usage(base, POLICY, "warm");
ChatModel m = base;
if (changedTool) {
m = AnthropicChatModel.builder().options(AnthropicChatOptions.builder().baseUrl(fake.url()).apiKey("test-key")
.model(MODEL).maxTokens(1024).maxRetries(0).cacheOptions(SYSTEM_AND_TOOLS)
.toolCallbacks(ToolCallbacks.from(new ChangedTools())).build()).build();
}
Usage u = Ask.usage(m, system, user);
t.line(" %-42s read=%-6d write=%-6d uncached=%d", label, u.getCacheReadInputTokens(), u.getCacheWriteInputTokens(),
u.getPromptTokens() - u.getCacheReadInputTokens() - u.getCacheWriteInputTokens());
return u;
}
private static void line(Transcript t, String label, Usage u) {
t.line(" %-7s getPromptTokens=%-5d getCacheReadInputTokens=%-6d getCacheWriteInputTokens=%d", label,
u.getPromptTokens(), u.getCacheReadInputTokens(), u.getCacheWriteInputTokens());
}
}