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-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:

  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.2.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.2-py3-none-any.whl (30.1 kB view details)

Uploaded Python 3

File details

Details for the file rag_cachex-0.1.2.tar.gz.

File metadata

  • Download URL: rag_cachex-0.1.2.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.2.tar.gz
Algorithm Hash digest
SHA256 d40afa5af600d408557d601e6656eae93773f5f6741e3155e019d768a3342278
MD5 b05bb60846892d065e5e519bcc6fe313
BLAKE2b-256 6e2ff459dc8c58e0aadd91a0bfccb655cd7b7028a532fc421a5333becbeb641f

See more details on using hashes here.

File details

Details for the file rag_cachex-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: rag_cachex-0.1.2-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.2-py3-none-any.whl
Algorithm Hash digest
SHA256 9dc13f9c5596bfc7a357bf0adf9dfa40dc65a81d3ada7a38ea8b7697a97929d3
MD5 8c6034afff9fd594aa60e8067eec323b
BLAKE2b-256 05d90bc969d6aca908f676da3a4d4aedc6113043a7f9f8c6deb69225a9471fa3

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