Metadata-Version: 2.1
Name: offline-rag-lite
Version: 0.2.0
Summary: Zero-runtime-dependency hybrid BM25 + Int8 vector RAG engine for offline mobile chat, PWAs, and local-first apps with portable .rag snapshots.
Author: Kotcherla Murali Krishna
License: MIT
Project-URL: Homepage, https://github.com/mkkotcherla/offline-rag-lite
Project-URL: Repository, https://github.com/mkkotcherla/offline-rag-lite
Project-URL: Issues, https://github.com/mkkotcherla/offline-rag-lite/issues
Keywords: rag,offline,bm25,vector-search,int8,quantization,rrf,sqlite,local-first,zero-dependency
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Text Processing :: Indexing
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE

# 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](https://img.shields.io/pypi/v/offline-rag-lite.svg?color=3775a9&logo=pypi&logoColor=white)](https://pypi.org/project/offline-rag-lite/)
[![npm version](https://img.shields.io/npm/v/offline-rag-lite.svg?color=cb3837&logo=npm)](https://www.npmjs.com/package/offline-rag-lite)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
[![Zero Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen.svg)](#why-offline-rag-lite)
[![Python 3.9+](https://img.shields.io/badge/Python-3.9%2B-3776ab.svg?logo=python&logoColor=white)](https://pypi.org/project/offline-rag-lite/)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.x-3178c6.svg?logo=typescript&logoColor=white)](https://www.npmjs.com/package/offline-rag-lite)

## Table of Contents

- [Install](#install)
- [Architecture](#architecture)
- [Why `offline-rag-lite`?](#why-offline-rag-lite)
- [How It Works Under the Hood](#how-it-works-under-the-hood)
- [Quick Start & End-to-End Recipes](#quick-start--end-to-end-recipes)
- [Complete API Reference](#complete-api-reference)
- [When NOT to Use (Non-Goals)](#when-not-to-use-non-goals)
- [License](#license)

---

## Install

```bash
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):

```mermaid
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 + Exact Quantized Cosine + RRF:** `quantize_int8()` stores vectors in compact signed 8-bit `array('b')` buffers (`[-127, 127]`) using `round_half_away_from_zero` for byte-for-byte Python ↔ TypeScript parity and precomputes each vector's integer L2 norm $\|q_i\|_2$ (stored in Section `0x02`). `SQLiteStorage` uses SQLite `FTS5` BM25 when available with pure-Python Okapi BM25 fallback, while hydrated `.rag` v2 snapshots query precompiled BM25 posting lists directly (zero re-tokenization). Both rankings merge via Reciprocal Rank Fusion (`rrf_k = 60`).
- **Portable `.rag` v2 7-Section Wire Protocol (`ORAG`):** 32-byte Little-Endian header + 96-byte section directory (`6 × 16` bytes) covering `0x01` SHA-256 digest (`hashlib.sha256` + `hmac.compare_digest`, integrity verification against corruption, raising `SnapshotIntegrityError` on mismatch), `0x02` scales & norms, `0x03` 8-byte-aligned vector matrix, `0x04` BM25 dictionary, `0x05` BM25 posting lists, and `0x06` offset-indexed cold metadata/text. Validates `max_snapshot_bytes` (default `100 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 deterministic `destroy(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 within `max_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`

```python
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)

```ts
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)

```python
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](https://github.com/mkkotcherla)
