Skip to main content

ContextCache

PyPI Version License: MIT Python Support CI Build Status

ContextCache is a context-aware, multi-level caching system designed to accelerate and optimize Retrieval-Augmented Generation (RAG) pipelines. Unlike traditional exact-match KV caches, ContextCache 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 context-cachex

Optional Backends:

  • Local FAISS Vector DB:
    pip install "context-cachex[faiss]"
    
  • Local Sentence-Transformers Embeddings:
    pip install "context-cachex[embeddings]"
    
  • Full Installation (All Backends):
    pip install "context-cachex[all]"
    

โšก Quick Start

Get running in less than 2 minutes using our high-level facade:

from rag_cache import ContextCache

# Initialize dual-layer cache facade
cache = ContextCache()

# 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

ContextCache supports configuration loading with the following precedence:

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

ContextCache 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 = ContextCache(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.

Download files

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

Source Distribution

context_cachex-0.1.0.tar.gz (73.9 kB view details)

Uploaded Source

Built Distribution

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

context_cachex-0.1.0-py3-none-any.whl (30.2 kB view details)

Uploaded Python 3

File details

Details for the file context_cachex-0.1.0.tar.gz.

File metadata

  • Download URL: context_cachex-0.1.0.tar.gz
  • Upload date:
  • Size: 73.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.13.5

File hashes

Hashes for context_cachex-0.1.0.tar.gz
Algorithm Hash digest
SHA256 08bfb4ef1ada7c9f030e58059850a14efbda945c9442ae8074292b4eeffecd72
MD5 a9e5d932de9fc49fbfd9aa6213959825
BLAKE2b-256 885da09b5ab6d43e3bff70178f7f6e1dab950c36247bedce42904b3fd0a9edfc

See more details on using hashes here.

File details

Details for the file context_cachex-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: context_cachex-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 30.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.13.5

File hashes

Hashes for context_cachex-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 89456deb9b4db0387adab58fffe9facd2c6bca09f02990312db5693429750dc1
MD5 40b269472f206eee23b3e1674241c156
BLAKE2b-256 b0f9f56ef1c9187561f6ab0a6bceefbe2f9e71b15d9dc6258d44727910f5dfc9

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 files

Supported by

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