diff --git a/admin_config_guard_test.go b/admin_config_guard_test.go index fb8472f..06a69a9 100644 --- a/admin_config_guard_test.go +++ b/admin_config_guard_test.go @@ -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, diff --git a/llmgateway.go b/llmgateway.go index 080b890..e690344 100644 --- a/llmgateway.go +++ b/llmgateway.go @@ -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, diff --git a/prompt_cache.go b/prompt_cache.go new file mode 100644 index 0000000..f964037 --- /dev/null +++ b/prompt_cache.go @@ -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 +} diff --git a/prompt_cache_test.go b/prompt_cache_test.go new file mode 100644 index 0000000..83ba933 --- /dev/null +++ b/prompt_cache_test.go @@ -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) + } +} diff --git a/provider_anthropic.go b/provider_anthropic.go index 03c675b..660d180 100644 --- a/provider_anthropic.go +++ b/provider_anthropic.go @@ -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 diff --git a/providers.go b/providers.go index f6e132d..1d1cd28 100644 --- a/providers.go +++ b/providers.go @@ -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) diff --git a/routes_messages.go b/routes_messages.go index 13e43ac..b7b8ae3 100644 --- a/routes_messages.go +++ b/routes_messages.go @@ -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 }