diff --git a/README.md b/README.md index d8cd9eb..dcc2aba 100644 --- a/README.md +++ b/README.md @@ -38,5 +38,6 @@ Runnable companion code for the Spring AI articles on [ankurm.com](https://ankur | [`chat-ui-htmx/`](chat-ui-htmx) | A streaming chat page with no JavaScript of our own: htmx and its SSE extension (vendored) post the message and append each token from a `Flux>` over `ChatClient` with `MessageChatMemoryAdvisor` keyed by the HTTP session. Measured traps: EventSource strips one leading space per data line, model text must be HTML-escaped, a cancelled stream left the upstream connection open in 7 of 8 runs until an OkHttp interceptor made it `call.cancel()` (closed in 8 of 8 after), and the SDK's push source ignores back-pressure (`limitRate` changes nothing; a bounded buffer does). Checked in headless Chromium. **The model is a stub OpenAI-compatible SSE server I wrote, not a language model; no real provider was run.** Spring Boot 4.1.2, Spring AI 2.0.2, htmx 2.0.11, Java 25. | [Streaming AI Chat UI with Spring AI, SSE and htmx (No React Needed)](https://ankurm.com/spring-ai-streaming-chat-ui-sse-htmx/) | | [`tool-confirmation/`](tool-confirmation) | Human-in-the-loop tool calls in Spring AI 2.1: `@Tool(requiresConfirmation = true)`, `ToolCallConfirmationPolicy` (by metadata, by name, by argument), the pause and resume with `ToolCallDecisions`, deny messages, and what the application must add itself: a server-side pause store, an approver check, a replay guard (one winner among 16 concurrent approvers), an audit log, and an approver page over SSE and htmx with model-chosen arguments HTML-escaped. Also measured: an open SSE stream holds up Spring Boot's graceful shutdown. **The model is a scripted `ChatModel`, not a language model; the htmx page was not opened in a browser.** Spring Boot 4.1.3, Spring AI 2.1.0, Java 25. | [Human-in-the-Loop Tool Calls in Spring AI 2.1](https://ankurm.com/spring-ai-2-1-human-in-the-loop-tool-call-confirmation/) | +| [`prompt-caching/`](prompt-caching) | Provider-side prompt caching on Spring AI 2.1: where each `AnthropicCacheStrategy` puts `cache_control` on the real request, what a hit, a miss and a write look like in `Usage` (`getPromptTokens()` now includes the cached tokens, which it did not on 2.0.1), what one changed word invalidates, 5-minute and 1-hour lifetimes, the 20-block lookback in a long chat, OpenAI's automatic caching with `prompt_cache_key`, and a cost table (a 5-minute entry that expires between requests makes caching cost more than none). **No vendor API called: the vendors are a local server that applies their documented rules; tokens are characters / 4 and prices are list prices read on 2026-11-24.** Spring Boot 4.2.0, Spring AI 2.1.0, Java 25. | [Prompt Caching in Spring AI](https://ankurm.com/spring-ai-prompt-caching-anthropic-openai-cost-table/) | Upgrading from Spring AI 1.x: [migration guide](https://ankurm.com/spring-ai-1-to-2-migration-guide/). diff --git a/prompt-caching/.gitignore b/prompt-caching/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/prompt-caching/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/prompt-caching/README.md b/prompt-caching/README.md new file mode 100644 index 0000000..3b1eff1 --- /dev/null +++ b/prompt-caching/README.md @@ -0,0 +1,47 @@ +# prompt-caching + +Provider-side prompt caching with Spring AI 2.1: where `AnthropicCacheStrategy` puts cache breakpoints on the request, what a hit, a miss and a write look like in `Usage`, what one changed word invalidates, the 5-minute and 1-hour lifetimes, the 20-block lookback in a long chat, OpenAI's automatic prefix caching and `prompt_cache_key`, and a cost table with the traps in it. + +**No vendor API was called, and no claim is made about any vendor's behaviour.** `FakeProviders` is a local HTTP server that answers in the Anthropic Messages and OpenAI chat-completions formats. The real `AnthropicChatModel` and `OpenAiChatModel` talk to it, so the requests it records are the requests those classes build. Everything on the vendor's side is simulation: a token is `ceil(characters / 4)`, the answer is fixed text, and cache hits follow the rules the vendors document (read on 2026-11-24) applied to the request that arrived. Not simulated: concurrent first requests, OpenAI's routing by `prompt_cache_key`, hidden system tokens, rounding of OpenAI cached counts, latency. So the cost table is a worked example of the price sheets, not a bill. + +| | | +|---|---| +| Spring Boot | 4.2.0 (GA 2026-11-19) | +| Spring AI | 2.1.0 (GA 2026-11-19) | +| Java | 25 (Temurin 25.0.5.1) | +| Prices | read 2026-11-24 from the Anthropic and OpenAI pricing pages | + +## Run it + +```bash +export JAVA_HOME=/path/to/jdk-25 +./scripts/run-all.sh # runs the tests; they write every file under output/ +``` + +Every figure in `output/` is also an assertion in a test, so a number that stops being true fails the build. No API key is needed. + +## Layout + +| Path | What it is | +|---|---| +| `src/main/.../CallUsage.java` | Turns Spring AI's `Usage` into plain / read / write / output tokens | +| `src/main/.../Cost.java`, `Rates.java`, `Prices.java` | Dollars from tokens; list prices with the date they were read | +| `src/main/.../Models.java` | Builds the real Anthropic and OpenAI chat models with cache options | +| `src/main/.../SupportPrompts.java`, `SupportTools.java` | Deterministic prompt, retrieved chunks and four tools | +| `src/test/.../support/FakeProviders.java` | The local stand-in for both vendors (the simulation) | +| `src/test/.../*Test.java` | One test per transcript | + +## Captured output + +| File | Test | What it shows | +|---|---|---| +| [`01-breakpoints-on-the-wire.txt`](output/01-breakpoints-on-the-wire.txt) | `WireTest` | Where each `AnthropicCacheStrategy` puts `cache_control` | +| [`02-hits-and-invalidation.txt`](output/02-hits-and-invalidation.txt) | `HitsTest` | A hit in `Usage`, and what one changed word costs | +| [`03-clock-in-the-system-prompt.txt`](output/03-clock-in-the-system-prompt.txt) | `HitsTest` | `multiBlockSystemCaching` and a clock in the system prompt | +| [`04-minimum-length.txt`](output/04-minimum-length.txt) | `MinimumLengthTest` | A prompt below the minimum: two zeros and no error | +| [`05-expiry.txt`](output/05-expiry.txt) | `ExpiryTest` | 5-minute and 1-hour lifetimes on a virtual clock | +| [`06-conversation.txt`](output/06-conversation.txt) | `ConversationTest` | `CONVERSATION_HISTORY` over 8 turns, and the 20-block lookback | +| [`07-openai-automatic-caching.txt`](output/07-openai-automatic-caching.txt) | `OpenAiTest` | `prompt_cache_key`, cached tokens in `Usage`, where a message boundary falls | +| [`08-cost.txt`](output/08-cost.txt) | `CostTest` | Cost of 1,000 requests by strategy, gap, model; break-even hits | + +The article walks through all of this in one page: [Prompt Caching in Spring AI](https://ankurm.com/spring-ai-prompt-caching-anthropic-openai-cost-table/). diff --git a/prompt-caching/output/01-breakpoints-on-the-wire.txt b/prompt-caching/output/01-breakpoints-on-the-wire.txt new file mode 100644 index 0000000..7afbb72 --- /dev/null +++ b/prompt-caching/output/01-breakpoints-on-the-wire.txt @@ -0,0 +1,9 @@ +# Where each AnthropicCacheStrategy puts cache_control (request: 4 tools, a system prompt, one user turn) + +Request shape: tools[0..3], system (one string), messages[0] = retrieved context + question + +NONE breakpoints=0 [] +TOOLS_ONLY breakpoints=1 [tools[3]] {"type":"ephemeral","ttl":"5m"} +SYSTEM_ONLY breakpoints=1 [system[0]] {"type":"ephemeral","ttl":"5m"} +SYSTEM_AND_TOOLS breakpoints=2 [tools[3], system[0]] {"type":"ephemeral","ttl":"5m"} +CONVERSATION_HISTORY breakpoints=3 [tools[3], system[0], messages[0].content[0]] {"type":"ephemeral","ttl":"5m"} diff --git a/prompt-caching/output/02-hits-and-invalidation.txt b/prompt-caching/output/02-hits-and-invalidation.txt new file mode 100644 index 0000000..8710800 --- /dev/null +++ b/prompt-caching/output/02-hits-and-invalidation.txt @@ -0,0 +1,14 @@ +# A cache hit in Spring AI's Usage, and what one changed word costs (SYSTEM_AND_TOOLS, 4 tools, 24,000-character system prompt) + +A. The same tools and system prompt, a different question each time + call 1 getPromptTokens=6959 getCacheReadInputTokens=0 getCacheWriteInputTokens=6628 + call 2 getPromptTokens=6957 getCacheReadInputTokens=6628 getCacheWriteInputTokens=0 + call 2: 6628 of 6957 prompt tokens came from the cache; 329 were billed at the plain input price + (getPromptTokens() includes the cached tokens in 2.1.0) + +B. After a warm-up call, what does each change do? (read = served from cache, write = stored again) + (the four tool definitions alone are 550 tokens; the whole prefix is 6628) + nothing changed read=6628 write=0 uncached=326 + only the retrieved context changed read=6628 write=0 uncached=1007 + one word of the system prompt changed read=550 write=6079 uncached=12 + one word of one tool description changed read=0 write=6628 uncached=12 diff --git a/prompt-caching/output/03-clock-in-the-system-prompt.txt b/prompt-caching/output/03-clock-in-the-system-prompt.txt new file mode 100644 index 0000000..3e93226 --- /dev/null +++ b/prompt-caching/output/03-clock-in-the-system-prompt.txt @@ -0,0 +1,8 @@ +# A clock in the system prompt: one joined block, or the static prefix pattern (SYSTEM_ONLY) + +multiBlockSystemCaching=false system blocks sent=1 breakpoints=[system[0]] + call 1: cacheWrite=6085 cacheRead=0 + call 2: cacheWrite=6085 cacheRead=0 (the clock changed between the calls) +multiBlockSystemCaching=true system blocks sent=2 breakpoints=[system[0]] + call 1: cacheWrite=6078 cacheRead=0 + call 2: cacheWrite=0 cacheRead=6078 (the clock changed between the calls) diff --git a/prompt-caching/output/04-minimum-length.txt b/prompt-caching/output/04-minimum-length.txt new file mode 100644 index 0000000..4808d42 --- /dev/null +++ b/prompt-caching/output/04-minimum-length.txt @@ -0,0 +1,9 @@ +# Below the vendor minimum: nothing is cached and nothing says so (SYSTEM_ONLY, no tools, simulated minimum 512 tokens) + +A. The breakpoint is sent either way; the vendor decides + system prompt 1,800 characters: breakpoint sent=true call 2 read=0 write=0 + system prompt 2,400 characters: breakpoint sent=true call 2 read=625 write=0 + +B. messageTypeMinContentLength(SYSTEM, 2000) keeps the breakpoint off short prompts, client side + system prompt 1,800 characters: breakpoint sent=false [] + system prompt 2,400 characters: breakpoint sent=true [system[0]] diff --git a/prompt-caching/output/05-expiry.txt b/prompt-caching/output/05-expiry.txt new file mode 100644 index 0000000..04a0125 --- /dev/null +++ b/prompt-caching/output/05-expiry.txt @@ -0,0 +1,18 @@ +# Cache lifetime: 5 minutes refreshed by every read, or 1 hour (SYSTEM_ONLY, virtual clock) + +TTL FIVE_MINUTES (cache_control sent: {"type":"ephemeral","ttl":"5m"}) + t= 0s (gap 0s) MISS write=6078 + t= 240s (gap 240s) HIT read=6078 + t= 530s (gap 290s) HIT read=6078 + t= 831s (gap 301s) MISS write=6078 + t= 931s (gap 100s) HIT read=6078 + t= 2731s (gap 1800s) MISS write=6078 + +TTL ONE_HOUR (cache_control sent: {"type":"ephemeral","ttl":"1h"}) + t= 0s (gap 0s) MISS write=6078 + t= 240s (gap 240s) HIT read=6078 + t= 530s (gap 290s) HIT read=6078 + t= 831s (gap 301s) HIT read=6078 + t= 931s (gap 100s) HIT read=6078 + t= 2731s (gap 1800s) HIT read=6078 + diff --git a/prompt-caching/output/06-conversation.txt b/prompt-caching/output/06-conversation.txt new file mode 100644 index 0000000..ebb7d50 --- /dev/null +++ b/prompt-caching/output/06-conversation.txt @@ -0,0 +1,38 @@ +# An 8-turn chat, each user turn about 1,600 characters of pasted log (claude-sonnet-5-5 prices, 5-minute cache) + +strategy NONE + turn 1 breakpoints=[] plain=6403 read=0 write=0 + turn 2 breakpoints=[] plain=6773 read=0 write=0 + turn 3 breakpoints=[] plain=7143 read=0 write=0 + turn 4 breakpoints=[] plain=7543 read=0 write=0 + turn 5 breakpoints=[] plain=7909 read=0 write=0 + turn 6 breakpoints=[] plain=8304 read=0 write=0 + turn 7 breakpoints=[] plain=8699 read=0 write=0 + turn 8 breakpoints=[] plain=9077 read=0 write=0 + 8 turns: plain=61851 read=0 write=0 input+output cost $0.1269 + +strategy SYSTEM_ONLY + turn 1 breakpoints=[system[0]] plain=325 read=0 write=6078 + turn 2 breakpoints=[system[0]] plain=695 read=6078 write=0 + turn 3 breakpoints=[system[0]] plain=1065 read=6078 write=0 + turn 4 breakpoints=[system[0]] plain=1465 read=6078 write=0 + turn 5 breakpoints=[system[0]] plain=1831 read=6078 write=0 + turn 6 breakpoints=[system[0]] plain=2226 read=6078 write=0 + turn 7 breakpoints=[system[0]] plain=2621 read=6078 write=0 + turn 8 breakpoints=[system[0]] plain=2999 read=6078 write=0 + 8 turns: plain=13227 read=42546 write=6078 input+output cost $0.0491 + +strategy CONVERSATION_HISTORY + turn 1 breakpoints=[system[0], messages[0].content[0]] plain=0 read=0 write=6403 + turn 2 breakpoints=[system[0], messages[2].content[0]] plain=0 read=6403 write=370 + turn 3 breakpoints=[system[0], messages[4].content[0]] plain=0 read=6773 write=370 + turn 4 breakpoints=[system[0], messages[6].content[0]] plain=0 read=7143 write=400 + turn 5 breakpoints=[system[0], messages[8].content[0]] plain=0 read=7543 write=366 + turn 6 breakpoints=[system[0], messages[10].content[0]] plain=0 read=7909 write=395 + turn 7 breakpoints=[system[0], messages[12].content[0]] plain=0 read=8304 write=395 + turn 8 breakpoints=[system[0], messages[14].content[0]] plain=0 read=8699 write=378 + 8 turns: plain=0 read=52774 write=9077 input+output cost $0.0312 + +The 20-block lookback: the same chat, but 24 messages are added between two turns + next turn, 2 messages added since the last breakpoint: read=6773 write=370 + next turn, 25 messages added since the last breakpoint: read=6078 write=1339 diff --git a/prompt-caching/output/07-openai-automatic-caching.txt b/prompt-caching/output/07-openai-automatic-caching.txt new file mode 100644 index 0000000..8b60e73 --- /dev/null +++ b/prompt-caching/output/07-openai-automatic-caching.txt @@ -0,0 +1,20 @@ +# OpenAI through Spring AI 2.1.0: no breakpoints to place, where a message boundary falls, and a cached count in Usage + +A. Same system prompt, different question (simulated rule: longest shared message-boundary prefix of at least 1,024 tokens) + request carried prompt_cache_key=support-assistant-v1 keys sent: [messages, model, prompt_cache_key] + call 1: getPromptTokens=6410 getCacheReadInputTokens=0 getCacheWriteInputTokens=null + call 2: getPromptTokens=6408 getCacheReadInputTokens=6080 getCacheWriteInputTokens=null + as a price-sheet bill: plain=328 read=6080 write=0 + +B. A clock inside the one big system message (the simulation caches whole messages, the GPT-5.6-and-later rule) + call 2: 0 of 6097 prompt tokens cached + +C. The clock moved to its own message after the stable one, so a message boundary falls where the text starts to change + call 2: 6080 of 6097 prompt tokens cached + +D. A prompt under 1,024 tokens (simulated minimum): no error, no caching + call 2: 0 of 635 prompt tokens cached + +E. Options that exist in Spring AI 2.1.0, and one that has to travel through extraBody + keys on the wire: [messages, model, prompt_cache_key, prompt_cache_retention] + prompt_cache_retention=24h diff --git a/prompt-caching/output/08-cost.txt b/prompt-caching/output/08-cost.txt new file mode 100644 index 0000000..7018fd9 --- /dev/null +++ b/prompt-caching/output/08-cost.txt @@ -0,0 +1,36 @@ +# 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) + +A. claude-sonnet-5-5: the same 300 requests, arriving every N seconds (cost per 1,000 requests) +gap setup plain read write dollars vs none +20 s no caching 2,187k 0k 0k $16.08 + SYSTEM_AND_TOOLS, 5 minutes 198k 1,982k 7k $3.54 -78% + SYSTEM_AND_TOOLS, 1 hour 198k 1,982k 7k $3.57 -78% + CONVERSATION_HISTORY, 5 minutes 0k 1,982k 205k $3.87 -76% + +240 s no caching 2,187k 0k 0k $16.08 + SYSTEM_AND_TOOLS, 5 minutes 198k 1,982k 7k $3.54 -78% + SYSTEM_AND_TOOLS, 1 hour 198k 1,982k 7k $3.57 -78% + CONVERSATION_HISTORY, 5 minutes 0k 1,982k 205k $3.87 -76% + +301 s no caching 2,187k 0k 0k $16.08 + SYSTEM_AND_TOOLS, 5 minutes 198k 0k 1,988k $19.39 +21% + SYSTEM_AND_TOOLS, 1 hour 198k 1,982k 7k $3.57 -78% + CONVERSATION_HISTORY, 5 minutes 0k 0k 2,187k $19.72 +23% + +3700 s no caching 2,187k 0k 0k $16.08 + SYSTEM_AND_TOOLS, 5 minutes 198k 0k 1,988k $19.39 +21% + SYSTEM_AND_TOOLS, 1 hour 198k 0k 1,988k $29.33 +82% + CONVERSATION_HISTORY, 5 minutes 0k 0k 2,187k $19.72 +23% + +B. The same requests every 20 seconds, per model (SYSTEM_AND_TOOLS with the 5-minute lifetime for Anthropic) +model no caching cached saving +claude-haiku-5-5 $0.80 $0.21 -74% +claude-sonnet-5-5 $16.08 $3.54 -78% +claude-opus-5-5 $32.15 $7.07 -78% +gpt-6.2-sol $16.35 $3.54 -78% (OpenAI: automatic; 'no caching' = every request sent with a changing first message) + +C. How many hits inside the lifetime does a write pay back? hits = (write multiple - 1) / (1 - read multiple) +model write 5m read hits (5m) hits (1h) +claude-haiku-5-5 1.25x 0.100x 0.28 1.11 +claude-sonnet-5-5 1.25x 0.050x 0.26 1.05 +claude-opus-5-5 1.25x 0.050x 0.26 1.05 diff --git a/prompt-caching/pom.xml b/prompt-caching/pom.xml new file mode 100644 index 0000000..07ce160 --- /dev/null +++ b/prompt-caching/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.2.0 + + + + com.ankurm + prompt-caching + 1.0.0 + prompt-caching + Provider-side prompt caching with Spring AI 2.1: Anthropic cache breakpoints, OpenAI automatic prefix caching, cache-hit usage and a cost model. + + + 25 + 2.1.0 + + + + + + org.springframework.ai + spring-ai-bom + ${spring-ai.version} + pom + import + + + + + + + org.springframework.ai + spring-ai-client-chat + + + org.springframework.ai + spring-ai-openai + + + org.springframework.ai + spring-ai-anthropic + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + -Duser.timezone=UTC -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8 + + + + + diff --git a/prompt-caching/scripts/run-all.sh b/prompt-caching/scripts/run-all.sh new file mode 100755 index 0000000..cb1efbf --- /dev/null +++ b/prompt-caching/scripts/run-all.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Regenerates every file under output/. The tests write them through the Transcript helper, so each +# figure in a transcript is also an assertion: if a number stops being true, the build fails. +# No network access to any model vendor is needed, and none is made: the vendors are a local server. +set -euo pipefail +cd "$(dirname "$0")/.." +rm -rf target output +mvn -q -B test +ls output diff --git a/prompt-caching/src/main/java/com/ankurm/promptcaching/CallUsage.java b/prompt-caching/src/main/java/com/ankurm/promptcaching/CallUsage.java new file mode 100644 index 0000000..8a6790c --- /dev/null +++ b/prompt-caching/src/main/java/com/ankurm/promptcaching/CallUsage.java @@ -0,0 +1,45 @@ +package com.ankurm.promptcaching; + +import org.springframework.ai.chat.metadata.Usage; + +/** + * One request's token bill in the vocabulary of the price sheet: tokens at the plain price, tokens read + * from the cache, tokens written to the cache, and output. + * + *

Spring AI 2.1.0 reports {@code Usage.getPromptTokens()} as the WHOLE prompt for both vendors, so the + * plain-price part is what is left after the cache tokens are taken out. That is not what the vendors + * send (Anthropic's {@code input_tokens} is only the part after the last breakpoint) and it is not what + * Spring AI 2.0.1 did: the {@code providers} module's committed transcript, taken on 2.0.1, shows + * {@code promptTokens=3} next to {@code cacheWrite=6011}. Code written for 2.0 that adds the three + * numbers together now counts the cached tokens twice. The conversion is written once, here, and tested. + * + * @param uncachedInput tokens billed at the plain input price + * @param cacheRead tokens billed at the cache-hit price + * @param cacheWrite tokens billed at the cache-write price + * @param output generated tokens + */ +public record CallUsage(long uncachedInput, long cacheRead, long cacheWrite, long output) { + + public static CallUsage from(Usage u) { + long read = n(u.getCacheReadInputTokens()); + long write = n(u.getCacheWriteInputTokens()); + return new CallUsage(n(u.getPromptTokens()) - read - write, read, write, n(u.getCompletionTokens())); + } + + public long totalInput() { + return uncachedInput + cacheRead + cacheWrite; + } + + public CallUsage plus(CallUsage o) { + return new CallUsage(uncachedInput + o.uncachedInput, cacheRead + o.cacheRead, cacheWrite + o.cacheWrite, + output + o.output); + } + + public static CallUsage zero() { + return new CallUsage(0, 0, 0, 0); + } + + private static long n(Number x) { + return x == null ? 0 : x.longValue(); + } +} diff --git a/prompt-caching/src/main/java/com/ankurm/promptcaching/Cost.java b/prompt-caching/src/main/java/com/ankurm/promptcaching/Cost.java new file mode 100644 index 0000000..cea357c --- /dev/null +++ b/prompt-caching/src/main/java/com/ankurm/promptcaching/Cost.java @@ -0,0 +1,30 @@ +package com.ankurm.promptcaching; + +import java.math.BigDecimal; +import java.math.MathContext; + +/** Turns a {@link CallUsage} into dollars. Plain arithmetic, kept apart so a test can pin it. */ +public final class Cost { + + private static final BigDecimal MILLION = new BigDecimal(1_000_000); + + private Cost() { + } + + /** + * @param writeRate the cache-write price per million tokens to apply: {@code rates.cacheWrite5m()} + * or {@code rates.cacheWrite1h()} + */ + public static BigDecimal dollars(Rates rates, BigDecimal writeRate, CallUsage u) { + return rates.input().multiply(BigDecimal.valueOf(u.uncachedInput())) + .add(rates.cacheRead().multiply(BigDecimal.valueOf(u.cacheRead()))) + .add(writeRate.multiply(BigDecimal.valueOf(u.cacheWrite()))) + .add(rates.output().multiply(BigDecimal.valueOf(u.output()))) + .divide(MILLION, MathContext.DECIMAL64); + } + + /** Dollars if no token had been cached: every input token at the plain price. */ + public static BigDecimal withoutCaching(Rates rates, CallUsage u) { + return dollars(rates, rates.input(), new CallUsage(u.totalInput(), 0, 0, u.output())); + } +} diff --git a/prompt-caching/src/main/java/com/ankurm/promptcaching/Models.java b/prompt-caching/src/main/java/com/ankurm/promptcaching/Models.java new file mode 100644 index 0000000..c0a40ca --- /dev/null +++ b/prompt-caching/src/main/java/com/ankurm/promptcaching/Models.java @@ -0,0 +1,46 @@ +package com.ankurm.promptcaching; + +import org.springframework.ai.anthropic.AnthropicCacheOptions; +import org.springframework.ai.anthropic.AnthropicChatModel; +import org.springframework.ai.anthropic.AnthropicChatOptions; +import org.springframework.ai.chat.model.ChatModel; +import org.springframework.ai.openai.OpenAiChatModel; +import org.springframework.ai.openai.OpenAiChatOptions; +import org.springframework.ai.support.ToolCallbacks; + +/** Builds the real Spring AI chat models. Only the base URL differs from production. */ +public final class Models { + + private Models() { + } + + /** + * An Anthropic model with the given cache options and, optionally, the four support tools. + * Cache options and tools are default options of the model, not per-call options: a per-call + * options object replaces more than it seems to (see the providers module). + */ + public static ChatModel anthropic(String baseUrl, String model, AnthropicCacheOptions cache, boolean withTools) { + AnthropicChatOptions.Builder o = AnthropicChatOptions.builder().baseUrl(baseUrl).apiKey("test-key") + .model(model).maxTokens(1024).maxRetries(0).cacheOptions(cache); + if (withTools) { + o.toolCallbacks(ToolCallbacks.from(new SupportTools())); + } + return AnthropicChatModel.builder().options(o.build()).build(); + } + + public static ChatModel openAi(String baseUrl, String model, String promptCacheKey) { + return openAi(baseUrl, model, promptCacheKey, false); + } + + public static ChatModel openAi(String baseUrl, String model, String promptCacheKey, boolean withTools) { + OpenAiChatOptions.Builder o = OpenAiChatOptions.builder().baseUrl(baseUrl + "/v1").apiKey("test-key") + .model(model).maxRetries(0); + if (withTools) { + o.toolCallbacks(ToolCallbacks.from(new SupportTools())); + } + if (promptCacheKey != null) { + o.promptCacheKey(promptCacheKey); + } + return OpenAiChatModel.builder().options(o.build()).build(); + } +} diff --git a/prompt-caching/src/main/java/com/ankurm/promptcaching/Prices.java b/prompt-caching/src/main/java/com/ankurm/promptcaching/Prices.java new file mode 100644 index 0000000..d8e3aa1 --- /dev/null +++ b/prompt-caching/src/main/java/com/ankurm/promptcaching/Prices.java @@ -0,0 +1,27 @@ +package com.ankurm.promptcaching; + +/** + * List prices read on 2026-11-24 from + * https://platform.claude.com/docs/en/about-claude/pricing and + * https://developers.openai.com/api/docs/pricing (standard tier, dollars per million tokens). + * They change; re-read the pages before you rely on a figure. + * + *

OpenAI has no separate 5-minute and 1-hour write price here: for the models in the table the + * caching guide describes a write charge only for GPT-5.6 and later (1.25x for the default 30-minute + * window), and Spring AI 2.1.0 does not report write tokens for OpenAI at all, so the OpenAI row + * prices every uncached token at the plain input rate. See the article for what that leaves out. + */ +public final class Prices { + + private Prices() { + } + + public static final Rates SONNET_5_5 = Rates.of("claude-sonnet-5-5", "2", "2.50", "4", "0.10", "10"); + + public static final Rates OPUS_5_5 = Rates.of("claude-opus-5-5", "4", "5", "8", "0.20", "20"); + + /** Prompts of 100K tokens or less; above that Haiku 5.5 is priced higher, which this module never reaches. */ + public static final Rates HAIKU_5_5 = Rates.of("claude-haiku-5-5", "0.10", "0.125", "0.20", "0.01", "0.50"); + + public static final Rates GPT_6_2_SOL = Rates.of("gpt-6.2-sol", "2.00", "2.00", "2.00", "0.10", "10.00"); +} diff --git a/prompt-caching/src/main/java/com/ankurm/promptcaching/Rates.java b/prompt-caching/src/main/java/com/ankurm/promptcaching/Rates.java new file mode 100644 index 0000000..c8532ee --- /dev/null +++ b/prompt-caching/src/main/java/com/ankurm/promptcaching/Rates.java @@ -0,0 +1,17 @@ +package com.ankurm.promptcaching; + +import java.math.BigDecimal; + +/** + * Dollars per million tokens for one model. {@code cacheWrite5m} and {@code cacheWrite1h} are what a + * token costs the first time it goes into the cache; {@code cacheRead} is what it costs on a hit. + * The numbers live in {@link Prices} with the date they were read from the vendors' pages. + */ +public record Rates(String model, BigDecimal input, BigDecimal cacheWrite5m, BigDecimal cacheWrite1h, + BigDecimal cacheRead, BigDecimal output) { + + public static Rates of(String model, String input, String write5m, String write1h, String read, String output) { + return new Rates(model, new BigDecimal(input), new BigDecimal(write5m), new BigDecimal(write1h), + new BigDecimal(read), new BigDecimal(output)); + } +} diff --git a/prompt-caching/src/main/java/com/ankurm/promptcaching/SupportPrompts.java b/prompt-caching/src/main/java/com/ankurm/promptcaching/SupportPrompts.java new file mode 100644 index 0000000..34f2ad3 --- /dev/null +++ b/prompt-caching/src/main/java/com/ankurm/promptcaching/SupportPrompts.java @@ -0,0 +1,59 @@ +package com.ankurm.promptcaching; + +import java.util.List; + +/** + * Deterministic prompt material for a support assistant, so a prompt's length (and therefore its cost) + * is known exactly and two runs of the suite produce the same transcript. + */ +public final class SupportPrompts { + + private SupportPrompts() { + } + + private static final String[] RULES = { + "Tickets that mention data loss, a security problem or a payment failure are priority high.", + "Tickets about slow pages, wrong totals or broken exports are priority medium.", + "Questions about how to use a feature, cosmetic problems and feature requests are priority low.", + "Keep the title under eight words and write it in the present tense without the customer's name.", + "If the ticket contains several problems, summarise the most severe one and ignore the rest.", + "Never repeat an email address, phone number or order number from the ticket in the title.", + }; + + /** A support policy of at least {@code chars} characters, built from numbered rules. */ + public static String policy(int chars) { + StringBuilder sb = new StringBuilder("You are the support assistant of an online shop. Follow every rule below.\n"); + int n = 1; + while (sb.length() < chars) { + sb.append("Rule ").append(n).append(": ").append(RULES[(n - 1) % RULES.length]).append('\n'); + n++; + } + return sb.toString(); + } + + private static final String[] TOPICS = {"refund window", "gift cards", "shipping to islands", "invoice corrections", + "two-factor reset", "subscription pause", "warranty claims", "address changes", "bulk orders", + "coupon stacking", "returns without a receipt", "export of order history"}; + + /** The knowledge-base chunk a retriever would return for topic number {@code i}; about 1,200 characters. */ + public static String chunk(int i) { + String topic = TOPICS[Math.floorMod(i, TOPICS.length)]; + StringBuilder sb = new StringBuilder("Knowledge base article: ").append(topic).append(" (revision ").append(i).append(")\n"); + int n = 1; + while (sb.length() < 1200) { + sb.append("Step ").append(n).append(" for ").append(topic).append(": check the order record, confirm the customer's identity, ") + .append("apply the policy for ").append(topic).append(" and write the outcome in the ticket.\n"); + n++; + } + return sb.toString(); + } + + /** The user turn of a retrieval-augmented request: retrieved chunks first, then the question. */ + public static String userTurn(List chunkIds, String question) { + StringBuilder sb = new StringBuilder("Context:\n"); + for (int id : chunkIds) { + sb.append(chunk(id)).append('\n'); + } + return sb.append("Question: ").append(question).toString(); + } +} diff --git a/prompt-caching/src/main/java/com/ankurm/promptcaching/SupportTools.java b/prompt-caching/src/main/java/com/ankurm/promptcaching/SupportTools.java new file mode 100644 index 0000000..6dd238c --- /dev/null +++ b/prompt-caching/src/main/java/com/ankurm/promptcaching/SupportTools.java @@ -0,0 +1,44 @@ +package com.ankurm.promptcaching; + +import org.springframework.ai.tool.annotation.Tool; +import org.springframework.ai.tool.annotation.ToolParam; + +/** + * Four tools with deliberately long descriptions. Tool definitions are the first thing in an + * Anthropic prompt (tools, then system, then messages), so they are part of every prefix. + */ +public class SupportTools { + + @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"; + } +} diff --git a/prompt-caching/src/test/java/com/ankurm/promptcaching/ChangedTools.java b/prompt-caching/src/test/java/com/ankurm/promptcaching/ChangedTools.java new file mode 100644 index 0000000..ba1ecec --- /dev/null +++ b/prompt-caching/src/test/java/com/ankurm/promptcaching/ChangedTools.java @@ -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"; + } +} diff --git a/prompt-caching/src/test/java/com/ankurm/promptcaching/ConversationTest.java b/prompt-caching/src/test/java/com/ankurm/promptcaching/ConversationTest.java new file mode 100644 index 0000000..5d1e7c8 --- /dev/null +++ b/prompt-caching/src/test/java/com/ankurm/promptcaching/ConversationTest.java @@ -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 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 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); + } + } +} diff --git a/prompt-caching/src/test/java/com/ankurm/promptcaching/CostTest.java b/prompt-caching/src/test/java/com/ankurm/promptcaching/CostTest.java new file mode 100644 index 0000000..6acca84 --- /dev/null +++ b/prompt-caching/src/test/java/com/ankurm/promptcaching/CostTest.java @@ -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 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 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 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) + "%"; + } +} diff --git a/prompt-caching/src/test/java/com/ankurm/promptcaching/ExpiryTest.java b/prompt-caching/src/test/java/com/ankurm/promptcaching/ExpiryTest.java new file mode 100644 index 0000000..58cd547 --- /dev/null +++ b/prompt-caching/src/test/java/com/ankurm/promptcaching/ExpiryTest.java @@ -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()); + } +} diff --git a/prompt-caching/src/test/java/com/ankurm/promptcaching/HitsTest.java b/prompt-caching/src/test/java/com/ankurm/promptcaching/HitsTest.java new file mode 100644 index 0000000..b30e63e --- /dev/null +++ b/prompt-caching/src/test/java/com/ankurm/promptcaching/HitsTest.java @@ -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()); + } +} diff --git a/prompt-caching/src/test/java/com/ankurm/promptcaching/MinimumLengthTest.java b/prompt-caching/src/test/java/com/ankurm/promptcaching/MinimumLengthTest.java new file mode 100644 index 0000000..5f880d5 --- /dev/null +++ b/prompt-caching/src/test/java/com/ankurm/promptcaching/MinimumLengthTest.java @@ -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); + } + } + } +} diff --git a/prompt-caching/src/test/java/com/ankurm/promptcaching/OpenAiTest.java b/prompt-caching/src/test/java/com/ankurm/promptcaching/OpenAiTest.java new file mode 100644 index 0000000..4732c8a --- /dev/null +++ b/prompt-caching/src/test/java/com/ankurm/promptcaching/OpenAiTest.java @@ -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(); + } +} diff --git a/prompt-caching/src/test/java/com/ankurm/promptcaching/WireTest.java b/prompt-caching/src/test/java/com/ankurm/promptcaching/WireTest.java new file mode 100644 index 0000000..c19c6ee --- /dev/null +++ b/prompt-caching/src/test/java/com/ankurm/promptcaching/WireTest.java @@ -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 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]"); + } + } + } + } +} diff --git a/prompt-caching/src/test/java/com/ankurm/promptcaching/support/Ask.java b/prompt-caching/src/test/java/com/ankurm/promptcaching/support/Ask.java new file mode 100644 index 0000000..c65ab0e --- /dev/null +++ b/prompt-caching/src/test/java/com/ankurm/promptcaching/support/Ask.java @@ -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 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 conversation(String system, List rest) { + List all = new ArrayList<>(); + all.add(new SystemMessage(system)); + all.addAll(rest); + return all; + } + + public static AssistantMessage reply(ChatResponse r) { + return r.getResult().getOutput(); + } +} diff --git a/prompt-caching/src/test/java/com/ankurm/promptcaching/support/FakeProviders.java b/prompt-caching/src/test/java/com/ankurm/promptcaching/support/FakeProviders.java new file mode 100644 index 0000000..9b7552f --- /dev/null +++ b/prompt-caching/src/test/java/com/ankurm/promptcaching/support/FakeProviders.java @@ -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. + * + *

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: + *

+ * 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 = new CopyOnWriteArrayList<>(); + + private final AtomicLong clockSeconds = new AtomicLong(); + + /** prefix text to {expiry second, lifetime seconds}. */ + private final Map anthropicCache = new HashMap<>(); + + private final Map 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() { + 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 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 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 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 keys = new ArrayList<>(); + List 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); + } + } +} diff --git a/prompt-caching/src/test/java/com/ankurm/promptcaching/support/Transcript.java b/prompt-caching/src/test/java/com/ankurm/promptcaching/support/Transcript.java new file mode 100644 index 0000000..6bd1882 --- /dev/null +++ b/prompt-caching/src/test/java/com/ankurm/promptcaching/support/Transcript.java @@ -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); + } +} diff --git a/prompt-caching/src/test/java/com/ankurm/promptcaching/support/Wire.java b/prompt-caching/src/test/java/com/ankurm/promptcaching/support/Wire.java new file mode 100644 index 0000000..d713000 --- /dev/null +++ b/prompt-caching/src/test/java/com/ankurm/promptcaching/support/Wire.java @@ -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 breakpoints(JsonNode body) { + List 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 ""; + } +}