feat: add ai-cache plugin
Description
Adds a new ai-cache plugin that caches LLM responses and replays them for subsequent requests that resolve to the same prompt, cutting upstream token cost and latency for repetitive workloads (FAQ bots, document Q&A, translation).
This PR implements the exact (L1) cache layer:
- Cache key — a SHA-256 fingerprint of the request as received: client protocol, requested model, normalized messages, and the remaining response-determining body parameters (
temperature,top_p,max_tokens,tools, …). Provider-agnostic viaai-protocols, so it works for every chat protocolai-proxysupports (OpenAI Chat, Anthropic Messages, Bedrock Converse, OpenAI Responses). The key also segments by the selected AI instance — theai-proxyprovider, or theai-proxy-multiinstance picked for the request (recomputed if aretry_on_errorfallback answers) — so identical prompts that resolve to instances backed by different models or providers never share an entry. - Storage — Redis (single-node); connection fields are sourced from
apisix.utils.redis-schemavia thepolicy+if/thenconvention used bylimit-count/limit-req/limit-conn. - Scope — per-route by default (
cache_key.share_across_routesto share one cache space across routes); opt-in per-consumer / per-variable isolation (cache_key.include_consumer/include_vars). - Behavior — write-on-200 only (non-streaming);
bypass_onopt-out (exact request-header match);fail_mode(skip/warn/error) when a request did not pass throughai-proxy/ai-proxy-multi;max_cache_body_sizecap;X-AI-Cache-Status/X-AI-Cache-Ageresponse headers; fails open (proxies as a normal miss) when Redis is unreachable. - Runs below
ai-proxy(priority1035) and depends onai-proxy/ai-proxy-multi.
Semantic cache, streaming support, and observability are planned as follow-up PRs. User-facing documentation will be added in a later PR once the series is further along.
Which issue(s) this PR fixes:
Related to #13290
Checklist
- [x] I have explained the need for this PR and the problem it solves
- [x] I have explained the changes or the new features added to this PR
- [x] I have added tests corresponding to this change
- [x] I have updated the documentation to reflect this change
- [x] I have verified that this change is backward compatible
I found two merge-blocking issues in the current ai-cache implementation:
[P1] Cache key does not include the effective model or picked AI instance
ai-cache computes the fingerprint from ctx.var.request_llm_model or body.model, but it does not include ctx.picked_ai_instance_name, provider, or the route / instance effective options.model:
apisix/plugins/ai-cache/key.lua: the fingerprint uses only protocol, requested model, normalized messages, and remaining body params.apisix/plugins/ai-cache.lua: the lookup happens inaccess, before the upstream request is built.ai-proxy-multihas already selectedctx.picked_ai_instancebefore lower-priority plugins run, so that selected instance is available at cache lookup time.
This can return the wrong provider/model response on an ai-proxy-multi route. A request can warm the cache through instance A, then a later identical request can be routed to instance B but still hit and replay instance A's response because both requests share the same cache key.
This should be fixed before merge by including the selected AI instance and/or effective model/provider in the cache key or scope, with a regression test covering ai-proxy-multi instances that use different models or providers.
[P2] The plugin can cache ordinary JSON traffic when it is not behind ai-proxy
The docs say ai-cache must be used with ai-proxy or ai-proxy-multi, but the implementation does not enforce or safely bypass that condition. ai-cache.access reads any JSON request body, computes a key, and marks the request as MISS; then log writes any 200 response to Redis. There is no ctx.picked_ai_instance guard like the existing AI moderation plugins use.
If the plugin is accidentally attached at Route / Service / Consumer level without an AI proxy, ordinary JSON upstream responses can be cached and replayed. That is a surprising behavior and can leak stale or incorrect non-AI responses.
Please add a guard before key computation, either bypassing by default or using the shared ai-protocols.binding fail_mode behavior, and add coverage for the no-ai-proxy case.
I rechecked the latest update. The no-ai-proxy guard looks addressed now: ai-cache.access checks ctx.picked_ai_instance first, uses the shared ai-protocols.binding fail_mode, and the tests cover both the default bypass behavior and fail_mode=error.
One merge-blocking cache-key issue still remains:
[P1] share_across_routes can still reuse a response across different effective models on plain ai-proxy routes
The new scope includes ctx.picked_ai_instance_name, which fixes the ai-proxy-multi case because different picked instances have different names. However, for the plain ai-proxy plugin, ctx.picked_ai_instance_name is only ai-proxy-<provider> (for example, ai-proxy-openai). It does not include the route-level effective model.
The fingerprint still uses the requested model from ctx.var.request_llm_model or body.model, not the effective model selected by ai-proxy from ai_instance.options.model or request_model. This leaves a real collision when cache sharing is enabled across routes:
- Route A uses
ai-proxywithprovider=openai,options.model=gpt-4o, andai-cache.cache_key.share_across_routes=true. - Route B uses
ai-proxywithprovider=openai,options.model=gpt-4o-mini, and the same Redis/cache settings. - The client sends the same body to both routes, especially if the body omits
modelor carries the same requestedmodel. - Both routes compute the same scope (
instance=ai-proxy-openai) and the same fingerprint, so Route B can replay Route A's cached response even though the effective upstream model is different.
This also contradicts the new docs, which say that even with share_across_routes enabled, responses from different upstream models or providers are kept in separate cache entries.
Please include the effective model in the key/scope for the plain ai-proxy case, for example by deriving it from ctx.picked_ai_instance.options.model or body.model before lookup. It would also be good to add a regression test with two plain ai-proxy routes using the same provider, different options.model, the same Redis, and share_across_routes=true; the second route should be a MISS, not a HIT.
I think this should be addressed before merge: the cache key is currently computed before ai-proxy builds the final upstream request, so it does not cover all server-side mutations that can affect the LLM response.
ai-cache computes ctx.ai_cache_fingerprint in access from the client request body and then scopes the key mostly by instance/model/route/consumer/vars. However, ai-proxy later mutates the request that is actually sent upstream through options, override.llm_options, and override.request_body. Those fields can change response-determining parameters such as temperature, top_p, max_tokens, tools, provider-specific body fields, etc.
A concrete failure case:
- Two routes enable
ai-cachewithcache_key.share_across_routes = true. - The client sends the same prompt and model to both routes.
- Route A configures
ai-proxy.options.temperature = 0.2. - Route B configures
ai-proxy.options.temperature = 0.8, or usesoverride.request_body/override.llm_optionsto change the final upstream request. - Route A warms the cache first.
- Route B can hit Route A's cached response even though the actual upstream LLM request should be different.
This breaks the exact-cache contract because the key no longer represents the final request that produced the cached response. It can return a response generated under a different route-side AI configuration.
Suggested fix: base the cache key on the final canonical upstream request body after ai-proxy has applied provider conversion, options, override.llm_options, and override.request_body; or include a canonicalized representation of all response-determining AI instance configuration in the key. Please also add regression tests covering shared-cache routes with identical client bodies but different server-side options / override values.
@membphis
Addressed all the previous concerns. The three cache-key reports were one root cause: the key was computed in access from the client request, but the response is determined by the effective upstream request ai-proxy builds later in before_proxy (after ai-cache runs), so server-side options/override never reached the key.
The fingerprint now identifies that effective request. Since final_body = f(client_body, protocol, instance{provider, options, override}) is deterministic, it hashes those inputs:
- client: protocol, messages, params
- effective: provider, effective model (
options.model or body.model),options,override.llm_options,override.request_body(+request_body_force_override),override.endpoint
scope() is reduced to pure isolation (route / consumer / include_vars). One rule closes all three cases, the plain-ai-proxy effective model, the options/override params, and the earlier instance/provider collision.
Keying off the final upstream body directly isn't feasible: before_proxy is where that body is built and where the upstream call happens, so a read-through cache that short-circuits in access can't see it but hashing the builder's inputs is equivalent.
While reworking this I also closed a related case: on ai-proxy-multi failover, the fallback instance's response could be written under the originally-picked instance's key. The log-phase write is now skipped when the serving instance differs from the one the key was computed for. Let me know what your view on this.
I studied your method, and after your explanation, I agree with the current implementation.