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.
Table of Contents
- Install
- Architecture
- Why
offline-rag-lite? - How It Works Under the Hood
- Quick Start & End-to-End Recipes
- Complete API Reference
- When NOT to Use (Non-Goals)
- License
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
faissorhnswliboften fail to compile on ARM edge devices, slim Docker containers, or air-gapped environments.offline-rag-liteuses 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
.ragindexes in Python CI/CD pipelines and load them directly into mobile browserIndexedDBwith 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 + Exact Quantized Cosine + RRF:
quantize_int8()stores vectors in compact signed 8-bitarray('b')buffers ([-127, 127]) usinground_half_away_from_zerofor byte-for-byte Python ↔ TypeScript parity and precomputes each vector's integer L2 norm $|q_i|_2$ (stored in Section0x02).SQLiteStorageuses SQLiteFTS5BM25 when available with pure-Python Okapi BM25 fallback, while hydrated.ragv2 snapshots query precompiled BM25 posting lists directly (zero re-tokenization). Both rankings merge via Reciprocal Rank Fusion (rrf_k = 60). - Portable
.ragv2 7-Section Wire Protocol (ORAG): 32-byte Little-Endian header + 96-byte section directory (6 × 16bytes) covering0x01SHA-256 digest (hashlib.sha256+hmac.compare_digest, integrity verification against corruption, raisingSnapshotIntegrityErroron mismatch),0x02scales & norms,0x038-byte-aligned vector matrix,0x04BM25 dictionary,0x05BM25 posting lists, and0x06offset-indexed cold metadata/text. Validatesmax_snapshot_bytes(default100 MiB) and non-overlapping section offsets before allocating buffers. - Memory & Logical Partitioning Hygiene: Bounded LRU query cache (
max_cache_entries=100), namespace-filtered logical partitioning (delete_namespace(ns)— not cryptographic tenant isolation), and deterministicdestroy(wipe_storage=False)that zeroes tracked Int8/Float32 array buffers and optionally deletes the SQLite file. - Chat Context Token Budgeting (
build_chat_context): Selects top-$K$ chunks withinmax_tokens=1500, deduplicates overlapping chunks, escapes literal</retrieved_context>tags, and wraps output in<retrieved_context>...</retrieved_context>structural context delimiters (not a complete prompt-injection defense).
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
.ragsnapshot distribution.
License
MIT © Kotcherla Murali Krishna
Metadata
Release files for offline-rag-lite 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| offline_rag_lite-0.2.0.tar.gz | 33.4 kB | Without provenance | Details for offline_rag_lite-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| offline_rag_lite-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for offline_rag_lite-0.2.0-py3-none-any.whl |
Total release size: 61.8 kB
Release files / offline_rag_lite-0.2.0.tar.gz
| Download URL | offline_rag_lite-0.2.0.tar.gz |
|---|---|
| Size | 33.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
6d348a94f273aca0055b69892832d9192574bbd4450badbe3169e6f56c1869a3
|
|
BLAKE2b-256 checksum How to use checksums |
a1bc58381ac708e8235fbac40bbffa74df2daba8d877053359d54c16e6ea17c5
|
| 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.2.0-py3-none-any.whl
| Download URL | offline_rag_lite-0.2.0-py3-none-any.whl |
|---|---|
| Size | 28.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b642be6992fc68e0e305184766b537da05491806d0a6583fe07d19d513794c1a
|
|
BLAKE2b-256 checksum How to use checksums |
9ba40b342d431bf366ef0a95092a0efebb733ea1aa25d6b18f538be31182b764
|
| 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.2.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.