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-cachex
Optional Backends:
- Local FAISS Vector DB:
pip install "rag-cachex[faiss]"
- Local Sentence-Transformers Embeddings:
pip install "rag-cachex[embeddings]"
- Full Installation (All Backends):
pip install "rag-cachex[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.
Metadata
Release files for rag-cachex 0.1.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| rag_cachex-0.1.2.tar.gz | 72.8 kB | Without provenance | Details for rag_cachex-0.1.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| rag_cachex-0.1.2-py3-none-any.whl | Python 3 | none | any | Details for rag_cachex-0.1.2-py3-none-any.whl |
Total release size: 102.9 kB
Release files / rag_cachex-0.1.2.tar.gz
| Download URL | rag_cachex-0.1.2.tar.gz |
|---|---|
| Size | 72.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d40afa5af600d408557d601e6656eae93773f5f6741e3155e019d768a3342278
|
|
BLAKE2b-256 checksum How to use checksums |
6e2ff459dc8c58e0aadd91a0bfccb655cd7b7028a532fc421a5333becbeb641f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.7
|
Release files / rag_cachex-0.1.2-py3-none-any.whl
| Download URL | rag_cachex-0.1.2-py3-none-any.whl |
|---|---|
| Size | 30.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9dc13f9c5596bfc7a357bf0adf9dfa40dc65a81d3ada7a38ea8b7697a97929d3
|
|
BLAKE2b-256 checksum How to use checksums |
05d90bc969d6aca908f676da3a4d4aedc6113043a7f9f8c6deb69225a9471fa3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.7
|
Security for rag-cachex 0.1.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.