From 2fe798ad82738c5a46667e1c0bcb34ab6e6e5a44 Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Thu, 26 Nov 2026 01:37:52 +0000 Subject: [PATCH] fix(openai): forward prompt_cache_key on translated messages only when enabled The translated messages path copied any prompt_cache_key into the upstream body, even with promptCache.key off. It now forwards the key only when the provider opted in. The gateway key travels in a private field, and a client key wins when present. --- prompt_cache.go | 35 +++++++++++++++++++++++++++++------ prompt_cache_key_test.go | 36 ++++++++++++++++++++++++++++++++++++ routes_messages.go | 4 +--- routes_unified.go | 2 +- 4 files changed, 67 insertions(+), 10 deletions(-) diff --git a/prompt_cache.go b/prompt_cache.go index 6afa3ea..23b998e 100644 --- a/prompt_cache.go +++ b/prompt_cache.go @@ -183,9 +183,12 @@ func injectCacheControl(req map[string]any) (map[string]any, int) { const ( promptCacheKeyField = "prompt_cache_key" - promptCacheKeyTag = "pck\x00" - promptCacheKeyBytes = 16 - promptCacheSep = "\x1f" + // gatewayPromptCacheKey carries the gateway-computed key on an Anthropic-format + // body, where translation would drop prompt_cache_key itself. + gatewayPromptCacheKey = "_llmgw_prompt_cache_key" + promptCacheKeyTag = "pck\x00" + promptCacheKeyBytes = 16 + promptCacheSep = "\x1f" ) // promptCacheSystemText returns the system prompt of an OpenAI or Anthropic body. @@ -245,8 +248,28 @@ func (g *Gateway) promptCacheKeyForRequest(req map[string]any, hdr http.Header, } // applyPromptCacheKey sets key on attemptReq when the candidate's provider opted in. -func (g *Gateway) applyPromptCacheKey(attemptReq map[string]any, providerName, key string) { - if key != "" && g.providerPromptCache(providerName).Key { - attemptReq[promptCacheKeyField] = key +func (g *Gateway) applyPromptCacheKey(attemptReq map[string]any, endpoint, providerName, key string) { + if key == "" || !g.providerPromptCache(providerName).Key { + return + } + if endpoint == cacheEndpointMessages { + attemptReq[gatewayPromptCacheKey] = key + return + } + attemptReq[promptCacheKeyField] = key +} + +// applyTranslatedPromptCacheKey sets the upstream key on a translated request for an +// opted-in provider. A client key wins over the gateway one; otherwise nothing is added. +func (g *Gateway) applyTranslatedPromptCacheKey(openaiReq, req map[string]any, providerName string) { + if !g.providerPromptCache(providerName).Key { + return + } + if client, ok := req[promptCacheKeyField]; ok { + openaiReq[promptCacheKeyField] = client + return + } + if key, ok := req[gatewayPromptCacheKey].(string); ok && key != "" { + openaiReq[promptCacheKeyField] = key } } diff --git a/prompt_cache_key_test.go b/prompt_cache_key_test.go index f53e977..da8a845 100644 --- a/prompt_cache_key_test.go +++ b/prompt_cache_key_test.go @@ -175,3 +175,39 @@ func TestTranslatedMessagesGetsKey(t *testing.T) { require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) assert.Regexp(t, `"prompt_cache_key":"[0-9a-f]{32}"`, ps.last("openai")) } + +func TestPromptCacheKeyMixedChainOnlyOptedIn(t *testing.T) { + gw, ps := newPckGateway(t, false, http.StatusInternalServerError) + gw.cfg.Providers["alpha"].PromptCache = &PromptCacheConfig{Key: true} + servePck(t, gw, pckBody("s", "u")) + assert.Contains(t, ps.last("alpha"), "prompt_cache_key") + assert.NotContains(t, ps.last("beta"), "prompt_cache_key") +} + +func messagesPckUpstream(t *testing.T, key bool, body map[string]any) string { + t.Helper() + ps := &pckServers{bodies: map[string][]string{}} + srv := httptest.NewServer(ps.handler("openai", http.StatusOK, `{"id":"c","object":"chat.completion","model":"gpt-real","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":8,"completion_tokens":4}}`)) + defer srv.Close() + gw := newMessagesTestGateway(t, "", srv.URL) + if key { + gw.cfg.Providers["openai"].PromptCache = &PromptCacheConfig{Key: true} + } + rec := httptest.NewRecorder() + gw.ServeHTTP(rec, newMessagesRequest(t, body, "x-api-key", "sk-alice")) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + return ps.last("openai") +} + +func TestTranslatedMessagesClientKeyOptionOff(t *testing.T) { + mk := func(withKey bool) map[string]any { + b := map[string]any{"model": "gpt-test", "max_tokens": 10, "messages": []any{map[string]any{"role": "user", "content": "hello"}}} + if withKey { + b["prompt_cache_key"] = "client-key" + } + return b + } + assert.Equal(t, messagesPckUpstream(t, false, mk(false)), messagesPckUpstream(t, false, mk(true))) + assert.NotContains(t, messagesPckUpstream(t, false, mk(true)), "prompt_cache_key") + assert.Contains(t, messagesPckUpstream(t, true, mk(true)), `"prompt_cache_key":"client-key"`) +} diff --git a/routes_messages.go b/routes_messages.go index 04249a2..0a632e2 100644 --- a/routes_messages.go +++ b/routes_messages.go @@ -411,9 +411,7 @@ func (g *Gateway) callTranslatedMessages(ctx context.Context, w http.ResponseWri g.warnf("messages route: request field %q has no OpenAI equivalent for provider %q and was dropped in translation", field, adapter.name()) } - if key, ok := req[promptCacheKeyField].(string); ok && key != "" { - openaiReq[promptCacheKeyField] = key - } + g.applyTranslatedPromptCacheKey(openaiReq, req, adapter.name()) rec := newMessagesResponseRecorder() result, err := adapter.chatCompletion(ctx, rec, openaiReq) diff --git a/routes_unified.go b/routes_unified.go index c63ee95..69917f9 100644 --- a/routes_unified.go +++ b/routes_unified.go @@ -475,7 +475,7 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop if cacheable { cacheKeyStr = cacheKey(cand.providerName, cand.upstreamModel, requestedModel, endpoint, attemptReq) } - g.applyPromptCacheKey(attemptReq, cand.providerName, pck) + g.applyPromptCacheKey(attemptReq, endpoint, cand.providerName, pck) attemptReq[gatewayAliasKey] = requestedModel if plan != nil { setRouterHeaders(sw.Header(), plan, i)