-
Notifications
You must be signed in to change notification settings - Fork 3.7k
feat(providers): prompt caching for Anthropic + Azure-Anthropic #5101
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
waleedlatif1
wants to merge
6
commits into
staging
Choose a base branch
from
feat/provider-prompt-caching
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ebe5447
feat(providers): prompt caching for Anthropic + Azure-Anthropic
waleedlatif1 3a44936
fix(providers): cache gate uses request system prompt; test uses vi.s…
waleedlatif1 3855e04
refactor(providers): always-on prompt caching via a directly-tested h…
waleedlatif1 38140c7
fix(providers): size prompt-cache gate on the larger of payload.syste…
waleedlatif1 5e90631
docs(providers): move prompt-cache inline comments into TSDoc
waleedlatif1 b9a453d
test(providers): add request-capture test for Anthropic prompt caching
waleedlatif1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' | ||
| import { shouldCacheStaticPrefix } from '@/providers/prompt-cache' | ||
|
|
||
| const LARGE = 'x'.repeat(8_000) // ~2,000 est. tokens, above the 1,024 gate | ||
| const SMALL = 'x'.repeat(400) // ~100 est. tokens, below the gate | ||
|
|
||
| describe('shouldCacheStaticPrefix', () => { | ||
| // vi.stubEnv cleanly sets/restores the kill switch without `delete` (which | ||
| // biome rewrites) or assigning `undefined` (which coerces to the string | ||
| // "undefined" and leaks to other tests in the worker). | ||
| beforeEach(() => { | ||
| vi.stubEnv('PROMPT_CACHE_DISABLED', '') | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| vi.unstubAllEnvs() | ||
| }) | ||
|
|
||
| it('caches a large system prompt that has tools (agent loop)', () => { | ||
| expect(shouldCacheStaticPrefix({ systemPrompt: LARGE, hasTools: true })).toBe(true) | ||
| }) | ||
|
|
||
| it('caches a large system prompt even without tools', () => { | ||
| expect(shouldCacheStaticPrefix({ systemPrompt: LARGE, hasTools: false })).toBe(true) | ||
| }) | ||
|
|
||
| it('reaches the threshold via tools when the system prompt alone is below it', () => { | ||
| // Small system + large serialized tools clears the combined threshold, and | ||
| // tools imply reuse, so it should cache. | ||
| expect( | ||
| shouldCacheStaticPrefix({ systemPrompt: SMALL, hasTools: true, toolsApproxChars: 8_000 }) | ||
| ).toBe(true) | ||
| }) | ||
|
|
||
| it('does NOT cache a small, tool-less prompt (one-shot write surcharge avoided)', () => { | ||
| expect(shouldCacheStaticPrefix({ systemPrompt: SMALL, hasTools: false })).toBe(false) | ||
| }) | ||
|
|
||
| it('does NOT cache a small system even with tools when the combined prefix is below threshold', () => { | ||
| expect( | ||
| shouldCacheStaticPrefix({ systemPrompt: SMALL, hasTools: true, toolsApproxChars: 400 }) | ||
| ).toBe(false) | ||
| }) | ||
|
|
||
| it('does NOT cache when there is no system prompt', () => { | ||
| expect( | ||
| shouldCacheStaticPrefix({ systemPrompt: '', hasTools: true, toolsApproxChars: 8_000 }) | ||
| ).toBe(false) | ||
| expect(shouldCacheStaticPrefix({ systemPrompt: null, hasTools: true })).toBe(false) | ||
| }) | ||
|
|
||
| it('is disabled by the PROMPT_CACHE_DISABLED kill switch', () => { | ||
| vi.stubEnv('PROMPT_CACHE_DISABLED', 'true') | ||
| expect(shouldCacheStaticPrefix({ systemPrompt: LARGE, hasTools: true })).toBe(false) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| import { getEnv, isTruthy } from '@/lib/core/config/env' | ||
|
|
||
| /** | ||
| * Minimum estimated static-prefix size (system + tool definitions) before it is | ||
| * worth marking a prompt-cache breakpoint. This is a rough lower bound across | ||
| * Claude models (some require more); below it, providers silently skip caching | ||
| * anyway, so this only avoids spending a breakpoint on a trivially small prefix. | ||
| */ | ||
| const MIN_CACHEABLE_PREFIX_TOKENS = 1024 | ||
|
|
||
| /** Rough token estimate (~4 chars/token) — fast and good enough for a gate. */ | ||
| function estimateTokens(text: string): number { | ||
| return Math.ceil(text.length / 4) | ||
| } | ||
|
|
||
| /** | ||
| * Decides whether to inject prompt-cache breakpoints on the static prefix | ||
| * (system prompt + tool definitions) for providers that require explicit cache | ||
| * control (Anthropic, Bedrock, and Anthropic models via OpenRouter). | ||
| * | ||
| * Caching only pays off when the prefix is large enough to be cacheable AND is | ||
| * actually re-read: agent tool-loops re-send the prefix on every iteration, and | ||
| * a large system prompt is typically reused across runs within the cache TTL. | ||
| * A small, tool-less prompt is intentionally skipped so a one-shot call never | ||
| * pays the cache-write surcharge for a prefix that is never read back. | ||
| * | ||
| * Set `PROMPT_CACHE_DISABLED=true` to turn this off globally (kill switch). | ||
| */ | ||
| export function shouldCacheStaticPrefix(params: { | ||
| systemPrompt: string | null | undefined | ||
| hasTools: boolean | ||
| toolsApproxChars?: number | ||
| }): boolean { | ||
| if (isTruthy(getEnv('PROMPT_CACHE_DISABLED'))) { | ||
| return false | ||
| } | ||
|
|
||
| const system = params.systemPrompt ?? '' | ||
| if (!system) { | ||
| return false | ||
| } | ||
|
|
||
| const systemTokens = estimateTokens(system) | ||
| const toolTokens = params.toolsApproxChars ? Math.ceil(params.toolsApproxChars / 4) : 0 | ||
| const prefixTokens = systemTokens + toolTokens | ||
|
|
||
| if (prefixTokens < MIN_CACHEABLE_PREFIX_TOKENS) { | ||
| return false | ||
| } | ||
|
|
||
| // Tools imply an agent loop (the prefix is re-read each iteration). Without | ||
| // tools, only cache when the system prompt alone is large enough to be worth | ||
| // the write on its own. | ||
| return params.hasTools || systemTokens >= MIN_CACHEABLE_PREFIX_TOKENS | ||
| } | ||
|
waleedlatif1 marked this conversation as resolved.
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.