Skip to main content

offline-rag-lite

Zero-runtime-dependency hybrid RAG engine (BM25 + Int8 quantized vector search + RRF) for browser IndexedDB, mobile chat windows, and Python SQLite with portable .rag binary snapshots.

PyPI version npm version License: MIT Zero Dependencies Python 3.9+ TypeScript

Table of Contents


Install

pip install offline-rag-lite
  • Zero runtime dependencies (dependencies = [], Python >= 3.9)
  • 100% Python standard library: sqlite3, json, struct, hashlib, math, array, re
  • Built-in SQLite + FTS5 storage with transparent pure-Python BM25 fallback

Architecture

Build, quantize, and verify your RAG index in Python using SQLiteStorage, then ship a single portable .rag binary snapshot directly to mobile browsers (IndexedDBStorage + Web Worker via the npm offline-rag-lite package):

flowchart LR
  subgraph Build["1. Offline Index Pre-Building (Python 3.9+)"]
    Raw["Raw Docs & Markdown"] --> Chunk["chunk_text (512 chars, 64 overlap)"]
    Chunk --> Embed["External embed() Callback"]
    Chunk --> Tok["BM25 Tokenizer (codes, IDs, terms)"]
    Embed --> Quant["quantize_int8 (array('b'), ~75% less RAM)"]
    Quant --> Pack["encode_snapshot"]
    Tok --> Pack
    Pack --> Snap[("knowledge.rag (ORAG v1 + SHA-256)")]
  end

  subgraph Runtime["2. Mobile / Browser Runtime (IndexedDB + Web Worker)"]
    Snap --> Verify["decodeSnapshot (Magic + SHA-256 Check)"]
    Verify --> IDB[("IndexedDBStorage (Cold Chunks + Quota Guards)")]
    Verify --> Worker["Web Worker RAM (Hot Int8Array + BM25 + LRU Cache)"]
    Query["User Chat Query"] --> Worker
    Worker --> RRF["Reciprocal Rank Fusion (k = 60) + Namespace Filter"]
    IDB --> RRF
    RRF --> Ctx["buildChatContext (maxTokens + Dedup + Boundary Tags)"]
  end

Why offline-rag-lite?

  • No C/C++/Rust build failures: Libraries like faiss or hnswlib often fail to compile on ARM edge devices, slim Docker containers, or air-gapped environments. offline-rag-lite uses strictly the Python standard library.
  • Exact keyword + semantic recall: Vector-only stores miss exact IDs, SKUs, and error codes (ERR-404) and stop working if an embedding service goes offline.
  • Native Python ↔ Browser bridge: Pre-build .rag indexes in Python CI/CD pipelines and load them directly into mobile browser IndexedDB with zero client-side embedding.
Capability offline-rag-lite Heavy WASM Vector DBs Vector-Only Python Libraries Cloud Vector Databases
Runtime Dependencies 0 (Python stdlib only) Multi-MB WASM runtime Native C/C++/Rust wheels Managed SaaS + HTTP SDK
Memory Footprint Very low (array('b') Int8 cuts vector RAM ~75%) High Moderate–High (float32) Server-managed
Offline Resilience 100% offline; auto-falls back to BM25 if embed() raises Offline, heavy startup Breaks without embedder Requires internet
Cross-Language Portability Shared .rag v1 binary (Python ↔ JS/IndexedDB) + SHA-256 Engine-specific dumps Pickle/format locked API-bound

How It Works Under the Hood

  • Hybrid BM25 + Int8 Quantized Vector Search + RRF: quantize_int8() stores vectors in compact signed 8-bit array('b') buffers ([-127, 127]) with a per-vector float32 scale factor (~75% RAM reduction vs float32, < 0.01 cosine drift). SQLiteStorage automatically uses SQLite FTS5 BM25 when compiled into sqlite3, falling back transparently to pure-Python Okapi BM25 (k1 = 1.5, b = 0.75). Both ranked lists are merged with Reciprocal Rank Fusion (rrf_k = 60).
  • Portable .rag Binary Snapshot Format (ORAG v1): 44-byte Little-Endian header (b"ORAG", version 0x01, quantization mode 0 = float32 / 1 = int8, dims uint16, chunk_count uint32, 32-byte hashlib.sha256 payload digest) + presence mask + packed vector matrix + float32 scales + UTF-8 JSON chunk metadata. Verified in constant time with hmac.compare_digest on import.
  • Memory & Storage Hygiene: Bounded LRU query cache (max_cache_entries=100), strict namespace isolation (delete_namespace(ns)), and deterministic destroy(wipe_storage=False) that zeroes all tracked Int8 array('b') buffers and optionally removes the SQLite database file.
  • Chat Context Token Budgeting (build_chat_context): Selects top-$K$ chunks within max_tokens=1500, deduplicates overlapping chunks, escapes literal </retrieved_context> tags inside untrusted content, and wraps output in <retrieved_context>...</retrieved_context>.

