From cff1761a212b6e446696d1435a43e2fffe4b73ef Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Thu, 26 Nov 2026 01:33:56 +0000 Subject: [PATCH] feat(openai): opt-in per-conversation prompt_cache_key When promptCache.key is set on an openai provider, the gateway sends a hashed prompt_cache_key per conversation. The key is the SHA-256 of the caller id and the session id. The session id is the client id, or the system prompt plus the first user message. The key is set only when the client sent no prompt_cache_key. It is set on each attempt copy after the response-cache key is computed. It is not stored, and it never carries a raw id. --- prompt_cache.go | 77 ++++++++++++++++- prompt_cache_key_test.go | 177 +++++++++++++++++++++++++++++++++++++++ routes_messages.go | 4 + routes_unified.go | 7 ++ 4 files changed, 264 insertions(+), 1 deletion(-) create mode 100644 prompt_cache_key_test.go diff --git a/prompt_cache.go b/prompt_cache.go index f964037..6afa3ea 100644 --- a/prompt_cache.go +++ b/prompt_cache.go @@ -1,6 +1,11 @@ package traefikllmgateway -import "fmt" +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "net/http" +) // PromptCacheConfig holds a provider's opt-in prompt-caching body changes. type PromptCacheConfig struct { @@ -175,3 +180,73 @@ func injectCacheControl(req map[string]any) (map[string]any, int) { } return out, added } + +const ( + promptCacheKeyField = "prompt_cache_key" + promptCacheKeyTag = "pck\x00" + promptCacheKeyBytes = 16 + promptCacheSep = "\x1f" +) + +// promptCacheSystemText returns the system prompt of an OpenAI or Anthropic body. +func promptCacheSystemText(req map[string]any) string { + if text, _, _ := smartContentText(req["system"]); text != "" { + return text + } + msgs, _ := req["messages"].([]any) + for i := 0; i < len(msgs); i++ { + msg, ok := msgs[i].(map[string]any) + if !ok { + continue + } + role, _ := msg["role"].(string) + if role != "system" && role != "developer" { + continue + } + if text, _, _ := smartContentText(msg["content"]); text != "" { + return text + } + } + return "" +} + +// promptCacheSessionID names one conversation: the client's own id, else its +// system prompt plus first user message, both stable across turns. +func promptCacheSessionID(req map[string]any, hdr http.Header) string { + if id := smartSessionClientID(req, hdr, ""); id != "" { + return id + } + return smartCut(promptCacheSystemText(req), sessionDerivedSys) + promptCacheSep + smartCut(smartFirstUserText(req), sessionDerivedUser) +} + +// hashPromptCacheKey hashes caller and session so the upstream never sees a raw id. +func hashPromptCacheKey(callerID, sessionID string) string { + sum := sha256.Sum256([]byte(promptCacheKeyTag + callerID + "\x00" + sessionID)) + return hex.EncodeToString(sum[:promptCacheKeyBytes]) +} + +// promptCacheKeyForRequest returns the key to send, or "" when the client chose +// its own prompt_cache_key (even an empty one) or no candidate provider opted in. +func (g *Gateway) promptCacheKeyForRequest(req map[string]any, hdr http.Header, scopes []limitScope, candidates []resolveCandidate) string { + if _, has := req[promptCacheKeyField]; has { + return "" + } + wanted := false + for i := 0; i < len(candidates); i++ { + if g.providerPromptCache(candidates[i].providerName).Key { + wanted = true + break + } + } + if !wanted { + return "" + } + return hashPromptCacheKey(smartCallerID(scopes, hdr), promptCacheSessionID(req, hdr)) +} + +// 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 + } +} diff --git a/prompt_cache_key_test.go b/prompt_cache_key_test.go new file mode 100644 index 0000000..f53e977 --- /dev/null +++ b/prompt_cache_key_test.go @@ -0,0 +1,177 @@ +package traefikllmgateway + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var pckPattern = regexp.MustCompile(`^[0-9a-f]{32}$`) + +func pckBody(system, first string, extra ...any) map[string]any { + msgs := []any{ + map[string]any{"role": "system", "content": system}, + map[string]any{"role": "user", "content": first}, + } + msgs = append(msgs, extra...) + return map[string]any{"model": "shared", "messages": msgs} +} + +func pckKey(t *testing.T, body map[string]any, callerScope string) string { + t.Helper() + return hashPromptCacheKey(smartCallerID([]limitScope{{kind: "user", id: callerScope}}, nil), promptCacheSessionID(body, nil)) +} + +func TestPromptCacheKeyStableAcrossTurns(t *testing.T) { + t.Parallel() + short := pckBody("be terse", "hello") + long := pckBody("be terse", "hello", + map[string]any{"role": "assistant", "content": "hi"}, + map[string]any{"role": "user", "content": "more"}) + assert.Equal(t, pckKey(t, short, "alice"), pckKey(t, long, "alice")) + assert.NotEqual(t, pckKey(t, short, "alice"), pckKey(t, pckBody("be terse", "other"), "alice")) +} + +func TestPromptCacheKeyDiffersByCaller(t *testing.T) { + t.Parallel() + b := pckBody("s", "u") + assert.NotEqual(t, pckKey(t, b, "alice"), pckKey(t, b, "bob")) +} + +func TestPromptCacheKeyNoRawID(t *testing.T) { + t.Parallel() + b := pckBody("s", "u") + b["metadata"] = map[string]any{"user_id": "alice@example.com"} + k := pckKey(t, b, "alice") + assert.Regexp(t, pckPattern, k) + assert.NotContains(t, k, "alice") +} + +type pckServers struct { + bodies map[string][]string + mu sync.Mutex +} + +func (p *pckServers) handler(name string, status int, resp string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + p.mu.Lock() + p.bodies[name] = append(p.bodies[name], string(b)) + p.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write([]byte(resp)) + } +} + +func (p *pckServers) last(name string) string { + p.mu.Lock() + defer p.mu.Unlock() + b := p.bodies[name] + if len(b) == 0 { + return "" + } + return b[len(b)-1] +} + +func newPckGateway(t *testing.T, key bool, alphaStatus int) (*Gateway, *pckServers) { + t.Helper() + ps := &pckServers{bodies: map[string][]string{}} + alpha := httptest.NewServer(ps.handler("alpha", alphaStatus, successRespBody)) + t.Cleanup(alpha.Close) + beta := httptest.NewServer(ps.handler("beta", http.StatusOK, successRespBody)) + t.Cleanup(beta.Close) + cfg := twoProviderFailoverConfig(alpha, beta) + if key { + cfg.Providers["alpha"].PromptCache = &PromptCacheConfig{Key: true} + cfg.Providers["beta"].PromptCache = &PromptCacheConfig{Key: true} + } + h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw") + require.NoError(t, err) + gw, ok := h.(*Gateway) + require.True(t, ok) + return gw, ps +} + +func servePck(t *testing.T, gw *Gateway, body map[string]any) *httptest.ResponseRecorder { + t.Helper() + rec := httptest.NewRecorder() + gw.ServeHTTP(rec, newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body)) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + return rec +} + +func TestPromptCacheKeyRespectsClient(t *testing.T) { + gw, ps := newPckGateway(t, true, http.StatusOK) + body := pckBody("s", "u") + body["prompt_cache_key"] = "" + servePck(t, gw, body) + got := ps.last("alpha") + ps.last("beta") + assert.Contains(t, got, `"prompt_cache_key":""`) +} + +func TestPromptCacheKeyNotInPristine(t *testing.T) { + gw, ps := newPckGateway(t, true, http.StatusInternalServerError) + body := pckBody("s", "u") + servePck(t, gw, body) + a, b := ps.last("alpha"), ps.last("beta") + require.NotEmpty(t, a) + require.NotEmpty(t, b) + re := regexp.MustCompile(`"prompt_cache_key":"([0-9a-f]{32})"`) + ma, mb := re.FindStringSubmatch(a), re.FindStringSubmatch(b) + require.Len(t, ma, 2) + require.Len(t, mb, 2) + assert.Equal(t, ma[1], mb[1], "same key on both attempts") + assert.Equal(t, 1, strings.Count(b, "prompt_cache_key"), "key set once on the failover attempt") + +} + +func TestPromptCacheKeyLeavesResponseCacheKey(t *testing.T) { + gw, _ := newPckGateway(t, true, http.StatusInternalServerError) + redisLn := newBehavioralRedisServer(t) + gw.cfg.Redis = &RedisConfig{Address: redisLn.Addr().String()} + gw.cfg.Cache = CacheConfig{Enabled: true, TTL: "1m"} + cfg := *gw.cfg + h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), &cfg, "llmgw") + require.NoError(t, err) + g2, ok := h.(*Gateway) + require.True(t, ok) + require.NotNil(t, g2.cache) + + body := pckBody("s", "u") + servePck(t, g2, body) + k := cacheKey("beta", "shared", "shared", cacheEndpointChat, map[string]any{"model": "shared", "messages": body["messages"]}) + _, hit := g2.cache.lookup(k) + assert.True(t, hit, "response-cache key must not include prompt_cache_key") +} + +func TestPromptCacheKeyOffByDefault(t *testing.T) { + gw, ps := newPckGateway(t, false, http.StatusOK) + servePck(t, gw, pckBody("s", "u")) + assert.NotContains(t, ps.last("alpha")+ps.last("beta"), "prompt_cache_key") +} + +func TestTranslatedMessagesGetsKey(t *testing.T) { + 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) + gw.cfg.Providers["openai"].PromptCache = &PromptCacheConfig{Key: true} + + body := map[string]any{ + "model": "gpt-test", "max_tokens": 10, "system": "be terse", + "messages": []any{map[string]any{"role": "user", "content": "hello"}}, + } + rec := httptest.NewRecorder() + gw.ServeHTTP(rec, newMessagesRequest(t, body, "x-api-key", "sk-alice")) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + assert.Regexp(t, `"prompt_cache_key":"[0-9a-f]{32}"`, ps.last("openai")) +} diff --git a/routes_messages.go b/routes_messages.go index b7b8ae3..04249a2 100644 --- a/routes_messages.go +++ b/routes_messages.go @@ -411,6 +411,10 @@ 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 + } + rec := newMessagesResponseRecorder() result, err := adapter.chatCompletion(ctx, rec, openaiReq) if err != nil { diff --git a/routes_unified.go b/routes_unified.go index 55c9b9e..c63ee95 100644 --- a/routes_unified.go +++ b/routes_unified.go @@ -348,6 +348,12 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop pristineReq[k] = v } + // Computed from the client body before any attempt sets the key. + pck := "" + if endpoint == cacheEndpointChat || endpoint == cacheEndpointMessages { + pck = g.promptCacheKeyForRequest(pristineReq, r.Header, scopes, candidates) + } + // preFailoverHeaders snapshots sw.Header() ONCE, before the loop below // ever runs (finding 7 fix, review-routes.md): every header present // here was staged by something OTHER than this loop — an earlier, @@ -469,6 +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) attemptReq[gatewayAliasKey] = requestedModel if plan != nil { setRouterHeaders(sw.Header(), plan, i)