Skip to main content

PatternMem RAG

CI PyPI version Python License: MIT

Framework-agnostic Python middleware that wraps any existing RAG pipeline and makes it self-improving — via persistent failure-pattern memory across queries.

# Before
answer = my_rag_pipeline(query)

# After — one line
answer = await PatternMemMiddleware(pipeline=my_rag_pipeline).ainvoke(query)

Why PatternMem?

Self-RAG, CRAG, and DSPy all reflect within a single query. PatternMem is the missing layer: it makes failure signals persistent across the entire query history — so the second time a pipeline fails on a similar question, it already knows what went wrong and pre-empts the failure.

PatternMem does not reimplement evaluation, LLM calling, or graph storage. It sits between your pipeline and the eval/storage libraries you already have.


Quickstart

pip install patternmem-rag
import asyncio
from patternmem import PatternMemMiddleware

async def my_rag_pipeline(query, **kwargs):
    # your existing pipeline here
    return {"answer": "...", "chunks": [...]}

async def main():
    async with PatternMemMiddleware(
        pipeline=my_rag_pipeline,
        backend="json",    # local file, zero credentials
        eval="auto",       # tries RAGAS → DeepEval → no-op
    ) as mw:
        answer = await mw.ainvoke("What is the capital of France?")
        print(answer)

asyncio.run(main())

Zero-credential mode (no API keys needed)

answer = await PatternMemMiddleware(
    pipeline=my_pipeline,
    backend="json",
    eval="none",
    observability=None,
).ainvoke(query)

Run the included demo:

python examples/zero_credential_demo.py

How it works

Query ──► [Phase 1: ~50ms]
           Embed query (MiniLM, local)
           Lookup patterns (cosine similarity ≥ 0.82)
           on HIT  → Augmenter injects retrieval_hint / generation_constraint
           Pipeline called → Answer returned to caller immediately

           [Phase 2: async background]
           EvalRouter: RAGAS / DeepEval / none → FailureSignal

           [Phase 3: async background]
           BackgroundReflector: LLM extracts FailurePattern → Backend write
           Decay/eviction loop (patterns below weight 0.1 are pruned)

The caller never waits for Phases 2 or 3.


Optional extras

Extra What it adds
pip install patternmem-rag[ragas] RAGAS evaluation adapter
pip install patternmem-rag[deepeval] DeepEval evaluation adapter
pip install patternmem-rag[neo4j] Neo4j / AuraDB backend
pip install patternmem-rag[langfuse] Langfuse observability
pip install patternmem-rag[networkx] NetworkX in-memory backend
pip install patternmem-rag[chroma] ChromaDB vector backend
pip install patternmem-rag[faiss] FAISS local vector index backend

Configuration reference

PatternMemMiddleware(
    pipeline,                          # any callable (sync or async)
    llm=None,                          # explicit LLM; auto-resolved if omitted
    backend="json",                    # "json" | "sqlite" | "networkx" | MemoryBackend
    eval="auto",                       # "ragas" | "deepeval" | "auto" | "none"
    observability=None,                # "langfuse" | "otel" | None
    similarity_threshold=0.82,         # cosine similarity floor for pattern lookup
    allow_param_override=False,        # allow temperature/CoT overrides
    rewrite_feedback=False,            # inject hints into query rewriter
)

Backend choice guide

Backend Best for Persistence Dependencies
"json" Zero-config, development File None
"sqlite" Single-process production File (WAL) aiosqlite (core)
"networkx" Notebooks, graph experiments Optional file networkx
"chroma" Large stores, existing Chroma setup File / HTTP server chromadb
"faiss" High-speed local search, no server File (index + sidecar) faiss-cpu
"neo4j" Multi-process, AuraDB, scale Native graph neo4j driver

Custom backend

Implement MemoryBackend and pass an instance directly:

from patternmem import MemoryBackend, PatternMemMiddleware

class MyRedisBackend(MemoryBackend):
    async def write_pattern(self, pattern): ...
    async def lookup_patterns(self, embedding, top_k=3): ...
    async def get_stats(self): ...
    async def update_pattern(self, id, decay_weight): ...
    async def delete_pattern(self, id): ...

mw = PatternMemMiddleware(pipeline=my_pipeline, backend=MyRedisBackend())

FAQ

Q: Does PatternMem replace RAGAS or DeepEval? No. It wraps them. It uses their scores as signals, stores the resulting patterns, and pre-empts future failures.

Q: Does it change my prompts? Never. All augmentation flows through augmented_input kwargs — PatternMem never touches your prompt template.

Q: What if evaluation isn't installed? eval="none" is a first-class mode. The middleware still runs the full 3-phase loop; Phase 2 returns an UNKNOWN signal and Phase 3 stores it with no external calls.

Q: What's the LLM used for? Only Phase 3 (root cause extraction and hint generation from a FailureSignal). It borrows your pipeline's LLM — it never creates one.

Q: What's out of scope? Celery integration (documented stub), Redis/Postgres backends (open ABC for community), any dashboard (use Langfuse's native UI).


Contributing

Contributions are welcome! Please open an issue first to discuss what you'd like to change.

  • All backends must pass the contract test suite in tests/contract/test_backend_contract.py.
  • Keep public API surface stable — anything not in patternmem.__init__.__all__ is internal.

License

MIT

Metadata

Release files for patternmem-rag 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for patternmem-rag 0.1.2
File Size Uploaded Provenance Actions
patternmem_rag-0.1.2.tar.gz 43.6 kB With provenance Details for patternmem_rag-0.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for patternmem-rag 0.1.2
File Interpreter ABI Platform Actions
patternmem_rag-0.1.2-py3-none-any.whl Python 3 none any Details for patternmem_rag-0.1.2-py3-none-any.whl

Total release size: 86.5 kB

Release files / patternmem_rag-0.1.2.tar.gz

Download URL patternmem_rag-0.1.2.tar.gz
Size 43.6 kB
Tags Source
SHA-256 checksum
How to use checksums
5688ea7b1ed033bb86f7e78965980643e6331e425320de6aeb566e98edd6bf24
BLAKE2b-256 checksum
How to use checksums
ec005e9ff640e0667067dc4c0c7a3d446b548249f4fe958db16c130dd2330ec2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 20, 2026.

Transparency log

Release files / patternmem_rag-0.1.2-py3-none-any.whl

Download URL patternmem_rag-0.1.2-py3-none-any.whl
Size 43.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3e0283eff61eedaf7fc8b5149910a46e7bc1c43a27135ebe7f3a6ded3b6766a4
BLAKE2b-256 checksum
How to use checksums
d3ebfda906fa8da1de79de6de603e3d2351908e170a3d4adbe8636e268f09091
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 20, 2026.

Transparency log

Security for patternmem-rag 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.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for patternmem_rag-0.1.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 20, 2026.

Transparency log

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.

Release history Release notifications | RSS feed

This release

0.1.2 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page