Quick Start & End-to-End Recipes

Recipe 1: Build & Export knowledge.rag with SQLiteStorage

from pathlib import Path
from offline_rag_lite import OfflineRag, SQLiteStorage

def my_embedder(texts: list[str]) -> list[list[float]]:
    # Connect any embedding provider or local model
    return [embed_text(t) for t in texts]

rag = OfflineRag(
    storage=SQLiteStorage("knowledge.sqlite3"),
    embed=my_embedder,
    chunk_size=512,
    overlap=64,
    quantization="int8",
)

rag.add_documents([
    {
        "id": "faq-1",
        "namespace": "support",
        "text": "Error code ERR-404 indicates the offline snapshot file must be refreshed.",
        "metadata": {"source": "faq.md"},
    },
    {
        "id": "sync-1",
        "namespace": "support",
        "text": "Mobile PWAs hydrate .rag snapshots into IndexedDB inside a Web Worker.",
        "metadata": {"source": "pwa.md"},
    },
])

# Query locally and build token-budgeted chat context
ctx = rag.build_chat_context(
    "ERR-404 snapshot refresh",
    namespace="support",
    top_k=5,
    max_tokens=1500,
)
print(ctx.context)

# Export portable .rag binary snapshot for browser/mobile clients
Path("knowledge.rag").write_bytes(rag.export_snapshot(namespace="support"))
rag.destroy(wipe_storage=False)

Recipe 2: Hydrate knowledge.rag in a Mobile Browser (npm Companion)

import { createOfflineRag, IndexedDBStorage } from 'offline-rag-lite';

const rag = createOfflineRag({
  storage: new IndexedDBStorage({ dbName: 'support-kb' }),
});

const bytes = new Uint8Array(await (await fetch('/assets/knowledge.rag')).arrayBuffer());
await rag.importSnapshot(bytes, { replace: true });

const { context } = await rag.buildChatContext('ERR-404', { namespace: 'support' });

Recipe 3: Offline BM25-Only Mode (No Embedder Required)

from offline_rag_lite import OfflineRag, MemoryStorage

rag = OfflineRag(storage=MemoryStorage())  # embed=None -> pure BM25 lexical mode
rag.add_documents([
    {"id": "ticket-9", "text": "Flight confirmation ZX-9918 departs at 08:30."},
])
hits = rag.search("ZX-9918", top_k=3)
print(hits[0].id, hits[0].bm25_score)

Complete API Reference

OfflineRag(...) Constructor

Name Type Default Description
storage Optional[StorageAdapter] MemoryStorage() Backing store (MemoryStorage or SQLiteStorage)
embed Optional[EmbedFunction] None External Callable[[List[str]], Sequence[Sequence[float]]] callback
chunk_size int 512 Maximum characters per chunk in add_documents()
overlap int 64 Character overlap between adjacent chunks
quantization str "int8" Quantization mode ("int8" or "float32")
max_cache_entries int 100 Bounded LRU query cache size (0 disables caching)
default_namespace str "default" Default namespace when omitted
fallback_to_lexical bool True Fall back to BM25 lexical search if embed() raises

OfflineRag Methods

