diff --git a/README.md b/README.md index b4f2995..2bf786d 100644 --- a/README.md +++ b/README.md @@ -545,6 +545,7 @@ byte-identically to before multi-group support existed. | `ttl` | `string` (Go duration) | `5m` | How long a cached response stays valid. A malformed duration string is a construction error. Zero or negative is accepted, not refused โ€” construction logs one warning, since the store floors it to a 1-second TTL rather than actually disabling the cache; set `enabled: false` to turn caching off. | | `maxBodyBytes` | `int` | `1048576` (1MiB) | Largest response body still eligible for caching; a larger one is skipped (never stored, never an error). Maximum accepted value is `8388608` (8MiB) โ€” above that is a construction error. | | `accountHits` | `bool` | `false` | When `true`, a cache hit adds the usage stored with the cached response to the requesting user's and group's token and cost counters, so budgets also bind repeated identical prompts. `false` counts a hit as a request only. | +| `cacheEmbeddings` | `bool` | `false` | When `true`, `/v1/embeddings` responses are cached too. `false`: embeddings always go upstream and are never stored, because vector bodies are large and rarely repeat. Chat caching is unaffected. | ### `BreakerConfig` @@ -1438,7 +1439,8 @@ disabled with one warning logged at construction, never a per-replica in-process fallback: divergent replicas would otherwise serve different cached bodies for the same request. -- **What's cacheable**: a non-streaming request to either route, whose +- **What's cacheable**: a non-streaming chat request, or a non-streaming + embeddings request when `cache.cacheEmbeddings` is `true`, whose upstream response was HTTP 200 and no larger than `cache.maxBodyBytes`. Never cached: a streaming request, native passthrough, MCP/A2A, the image/audio endpoints (see [Image and audio endpoints](#image-and-audio-endpoints)), diff --git a/cache.go b/cache.go index 8100d84..437535f 100644 --- a/cache.go +++ b/cache.go @@ -115,7 +115,9 @@ func buildResponseCache(cc CacheConfig, client *respClient, logf, warnf, errorf logf("cache: enabled but redis is not configured; response caching disabled") return nil, nil } - return newResponseCache(client, ttl, maxBody, logf, errorf), nil + c := newResponseCache(client, ttl, maxBody, logf, errorf) + c.embeddings = cc.CacheEmbeddings + return c, nil } // groupCacheEnabled resolves whether grp's requests are cacheable, given @@ -229,6 +231,7 @@ type responseCache struct { lastFailure time.Time ttl time.Duration maxBodyBytes int + embeddings bool // CacheConfig.CacheEmbeddings logMu sync.Mutex } diff --git a/llmgateway.go b/llmgateway.go index c34e0cf..125adc6 100644 --- a/llmgateway.go +++ b/llmgateway.go @@ -473,6 +473,10 @@ type CacheConfig struct { // budgets also bind repeated identical prompts. Defaults to false: a // hit then adds only to the request counters. AccountHits bool `json:"accountHits,omitempty"` + // CacheEmbeddings opts /v1/embeddings responses into the cache. Off by + // default: a vector body is large and rarely repeats, so it fills the + // shared Redis for little benefit. + CacheEmbeddings bool `json:"cacheEmbeddings,omitempty"` } // BreakerConfig configures the per-provider discovery circuit breaker diff --git a/routes_unified.go b/routes_unified.go index 093dbe4..7b145a2 100644 --- a/routes_unified.go +++ b/routes_unified.go @@ -314,7 +314,8 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop // depends only on req["stream"]/grp, neither of which a failover // attempt changes. streaming, _ := req["stream"].(bool) - cacheable := !streaming && g.cache != nil && groupCacheEnabled(grp) + cacheable := !streaming && g.cache != nil && groupCacheEnabled(grp) && + (endpoint != cacheEndpointEmbeddings || g.cache.embeddings) // pristineReq is the client's own decoded request, snapshotted ONCE, // BEFORE any candidate's adapter ever touches it, with "model" diff --git a/routes_unified_test.go b/routes_unified_test.go index 3b5b6af..3a311ff 100644 --- a/routes_unified_test.go +++ b/routes_unified_test.go @@ -1569,6 +1569,87 @@ func TestHandleChat_CacheHitMiss_EndToEnd_CountersAndHeaders(t *testing.T) { } } +// postEmbeddingsTwice sends the same /v1/embeddings request twice through gw +// and returns both X-Llmgw-Cache headers. +func postEmbeddingsTwice(t *testing.T, gw *Gateway) (first, second string) { + t.Helper() + body := map[string]any{"model": "gpt-test", "input": "hello"} + var got [2]string + for i := range got { + rec := httptest.NewRecorder() + gw.ServeHTTP(rec, newUnifiedRequest(t, http.MethodPost, "/v1/embeddings", "sk-alice", body)) + if rec.Code != http.StatusOK { + t.Fatalf("request %d: status = %d, body=%s", i+1, rec.Code, rec.Body.String()) + } + got[i] = rec.Header().Get("X-Llmgw-Cache") + } + return got[0], got[1] +} + +// TestHandleEmbeddings_CacheOffByDefault_NeverCached pins that a gateway with +// the cache enabled still sends every embeddings request upstream, while chat +// keeps its cache. +func TestHandleEmbeddings_CacheOffByDefault_NeverCached(t *testing.T) { + const respBody = `{"object":"list","data":[{"embedding":[0.1,0.2]}],"model":"gpt-test","usage":{"prompt_tokens":5,"total_tokens":5}}` + var upstreamCalls int + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls++ + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(respBody)) + })) + defer srv.Close() + + gw := newCacheTestGateway(t, srv, nil, defaultCacheMaxBodyBytes) + first, second := postEmbeddingsTwice(t, gw) + + if first != "" || second != "" { + t.Errorf("X-Llmgw-Cache = %q then %q, want no header on both (embeddings not cached)", first, second) + } + if upstreamCalls != 2 { + t.Errorf("upstreamCalls = %d, want 2 (every embeddings request goes upstream)", upstreamCalls) + } +} + +// TestHandleEmbeddings_CacheEmbeddingsEnabled_HitsOnSecondRequest covers the +// opt-in: with CacheEmbeddings set the second identical request is a hit. +func TestHandleEmbeddings_CacheEmbeddingsEnabled_HitsOnSecondRequest(t *testing.T) { + const respBody = `{"object":"list","data":[{"embedding":[0.1,0.2]}],"model":"gpt-test","usage":{"prompt_tokens":5,"total_tokens":5}}` + var upstreamCalls int + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls++ + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(respBody)) + })) + defer srv.Close() + + gw := newCacheTestGateway(t, srv, nil, defaultCacheMaxBodyBytes) + gw.cache.embeddings = true + first, second := postEmbeddingsTwice(t, gw) + + if first != "miss" || second != "hit" { + t.Errorf("X-Llmgw-Cache = %q then %q, want miss then hit", first, second) + } + if upstreamCalls != 1 { + t.Errorf("upstreamCalls = %d, want 1 (second request served from cache)", upstreamCalls) + } +} + +// TestBuildResponseCache_CacheEmbeddingsFlag_Propagates checks the config +// field reaches the cache. +func TestBuildResponseCache_CacheEmbeddingsFlag_Propagates(t *testing.T) { + noop := func(string, ...any) {} + client := &respClient{} + for _, want := range []bool{false, true} { + c, err := buildResponseCache(CacheConfig{Enabled: true, CacheEmbeddings: want}, client, noop, noop, noop) + if err != nil || c == nil { + t.Fatalf("buildResponseCache(CacheEmbeddings=%v) = %v, %v", want, c, err) + } + if c.embeddings != want { + t.Errorf("CacheEmbeddings=%v: cache.embeddings = %v", want, c.embeddings) + } + } +} + // TestHandleChat_CacheGroupOptOut_NeverServesFromCache is spec ยง2's // per-group override: GroupConfig.Cache=false must opt the group out even // though the global cache is enabled โ€” every request goes to the