Skip to main content

A context-aware, multi-level caching system for Retrieval-Augmented Generation (RAG) applications.

Project description

RAGCache

PyPI Version License: MIT Python Support CI Build Status

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:

  1. Keyword overrides in constructor (e.g. RAGCache(redis_url="...")).
  2. Environment variables (REDIS_URL, L1_TTL, L2_TTL, SIMILARITY_THRESHOLD).
  3. YAML configuration file (e.g. loaded via RAGCache.from_config("config.yaml")).
  4. 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rag_cachex-0.1.1.tar.gz (72.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

rag_cachex-0.1.1-py3-none-any.whl (30.1 kB view details)

Uploaded Python 3

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

Hashes for rag_cachex-0.1.1.tar.gz
Algorithm Hash digest
SHA256 b3351970a9dbdbd2d8a7417328a5382b1827074745fabcd09e263cdff6408ca3
MD5 29369078b05891a5156670ef65e3d894
BLAKE2b-256 6e0d25372f7241ff84f105fb3601f6646905eb15f9a8b89ad28608e9cecfa746

See more details on using hashes here.

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

Hashes for rag_cachex-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 8f10969ba1cea6a0ca984ef0e2763592cb96aba99b53b44d81d7f0d47a2f3c67
MD5 0734045d460ec0948f903a81d6855123
BLAKE2b-256 e85bea6019fab1676705edd257670da4d2041692162b47a6d90a49a25b706496

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page