Name Type Default Description
add_documents(docs) (docs: Sequence[Dict[str, Any]]) -> List[str] — Chunks, tokenizes, optionally embeds, and upserts documents
search(query, ...) (query, top_k=5, namespace=None, rrf_k=60, metadata_filter=None, mode="hybrid") -> List[SearchResult] top_k=5, rrf_k=60, mode="hybrid" Hybrid BM25 + Int8 vector RRF search scoped to namespace
build_chat_context(query, ...) (query, top_k=5, namespace=None, max_tokens=1500, estimate_tokens=None, separator="\n\n---\n\n", tag_name="retrieved_context") -> ChatContextResult max_tokens=1500 Searches, deduplicates, and wraps top chunks in <retrieved_context>
export_snapshot(namespace=None, quantization=None) (namespace=None, quantization=None) -> bytes all namespaces, engine quantization Encodes portable .rag v1 binary snapshot with SHA-256 checksum
import_snapshot(data, replace=False) (data: bytes | bytearray | memoryview, replace=False) -> int replace=False Verifies SHA-256 checksum and imports chunks
clear_cache() () -> None — Clears the bounded LRU query cache
delete_namespace(namespace) (namespace: str) -> int — Deletes all chunks in namespace and invalidates cache
count(namespace=None) (namespace: Optional[str] = None) -> int all namespaces Returns stored chunk count
destroy(wipe_storage=False) (wipe_storage: bool = False) -> None wipe_storage=False Zeroes tracked Int8 array('b') buffers, clears cache, optionally deletes SQLite file

Storage Adapters & Standalone Helpers

Name Type Default Description
MemoryStorage() StorageAdapter — In-memory store with Int8 buffer zeroing on destroy()
SQLiteStorage(path=":memory:", use_fts5=True) StorageAdapter ":memory:", use_fts5=True SQLite persistence with FTS5 BM25 auto-detection and pure-Python fallback
chunk_text(text, chunk_size=512, overlap=64) (str, int, int) -> List[str] 512, 64 Sentence/paragraph-aware Markdown/text chunker
build_chat_context(results, ...) (Sequence[SearchResult], ...) -> ChatContextResult max_tokens=1500 Standalone token-budgeted, deduplicated context formatter
encode_snapshot(chunks, quantization="int8") (Sequence[StoredChunk], str) -> bytes "int8" Low-level .rag v1 binary encoder
decode_snapshot(data) (bytes | bytearray | memoryview) -> DecodedSnapshot — Low-level .rag v1 decoder with SHA-256 verification (SnapshotError)
quantize_int8 / dequantize_int8 (Sequence[float]) -> Tuple[array, float] — Symmetric Int8 quantization and reconstruction
cosine_similarity_int8 / dot_product_int8 (Sequence[int], ...) -> float — Fast Int8 cosine similarity and scaled dot product
tokenize / score_bm25 (str, Sequence[Tuple[str, Sequence[str]]], k1=1.5, b=0.75) -> Dict[str, float] k1=1.5, b=0.75 Built-in lexical tokenizer and Okapi BM25 scorer

When NOT to Use (Non-Goals)

  • Millions of vectors / distributed search clusters: Uses exact linear Int8 scans tailored for local-first apps and pre-built mobile snapshots, not server-side HNSW clusters.
  • Bundled ML embedding weights: Keeps zero runtime dependencies by delegating embeddings to your own embed() callback.
  • Multi-writer cloud replication: Built for single-device SQLite persistence and portable .rag snapshot distribution.

License

MIT © Kotcherla Murali Krishna

Metadata

Release files for offline-rag-lite 0.1.0

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

Source distribution (sdist)

Source distribution for offline-rag-lite 0.1.0
File Size Uploaded Provenance Actions
offline_rag_lite-0.1.0.tar.gz 26.6 kB Without provenance Details for offline_rag_lite-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for offline-rag-lite 0.1.0
File Interpreter ABI Platform Actions
offline_rag_lite-0.1.0-py3-none-any.whl Python 3 none any Details for offline_rag_lite-0.1.0-py3-none-any.whl

Total release size: 48.6 kB

Release files / offline_rag_lite-0.1.0.tar.gz

Download URL offline_rag_lite-0.1.0.tar.gz
Size 26.6 kB
Tags Source
SHA-256 checksum
How to use checksums
3390a32b0e609349b8b42a212a123ea3b84f092e96bff558d691d8f3d7360ecb
BLAKE2b-256 checksum
How to use checksums
03a2fd5109850c63501dcda25a23b0df26c0ed45e8aaaa9936f6a9fa0c866bef
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.8

Release files / offline_rag_lite-0.1.0-py3-none-any.whl

Download URL offline_rag_lite-0.1.0-py3-none-any.whl
Size 22.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
72accab3f7ec3c99762ea55d9cd242688949876660b3bbc09315f10dcb9d9fa7
BLAKE2b-256 checksum
How to use checksums
f954f40a815b19f49e001e99e16565af2bfaf3624eec14006308672bddb6c536
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.8

Security for offline-rag-lite 0.1.0

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.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No 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