From c1b4041f35ad2e83f084e58f8ebd45957dd59b07 Mon Sep 17 00:00:00 2001 From: feeeei Date: Mon, 30 Nov 2026 11:22:22 +0800 Subject: [PATCH] feat(gateway): enable top-level auto cache_control for chat completions to Anthropic Add top-level CacheControl to apicompat.AnthropicRequest and inject {"type":"ephemeral"} on Chat Completions to Anthropic API-key forwarding paths for Claude models, respecting explicit client cache_control overrides and null/false opt-out. Also count top-level cache_control objects toward Anthropic's 4-breakpoint limit in enforceCacheControlBlockLimit. --- .../apicompat/anthropic_cache_control_test.go | 39 ++++ backend/internal/pkg/apicompat/types.go | 1 + .../service/chat_completions_cache_control.go | 60 ++++++ .../chat_completions_cache_control_test.go | 201 ++++++++++++++++++ .../service/gateway_cache_ttl_order_test.go | 64 ++++++ .../service/gateway_claude_oauth_body.go | 12 +- .../gateway_forward_as_chat_completions.go | 3 + .../gateway_request_json_equivalence_test.go | 37 ++-- ...teway_chat_completions_anthropic_native.go | 2 + 9 files changed, 398 insertions(+), 21 deletions(-) create mode 100644 backend/internal/pkg/apicompat/anthropic_cache_control_test.go create mode 100644 backend/internal/service/chat_completions_cache_control.go create mode 100644 backend/internal/service/chat_completions_cache_control_test.go diff --git a/backend/internal/pkg/apicompat/anthropic_cache_control_test.go b/backend/internal/pkg/apicompat/anthropic_cache_control_test.go new file mode 100644 index 0000000000..66b92d3551 --- /dev/null +++ b/backend/internal/pkg/apicompat/anthropic_cache_control_test.go @@ -0,0 +1,39 @@ +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAnthropicRequest_TopLevelCacheControlJSON(t *testing.T) { + t.Run("omitted when nil", func(t *testing.T) { + req := AnthropicRequest{ + Model: "claude-opus-5-5", + MaxTokens: 1024, + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + } + raw, err := json.Marshal(req) + require.NoError(t, err) + require.NotContains(t, string(raw), `"cache_control"`) + }) + + t.Run("round-trips top-level cache_control", func(t *testing.T) { + req := AnthropicRequest{ + Model: "claude-opus-5-5", + MaxTokens: 1024, + Messages: []AnthropicMessage{{Role: "user", Content: json.RawMessage(`"hi"`)}}, + CacheControl: &AnthropicCacheControl{Type: "ephemeral", TTL: "1h"}, + } + raw, err := json.Marshal(req) + require.NoError(t, err) + require.Contains(t, string(raw), `"cache_control":{"type":"ephemeral","ttl":"1h"}`) + + var decoded AnthropicRequest + require.NoError(t, json.Unmarshal(raw, &decoded)) + require.NotNil(t, decoded.CacheControl) + require.Equal(t, "ephemeral", decoded.CacheControl.Type) + require.Equal(t, "1h", decoded.CacheControl.TTL) + }) +} diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 12c1dee5c4..4b72e9fdd5 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -33,6 +33,7 @@ type AnthropicRequest struct { // user_id,进而导致请求被归类为第三方 app。 Metadata json.RawMessage `json:"metadata,omitempty"` OutputConfig *AnthropicOutputConfig `json:"output_config,omitempty"` + CacheControl *AnthropicCacheControl `json:"cache_control,omitempty"` } // AnthropicOutputConfig controls output generation parameters. diff --git a/backend/internal/service/chat_completions_cache_control.go b/backend/internal/service/chat_completions_cache_control.go new file mode 100644 index 0000000000..47ccb26c2d --- /dev/null +++ b/backend/internal/service/chat_completions_cache_control.go @@ -0,0 +1,60 @@ +package service + +import ( + "encoding/json" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/tidwall/gjson" +) + +// isClaudeAnthropicModel reports whether the resolved upstream model is a +// Claude model that supports Anthropic automatic prompt caching. +func isClaudeAnthropicModel(model string) bool { + return strings.Contains(strings.ToLower(strings.TrimSpace(model)), "claude") +} + +// applyChatCompletionsAnthropicAutoCache configures top-level automatic prompt +// caching on an Anthropic Messages request converted from OpenAI Chat +// Completions for Anthropic API-key upstreams serving Claude models. +// +// OAuth/SetupToken accounts follow the Claude Code mimicry breakpoint pipeline, +// and non-API-key upstreams (such as Vertex or Bedrock) or non-Claude models +// are left untouched. If the incoming Chat Completions payload explicitly sets +// top-level cache_control to null or false, automatic injection is skipped; if +// it supplies an ephemeral cache_control object, that object (including its +// trimmed ttl) is preserved. +func applyChatCompletionsAnthropicAutoCache( + account *Account, + mappedModel string, + chatBody []byte, + anthropicReq *apicompat.AnthropicRequest, +) { + if account == nil || anthropicReq == nil || anthropicReq.CacheControl != nil { + return + } + if account.Type != AccountTypeAPIKey || !isClaudeAnthropicModel(mappedModel) { + return + } + + if rawCC := gjson.GetBytes(chatBody, "cache_control"); rawCC.Exists() { + if rawCC.Type == gjson.Null || rawCC.Type == gjson.False { + return + } + if rawCC.IsObject() { + var cc apicompat.AnthropicCacheControl + if err := json.Unmarshal([]byte(rawCC.Raw), &cc); err == nil { + cc.Type = strings.TrimSpace(cc.Type) + cc.TTL = strings.TrimSpace(cc.TTL) + if cc.Type == "ephemeral" { + anthropicReq.CacheControl = &cc + return + } + } + } + } + + anthropicReq.CacheControl = &apicompat.AnthropicCacheControl{ + Type: "ephemeral", + } +} diff --git a/backend/internal/service/chat_completions_cache_control_test.go b/backend/internal/service/chat_completions_cache_control_test.go new file mode 100644 index 0000000000..864bfc011c --- /dev/null +++ b/backend/internal/service/chat_completions_cache_control_test.go @@ -0,0 +1,201 @@ +//go:build unit + +package service + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestForwardAsChatCompletions_TopLevelAutoCache(t *testing.T) { + t.Run("api key claude model injects top-level ephemeral cache_control", func(t *testing.T) { + body := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"system","content":"be concise"},{"role":"user","content":"hi"}],"stream":true}`) + upstream := chatMetaStreamUpstream() + svc := &GatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := &Account{ + ID: 1, + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + } + + _, err := svc.ForwardAsChatCompletions(context.Background(), chatMetaContext(body), account, body, nil) + require.NoError(t, err) + require.NotEmpty(t, upstream.lastBody) + require.Equal(t, `{"type":"ephemeral"}`, gjson.GetBytes(upstream.lastBody, "cache_control").Raw, string(upstream.lastBody)) + }) + + t.Run("api key preserves explicit client top-level cache_control", func(t *testing.T) { + body := []byte(`{"model":"claude-opus-5-5","cache_control":{"type":"ephemeral","ttl":"1h"},"messages":[{"role":"user","content":"hi"}],"stream":true}`) + upstream := chatMetaStreamUpstream() + svc := &GatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := &Account{ + ID: 1, + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + } + + _, err := svc.ForwardAsChatCompletions(context.Background(), chatMetaContext(body), account, body, nil) + require.NoError(t, err) + require.Equal(t, "ephemeral", gjson.GetBytes(upstream.lastBody, "cache_control.type").String()) + require.Equal(t, "1h", gjson.GetBytes(upstream.lastBody, "cache_control.ttl").String()) + }) + + t.Run("api key respects explicit null or false opt-out", func(t *testing.T) { + for _, optOut := range []string{"null", "false"} { + t.Run(optOut, func(t *testing.T) { + body := []byte(`{"model":"claude-opus-5-5","cache_control":` + optOut + `,"messages":[{"role":"user","content":"hi"}],"stream":true}`) + upstream := chatMetaStreamUpstream() + svc := &GatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := &Account{ + ID: 1, + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + } + + _, err := svc.ForwardAsChatCompletions(context.Background(), chatMetaContext(body), account, body, nil) + require.NoError(t, err) + require.False(t, gjson.GetBytes(upstream.lastBody, "cache_control").Exists(), string(upstream.lastBody)) + }) + } + }) + + t.Run("api key non-claude model skips top-level cache_control", func(t *testing.T) { + body := []byte(`{"model":"deepseek-v4","messages":[{"role":"user","content":"hi"}],"stream":true}`) + upstream := chatMetaStreamUpstream() + svc := &GatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := &Account{ + ID: 1, + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + } + + _, err := svc.ForwardAsChatCompletions(context.Background(), chatMetaContext(body), account, body, nil) + require.NoError(t, err) + require.False(t, gjson.GetBytes(upstream.lastBody, "cache_control").Exists(), string(upstream.lastBody)) + }) + + t.Run("oauth account keeps mimicry path without top-level cache_control", func(t *testing.T) { + body := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}],"stream":true}`) + upstream := chatMetaStreamUpstream() + svc := &GatewayService{ + cfg: rawChatCompletionsTestConfig(), + httpUpstream: upstream, + identityService: NewIdentityService(&stubIdentityCache{fingerprint: &Fingerprint{ + UserAgent: "claude-cli/2.9.0 (external, cli)", ClientID: "test-client", UpdatedAt: time.Now().Unix(), + }}), + } + account := &Account{ + ID: 1, + Platform: PlatformAnthropic, + Type: AccountTypeOAuth, + Credentials: map[string]any{"access_token": "tok"}, + } + + _, err := svc.ForwardAsChatCompletions(context.Background(), chatMetaContext(body), account, body, nil) + require.NoError(t, err) + require.False(t, gjson.GetBytes(upstream.lastBody, "cache_control").Exists(), string(upstream.lastBody)) + }) + + t.Run("setup-token account keeps mimicry path without top-level cache_control", func(t *testing.T) { + body := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}],"stream":true}`) + upstream := chatMetaStreamUpstream() + svc := &GatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + account := &Account{ + ID: 2, + Platform: PlatformAnthropic, + Type: AccountTypeSetupToken, + Credentials: map[string]any{"access_token": "setup-tok"}, + } + + _, err := svc.ForwardAsChatCompletions(context.Background(), chatMetaContext(body), account, body, nil) + require.NoError(t, err) + require.False(t, gjson.GetBytes(upstream.lastBody, "cache_control").Exists(), string(upstream.lastBody)) + }) +} + +func TestApplyChatCompletionsAnthropicAutoCache_AccountAndModelGuard(t *testing.T) { + chatBody := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hi"}]}`) + + t.Run("skips non-api-key account types", func(t *testing.T) { + for _, accountType := range []string{ + AccountTypeOAuth, + AccountTypeSetupToken, + AccountTypeServiceAccount, + AccountTypeBedrock, + } { + req := &apicompat.AnthropicRequest{Model: "claude-opus-5-5"} + applyChatCompletionsAnthropicAutoCache(&Account{Platform: PlatformAnthropic, Type: accountType}, "claude-opus-5-5", chatBody, req) + require.Nil(t, req.CacheControl, "account type %s should not get top-level cache_control", accountType) + } + }) + + t.Run("skips nil inputs and keeps existing cache_control", func(t *testing.T) { + req := &apicompat.AnthropicRequest{Model: "claude-opus-5-5"} + applyChatCompletionsAnthropicAutoCache(nil, "claude-opus-5-5", chatBody, req) + require.Nil(t, req.CacheControl) + + existing := &apicompat.AnthropicCacheControl{Type: "ephemeral", TTL: "1h"} + req.CacheControl = existing + applyChatCompletionsAnthropicAutoCache(&Account{Platform: PlatformAnthropic, Type: AccountTypeAPIKey}, "claude-opus-5-5", chatBody, req) + require.Same(t, existing, req.CacheControl) + }) + + t.Run("matches claude models case-insensitively and ignores other families", func(t *testing.T) { + apiKeyAcc := &Account{Platform: PlatformAnthropic, Type: AccountTypeAPIKey} + for _, model := range []string{"claude-opus-5-5", "CLAUDE-SONNET-4-6", "anthropic/claude-fable-5-2"} { + req := &apicompat.AnthropicRequest{Model: model} + applyChatCompletionsAnthropicAutoCache(apiKeyAcc, model, chatBody, req) + require.Equal(t, &apicompat.AnthropicCacheControl{Type: "ephemeral"}, req.CacheControl, model) + } + for _, model := range []string{"deepseek-v4", "glm-4.7", "kimi-k3", "gpt-5.5"} { + req := &apicompat.AnthropicRequest{Model: model} + applyChatCompletionsAnthropicAutoCache(apiKeyAcc, model, chatBody, req) + require.Nil(t, req.CacheControl, model) + } + }) + + t.Run("trims client cache_control whitespace and falls back on non-ephemeral type", func(t *testing.T) { + apiKeyAcc := &Account{Platform: PlatformAnthropic, Type: AccountTypeAPIKey} + + req := &apicompat.AnthropicRequest{Model: "claude-opus-5-5"} + applyChatCompletionsAnthropicAutoCache(apiKeyAcc, "claude-opus-5-5", + []byte(`{"model":"claude-opus-5-5","cache_control":{"type":" ephemeral ","ttl":" "},"messages":[{"role":"user","content":"hi"}]}`), req) + require.Equal(t, &apicompat.AnthropicCacheControl{Type: "ephemeral"}, req.CacheControl) + + req2 := &apicompat.AnthropicRequest{Model: "claude-opus-5-5"} + applyChatCompletionsAnthropicAutoCache(apiKeyAcc, "claude-opus-5-5", + []byte(`{"model":"claude-opus-5-5","cache_control":{"type":"disabled"},"messages":[{"role":"user","content":"hi"}]}`), req2) + require.Equal(t, &apicompat.AnthropicCacheControl{Type: "ephemeral"}, req2.CacheControl) + }) +} + +func TestForwardChatCompletionsViaNativeAnthropic_TopLevelAutoCache(t *testing.T) { + t.Run("claude model injects top-level ephemeral cache_control", func(t *testing.T) { + body := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"user","content":"hi"}],"stream":true}`) + upstream := chatMetaStreamUpstream() + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + + _, err := svc.forwardChatCompletionsViaNativeAnthropic(context.Background(), chatMetaContext(body), nativeAnthropicTestAccount(), body, "") + require.NoError(t, err) + require.Equal(t, `{"type":"ephemeral"}`, gjson.GetBytes(upstream.lastBody, "cache_control").Raw, string(upstream.lastBody)) + }) + + t.Run("non-claude model skips top-level cache_control", func(t *testing.T) { + body := []byte(`{"model":"glm-4.7","messages":[{"role":"user","content":"hi"}],"stream":true}`) + upstream := chatMetaStreamUpstream() + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + + _, err := svc.forwardChatCompletionsViaNativeAnthropic(context.Background(), chatMetaContext(body), nativeAnthropicTestAccount(), body, "") + require.NoError(t, err) + require.False(t, gjson.GetBytes(upstream.lastBody, "cache_control").Exists(), string(upstream.lastBody)) + }) +} diff --git a/backend/internal/service/gateway_cache_ttl_order_test.go b/backend/internal/service/gateway_cache_ttl_order_test.go index fe319052f5..31872d6940 100644 --- a/backend/internal/service/gateway_cache_ttl_order_test.go +++ b/backend/internal/service/gateway_cache_ttl_order_test.go @@ -25,6 +25,9 @@ func requireCacheTTLOrderAccepted(t *testing.T, body []byte) { paths = append(paths, toolPaths...) paths = append(paths, systemPaths...) paths = append(paths, messagePaths...) + if gjson.GetBytes(body, "cache_control").IsObject() { + paths = append(paths, "cache_control") + } shortTTLPath := "" for _, path := range paths { if gjson.GetBytes(body, path+".ttl").String() == cacheTTLTarget1h { @@ -154,3 +157,64 @@ func TestForwardCountTokens_MimicPathKeepsClient1hBreakpointValid(t *testing.T) "the mimic tools breakpoint should still be present") requireCacheTTLOrderAccepted(t, upstream.lastBody) } + +func TestEnforceCacheControlLimit_CountsTopLevelBreakpoint(t *testing.T) { + t.Run("top-level plus four block breakpoints trims to four total", func(t *testing.T) { + body := []byte(`{"cache_control":{"type":"ephemeral"},` + + `"tools":[{"name":"a","cache_control":{"type":"ephemeral"}}],` + + `"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],` + + `"messages":[{"role":"user","content":[` + + `{"type":"text","text":"one","cache_control":{"type":"ephemeral"}},` + + `{"type":"text","text":"two","cache_control":{"type":"ephemeral"}}]}]}`) + + out := enforceCacheControlLimit(body) + + require.True(t, gjson.GetBytes(out, "cache_control").Exists(), "top-level cache_control must be preserved") + require.False(t, gjson.GetBytes(out, "tools.0.cache_control").Exists(), "tools breakpoint is trimmed first") + _, msgPaths, toolPaths, sysPaths := collectCacheControlPaths(out) + require.Equal(t, maxCacheControlBlocks-1, len(msgPaths)+len(toolPaths)+len(sysPaths)) + }) + + t.Run("top-level plus three block breakpoints stays unchanged", func(t *testing.T) { + body := []byte(`{"cache_control":{"type":"ephemeral"},` + + `"tools":[{"name":"a","cache_control":{"type":"ephemeral"}}],` + + `"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],` + + `"messages":[{"role":"user","content":[{"type":"text","text":"one","cache_control":{"type":"ephemeral"}}]}]}`) + + out := enforceCacheControlLimit(body) + require.Equal(t, string(body), string(out)) + }) + + t.Run("non-object top-level cache_control does not count toward block limit", func(t *testing.T) { + for _, rawTop := range []string{"null", "false", `"bad"`} { + t.Run(rawTop, func(t *testing.T) { + body := []byte(`{"cache_control":` + rawTop + `,` + + `"tools":[{"name":"a","cache_control":{"type":"ephemeral"}}],` + + `"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],` + + `"messages":[{"role":"user","content":[` + + `{"type":"text","text":"one","cache_control":{"type":"ephemeral"}},` + + `{"type":"text","text":"two","cache_control":{"type":"ephemeral"}}]}]}`) + + out := enforceCacheControlLimit(body) + _, msgPaths, toolPaths, sysPaths := collectCacheControlPaths(out) + require.Equal(t, maxCacheControlBlocks, len(msgPaths)+len(toolPaths)+len(sysPaths)) + }) + } + }) + + t.Run("top-level 1h with four block breakpoints trims and raises remaining ttl", func(t *testing.T) { + body := []byte(`{"cache_control":{"type":"ephemeral","ttl":"1h"},` + + `"tools":[{"name":"a","cache_control":{"type":"ephemeral","ttl":"5m"}}],` + + `"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral","ttl":"5m"}}],` + + `"messages":[{"role":"user","content":[` + + `{"type":"text","text":"one","cache_control":{"type":"ephemeral","ttl":"5m"}},` + + `{"type":"text","text":"two","cache_control":{"type":"ephemeral","ttl":"5m"}}]}]}`) + + out := enforceCacheControlLimit(body) + require.False(t, gjson.GetBytes(out, "tools.0.cache_control").Exists()) + require.Equal(t, "1h", gjson.GetBytes(out, "system.0.cache_control.ttl").String()) + require.Equal(t, "1h", gjson.GetBytes(out, "messages.0.content.0.cache_control.ttl").String()) + require.Equal(t, "1h", gjson.GetBytes(out, "messages.0.content.1.cache_control.ttl").String()) + requireCacheTTLOrderAccepted(t, out) + }) +} diff --git a/backend/internal/service/gateway_claude_oauth_body.go b/backend/internal/service/gateway_claude_oauth_body.go index 79da81b6f8..50d94f4436 100644 --- a/backend/internal/service/gateway_claude_oauth_body.go +++ b/backend/internal/service/gateway_claude_oauth_body.go @@ -1102,8 +1102,9 @@ func enforceCacheControlLimit(body []byte) []byte { return normalizeCacheControlTTLOrder(out) } -// enforceCacheControlBlockLimit 强制执行 cache_control 块数量限制(最多 4 个) -// 超限时优先移除工具断点,再移除 messages 断点,最后才移除 system 断点。 +// enforceCacheControlBlockLimit 强制执行 cache_control 块数量限制(最多 4 个)。 +// 顶层 cache_control 对象计入该上限且始终保留;超限时优先移除工具断点, +// 再移除 messages 断点,最后才移除 system 断点。 func enforceCacheControlBlockLimit(body []byte) []byte { if len(body) == 0 { return body @@ -1127,7 +1128,12 @@ func enforceCacheControlBlockLimit(body []byte) []byte { logger.LegacyPrintf("service.gateway", "%s", item.log) } - count := len(messagePaths) + len(toolPaths) + len(systemPaths) + topLevelCount := 0 + if gjson.GetBytes(out, "cache_control").IsObject() { + topLevelCount = 1 + } + + count := len(messagePaths) + len(toolPaths) + len(systemPaths) + topLevelCount if count <= maxCacheControlBlocks { if modified { return out diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index 09b9793f21..99e501c6fa 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -82,6 +82,9 @@ func (s *GatewayService) ForwardAsChatCompletions( anthropicReq.Stream = true reqStream := true + // 4. Enable top-level automatic prompt caching for Claude API-key upstreams + applyChatCompletionsAnthropicAutoCache(account, mappedModel, body, anthropicReq) + logger.L().Debug("gateway forward_as_chat_completions: model mapping applied", zap.Int64("account_id", account.ID), zap.String("original_model", originalModel), diff --git a/backend/internal/service/gateway_request_json_equivalence_test.go b/backend/internal/service/gateway_request_json_equivalence_test.go index e8fc31be32..182e241db1 100644 --- a/backend/internal/service/gateway_request_json_equivalence_test.go +++ b/backend/internal/service/gateway_request_json_equivalence_test.go @@ -51,24 +51,25 @@ func legacyNormalizeCacheControlTTLOrder(body []byte) []byte { func cacheControlEquivalenceCases() map[string]string { return map[string]string{ - "empty": ``, - "no_cc": `{"model":"claude","messages":[{"role":"user","content":"hi"}]}`, - "one_cc": `{"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"hi"}]}`, - "four_cc": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"}},{"type":"text","text":"b","cache_control":{"type":"ephemeral"}}]}]}`, - "five_cc": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral"}},{"name":"b","cache_control":{"type":"ephemeral"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"}},{"type":"text","text":"b","cache_control":{"type":"ephemeral"}}]}]}`, - "thinking_cc": `{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"x","cache_control":{"type":"ephemeral"}}]}]}`, - "thinking_text": `{"messages":[{"role":"user","content":[{"type":"text","text":"thinking about it","cache_control":{"type":"ephemeral"}}]}]}`, - "ttl_order": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral","ttl":"5m"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, - "ttl_all_1h": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, - "top_level_1h": `{"cache_control":{"type":"ephemeral","ttl":"1h"},"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"hi"}]}`, - "1h_in_text": `{"system":[{"type":"text","text":"\"1h\"","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"1h"}]}`, - "escaped_key": `{"messages":[{"role":"user","content":[{"type":"text","text":"a","cache\u005fcontrol":{"type":"ephemeral","ttl":"1h"}}]}],"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}]}`, - "escaped_ttl": `{"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"\u0031h"}}]}]}`, - "escaped_think": `{"messages":[{"role":"assistant","content":[{"type":"\u0074hinking","thinking":"x","cache_control":{"type":"ephemeral"}}]}]}`, - "non_ephemeral": `{"tools":[{"name":"a","cache_control":{"type":"persistent"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, - "cc_in_string": `{"messages":[{"role":"user","content":"please explain \"cache_control\" and \"thinking\""}]}`, - "duplicate_key": `{"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"},"cache_control":{"type":"ephemeral","ttl":"1h"}}]}],"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}]}`, - "invalid_json": `{"messages":[`, + "empty": ``, + "no_cc": `{"model":"claude","messages":[{"role":"user","content":"hi"}]}`, + "one_cc": `{"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"hi"}]}`, + "four_cc": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"}},{"type":"text","text":"b","cache_control":{"type":"ephemeral"}}]}]}`, + "five_cc": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral"}},{"name":"b","cache_control":{"type":"ephemeral"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"}},{"type":"text","text":"b","cache_control":{"type":"ephemeral"}}]}]}`, + "thinking_cc": `{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"x","cache_control":{"type":"ephemeral"}}]}]}`, + "thinking_text": `{"messages":[{"role":"user","content":[{"type":"text","text":"thinking about it","cache_control":{"type":"ephemeral"}}]}]}`, + "ttl_order": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral","ttl":"5m"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, + "ttl_all_1h": `{"tools":[{"name":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, + "top_level_1h": `{"cache_control":{"type":"ephemeral","ttl":"1h"},"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"hi"}]}`, + "top_level_five_cc": `{"cache_control":{"type":"ephemeral"},"tools":[{"name":"a","cache_control":{"type":"ephemeral"}}],"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"}},{"type":"text","text":"b","cache_control":{"type":"ephemeral"}}]}]}`, + "1h_in_text": `{"system":[{"type":"text","text":"\"1h\"","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"1h"}]}`, + "escaped_key": `{"messages":[{"role":"user","content":[{"type":"text","text":"a","cache\u005fcontrol":{"type":"ephemeral","ttl":"1h"}}]}],"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}]}`, + "escaped_ttl": `{"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"\u0031h"}}]}]}`, + "escaped_think": `{"messages":[{"role":"assistant","content":[{"type":"\u0074hinking","thinking":"x","cache_control":{"type":"ephemeral"}}]}]}`, + "non_ephemeral": `{"tools":[{"name":"a","cache_control":{"type":"persistent"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, + "cc_in_string": `{"messages":[{"role":"user","content":"please explain \"cache_control\" and \"thinking\""}]}`, + "duplicate_key": `{"messages":[{"role":"user","content":[{"type":"text","text":"a","cache_control":{"type":"ephemeral"},"cache_control":{"type":"ephemeral","ttl":"1h"}}]}],"tools":[{"name":"t","cache_control":{"type":"ephemeral"}}]}`, + "invalid_json": `{"messages":[`, } } diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index 116c991625..31f3021668 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -82,6 +82,8 @@ func (s *OpenAIGatewayService) forwardChatCompletionsViaNativeAnthropic( anthropicReq.Stream = true reqStream := true + applyChatCompletionsAnthropicAutoCache(account, upstreamModel, body, anthropicReq) + logger.L().Debug("openai chat_completions: forwarding via native anthropic endpoint", zap.Int64("account_id", account.ID), zap.String("original_model", originalModel),