feat(anthropic): opt-in rolling prompt-cache breakpoints

Add providers.<name>.promptCache with inject and key flags. When inject is true on an anthropic provider, the gateway adds up to four cache_control breakpoints. They go on the last tool, the last system block, and the last two user messages. The translated chat path and the /v1/messages passthrough both use it. A body that already has any cache_control is left unchanged. The input body is never mutated. The default config changes no request body.
This commit is contained in:
2026-11-26 01:28:51 +00:00
parent bc77e16e45
commit 5ffd44874c
7 changed files with 428 additions and 7 deletions
+1 -1
View File
@@ -9,7 +9,7 @@ import (
// nonSecretConfigKeys lists every string-valued JSON key in Config reviewed as
// non-secret. A new key must be classified here or in the redaction sets.
var nonSecretConfigKeys = map[string]bool{
"agents": true, "allowedCIDRs": true, "backoff": true, "cacheTTL": true, "maxDelay": true,
"agents": true, "promptCache": true, "inject": true, "key": true, "allowedCIDRs": true, "backoff": true, "cacheTTL": true, "maxDelay": true,
"card": true, "discoveryInterval": true, "file": true, "group": true,
"groups": true, "maxOpenDuration": true, "mcpServers": true,
"kinds": true, "limitExemptKinds": true, "metadataPath": true, "modelAliases": true, "modelBaseUrls": true, "models": true, "name": true,
+8 -5
View File
@@ -230,11 +230,14 @@ type ProviderConfig struct {
// operators who route native tools like macstudio-rerank/parakeet-
// mlx/piper-tts through THIS field's route must leave it unset or
// true to keep that traffic flowing.
Passthrough *bool `json:"passthrough,omitempty"`
Type string `json:"type"`
BaseURL string `json:"baseUrl,omitempty"`
APIKey string `json:"apiKey"`
DiscoveryInterval string `json:"discoveryInterval,omitempty"`
// PromptCache opts this provider into prompt-caching body changes.
// nil (the default) leaves every request body unchanged.
PromptCache *PromptCacheConfig `json:"promptCache,omitempty"`
Passthrough *bool `json:"passthrough,omitempty"`
Type string `json:"type"`
BaseURL string `json:"baseUrl,omitempty"`
APIKey string `json:"apiKey"`
DiscoveryInterval string `json:"discoveryInterval,omitempty"`
// RequestTimeout overrides the global Config.RequestTimeout for this
// provider alone — an explicit per-provider override always wins over
// the global default (house rule). Same Go-duration-string form,
+177
View File
@@ -0,0 +1,177 @@
package traefikllmgateway
import "fmt"
// PromptCacheConfig holds a provider's opt-in prompt-caching body changes.
type PromptCacheConfig struct {
// Inject adds Anthropic cache_control breakpoints. anthropic type only.
Inject bool `json:"inject,omitempty"`
// Key adds a hashed prompt_cache_key. openai type only.
Key bool `json:"key,omitempty"`
}
// maxCacheBreakpoints is Anthropic's limit on cache_control markers per request.
const maxCacheBreakpoints = 4
// providerPromptCache returns the provider's promptCache config, or the
// zero value when the provider or the block is absent.
func (g *Gateway) providerPromptCache(name string) PromptCacheConfig {
if g == nil || g.cfg == nil {
return PromptCacheConfig{}
}
pc := g.cfg.Providers[name]
if pc == nil || pc.PromptCache == nil {
return PromptCacheConfig{}
}
return *pc.PromptCache
}
func validatePromptCache(name, providerType string, pc *PromptCacheConfig) error {
if pc == nil {
return nil
}
if pc.Inject && providerType != providerTypeAnthropic {
return fmt.Errorf("llmgateway: provider %q: promptCache.inject is supported for type %q only", name, providerTypeAnthropic)
}
if pc.Key && providerType != providerTypeOpenAI {
return fmt.Errorf("llmgateway: provider %q: promptCache.key is supported for type %q only", name, providerTypeOpenAI)
}
return nil
}
func newCacheMarker() map[string]any {
return map[string]any{"type": "ephemeral"}
}
// hasCacheControl reports whether any map under v carries a cache_control key.
func hasCacheControl(v any) bool {
switch t := v.(type) {
case map[string]any:
if _, ok := t["cache_control"]; ok {
return true
}
for _, c := range t {
if hasCacheControl(c) {
return true
}
}
case []any:
for i := 0; i < len(t); i++ {
if hasCacheControl(t[i]) {
return true
}
}
}
return false
}
// markBlock returns a copy of block carrying a cache_control marker.
func markBlock(block any) (any, bool) {
m, ok := block.(map[string]any)
if !ok {
return block, false
}
cp := make(map[string]any, len(m)+1)
for k, v := range m {
cp[k] = v
}
cp["cache_control"] = newCacheMarker()
return cp, true
}
// markLastBlock returns a copy of blocks with the last entry marked.
func markLastBlock(blocks []any) ([]any, bool) {
if len(blocks) == 0 {
return blocks, false
}
marked, ok := markBlock(blocks[len(blocks)-1])
if !ok {
return blocks, false
}
cp := make([]any, len(blocks))
copy(cp, blocks)
cp[len(cp)-1] = marked
return cp, true
}
// markContent returns content (string or block list) with its last block marked.
func markContent(content any) (any, bool) {
switch c := content.(type) {
case string:
if c == "" {
return content, false
}
return []any{map[string]any{"type": "text", "text": c, "cache_control": newCacheMarker()}}, true
case []any:
out, ok := markLastBlock(c)
return out, ok
}
return content, false
}
// markMessage returns a copy of messages with entry idx's last content block marked.
func markMessage(messages []any, idx int) ([]any, bool) {
msg, ok := messages[idx].(map[string]any)
if !ok {
return messages, false
}
content, ok := markContent(msg["content"])
if !ok {
return messages, false
}
msgCopy := make(map[string]any, len(msg))
for k, v := range msg {
msgCopy[k] = v
}
msgCopy["content"] = content
cp := make([]any, len(messages))
copy(cp, messages)
cp[idx] = msgCopy
return cp, true
}
// injectCacheControl adds up to four cache breakpoints to an Anthropic-format
// body: last tool, last system block, and the last two user messages. It
// never mutates req; touched nodes are copied. A body that already carries
// any cache_control is returned unchanged.
func injectCacheControl(req map[string]any) (map[string]any, int) {
if hasCacheControl(req["tools"]) || hasCacheControl(req["system"]) || hasCacheControl(req["messages"]) {
return req, 0
}
out := make(map[string]any, len(req))
for k, v := range req {
out[k] = v
}
added := 0
if tools, ok := req["tools"].([]any); ok {
if marked, done := markLastBlock(tools); done {
out["tools"] = marked
added++
}
}
if system, done := markContent(req["system"]); done {
out["system"] = system
added++
}
if messages, ok := req["messages"].([]any); ok {
users := make([]int, 0, 2)
for i := len(messages) - 1; i >= 0 && len(users) < 2; i-- {
if m, isMap := messages[i].(map[string]any); isMap && m["role"] == "user" {
users = append(users, i)
}
}
cur := messages
for _, idx := range users {
if marked, done := markMessage(cur, idx); done {
cur = marked
added++
}
}
out["messages"] = cur
}
if added > maxCacheBreakpoints {
return req, 0
}
return out, added
}
+222
View File
@@ -0,0 +1,222 @@
package traefikllmgateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
)
func cloneJSON(t *testing.T, v map[string]any) map[string]any {
t.Helper()
b, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
var out map[string]any
if err := json.Unmarshal(b, &out); err != nil {
t.Fatal(err)
}
return out
}
func lastBlockHasMarker(t *testing.T, content any) bool {
t.Helper()
blocks, ok := content.([]any)
if !ok || len(blocks) == 0 {
return false
}
m, _ := blocks[len(blocks)-1].(map[string]any)
cc, _ := m["cache_control"].(map[string]any)
return cc["type"] == "ephemeral"
}
func fiveMessageBody() map[string]any {
return map[string]any{
"model": "claude-x",
"system": "sys",
"tools": []any{map[string]any{"name": "a"}, map[string]any{"name": "b"}},
"messages": []any{
map[string]any{"role": "user", "content": "u0"},
map[string]any{"role": "assistant", "content": "a1"},
map[string]any{"role": "user", "content": "u2"},
map[string]any{"role": "assistant", "content": "a3"},
map[string]any{"role": "user", "content": []any{map[string]any{"type": "text", "text": "u4"}}},
},
}
}
func TestInjectCacheControlFourBreakpoints(t *testing.T) {
out, n := injectCacheControl(fiveMessageBody())
if n != 4 {
t.Fatalf("added = %d, want 4", n)
}
tools := out["tools"].([]any)
if _, ok := tools[0].(map[string]any)["cache_control"]; ok {
t.Fatal("first tool marked")
}
if tools[1].(map[string]any)["cache_control"].(map[string]any)["type"] != "ephemeral" {
t.Fatal("last tool not marked")
}
if !lastBlockHasMarker(t, out["system"]) {
t.Fatalf("system not marked: %#v", out["system"])
}
msgs := out["messages"].([]any)
for i, want := range []bool{false, false, true, false, true} {
got := lastBlockHasMarker(t, msgs[i].(map[string]any)["content"])
if got != want {
t.Fatalf("message %d marked = %v, want %v", i, got, want)
}
}
}
func TestInjectCacheControlRollsForward(t *testing.T) {
out1, _ := injectCacheControl(fiveMessageBody())
_ = out1
b := fiveMessageBody()
msgs := b["messages"].([]any)
b["messages"] = append(msgs,
map[string]any{"role": "assistant", "content": "a5"},
map[string]any{"role": "user", "content": "u6"})
out2, n := injectCacheControl(b)
if n != 4 {
t.Fatalf("added = %d", n)
}
m2 := out2["messages"].([]any)
if !lastBlockHasMarker(t, m2[4].(map[string]any)["content"]) {
t.Fatal("marker 3 not on the former marker-4 message")
}
if !lastBlockHasMarker(t, m2[6].(map[string]any)["content"]) {
t.Fatal("marker 4 not on the new last user message")
}
if lastBlockHasMarker(t, m2[2].(map[string]any)["content"]) {
t.Fatal("old marker 3 still present")
}
}
func TestInjectCacheControlSkipsWhenClientMarked(t *testing.T) {
b := fiveMessageBody()
b["messages"].([]any)[2] = map[string]any{"role": "user", "content": []any{
map[string]any{"type": "text", "text": "u2", "cache_control": map[string]any{"type": "ephemeral"}},
}}
want := cloneJSON(t, b)
out, n := injectCacheControl(b)
if n != 0 {
t.Fatalf("added = %d, want 0", n)
}
if !reflect.DeepEqual(out, want) {
t.Fatal("body changed")
}
}
func TestInjectCacheControlLeavesInputUntouched(t *testing.T) {
b := fiveMessageBody()
want := cloneJSON(t, b)
out, n := injectCacheControl(b)
if n == 0 {
t.Fatal("expected markers")
}
if !reflect.DeepEqual(b, want) {
t.Fatal("input mutated")
}
if reflect.DeepEqual(out, want) {
t.Fatal("output equals input")
}
}
func TestInjectCacheControlNoToolsNoSystem(t *testing.T) {
b := map[string]any{"model": "m", "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
out, n := injectCacheControl(b)
if n != 1 {
t.Fatalf("added = %d, want 1", n)
}
if !lastBlockHasMarker(t, out["messages"].([]any)[0].(map[string]any)["content"]) {
t.Fatal("user message not marked")
}
if _, ok := out["system"]; ok {
t.Fatal("system created")
}
}
func TestPromptCacheConfigValidation(t *testing.T) {
cases := map[string]*ProviderConfig{
"inject-on-openai": {Type: providerTypeOpenAI, BaseURL: "http://x", PromptCache: &PromptCacheConfig{Inject: true}},
"key-on-anthropic": {Type: providerTypeAnthropic, BaseURL: "http://x", APIKey: "k", PromptCache: &PromptCacheConfig{Key: true}},
}
for name, pc := range cases {
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"prov": pc}
_, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw")
if err == nil || !strings.Contains(err.Error(), `"prov"`) {
t.Fatalf("%s: err = %v", name, err)
}
}
}
func TestAnthropicAdapterInjectsOnlyWhenEnabled(t *testing.T) {
run := func(inject bool) string {
var got string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
got = string(b)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"m","type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"model":"claude-test","stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`))
}))
defer srv.Close()
a, err := newAnthropicAdapter("anthropic", srv.URL, "sk-ant")
if err != nil {
t.Fatal(err)
}
a.cacheInject = inject
req := map[string]any{"model": "claude-test", "messages": []any{
map[string]any{"role": "system", "content": "sys"},
map[string]any{"role": "user", "content": "hi"},
}}
if _, err := a.chatCompletion(context.Background(), httptest.NewRecorder(), req); err != nil {
t.Fatal(err)
}
return got
}
on, off := run(true), run(false)
if strings.Contains(off, "cache_control") {
t.Fatalf("disabled body has markers: %s", off)
}
if strings.Count(on, `"cache_control":{"type":"ephemeral"}`) != 2 {
t.Fatalf("enabled body = %s", on)
}
}
func TestMessagesPassthroughInjects(t *testing.T) {
run := func(inject bool) string {
var got string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
got = string(b)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"m","type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"model":"claude-test","stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`))
}))
defer srv.Close()
gw := newMessagesTestGateway(t, srv.URL, "")
if inject {
gw.cfg.Providers["anthropic"].PromptCache = &PromptCacheConfig{Inject: true}
}
body := map[string]any{"model": "claude-test", "max_tokens": 10, "system": "sys", "messages": []any{map[string]any{"role": "user", "content": "hi"}}}
rec := httptest.NewRecorder()
gw.ServeHTTP(rec, newMessagesRequest(t, body, "Authorization", "Bearer sk-alice"))
if rec.Code != http.StatusOK {
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
}
return got
}
on, off := run(true), run(false)
if strings.Contains(off, "cache_control") {
t.Fatalf("disabled body has markers: %s", off)
}
if strings.Count(on, `"cache_control":{"type":"ephemeral"}`) != 2 {
t.Fatalf("enabled body = %s", on)
}
}
+8
View File
@@ -37,6 +37,9 @@ type anthropicAdapter struct {
// defaultRequestTimeout at construction rather than left at its zero
// value the way retry is.
timeout time.Duration
// cacheInject adds cache_control breakpoints to translated requests
// (promptCache.inject). false (the default) leaves the body unchanged.
cacheInject bool
}
// newAnthropicAdapter returns an anthropicAdapter for provider name, with
@@ -129,6 +132,11 @@ func (a *anthropicAdapter) chatCompletion(ctx context.Context, w http.ResponseWr
return usage{}, err
}
if a.cacheInject {
injected, _ := injectCacheControl(body)
body = injected
}
hdr := a.requestHeaders(true)
if streaming {
// Ask the upstream for an SSE response. The Content-Type check
+5
View File
@@ -684,6 +684,10 @@ func buildAdapters(cfg *Config) (map[string]providerAdapter, error) {
return nil, fmt.Errorf("llmgateway: provider %q: modelBaseUrls and pathBaseUrls are supported for type %q only", name, providerTypeOpenAI)
}
if err := validatePromptCache(name, pc.Type, pc.PromptCache); err != nil {
return nil, err
}
switch pc.Type {
case providerTypeOpenAI:
a := newOpenAIAdapter(name, base, apiKey)
@@ -710,6 +714,7 @@ func buildAdapters(cfg *Config) (map[string]providerAdapter, error) {
a.retry = policy
a.timeout = timeout
a.client = newAdapterHTTPClient(timeout)
a.cacheInject = pc.PromptCache != nil && pc.PromptCache.Inject
adapters[name] = a
case providerTypeGemini:
g, err := newGeminiAdapter(name, base, apiKey)
+7 -1
View File
@@ -227,7 +227,13 @@ func (g *Gateway) callAnthropicMessagesPassthrough(ctx context.Context, w http.R
// documented, not incidental.
adapter.injectAuth(&http.Request{Header: hdr})
resp, err := upstreamJSON(ctx, adapter.httpClient(), http.MethodPost, adapter.base()+anthropicMessagesPath, hdr, req, retry, adapter.requestTimeout(), adapter.name())
upstreamBody := req
if g.providerPromptCache(adapter.name()).Inject {
injected, _ := injectCacheControl(req)
upstreamBody = injected
}
resp, err := upstreamJSON(ctx, adapter.httpClient(), http.MethodPost, adapter.base()+anthropicMessagesPath, hdr, upstreamBody, retry, adapter.requestTimeout(), adapter.name())
if err != nil {
return usage{}, err
}