A context-aware, multi-level caching system for Retrieval-Augmented Generation (RAG) applications.
Project description
RAGCache
RAGCache is a context-aware, multi-level caching system designed to accelerate and optimize Retrieval-Augmented Generation (RAG) pipelines. Unlike traditional exact-match KV caches, RAGCache utilizes semantic similarity, context stability validation, and user intent classification to safely reuse LLM responses while strictly preserving correctness.
๐ Key Features
- Dual-Layer Caching (L1 & L2):
- L1 (Retrieval Cache): Low-latency exact-match string cache mapping queries directly to document IDs, bypassing heavy vector search lookups.
- L2 (Generation Cache): High-performance semantic cache mapping queries and contexts to LLM responses.
- Context Stability Validation: Analyzes document overlaps using Jaccard Similarity to reject cache hits if retrieved context documents have drifted.
- Intent-Aware Caching: Classifies queries (e.g. action, informational) to bypass caching automatically for mutation operations.
- Strict Tenant Isolation: Restricts cache retrieval scope dynamically to prevent context leakages across different users and tenants.
- Prometheus Observability: Native latency histograms, cache hit-rate counters, and memory tracking.
- Optimization ROI: Speeds up RAG pipelines by 2.3x and reduces API token costs by up to 60% with zero loss in contextual accuracy.
๐ Architecture Overview
User Query
โ
โผ
โโโโโโโโโโโโโโโโ
โ L1 Cache โโโโโโโโโโโบ Hit (Yields Doc IDs)
โโโโโโโโฌโโโโโโโโ โ
โ Miss โ
โผ โ
โโโโโโโโโโโโโโโโ โ
โ Vector DB โโโโโโโโโโโโโโโโโโโ
โโโโโโโโฌโโโโโโโโ
โ doc_ids
โผ
โโโโโโโโโโโโโโโโ
โ L2 Cache โโโโโโโโโโโบ Hit (Returns LLM Response)
โโโโโโโโฌโโโโโโโโ
โ Miss
โผ
โโโโโโโโโโโโโโโโ
โ Expensive โ
โ LLM API โ
โโโโโโโโโโโโโโโโ
For a deep dive into caching layers and algorithms, read the Architecture Guide.
๐ฆ Installation
Install the core library (includes Redis support and Prometheus telemetry):
pip install rag-cache
Optional Backends:
- Local FAISS Vector DB:
pip install "rag-cache[faiss]"
- Local Sentence-Transformers Embeddings:
pip install "rag-cache[embeddings]"
- Full Installation (All Backends):
pip install "rag-cache[all]"
โก Quick Start
Get running in less than 2 minutes using our high-level facade:
from rag_cache import RAGCache
# Initialize dual-layer cache facade
cache = RAGCache()
# Wrap your existing RAG execution function
def query_rag_pipeline(query: str):
# Pass query, retriever callback, and LLM callback
result = cache.run(
query=query,
retriever=lambda q: ["doc_abc", "doc_xyz"],
llm=lambda q, doc_ids: "Context-aware systems ensure LLM correctness."
)
return result["answer"]
# Executes LLM call (miss)
print(query_rag_pipeline("What is context-aware caching?"))
# Returns cached response immediately (semantic hit!)
print(query_rag_pipeline("Explain context-aware caching."))
For more execution models and advanced configurations, see the Quick Start Guide.
โ๏ธ Configuration
RAGCache supports configuration loading with the following precedence:
- Keyword overrides in constructor (e.g.
RAGCache(redis_url="...")). - Environment variables (
REDIS_URL,L1_TTL,L2_TTL,SIMILARITY_THRESHOLD). - YAML configuration file (e.g. loaded via
RAGCache.from_config("config.yaml")). - Built-in defaults.
See config_example.yaml for a complete template configuration.
๐ Tenant Isolation
Ensure user data boundaries are strictly isolated by passing a tenant_id to caching endpoints:
result = cache.run(
query=query,
retriever=retriever_fn,
llm=llm_fn,
tenant_id="customer_company_a",
scope="tenant" # Options: "tenant" (default), "user", or "global"
)
For details on namespacing strategies in Redis, see Architecture Guide.
๐ Metrics & Telemetry
RAGCache collects statistics out-of-the-box using Prometheus:
- Cache hits/misses split by L1 and L2 layers.
- Operational latency histograms for Redis, FAISS, and Embeddings.
- Eviction count and Redis memory usage.
To enable the HTTP telemetry server, set the prometheus_port config parameter:
cache = RAGCache(prometheus_port=8000)
Scrape metrics at http://localhost:8000/metrics. We provision pre-built Grafana dashboards under config/grafana/dashboards.
๐งช Calibration & Benchmarking
To optimize caching threshold parameters for your specific RAG datasets, run the offline calibration script:
python tools/calibration/calibrate.py
This runs a threshold sweep to recommend optimal parameters under Safety-First, Max F1, and Balanced profiles. Read the Benchmark Documentation for more details.
๐ License
This project is licensed under the MIT License. See LICENSE for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file rag_cachex-0.1.1.tar.gz.
File metadata
- Download URL: rag_cachex-0.1.1.tar.gz
- Upload date:
- Size: 72.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b3351970a9dbdbd2d8a7417328a5382b1827074745fabcd09e263cdff6408ca3
|
|
| MD5 |
29369078b05891a5156670ef65e3d894
|
|
| BLAKE2b-256 |
6e0d25372f7241ff84f105fb3601f6646905eb15f9a8b89ad28608e9cecfa746
|
File details
Details for the file rag_cachex-0.1.1-py3-none-any.whl.
File metadata
- Download URL: rag_cachex-0.1.1-py3-none-any.whl
- Upload date:
- Size: 30.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8f10969ba1cea6a0ca984ef0e2763592cb96aba99b53b44d81d7f0d47a2f3c67
|
|
| MD5 |
0734045d460ec0948f903a81d6855123
|
|
| BLAKE2b-256 |
e85bea6019fab1676705edd257670da4d2041692162b47a6d90a49a25b706496
|