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:
@@ -0,0 +1,41 @@
|
||||
package com.ankurm.promptcaching;
|
||||
|
||||
import org.springframework.ai.tool.annotation.Tool;
|
||||
import org.springframework.ai.tool.annotation.ToolParam;
|
||||
|
||||
/** The same four tools as {@link SupportTools} with one word changed in one description. */
|
||||
public class ChangedTools {
|
||||
|
||||
@Tool(description = "Look up one order by its order number and return its status, line items, shipping address "
|
||||
+ "and payment state. Use it whenever the customer names an order. The order number is the nine digit "
|
||||
+ "number printed on the confirmation email, not the invoice number. Never call it with a guessed "
|
||||
+ "number. Returns a short plain text summary and never returns card details.")
|
||||
public String lookupOrder(@ToolParam(description = "Nine digit order number") String orderNumber) {
|
||||
return "order " + orderNumber + ": shipped";
|
||||
}
|
||||
|
||||
@Tool(description = "Start a refund for one order line. Only call it after the policy check says the order is "
|
||||
+ "inside the refund window and the customer has confirmed the line. The refund goes back to the "
|
||||
+ "original payment method and takes three to five working days. Returns a refund reference that "
|
||||
+ "must be quoted to the customer. A refund can be started once per line.")
|
||||
public String startRefund(@ToolParam(description = "Nine digit order number") String orderNumber,
|
||||
@ToolParam(description = "Line number inside the order, starting at 1") int line) {
|
||||
return "refund R-" + orderNumber + "-" + line;
|
||||
}
|
||||
|
||||
@Tool(description = "Reset the two-factor authentication of a customer account after the identity checks in the "
|
||||
+ "policy have passed. The customer receives an email with a link that is valid for one hour. Do not "
|
||||
+ "describe the checks to the customer and do not call this tool for a lost password; that has its "
|
||||
+ "own flow. Returns the word sent when the email has been queued.")
|
||||
public String resetTwoFactor(@ToolParam(description = "Account email address") String email) {
|
||||
return "sent";
|
||||
}
|
||||
|
||||
@Tool(description = "Create a ticket for a human agent when the question is outside the policy or the customer "
|
||||
+ "asks for a person. Include a title of under eight words and the priority. Returns the ticket id. "
|
||||
+ "Do not create a ticket for a question the knowledge base article already answers!")
|
||||
public String createTicket(@ToolParam(description = "Short title") String title,
|
||||
@ToolParam(description = "high, medium or low") String priority) {
|
||||
return "T-1";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.ankurm.promptcaching;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.ArrayList;
|
||||
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.chat.messages.AssistantMessage;
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
import org.springframework.ai.chat.messages.UserMessage;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
|
||||
/** A multi-turn chat: CONVERSATION_HISTORY moves one breakpoint to the newest user message every turn. */
|
||||
class ConversationTest {
|
||||
|
||||
static final String POLICY = SupportPrompts.policy(24000);
|
||||
|
||||
@Test
|
||||
void conversation() throws Exception {
|
||||
try (FakeProviders fake = new FakeProviders();
|
||||
Transcript t = new Transcript("06-conversation.txt",
|
||||
"An 8-turn chat, each user turn about 1,600 characters of pasted log (claude-sonnet-5-5 prices, 5-minute cache)")) {
|
||||
BigDecimal none = null;
|
||||
for (AnthropicCacheStrategy s : new AnthropicCacheStrategy[] {AnthropicCacheStrategy.NONE,
|
||||
AnthropicCacheStrategy.SYSTEM_ONLY, AnthropicCacheStrategy.CONVERSATION_HISTORY}) {
|
||||
fake.reset();
|
||||
ChatModel m = Models.anthropic(fake.url(), "claude-sonnet-5-5", AnthropicCacheOptions.builder().strategy(s).build(), false);
|
||||
t.line("strategy %s", s);
|
||||
List<Message> history = new ArrayList<>();
|
||||
CallUsage total = CallUsage.zero();
|
||||
for (int turn = 1; turn <= 8; turn++) {
|
||||
history.add(new UserMessage("Turn " + turn + " log excerpt:\n" + SupportPrompts.chunk(turn)));
|
||||
ChatResponse r = Ask.call(m, Ask.conversation(POLICY, history));
|
||||
CallUsage u = CallUsage.from(r.getMetadata().getUsage());
|
||||
total = total.plus(u);
|
||||
t.line(" turn %d breakpoints=%-52s plain=%-5d read=%-6d write=%d", turn,
|
||||
Wire.breakpoints(fake.last().body()), u.uncachedInput(), u.cacheRead(), u.cacheWrite());
|
||||
history.add(Ask.reply(r));
|
||||
fake.advance(20);
|
||||
}
|
||||
BigDecimal cost = Cost.dollars(Prices.SONNET_5_5, Prices.SONNET_5_5.cacheWrite5m(), total);
|
||||
t.line(" 8 turns: plain=%d read=%d write=%d input+output cost $%s", total.uncachedInput(), total.cacheRead(),
|
||||
total.cacheWrite(), cost.setScale(4, RoundingMode.HALF_UP));
|
||||
t.blank();
|
||||
if (s == AnthropicCacheStrategy.NONE) {
|
||||
none = cost;
|
||||
}
|
||||
else if (s == AnthropicCacheStrategy.CONVERSATION_HISTORY) {
|
||||
assertThat(cost).isLessThan(none);
|
||||
assertThat(total.cacheRead()).isGreaterThan(total.cacheWrite());
|
||||
}
|
||||
}
|
||||
|
||||
t.line("The 20-block lookback: the same chat, but 24 messages are added between two turns");
|
||||
fake.reset();
|
||||
ChatModel m = Models.anthropic(fake.url(), "claude-sonnet-5-5",
|
||||
AnthropicCacheOptions.builder().strategy(AnthropicCacheStrategy.CONVERSATION_HISTORY).build(), false);
|
||||
List<Message> history = new ArrayList<>();
|
||||
ChatResponse last = null;
|
||||
for (int turn = 1; turn <= 2; turn++) {
|
||||
history.add(new UserMessage("Turn " + turn + " log excerpt:\n" + SupportPrompts.chunk(turn)));
|
||||
last = Ask.call(m, Ask.conversation(POLICY, history));
|
||||
history.add(Ask.reply(last));
|
||||
}
|
||||
int normalGap = 0;
|
||||
history.add(new UserMessage("Turn 3 log excerpt:\n" + SupportPrompts.chunk(3)));
|
||||
CallUsage normal = CallUsage.from(Ask.call(m, Ask.conversation(POLICY, history)).getMetadata().getUsage());
|
||||
t.line(" next turn, 2 messages added since the last breakpoint: read=%-6d write=%d", normal.cacheRead(), normal.cacheWrite());
|
||||
history.remove(history.size() - 1);
|
||||
for (int i = 0; i < 12; i++) {
|
||||
history.add(new UserMessage("short note " + i));
|
||||
history.add(new AssistantMessage("ok " + i));
|
||||
}
|
||||
history.add(new UserMessage("Turn 4 log excerpt:\n" + SupportPrompts.chunk(4)));
|
||||
CallUsage jump = CallUsage.from(Ask.call(m, Ask.conversation(POLICY, history)).getMetadata().getUsage());
|
||||
t.line(" next turn, 25 messages added since the last breakpoint: read=%-6d write=%d", jump.cacheRead(), jump.cacheWrite());
|
||||
assertThat(normal.cacheRead()).isGreaterThan(jump.cacheRead());
|
||||
assertThat(jump.cacheRead()).isBetween(5900L, 6200L);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.ankurm.promptcaching;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.MathContext;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
import com.ankurm.promptcaching.support.Ask;
|
||||
import com.ankurm.promptcaching.support.FakeProviders;
|
||||
import com.ankurm.promptcaching.support.Transcript;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.ai.anthropic.AnthropicCacheOptions;
|
||||
import org.springframework.ai.anthropic.AnthropicCacheStrategy;
|
||||
import org.springframework.ai.anthropic.AnthropicCacheTtl;
|
||||
import org.springframework.ai.chat.messages.MessageType;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
|
||||
/**
|
||||
* The cost table. Every request is a real Spring AI call; the usage Spring AI reads back is what the
|
||||
* simulated server produced from the documented rules, and the prices are the vendors' list prices on
|
||||
* 2026-11-24. So the table is a worked example of the price sheets, not a bill, and nothing here
|
||||
* measures how often a real vendor hits its cache.
|
||||
*/
|
||||
class CostTest {
|
||||
|
||||
static final String POLICY = SupportPrompts.policy(24000);
|
||||
|
||||
static final int REQUESTS = 300;
|
||||
|
||||
static final int ANSWER_TOKENS = 150;
|
||||
|
||||
record Setup(String label, AnthropicCacheStrategy strategy, AnthropicCacheTtl ttl) {
|
||||
}
|
||||
|
||||
static final List<Setup> SETUPS = List.of(
|
||||
new Setup("no caching", AnthropicCacheStrategy.NONE, AnthropicCacheTtl.FIVE_MINUTES),
|
||||
new Setup("SYSTEM_AND_TOOLS, 5 minutes", AnthropicCacheStrategy.SYSTEM_AND_TOOLS, AnthropicCacheTtl.FIVE_MINUTES),
|
||||
new Setup("SYSTEM_AND_TOOLS, 1 hour", AnthropicCacheStrategy.SYSTEM_AND_TOOLS, AnthropicCacheTtl.ONE_HOUR),
|
||||
new Setup("CONVERSATION_HISTORY, 5 minutes", AnthropicCacheStrategy.CONVERSATION_HISTORY, AnthropicCacheTtl.FIVE_MINUTES));
|
||||
|
||||
@Test
|
||||
void costTable() throws Exception {
|
||||
try (FakeProviders fake = new FakeProviders();
|
||||
Transcript t = new Transcript("08-cost.txt",
|
||||
"Cost of 1,000 requests: a 24,000-character policy + 4 tools + 2 retrieved chunks + a question, 150 output tokens (list prices 2026-11-24)")) {
|
||||
fake.answerTokens(ANSWER_TOKENS);
|
||||
|
||||
t.line("A. claude-sonnet-5-5: the same %d requests, arriving every N seconds (cost per 1,000 requests)", REQUESTS);
|
||||
t.line("%-8s %-33s %9s %9s %9s %10s %9s", "gap", "setup", "plain", "read", "write", "dollars", "vs none");
|
||||
BigDecimal[][] cost = new BigDecimal[4][SETUPS.size()];
|
||||
long[] gaps = {20, 240, 301, 3700};
|
||||
for (int g = 0; g < gaps.length; g++) {
|
||||
for (int s = 0; s < SETUPS.size(); s++) {
|
||||
Setup setup = SETUPS.get(s);
|
||||
CallUsage total = replay(fake, Models.anthropic(fake.url(), "claude-sonnet-5-5", options(setup), true), gaps[g]);
|
||||
BigDecimal writeRate = setup.ttl() == AnthropicCacheTtl.ONE_HOUR ? Prices.SONNET_5_5.cacheWrite1h()
|
||||
: Prices.SONNET_5_5.cacheWrite5m();
|
||||
cost[g][s] = Cost.dollars(Prices.SONNET_5_5, writeRate, total).multiply(per1000());
|
||||
t.line("%-8s %-33s %9s %9s %9s %10s %9s", s == 0 ? gaps[g] + " s" : "", setup.label(), k(total.uncachedInput()),
|
||||
k(total.cacheRead()), k(total.cacheWrite()), money(cost[g][s]), s == 0 ? "" : pct(cost[g][s], cost[g][0]));
|
||||
}
|
||||
t.blank();
|
||||
}
|
||||
// gap 20 s: caching the prefix is the big win
|
||||
assertThat(cost[0][1]).isLessThan(cost[0][0].multiply(new BigDecimal("0.5")));
|
||||
// gap 301 s: every 5-minute entry has expired by the next request, so each request pays the write premium
|
||||
assertThat(cost[2][1]).isGreaterThan(cost[2][0]);
|
||||
// the 1-hour lifetime survives it
|
||||
assertThat(cost[2][2]).isLessThan(cost[2][0]);
|
||||
// an hour and a bit between requests: even the 1-hour entry has expired, and it was written at twice the price
|
||||
assertThat(cost[3][2]).isGreaterThan(cost[3][0]);
|
||||
// retrieved context changes every request, so a breakpoint on the user turn is a write that is never read
|
||||
assertThat(cost[0][3]).isGreaterThan(cost[0][1]);
|
||||
|
||||
t.line("B. The same requests every 20 seconds, per model (SYSTEM_AND_TOOLS with the 5-minute lifetime for Anthropic)");
|
||||
t.line("%-20s %12s %12s %9s", "model", "no caching", "cached", "saving");
|
||||
for (Rates r : List.of(Prices.HAIKU_5_5, Prices.SONNET_5_5, Prices.OPUS_5_5)) {
|
||||
CallUsage plain = replay(fake, Models.anthropic(fake.url(), r.model(), options(SETUPS.get(0)), true), 20);
|
||||
CallUsage cached = replay(fake, Models.anthropic(fake.url(), r.model(), options(SETUPS.get(1)), true), 20);
|
||||
BigDecimal a = Cost.dollars(r, r.input(), plain).multiply(per1000());
|
||||
BigDecimal b = Cost.dollars(r, r.cacheWrite5m(), cached).multiply(per1000());
|
||||
t.line("%-20s %12s %12s %9s", r.model(), money(a), money(b), pct(b, a));
|
||||
assertThat(b).isLessThan(a);
|
||||
}
|
||||
CallUsage oaPlain = replayOpenAi(fake, 20, false);
|
||||
CallUsage oaCached = replayOpenAi(fake, 20, true);
|
||||
BigDecimal oa = Cost.dollars(Prices.GPT_6_2_SOL, Prices.GPT_6_2_SOL.input(), oaPlain).multiply(per1000());
|
||||
BigDecimal ob = Cost.dollars(Prices.GPT_6_2_SOL, Prices.GPT_6_2_SOL.input(), oaCached).multiply(per1000());
|
||||
t.line("%-20s %12s %12s %9s (OpenAI: automatic; 'no caching' = every request sent with a changing first message)",
|
||||
Prices.GPT_6_2_SOL.model(), money(oa), money(ob), pct(ob, oa));
|
||||
assertThat(ob).isLessThan(oa);
|
||||
|
||||
t.blank();
|
||||
t.line("C. How many hits inside the lifetime does a write pay back? hits = (write multiple - 1) / (1 - read multiple)");
|
||||
t.line("%-20s %9s %9s %12s %12s", "model", "write 5m", "read", "hits (5m)", "hits (1h)");
|
||||
for (Rates r : List.of(Prices.HAIKU_5_5, Prices.SONNET_5_5, Prices.OPUS_5_5)) {
|
||||
BigDecimal w5 = r.cacheWrite5m().divide(r.input(), MathContext.DECIMAL64);
|
||||
BigDecimal w1 = r.cacheWrite1h().divide(r.input(), MathContext.DECIMAL64);
|
||||
BigDecimal rd = r.cacheRead().divide(r.input(), MathContext.DECIMAL64);
|
||||
BigDecimal h5 = w5.subtract(BigDecimal.ONE).divide(BigDecimal.ONE.subtract(rd), MathContext.DECIMAL64);
|
||||
BigDecimal h1 = w1.subtract(BigDecimal.ONE).divide(BigDecimal.ONE.subtract(rd), MathContext.DECIMAL64);
|
||||
t.line("%-20s %8sx %8sx %12s %12s", r.model(), w5.setScale(2, RoundingMode.HALF_UP), rd.setScale(3, RoundingMode.HALF_UP),
|
||||
h5.setScale(2, RoundingMode.HALF_UP), h1.setScale(2, RoundingMode.HALF_UP));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static AnthropicCacheOptions options(Setup s) {
|
||||
return AnthropicCacheOptions.builder().strategy(s.strategy()).messageTypeTtl(MessageType.SYSTEM, s.ttl())
|
||||
.messageTypeTtl(MessageType.TOOL, s.ttl()).build();
|
||||
}
|
||||
|
||||
/** 300 requests, one every {@code gap} seconds of the virtual clock; the retrieved chunks vary, the prefix does not. */
|
||||
static CallUsage replay(FakeProviders fake, ChatModel m, long gap) {
|
||||
fake.reset();
|
||||
Random rnd = new Random(42);
|
||||
CallUsage total = CallUsage.zero();
|
||||
for (int i = 0; i < REQUESTS; i++) {
|
||||
List<Integer> chunks = List.of(rnd.nextInt(12), 12 + rnd.nextInt(12));
|
||||
total = total.plus(CallUsage.from(Ask.usage(m, POLICY, SupportPrompts.userTurn(chunks, "Question " + i))));
|
||||
fake.advance(gap);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/** OpenAI: either a stable prefix, or the same text with the request number on the first line (no shared prefix). */
|
||||
static CallUsage replayOpenAi(FakeProviders fake, long gap, boolean stablePrefix) {
|
||||
fake.reset();
|
||||
ChatModel m = Models.openAi(fake.url(), Prices.GPT_6_2_SOL.model(), "support-assistant-v1", true);
|
||||
Random rnd = new Random(42);
|
||||
CallUsage total = CallUsage.zero();
|
||||
for (int i = 0; i < REQUESTS; i++) {
|
||||
List<Integer> chunks = List.of(rnd.nextInt(12), 12 + rnd.nextInt(12));
|
||||
String system = stablePrefix ? POLICY : "Request " + i + "\n" + POLICY;
|
||||
total = total.plus(CallUsage.from(Ask.usage(m, system, SupportPrompts.userTurn(chunks, "Question " + i))));
|
||||
fake.advance(gap);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
static BigDecimal per1000() {
|
||||
return new BigDecimal(1000).divide(new BigDecimal(REQUESTS), MathContext.DECIMAL64);
|
||||
}
|
||||
|
||||
static String k(long tokens) {
|
||||
return String.format("%,.0fk", tokens / 1000.0);
|
||||
}
|
||||
|
||||
static String money(BigDecimal d) {
|
||||
return "$" + d.setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
static String pct(BigDecimal value, BigDecimal base) {
|
||||
BigDecimal change = value.subtract(base).divide(base, MathContext.DECIMAL64).multiply(new BigDecimal(100));
|
||||
return (change.signum() > 0 ? "+" : "") + change.setScale(0, RoundingMode.HALF_UP) + "%";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.ankurm.promptcaching;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
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.AnthropicCacheTtl;
|
||||
import org.springframework.ai.chat.messages.MessageType;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
|
||||
/** The 5-minute and 1-hour lifetimes, and the fact that a read refreshes them. Time is a virtual clock. */
|
||||
class ExpiryTest {
|
||||
|
||||
static final String POLICY = SupportPrompts.policy(24000);
|
||||
|
||||
@Test
|
||||
void lifetimes() throws Exception {
|
||||
try (FakeProviders fake = new FakeProviders();
|
||||
Transcript t = new Transcript("05-expiry.txt",
|
||||
"Cache lifetime: 5 minutes refreshed by every read, or 1 hour (SYSTEM_ONLY, virtual clock)")) {
|
||||
long[] gaps = {0, 240, 290, 301, 100, 1800};
|
||||
for (AnthropicCacheTtl ttl : AnthropicCacheTtl.values()) {
|
||||
fake.reset();
|
||||
ChatModel m = Models.anthropic(fake.url(), "claude-sonnet-5-5", AnthropicCacheOptions.builder()
|
||||
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY).messageTypeTtl(MessageType.SYSTEM, ttl).build(), false);
|
||||
t.line("TTL %s (cache_control sent: %s)", ttl, firstTtl(fake, m));
|
||||
fake.reset();
|
||||
long[] read = new long[gaps.length];
|
||||
long[] write = new long[gaps.length];
|
||||
for (int i = 0; i < gaps.length; i++) {
|
||||
fake.advance(gaps[i]);
|
||||
var u = Ask.usage(m, POLICY, "ticket " + i);
|
||||
read[i] = u.getCacheReadInputTokens();
|
||||
write[i] = u.getCacheWriteInputTokens();
|
||||
t.line(" t=%5ds (gap %4ds) %s", fake.now(), gaps[i], read[i] > 0 ? "HIT read=" + read[i] : "MISS write=" + write[i]);
|
||||
}
|
||||
t.blank();
|
||||
if (ttl == AnthropicCacheTtl.FIVE_MINUTES) {
|
||||
assertThat(read[1]).isPositive(); // 240 s after the write
|
||||
assertThat(read[2]).isPositive(); // 290 s after the READ at 240, which refreshed it
|
||||
assertThat(write[3]).isPositive(); // 301 s after the last read: expired
|
||||
assertThat(read[4]).isPositive();
|
||||
assertThat(write[5]).isPositive(); // 1,800 s
|
||||
}
|
||||
else {
|
||||
assertThat(read[1]).isPositive();
|
||||
assertThat(read[3]).isPositive(); // survives 301 s
|
||||
assertThat(read[5]).isPositive(); // survives 1,800 s
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String firstTtl(FakeProviders fake, ChatModel m) {
|
||||
Ask.usage(m, POLICY, "probe");
|
||||
return Wire.firstCacheControl(fake.last().body());
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
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.chat.messages.MessageType;
|
||||
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;
|
||||
|
||||
/**
|
||||
* A prompt below the vendor's minimum is processed normally, no error, no caching. The only sign is two
|
||||
* zeros in the usage. Spring AI's own {@code messageTypeMinContentLength} is a separate, client-side
|
||||
* switch that decides whether a breakpoint is even sent.
|
||||
*/
|
||||
class MinimumLengthTest {
|
||||
|
||||
@Test
|
||||
void belowTheMinimum() throws Exception {
|
||||
try (FakeProviders fake = new FakeProviders();
|
||||
Transcript t = new Transcript("04-minimum-length.txt",
|
||||
"Below the vendor minimum: nothing is cached and nothing says so (SYSTEM_ONLY, no tools, simulated minimum 512 tokens)")) {
|
||||
t.line("A. The breakpoint is sent either way; the vendor decides");
|
||||
for (int chars : new int[] {1800, 2400}) {
|
||||
fake.reset();
|
||||
ChatModel m = Models.anthropic(fake.url(), "claude-sonnet-5-5",
|
||||
AnthropicCacheOptions.builder().strategy(AnthropicCacheStrategy.SYSTEM_ONLY).build(), false);
|
||||
Ask.usage(m, SupportPrompts.policy(chars), "ticket 1");
|
||||
var sent = Wire.breakpoints(fake.last().body());
|
||||
Usage u = Ask.usage(m, SupportPrompts.policy(chars), "ticket 2");
|
||||
t.line(" system prompt %,d characters: breakpoint sent=%s call 2 read=%d write=%d", chars, !sent.isEmpty(),
|
||||
u.getCacheReadInputTokens(), u.getCacheWriteInputTokens());
|
||||
assertThat(sent).isNotEmpty();
|
||||
if (chars == 1800) {
|
||||
assertThat(u.getCacheReadInputTokens()).isZero();
|
||||
assertThat(u.getCacheWriteInputTokens()).isZero();
|
||||
}
|
||||
else {
|
||||
assertThat(u.getCacheReadInputTokens()).isGreaterThan(500);
|
||||
}
|
||||
}
|
||||
|
||||
t.blank();
|
||||
t.line("B. messageTypeMinContentLength(SYSTEM, 2000) keeps the breakpoint off short prompts, client side");
|
||||
for (int chars : new int[] {1800, 2400}) {
|
||||
fake.reset();
|
||||
ChatModel m = Models.anthropic(fake.url(), "claude-sonnet-5-5", AnthropicCacheOptions.builder()
|
||||
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY).messageTypeMinContentLength(MessageType.SYSTEM, 2000).build(),
|
||||
false);
|
||||
m.call(new Prompt(List.of(new SystemMessage(SupportPrompts.policy(chars)), new UserMessage("ticket 1"))));
|
||||
var sent = Wire.breakpoints(fake.last().body());
|
||||
t.line(" system prompt %,d characters: breakpoint sent=%s %s", chars, !sent.isEmpty(), sent);
|
||||
assertThat(sent.isEmpty()).isEqualTo(chars == 1800);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.ankurm.promptcaching;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.ankurm.promptcaching.support.Ask;
|
||||
import com.ankurm.promptcaching.support.FakeProviders;
|
||||
import com.ankurm.promptcaching.support.Transcript;
|
||||
import org.junit.jupiter.api.Test;
|
||||
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.openai.OpenAiChatModel;
|
||||
import org.springframework.ai.openai.OpenAiChatOptions;
|
||||
|
||||
/**
|
||||
* OpenAI has no switch: a long enough shared prefix is cached automatically. What Spring AI adds is a
|
||||
* way to send {@code prompt_cache_key} and a Usage getter for the cached count.
|
||||
*/
|
||||
class OpenAiTest {
|
||||
|
||||
static final String MODEL = "gpt-6.2-sol";
|
||||
|
||||
static final String POLICY = SupportPrompts.policy(24000);
|
||||
|
||||
@Test
|
||||
void automaticPrefixCaching() throws Exception {
|
||||
try (FakeProviders fake = new FakeProviders();
|
||||
Transcript t = new Transcript("07-openai-automatic-caching.txt",
|
||||
"OpenAI through Spring AI 2.1.0: no breakpoints to place, where a message boundary falls, and a cached count in Usage")) {
|
||||
t.line("A. Same system prompt, different question (simulated rule: longest shared message-boundary prefix of at least 1,024 tokens)");
|
||||
ChatModel m = Models.openAi(fake.url(), MODEL, "support-assistant-v1");
|
||||
Usage u1 = Ask.usage(m, POLICY, SupportPrompts.userTurn(List.of(1), "How do I get a refund?"));
|
||||
var body = fake.last().body();
|
||||
Usage u2 = Ask.usage(m, POLICY, SupportPrompts.userTurn(List.of(2), "Can I pause my subscription?"));
|
||||
t.line(" request carried prompt_cache_key=%s keys sent: %s", body.path("prompt_cache_key").asString(), body.propertyNames());
|
||||
t.line(" call 1: getPromptTokens=%-5d getCacheReadInputTokens=%-5d getCacheWriteInputTokens=%s", u1.getPromptTokens(),
|
||||
u1.getCacheReadInputTokens(), u1.getCacheWriteInputTokens());
|
||||
t.line(" call 2: getPromptTokens=%-5d getCacheReadInputTokens=%-5d getCacheWriteInputTokens=%s", u2.getPromptTokens(),
|
||||
u2.getCacheReadInputTokens(), u2.getCacheWriteInputTokens());
|
||||
assertThat(body.path("prompt_cache_key").asString()).isEqualTo("support-assistant-v1");
|
||||
assertThat(u1.getCacheReadInputTokens()).isZero();
|
||||
assertThat(u2.getCacheReadInputTokens()).isGreaterThan(5000);
|
||||
assertThat(u2.getPromptTokens().longValue()).isGreaterThan(u2.getCacheReadInputTokens());
|
||||
assertThat(u2.getCacheWriteInputTokens()).as("Spring AI has no OpenAI cache-write figure").isNull();
|
||||
CallUsage c = CallUsage.from(u2);
|
||||
t.line(" as a price-sheet bill: plain=%d read=%d write=%d", c.uncachedInput(), c.cacheRead(), c.cacheWrite());
|
||||
|
||||
t.blank();
|
||||
t.line("B. A clock inside the one big system message (the simulation caches whole messages, the GPT-5.6-and-later rule)");
|
||||
fake.reset();
|
||||
Usage a0 = Ask.usage(m, system(false, "10:00:01"), "Where is my parcel?");
|
||||
Usage b0 = Ask.usage(m, system(false, "10:00:02"), "Where is my parcel?");
|
||||
t.line(" call 2: %d of %d prompt tokens cached", b0.getCacheReadInputTokens(), b0.getPromptTokens());
|
||||
assertThat(a0.getCacheReadInputTokens()).isZero();
|
||||
assertThat(b0.getCacheReadInputTokens()).isZero();
|
||||
|
||||
t.blank();
|
||||
t.line("C. The clock moved to its own message after the stable one, so a message boundary falls where the text starts to change");
|
||||
fake.reset();
|
||||
Usage a1 = twoMessages(m, "10:00:01");
|
||||
Usage b1 = twoMessages(m, "10:00:02");
|
||||
t.line(" call 2: %d of %d prompt tokens cached", b1.getCacheReadInputTokens(), b1.getPromptTokens());
|
||||
assertThat(a1.getCacheReadInputTokens()).isZero();
|
||||
assertThat(b1.getCacheReadInputTokens()).isGreaterThan(5000);
|
||||
|
||||
t.blank();
|
||||
t.line("D. A prompt under 1,024 tokens (simulated minimum): no error, no caching");
|
||||
fake.reset();
|
||||
Ask.usage(m, SupportPrompts.policy(2400), "ticket 1");
|
||||
Usage s = Ask.usage(m, SupportPrompts.policy(2400), "ticket 2");
|
||||
t.line(" call 2: %d of %d prompt tokens cached", s.getCacheReadInputTokens(), s.getPromptTokens());
|
||||
assertThat(s.getCacheReadInputTokens()).isZero();
|
||||
|
||||
t.blank();
|
||||
t.line("E. Options that exist in Spring AI 2.1.0, and one that has to travel through extraBody");
|
||||
fake.reset();
|
||||
ChatModel withExtra = OpenAiChatModel.builder().options(OpenAiChatOptions.builder().baseUrl(fake.url() + "/v1")
|
||||
.apiKey("test-key").model(MODEL).maxRetries(0).promptCacheKey("support-assistant-v1")
|
||||
.extraBody(Map.of("prompt_cache_retention", "24h")).build()).build();
|
||||
withExtra.call(new Prompt(List.of(new SystemMessage(POLICY), new UserMessage("hi"))));
|
||||
var sent = fake.last().body();
|
||||
t.line(" keys on the wire: %s", sent.propertyNames());
|
||||
t.line(" prompt_cache_retention=%s", sent.path("prompt_cache_retention").asString());
|
||||
assertThat(sent.path("prompt_cache_retention").asString()).isEqualTo("24h");
|
||||
}
|
||||
}
|
||||
|
||||
static String system(boolean clockFirst, String clock) {
|
||||
return clockFirst ? "Current time: " + clock + "\n" + POLICY : POLICY + "Current time: " + clock + "\n";
|
||||
}
|
||||
|
||||
|
||||
static Usage twoMessages(ChatModel m, String clock) {
|
||||
return m.call(new Prompt(List.of(new SystemMessage(POLICY), new UserMessage("Current time: " + clock + ". Where is my parcel?"))))
|
||||
.getMetadata().getUsage();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.ankurm.promptcaching;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
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.chat.messages.SystemMessage;
|
||||
import org.springframework.ai.chat.messages.UserMessage;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
|
||||
/**
|
||||
* Where does each Spring AI cache strategy put its breakpoints? The request is the real one: the
|
||||
* Anthropic model class built it and sent it to a local server that only wrote it down.
|
||||
*/
|
||||
class WireTest {
|
||||
|
||||
static final String MODEL = "claude-sonnet-5-5";
|
||||
|
||||
static final String POLICY = SupportPrompts.policy(24000);
|
||||
|
||||
@Test
|
||||
void strategiesOnTheWire() throws Exception {
|
||||
try (FakeProviders fake = new FakeProviders();
|
||||
Transcript t = new Transcript("01-breakpoints-on-the-wire.txt",
|
||||
"Where each AnthropicCacheStrategy puts cache_control (request: 4 tools, a system prompt, one user turn)")) {
|
||||
t.line("Request shape: tools[0..3], system (one string), messages[0] = retrieved context + question");
|
||||
t.blank();
|
||||
for (AnthropicCacheStrategy s : AnthropicCacheStrategy.values()) {
|
||||
fake.reset();
|
||||
ChatModel m = Models.anthropic(fake.url(), MODEL, AnthropicCacheOptions.builder().strategy(s).build(), true);
|
||||
m.call(new Prompt(List.of(new SystemMessage(POLICY),
|
||||
new UserMessage(SupportPrompts.userTurn(List.of(1, 2), "How do I get a refund?")))));
|
||||
var body = fake.last().body();
|
||||
List<String> bps = Wire.breakpoints(body);
|
||||
t.line("%-20s breakpoints=%d %s %s", s, bps.size(), bps, Wire.firstCacheControl(body));
|
||||
switch (s) {
|
||||
case NONE -> assertThat(bps).isEmpty();
|
||||
case TOOLS_ONLY -> assertThat(bps).containsExactly("tools[3]");
|
||||
case SYSTEM_ONLY -> assertThat(bps).containsExactly("system[0]");
|
||||
case SYSTEM_AND_TOOLS -> assertThat(bps).containsExactly("tools[3]", "system[0]");
|
||||
case CONVERSATION_HISTORY -> assertThat(bps).hasSize(3).contains("tools[3]", "system[0]");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ankurm.promptcaching.support;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.ankurm.promptcaching.CallUsage;
|
||||
import org.springframework.ai.chat.messages.AssistantMessage;
|
||||
import org.springframework.ai.chat.messages.Message;
|
||||
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.model.ChatResponse;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
|
||||
/** Small helpers so each test reads as the scenario and not as plumbing. */
|
||||
public final class Ask {
|
||||
|
||||
private Ask() {
|
||||
}
|
||||
|
||||
public static ChatResponse call(ChatModel m, List<Message> messages) {
|
||||
return m.call(new Prompt(messages));
|
||||
}
|
||||
|
||||
public static Usage usage(ChatModel m, String system, String user) {
|
||||
return call(m, List.of(new SystemMessage(system), new UserMessage(user))).getMetadata().getUsage();
|
||||
}
|
||||
|
||||
public static CallUsage anthropic(ChatModel m, String system, String user) {
|
||||
return CallUsage.from(usage(m, system, user));
|
||||
}
|
||||
|
||||
public static List<Message> conversation(String system, List<Message> rest) {
|
||||
List<Message> all = new ArrayList<>();
|
||||
all.add(new SystemMessage(system));
|
||||
all.addAll(rest);
|
||||
return all;
|
||||
}
|
||||
|
||||
public static AssistantMessage reply(ChatResponse r) {
|
||||
return r.getResult().getOutput();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package com.ankurm.promptcaching.support;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
|
||||
/**
|
||||
* A local HTTP server that answers like Anthropic's Messages API and OpenAI's chat completions, so the
|
||||
* REAL Spring AI model classes can be pointed at it and the requests they build can be recorded.
|
||||
*
|
||||
* <p>It is not a language model and it is not a vendor. What is REAL in this repository is the request
|
||||
* Spring AI builds and how Spring AI reads the response. What is SIMULATED, and so is never a measurement
|
||||
* of a vendor, is everything on the vendor's side:
|
||||
* <ul>
|
||||
* <li>a token is {@code ceil(characters / 4)} of the JSON the client sent;</li>
|
||||
* <li>the answer is fixed text of a chosen length;</li>
|
||||
* <li>whether a prefix is found in the cache follows the rules the vendors DOCUMENT (read on 2026-11-24),
|
||||
* applied to the request that really arrived: tools, then system, then messages; a write at each
|
||||
* breakpoint whose prefix reaches the minimum length; a 20-block lookback from each breakpoint; a read of the longest breakpoint prefix still
|
||||
* alive; a 5-minute or 1-hour lifetime that a read refreshes. Time is a virtual clock the test advances.</li>
|
||||
* </ul>
|
||||
* Not simulated: concurrent first requests, OpenAI's routing by
|
||||
* {@code prompt_cache_key}, hidden system tokens, rounding of OpenAI cached counts, and latency.
|
||||
*/
|
||||
public final class FakeProviders implements AutoCloseable {
|
||||
|
||||
/** One request the server received. */
|
||||
public record Seen(String provider, JsonNode body) {
|
||||
}
|
||||
|
||||
private static final JsonMapper JSON = JsonMapper.builder().build();
|
||||
|
||||
private static final JsonMapper SORTED = JsonMapper.builder()
|
||||
.enable(tools.jackson.databind.SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS).build();
|
||||
|
||||
private final HttpServer server;
|
||||
|
||||
private final List<Seen> seen = new CopyOnWriteArrayList<>();
|
||||
|
||||
private final AtomicLong clockSeconds = new AtomicLong();
|
||||
|
||||
/** prefix text to {expiry second, lifetime seconds}. */
|
||||
private final Map<String, long[]> anthropicCache = new HashMap<>();
|
||||
|
||||
private final Map<String, Long> openAiCache = new HashMap<>();
|
||||
|
||||
private volatile int anthropicMinTokens = 512;
|
||||
|
||||
private volatile int openAiMinTokens = 1024;
|
||||
|
||||
private volatile long openAiLifetimeSeconds = 1800;
|
||||
|
||||
private volatile int answerTokens = 40;
|
||||
|
||||
public FakeProviders() throws IOException {
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/", this::handle);
|
||||
server.start();
|
||||
}
|
||||
|
||||
public String url() {
|
||||
return "http://127.0.0.1:" + server.getAddress().getPort();
|
||||
}
|
||||
|
||||
public List<Seen> seen() {
|
||||
return seen;
|
||||
}
|
||||
|
||||
public Seen last() {
|
||||
return seen.get(seen.size() - 1);
|
||||
}
|
||||
|
||||
/** Forget every request and every cache entry; keep the settings. */
|
||||
public void reset() {
|
||||
seen.clear();
|
||||
anthropicCache.clear();
|
||||
openAiCache.clear();
|
||||
clockSeconds.set(0);
|
||||
}
|
||||
|
||||
public void advance(long seconds) {
|
||||
clockSeconds.addAndGet(seconds);
|
||||
}
|
||||
|
||||
public long now() {
|
||||
return clockSeconds.get();
|
||||
}
|
||||
|
||||
public FakeProviders anthropicMinTokens(int n) {
|
||||
this.anthropicMinTokens = n;
|
||||
return this;
|
||||
}
|
||||
|
||||
public FakeProviders openAiMinTokens(int n) {
|
||||
this.openAiMinTokens = n;
|
||||
return this;
|
||||
}
|
||||
|
||||
public FakeProviders answerTokens(int n) {
|
||||
this.answerTokens = n;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Estimated tokens: one per four characters, rounded up. */
|
||||
public static int tokens(long chars) {
|
||||
return (int) ((chars + 3) / 4);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------
|
||||
|
||||
private void handle(HttpExchange ex) throws IOException {
|
||||
String path = ex.getRequestURI().getPath();
|
||||
String raw = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
|
||||
JsonNode body = JSON.readTree(raw);
|
||||
String provider;
|
||||
String reply;
|
||||
synchronized (this) {
|
||||
if (path.endsWith("/messages")) {
|
||||
provider = "anthropic";
|
||||
seen.add(new Seen(provider, body));
|
||||
reply = anthropic(body);
|
||||
}
|
||||
else if (path.endsWith("/chat/completions")) {
|
||||
provider = "openai";
|
||||
seen.add(new Seen(provider, body));
|
||||
reply = openAi(body);
|
||||
}
|
||||
else {
|
||||
send(ex, 404, "{\"error\":\"unknown path " + path + "\"}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
send(ex, 200, reply);
|
||||
}
|
||||
|
||||
/** A block of the prompt in cache order, with the text that decides whether two prompts share it. */
|
||||
private record Block(String path, String text, JsonNode cacheControl) {
|
||||
}
|
||||
|
||||
private String answer() {
|
||||
return "x".repeat(answerTokens * 4);
|
||||
}
|
||||
|
||||
/** A string and a one-element text block mean the same thing to the vendor, so they must key the same. */
|
||||
private static String textBlock(String text) {
|
||||
ObjectNode n = JSON.createObjectNode();
|
||||
n.put("type", "text").put("text", text);
|
||||
return canonical(n);
|
||||
}
|
||||
|
||||
/** The block without its cache_control, with keys sorted: the SDK and a hand-built node order them differently. */
|
||||
private static String canonical(JsonNode node) {
|
||||
ObjectNode copy = (ObjectNode) node.deepCopy();
|
||||
copy.remove("cache_control");
|
||||
return SORTED.writeValueAsString(JSON.convertValue(copy, Object.class));
|
||||
}
|
||||
|
||||
private String anthropic(JsonNode b) {
|
||||
List<Block> blocks = new ArrayList<>();
|
||||
int i = 0;
|
||||
for (JsonNode tool : b.path("tools")) {
|
||||
blocks.add(new Block("tools[" + i++ + "]", canonical(tool), tool.get("cache_control")));
|
||||
}
|
||||
JsonNode sys = b.path("system");
|
||||
if (sys.isString()) {
|
||||
blocks.add(new Block("system", textBlock(sys.asString()), null));
|
||||
}
|
||||
else {
|
||||
i = 0;
|
||||
for (JsonNode s : sys) {
|
||||
blocks.add(new Block("system[" + i++ + "]", canonical(s), s.get("cache_control")));
|
||||
}
|
||||
}
|
||||
int mi = 0;
|
||||
for (JsonNode m : b.path("messages")) {
|
||||
String role = m.path("role").asString();
|
||||
if (m.path("content").isString()) {
|
||||
blocks.add(new Block("messages[" + mi + "]", role + ":" + textBlock(m.path("content").asString()), null));
|
||||
}
|
||||
else {
|
||||
int ci = 0;
|
||||
for (JsonNode c : m.path("content")) {
|
||||
blocks.add(new Block("messages[" + mi + "].content[" + ci++ + "]", role + ":" + canonical(c),
|
||||
c.get("cache_control")));
|
||||
}
|
||||
}
|
||||
mi++;
|
||||
}
|
||||
long[] chars = new long[blocks.size()];
|
||||
String[] prefix = new String[blocks.size()];
|
||||
StringBuilder sb = new StringBuilder();
|
||||
long running = 0;
|
||||
for (int k = 0; k < blocks.size(); k++) {
|
||||
sb.append(blocks.get(k).text()).append('\u0001');
|
||||
running += blocks.get(k).text().length();
|
||||
chars[k] = running;
|
||||
prefix[k] = sb.toString();
|
||||
}
|
||||
int total = tokens(running);
|
||||
long now = clockSeconds.get();
|
||||
|
||||
List<Integer> breakpoints = new ArrayList<>();
|
||||
for (int k = 0; k < blocks.size(); k++) {
|
||||
if (blocks.get(k).cacheControl() != null) {
|
||||
breakpoints.add(k);
|
||||
}
|
||||
}
|
||||
int read = 0;
|
||||
int hit = -1;
|
||||
// Lookback: from each breakpoint, look at that block and the 19 before it for an entry an earlier
|
||||
// request wrote (a write only ever happens at a breakpoint). The highest live entry wins, and a
|
||||
// read refreshes its lifetime.
|
||||
for (int pos = blocks.size() - 1; pos >= 0 && hit < 0; pos--) {
|
||||
boolean reachable = false;
|
||||
for (int idx : breakpoints) {
|
||||
if (pos <= idx && pos > idx - LOOKBACK) {
|
||||
reachable = true;
|
||||
}
|
||||
}
|
||||
long[] entry = reachable ? anthropicCache.get(prefix[pos]) : null;
|
||||
if (entry != null && entry[0] > now) {
|
||||
read = tokens(chars[pos]);
|
||||
hit = pos;
|
||||
entry[0] = now + entry[1];
|
||||
}
|
||||
}
|
||||
int created5m = 0;
|
||||
int created1h = 0;
|
||||
int writtenTo = read;
|
||||
for (int idx : breakpoints) {
|
||||
if (idx <= hit) {
|
||||
continue;
|
||||
}
|
||||
int upTo = tokens(chars[idx]);
|
||||
if (upTo < anthropicMinTokens) {
|
||||
continue;
|
||||
}
|
||||
long life = lifetime(blocks.get(idx).cacheControl());
|
||||
anthropicCache.put(prefix[idx], new long[] {now + life, life});
|
||||
int segment = upTo - writtenTo;
|
||||
if (life >= 3600) {
|
||||
created1h += segment;
|
||||
}
|
||||
else {
|
||||
created5m += segment;
|
||||
}
|
||||
writtenTo = upTo;
|
||||
}
|
||||
int created = created5m + created1h;
|
||||
ObjectNode r = JSON.createObjectNode();
|
||||
r.put("id", "msg_fake").put("type", "message").put("role", "assistant").put("model", b.path("model").asString(""))
|
||||
.put("stop_reason", "end_turn").putNull("stop_sequence");
|
||||
r.putArray("content").addObject().put("type", "text").put("text", answer());
|
||||
ObjectNode u = r.putObject("usage");
|
||||
u.put("input_tokens", total - read - created).put("output_tokens", answerTokens)
|
||||
.put("cache_creation_input_tokens", created).put("cache_read_input_tokens", read);
|
||||
u.putObject("cache_creation").put("ephemeral_5m_input_tokens", created5m).put("ephemeral_1h_input_tokens", created1h);
|
||||
return JSON.writeValueAsString(r);
|
||||
}
|
||||
|
||||
/** The documented lookback: at most 20 positions per breakpoint, counting the breakpoint itself. */
|
||||
private static final int LOOKBACK = 20;
|
||||
|
||||
private static long lifetime(JsonNode cacheControl) {
|
||||
return "1h".equals(cacheControl.path("ttl").asString("5m")) ? 3600 : 300;
|
||||
}
|
||||
|
||||
/** OpenAI: automatic prefix caching at message boundaries, minimum 1,024 tokens. No switch to turn on. */
|
||||
private String openAi(JsonNode b) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
if (b.has("tools")) {
|
||||
parts.add(JSON.writeValueAsString(b.get("tools")));
|
||||
}
|
||||
for (JsonNode m : b.path("messages")) {
|
||||
parts.add(canonical(m));
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
long running = 0;
|
||||
long now = clockSeconds.get();
|
||||
int cached = 0;
|
||||
List<String> keys = new ArrayList<>();
|
||||
List<Integer> tokensAt = new ArrayList<>();
|
||||
for (String p : parts) {
|
||||
sb.append(p).append('\u0001');
|
||||
running += p.length();
|
||||
keys.add(sb.toString());
|
||||
tokensAt.add(tokens(running));
|
||||
}
|
||||
for (int k = keys.size() - 1; k >= 0; k--) {
|
||||
Long expires = openAiCache.get(keys.get(k));
|
||||
if (expires != null && expires > now && tokensAt.get(k) >= openAiMinTokens) {
|
||||
cached = tokensAt.get(k);
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int k = 0; k < keys.size(); k++) {
|
||||
if (tokensAt.get(k) >= openAiMinTokens) {
|
||||
openAiCache.put(keys.get(k), now + openAiLifetimeSeconds);
|
||||
}
|
||||
}
|
||||
int total = tokens(running);
|
||||
ObjectNode r = JSON.createObjectNode();
|
||||
r.put("id", "chatcmpl-fake").put("object", "chat.completion").put("created", 1700000000)
|
||||
.put("model", b.path("model").asString(""));
|
||||
ObjectNode msg = r.putArray("choices").addObject().put("index", 0).put("finish_reason", "stop")
|
||||
.putObject("message").put("role", "assistant").put("content", answer());
|
||||
msg.putNull("refusal");
|
||||
ObjectNode u = r.putObject("usage").put("prompt_tokens", total).put("completion_tokens", answerTokens)
|
||||
.put("total_tokens", total + answerTokens);
|
||||
u.putObject("prompt_tokens_details").put("cached_tokens", cached);
|
||||
return JSON.writeValueAsString(r);
|
||||
}
|
||||
|
||||
private static void send(HttpExchange ex, int status, String json) throws IOException {
|
||||
byte[] out = json.getBytes(StandardCharsets.UTF_8);
|
||||
ex.getResponseHeaders().add("Content-Type", "application/json");
|
||||
ex.sendResponseHeaders(status, out.length);
|
||||
try (OutputStream os = ex.getResponseBody()) {
|
||||
os.write(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.ankurm.promptcaching.support;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Writes a numbered transcript under {@code output/} (repository root, not {@code docs/}) and
|
||||
* echoes it to the console. Every console block quoted in the article comes out of one of these
|
||||
* files verbatim.
|
||||
*/
|
||||
public final class Transcript implements AutoCloseable {
|
||||
|
||||
private final Path path;
|
||||
private final StringWriter buffer = new StringWriter();
|
||||
private final PrintWriter out = new PrintWriter(buffer);
|
||||
|
||||
public Transcript(String fileName, String title) {
|
||||
this.path = Path.of("output", fileName);
|
||||
out.println("# " + title);
|
||||
out.println();
|
||||
}
|
||||
|
||||
public Transcript line(String format, Object... args) {
|
||||
out.println(args.length == 0 ? format : String.format(format, args));
|
||||
return this;
|
||||
}
|
||||
|
||||
public Transcript blank() {
|
||||
out.println();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
out.flush();
|
||||
try {
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, buffer.toString());
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("could not write " + path, e);
|
||||
}
|
||||
System.out.print(buffer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.ankurm.promptcaching.support;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import tools.jackson.databind.JsonNode;
|
||||
|
||||
/** Reads the request body Spring AI sent: where are the cache breakpoints? */
|
||||
public final class Wire {
|
||||
|
||||
private Wire() {
|
||||
}
|
||||
|
||||
/** Paths of every block that carries {@code cache_control}, in request order, e.g. {@code tools[3]}. */
|
||||
public static List<String> breakpoints(JsonNode body) {
|
||||
List<String> out = new ArrayList<>();
|
||||
int i = 0;
|
||||
for (JsonNode t : body.path("tools")) {
|
||||
if (t.has("cache_control")) {
|
||||
out.add("tools[" + i + "]");
|
||||
}
|
||||
i++;
|
||||
}
|
||||
JsonNode sys = body.path("system");
|
||||
if (sys.isArray()) {
|
||||
i = 0;
|
||||
for (JsonNode s : sys) {
|
||||
if (s.has("cache_control")) {
|
||||
out.add("system[" + i + "]");
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
int mi = 0;
|
||||
for (JsonNode m : body.path("messages")) {
|
||||
if (m.path("content").isArray()) {
|
||||
int ci = 0;
|
||||
for (JsonNode c : m.path("content")) {
|
||||
if (c.has("cache_control")) {
|
||||
out.add("messages[" + mi + "].content[" + ci + "]");
|
||||
}
|
||||
ci++;
|
||||
}
|
||||
}
|
||||
mi++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The {@code cache_control} JSON of the first breakpoint, or an empty string. */
|
||||
public static String firstCacheControl(JsonNode body) {
|
||||
for (JsonNode t : body.path("tools")) {
|
||||
if (t.has("cache_control")) {
|
||||
return t.get("cache_control").toString();
|
||||
}
|
||||
}
|
||||
for (JsonNode s : body.path("system")) {
|
||||
if (s.has("cache_control")) {
|
||||
return s.get("cache_control").toString();
|
||||
}
|
||||
}
|
||||
for (JsonNode m : body.path("messages")) {
|
||||
for (JsonNode c : m.path("content")) {
|
||||
if (c.has("cache_control")) {
|
||||
return c.get("cache_control").toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user