Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4gvXXQgw1eTk5EoTT
161 lines
9.0 KiB
Java
161 lines
9.0 KiB
Java
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) + "%";
|
|
}
|
|
}
|