offline-rag-lite 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- offline_rag_lite-0.1.0/LICENSE +21 -0
- offline_rag_lite-0.1.0/PKG-INFO +248 -0
- offline_rag_lite-0.1.0/README.md +222 -0
- offline_rag_lite-0.1.0/pyproject.toml +58 -0
- offline_rag_lite-0.1.0/setup.cfg +4 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite/__init__.py +58 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite/bm25.py +74 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite/chunker.py +116 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite/context.py +112 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite/engine.py +341 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite/py.typed +0 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite/quantize.py +90 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite/snapshot.py +228 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite/storage.py +267 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite/types.py +38 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite.egg-info/PKG-INFO +248 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite.egg-info/SOURCES.txt +19 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite.egg-info/dependency_links.txt +1 -0
- offline_rag_lite-0.1.0/src/offline_rag_lite.egg-info/top_level.txt +1 -0
- offline_rag_lite-0.1.0/tests/test_core.py +207 -0
- offline_rag_lite-0.1.0/tests/test_snapshot.py +89 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kotcherla Murali Krishna
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: offline-rag-lite
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zero-runtime-dependency hybrid BM25 + Int8 vector RAG engine for offline mobile chat, PWAs, and local-first apps with portable .rag snapshots.
|
|
5
|
+
Author: Kotcherla Murali Krishna
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/mkkotcherla/offline-rag-lite
|
|
8
|
+
Project-URL: Repository, https://github.com/mkkotcherla/offline-rag-lite
|
|
9
|
+
Project-URL: Issues, https://github.com/mkkotcherla/offline-rag-lite/issues
|
|
10
|
+
Keywords: rag,offline,bm25,vector-search,int8,quantization,rrf,sqlite,local-first,zero-dependency
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Classifier: Topic :: Text Processing :: Indexing
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
|
|
27
|
+
# offline-rag-lite
|
|
28
|
+
|
|
29
|
+
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.
|
|
30
|
+
|
|
31
|
+
[](https://pypi.org/project/offline-rag-lite/)
|
|
32
|
+
[](https://www.npmjs.com/package/offline-rag-lite)
|
|
33
|
+
[](./LICENSE)
|
|
34
|
+
[](#why-offline-rag-lite)
|
|
35
|
+
[](https://pypi.org/project/offline-rag-lite/)
|
|
36
|
+
[](https://www.npmjs.com/package/offline-rag-lite)
|
|
37
|
+
|
|
38
|
+
## Table of Contents
|
|
39
|
+
|
|
40
|
+
- [Install](#install)
|
|
41
|
+
- [Architecture](#architecture)
|
|
42
|
+
- [Why `offline-rag-lite`?](#why-offline-rag-lite)
|
|
43
|
+
- [How It Works Under the Hood](#how-it-works-under-the-hood)
|
|
44
|
+
- [Quick Start & End-to-End Recipes](#quick-start--end-to-end-recipes)
|
|
45
|
+
- [Complete API Reference](#complete-api-reference)
|
|
46
|
+
- [When NOT to Use (Non-Goals)](#when-not-to-use-non-goals)
|
|
47
|
+
- [License](#license)
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## Install
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
pip install offline-rag-lite
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
- **Zero runtime dependencies** (`dependencies = []`, Python `>= 3.9`)
|
|
58
|
+
- **100% Python standard library:** `sqlite3`, `json`, `struct`, `hashlib`, `math`, `array`, `re`
|
|
59
|
+
- **Built-in SQLite + FTS5 storage** with transparent pure-Python BM25 fallback
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## Architecture
|
|
64
|
+
|
|
65
|
+
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):
|
|
66
|
+
|
|
67
|
+
```mermaid
|
|
68
|
+
flowchart LR
|
|
69
|
+
subgraph Build["1. Offline Index Pre-Building (Python 3.9+)"]
|
|
70
|
+
Raw["Raw Docs & Markdown"] --> Chunk["chunk_text (512 chars, 64 overlap)"]
|
|
71
|
+
Chunk --> Embed["External embed() Callback"]
|
|
72
|
+
Chunk --> Tok["BM25 Tokenizer (codes, IDs, terms)"]
|
|
73
|
+
Embed --> Quant["quantize_int8 (array('b'), ~75% less RAM)"]
|
|
74
|
+
Quant --> Pack["encode_snapshot"]
|
|
75
|
+
Tok --> Pack
|
|
76
|
+
Pack --> Snap[("knowledge.rag (ORAG v1 + SHA-256)")]
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
subgraph Runtime["2. Mobile / Browser Runtime (IndexedDB + Web Worker)"]
|
|
80
|
+
Snap --> Verify["decodeSnapshot (Magic + SHA-256 Check)"]
|
|
81
|
+
Verify --> IDB[("IndexedDBStorage (Cold Chunks + Quota Guards)")]
|
|
82
|
+
Verify --> Worker["Web Worker RAM (Hot Int8Array + BM25 + LRU Cache)"]
|
|
83
|
+
Query["User Chat Query"] --> Worker
|
|
84
|
+
Worker --> RRF["Reciprocal Rank Fusion (k = 60) + Namespace Filter"]
|
|
85
|
+
IDB --> RRF
|
|
86
|
+
RRF --> Ctx["buildChatContext (maxTokens + Dedup + Boundary Tags)"]
|
|
87
|
+
end
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## Why `offline-rag-lite`?
|
|
93
|
+
|
|
94
|
+
- **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.
|
|
95
|
+
- **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.
|
|
96
|
+
- **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.
|
|
97
|
+
|
|
98
|
+
| Capability | `offline-rag-lite` | Heavy WASM Vector DBs | Vector-Only Python Libraries | Cloud Vector Databases |
|
|
99
|
+
| --- | --- | --- | --- | --- |
|
|
100
|
+
| **Runtime Dependencies** | `0` (Python stdlib only) | Multi-MB WASM runtime | Native C/C++/Rust wheels | Managed SaaS + HTTP SDK |
|
|
101
|
+
| **Memory Footprint** | Very low (`array('b')` Int8 cuts vector RAM ~75%) | High | Moderate–High (`float32`) | Server-managed |
|
|
102
|
+
| **Offline Resilience** | 100% offline; auto-falls back to BM25 if `embed()` raises | Offline, heavy startup | Breaks without embedder | Requires internet |
|
|
103
|
+
| **Cross-Language Portability** | Shared `.rag` v1 binary (Python ↔ JS/IndexedDB) + SHA-256 | Engine-specific dumps | Pickle/format locked | API-bound |
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
## How It Works Under the Hood
|
|
108
|
+
|
|
109
|
+
- **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`).
|
|
110
|
+
- **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.
|
|
111
|
+
- **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.
|
|
112
|
+
- **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>`.
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## Quick Start & End-to-End Recipes
|
|
117
|
+
|
|
118
|
+
### Recipe 1: Build & Export `knowledge.rag` with `SQLiteStorage`
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from pathlib import Path
|
|
122
|
+
from offline_rag_lite import OfflineRag, SQLiteStorage
|
|
123
|
+
|
|
124
|
+
def my_embedder(texts: list[str]) -> list[list[float]]:
|
|
125
|
+
# Connect any embedding provider or local model
|
|
126
|
+
return [embed_text(t) for t in texts]
|
|
127
|
+
|
|
128
|
+
rag = OfflineRag(
|
|
129
|
+
storage=SQLiteStorage("knowledge.sqlite3"),
|
|
130
|
+
embed=my_embedder,
|
|
131
|
+
chunk_size=512,
|
|
132
|
+
overlap=64,
|
|
133
|
+
quantization="int8",
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
rag.add_documents([
|
|
137
|
+
{
|
|
138
|
+
"id": "faq-1",
|
|
139
|
+
"namespace": "support",
|
|
140
|
+
"text": "Error code ERR-404 indicates the offline snapshot file must be refreshed.",
|
|
141
|
+
"metadata": {"source": "faq.md"},
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
"id": "sync-1",
|
|
145
|
+
"namespace": "support",
|
|
146
|
+
"text": "Mobile PWAs hydrate .rag snapshots into IndexedDB inside a Web Worker.",
|
|
147
|
+
"metadata": {"source": "pwa.md"},
|
|
148
|
+
},
|
|
149
|
+
])
|
|
150
|
+
|
|
151
|
+
# Query locally and build token-budgeted chat context
|
|
152
|
+
ctx = rag.build_chat_context(
|
|
153
|
+
"ERR-404 snapshot refresh",
|
|
154
|
+
namespace="support",
|
|
155
|
+
top_k=5,
|
|
156
|
+
max_tokens=1500,
|
|
157
|
+
)
|
|
158
|
+
print(ctx.context)
|
|
159
|
+
|
|
160
|
+
# Export portable .rag binary snapshot for browser/mobile clients
|
|
161
|
+
Path("knowledge.rag").write_bytes(rag.export_snapshot(namespace="support"))
|
|
162
|
+
rag.destroy(wipe_storage=False)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
### Recipe 2: Hydrate `knowledge.rag` in a Mobile Browser (npm Companion)
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
import { createOfflineRag, IndexedDBStorage } from 'offline-rag-lite';
|
|
169
|
+
|
|
170
|
+
const rag = createOfflineRag({
|
|
171
|
+
storage: new IndexedDBStorage({ dbName: 'support-kb' }),
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
const bytes = new Uint8Array(await (await fetch('/assets/knowledge.rag')).arrayBuffer());
|
|
175
|
+
await rag.importSnapshot(bytes, { replace: true });
|
|
176
|
+
|
|
177
|
+
const { context } = await rag.buildChatContext('ERR-404', { namespace: 'support' });
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### Recipe 3: Offline BM25-Only Mode (No Embedder Required)
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
from offline_rag_lite import OfflineRag, MemoryStorage
|
|
184
|
+
|
|
185
|
+
rag = OfflineRag(storage=MemoryStorage()) # embed=None -> pure BM25 lexical mode
|
|
186
|
+
rag.add_documents([
|
|
187
|
+
{"id": "ticket-9", "text": "Flight confirmation ZX-9918 departs at 08:30."},
|
|
188
|
+
])
|
|
189
|
+
hits = rag.search("ZX-9918", top_k=3)
|
|
190
|
+
print(hits[0].id, hits[0].bm25_score)
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
195
|
+
## Complete API Reference
|
|
196
|
+
|
|
197
|
+
### `OfflineRag(...)` Constructor
|
|
198
|
+
|
|
199
|
+
| Name | Type | Default | Description |
|
|
200
|
+
| --- | --- | --- | --- |
|
|
201
|
+
| `storage` | `Optional[StorageAdapter]` | `MemoryStorage()` | Backing store (`MemoryStorage` or `SQLiteStorage`) |
|
|
202
|
+
| `embed` | `Optional[EmbedFunction]` | `None` | External `Callable[[List[str]], Sequence[Sequence[float]]]` callback |
|
|
203
|
+
| `chunk_size` | `int` | `512` | Maximum characters per chunk in `add_documents()` |
|
|
204
|
+
| `overlap` | `int` | `64` | Character overlap between adjacent chunks |
|
|
205
|
+
| `quantization` | `str` | `"int8"` | Quantization mode (`"int8"` or `"float32"`) |
|
|
206
|
+
| `max_cache_entries` | `int` | `100` | Bounded LRU query cache size (`0` disables caching) |
|
|
207
|
+
| `default_namespace` | `str` | `"default"` | Default namespace when omitted |
|
|
208
|
+
| `fallback_to_lexical` | `bool` | `True` | Fall back to BM25 lexical search if `embed()` raises |
|
|
209
|
+
|
|
210
|
+
### `OfflineRag` Methods
|
|
211
|
+
|
|
212
|
+
| Name | Type | Default | Description |
|
|
213
|
+
| --- | --- | --- | --- |
|
|
214
|
+
| `add_documents(docs)` | `(docs: Sequence[Dict[str, Any]]) -> List[str]` | — | Chunks, tokenizes, optionally embeds, and upserts documents |
|
|
215
|
+
| `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` |
|
|
216
|
+
| `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>` |
|
|
217
|
+
| `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 |
|
|
218
|
+
| `import_snapshot(data, replace=False)` | `(data: bytes \| bytearray \| memoryview, replace=False) -> int` | `replace=False` | Verifies SHA-256 checksum and imports chunks |
|
|
219
|
+
| `clear_cache()` | `() -> None` | — | Clears the bounded LRU query cache |
|
|
220
|
+
| `delete_namespace(namespace)` | `(namespace: str) -> int` | — | Deletes all chunks in `namespace` and invalidates cache |
|
|
221
|
+
| `count(namespace=None)` | `(namespace: Optional[str] = None) -> int` | all namespaces | Returns stored chunk count |
|
|
222
|
+
| `destroy(wipe_storage=False)` | `(wipe_storage: bool = False) -> None` | `wipe_storage=False` | Zeroes tracked Int8 `array('b')` buffers, clears cache, optionally deletes SQLite file |
|
|
223
|
+
|
|
224
|
+
### Storage Adapters & Standalone Helpers
|
|
225
|
+
|
|
226
|
+
| Name | Type | Default | Description |
|
|
227
|
+
| --- | --- | --- | --- |
|
|
228
|
+
| `MemoryStorage()` | `StorageAdapter` | — | In-memory store with Int8 buffer zeroing on `destroy()` |
|
|
229
|
+
| `SQLiteStorage(path=":memory:", use_fts5=True)` | `StorageAdapter` | `":memory:"`, `use_fts5=True` | SQLite persistence with `FTS5` BM25 auto-detection and pure-Python fallback |
|
|
230
|
+
| `chunk_text(text, chunk_size=512, overlap=64)` | `(str, int, int) -> List[str]` | `512`, `64` | Sentence/paragraph-aware Markdown/text chunker |
|
|
231
|
+
| `build_chat_context(results, ...)` | `(Sequence[SearchResult], ...) -> ChatContextResult` | `max_tokens=1500` | Standalone token-budgeted, deduplicated context formatter |
|
|
232
|
+
| `encode_snapshot(chunks, quantization="int8")` | `(Sequence[StoredChunk], str) -> bytes` | `"int8"` | Low-level `.rag` v1 binary encoder |
|
|
233
|
+
| `decode_snapshot(data)` | `(bytes \| bytearray \| memoryview) -> DecodedSnapshot` | — | Low-level `.rag` v1 decoder with SHA-256 verification (`SnapshotError`) |
|
|
234
|
+
| `quantize_int8` / `dequantize_int8` | `(Sequence[float]) -> Tuple[array, float]` | — | Symmetric Int8 quantization and reconstruction |
|
|
235
|
+
| `cosine_similarity_int8` / `dot_product_int8` | `(Sequence[int], ...) -> float` | — | Fast Int8 cosine similarity and scaled dot product |
|
|
236
|
+
| `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 |
|
|
237
|
+
|
|
238
|
+
---
|
|
239
|
+
|
|
240
|
+
## When NOT to Use (Non-Goals)
|
|
241
|
+
|
|
242
|
+
- **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.
|
|
243
|
+
- **Bundled ML embedding weights:** Keeps zero runtime dependencies by delegating embeddings to your own `embed()` callback.
|
|
244
|
+
- **Multi-writer cloud replication:** Built for single-device SQLite persistence and portable `.rag` snapshot distribution.
|
|
245
|
+
|
|
246
|
+
## License
|
|
247
|
+
|
|
248
|
+
MIT © [Kotcherla Murali Krishna](https://github.com/mkkotcherla)
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
# offline-rag-lite
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
[](https://pypi.org/project/offline-rag-lite/)
|
|
6
|
+
[](https://www.npmjs.com/package/offline-rag-lite)
|
|
7
|
+
[](./LICENSE)
|
|
8
|
+
[](#why-offline-rag-lite)
|
|
9
|
+
[](https://pypi.org/project/offline-rag-lite/)
|
|
10
|
+
[](https://www.npmjs.com/package/offline-rag-lite)
|
|
11
|
+
|
|
12
|
+
## Table of Contents
|
|
13
|
+
|
|
14
|
+
- [Install](#install)
|
|
15
|
+
- [Architecture](#architecture)
|
|
16
|
+
- [Why `offline-rag-lite`?](#why-offline-rag-lite)
|
|
17
|
+
- [How It Works Under the Hood](#how-it-works-under-the-hood)
|
|
18
|
+
- [Quick Start & End-to-End Recipes](#quick-start--end-to-end-recipes)
|
|
19
|
+
- [Complete API Reference](#complete-api-reference)
|
|
20
|
+
- [When NOT to Use (Non-Goals)](#when-not-to-use-non-goals)
|
|
21
|
+
- [License](#license)
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install offline-rag-lite
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
- **Zero runtime dependencies** (`dependencies = []`, Python `>= 3.9`)
|
|
32
|
+
- **100% Python standard library:** `sqlite3`, `json`, `struct`, `hashlib`, `math`, `array`, `re`
|
|
33
|
+
- **Built-in SQLite + FTS5 storage** with transparent pure-Python BM25 fallback
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## Architecture
|
|
38
|
+
|
|
39
|
+
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):
|
|
40
|
+
|
|
41
|
+
```mermaid
|
|
42
|
+
flowchart LR
|
|
43
|
+
subgraph Build["1. Offline Index Pre-Building (Python 3.9+)"]
|
|
44
|
+
Raw["Raw Docs & Markdown"] --> Chunk["chunk_text (512 chars, 64 overlap)"]
|
|
45
|
+
Chunk --> Embed["External embed() Callback"]
|
|
46
|
+
Chunk --> Tok["BM25 Tokenizer (codes, IDs, terms)"]
|
|
47
|
+
Embed --> Quant["quantize_int8 (array('b'), ~75% less RAM)"]
|
|
48
|
+
Quant --> Pack["encode_snapshot"]
|
|
49
|
+
Tok --> Pack
|
|
50
|
+
Pack --> Snap[("knowledge.rag (ORAG v1 + SHA-256)")]
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
subgraph Runtime["2. Mobile / Browser Runtime (IndexedDB + Web Worker)"]
|
|
54
|
+
Snap --> Verify["decodeSnapshot (Magic + SHA-256 Check)"]
|
|
55
|
+
Verify --> IDB[("IndexedDBStorage (Cold Chunks + Quota Guards)")]
|
|
56
|
+
Verify --> Worker["Web Worker RAM (Hot Int8Array + BM25 + LRU Cache)"]
|
|
57
|
+
Query["User Chat Query"] --> Worker
|
|
58
|
+
Worker --> RRF["Reciprocal Rank Fusion (k = 60) + Namespace Filter"]
|
|
59
|
+
IDB --> RRF
|
|
60
|
+
RRF --> Ctx["buildChatContext (maxTokens + Dedup + Boundary Tags)"]
|
|
61
|
+
end
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
## Why `offline-rag-lite`?
|
|
67
|
+
|
|
68
|
+
- **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.
|
|
69
|
+
- **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.
|
|
70
|
+
- **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.
|
|
71
|
+
|
|
72
|
+
| Capability | `offline-rag-lite` | Heavy WASM Vector DBs | Vector-Only Python Libraries | Cloud Vector Databases |
|
|
73
|
+
| --- | --- | --- | --- | --- |
|
|
74
|
+
| **Runtime Dependencies** | `0` (Python stdlib only) | Multi-MB WASM runtime | Native C/C++/Rust wheels | Managed SaaS + HTTP SDK |
|
|
75
|
+
| **Memory Footprint** | Very low (`array('b')` Int8 cuts vector RAM ~75%) | High | Moderate–High (`float32`) | Server-managed |
|
|
76
|
+
| **Offline Resilience** | 100% offline; auto-falls back to BM25 if `embed()` raises | Offline, heavy startup | Breaks without embedder | Requires internet |
|
|
77
|
+
| **Cross-Language Portability** | Shared `.rag` v1 binary (Python ↔ JS/IndexedDB) + SHA-256 | Engine-specific dumps | Pickle/format locked | API-bound |
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
81
|
+
## How It Works Under the Hood
|
|
82
|
+
|
|
83
|
+
- **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`).
|
|
84
|
+
- **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.
|
|
85
|
+
- **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.
|
|
86
|
+
- **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>`.
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## Quick Start & End-to-End Recipes
|
|
91
|
+
|
|
92
|
+
### Recipe 1: Build & Export `knowledge.rag` with `SQLiteStorage`
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from pathlib import Path
|
|
96
|
+
from offline_rag_lite import OfflineRag, SQLiteStorage
|
|
97
|
+
|
|
98
|
+
def my_embedder(texts: list[str]) -> list[list[float]]:
|
|
99
|
+
# Connect any embedding provider or local model
|
|
100
|
+
return [embed_text(t) for t in texts]
|
|
101
|
+
|
|
102
|
+
rag = OfflineRag(
|
|
103
|
+
storage=SQLiteStorage("knowledge.sqlite3"),
|
|
104
|
+
embed=my_embedder,
|
|
105
|
+
chunk_size=512,
|
|
106
|
+
overlap=64,
|
|
107
|
+
quantization="int8",
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
rag.add_documents([
|
|
111
|
+
{
|
|
112
|
+
"id": "faq-1",
|
|
113
|
+
"namespace": "support",
|
|
114
|
+
"text": "Error code ERR-404 indicates the offline snapshot file must be refreshed.",
|
|
115
|
+
"metadata": {"source": "faq.md"},
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
"id": "sync-1",
|
|
119
|
+
"namespace": "support",
|
|
120
|
+
"text": "Mobile PWAs hydrate .rag snapshots into IndexedDB inside a Web Worker.",
|
|
121
|
+
"metadata": {"source": "pwa.md"},
|
|
122
|
+
},
|
|
123
|
+
])
|
|
124
|
+
|
|
125
|
+
# Query locally and build token-budgeted chat context
|
|
126
|
+
ctx = rag.build_chat_context(
|
|
127
|
+
"ERR-404 snapshot refresh",
|
|
128
|
+
namespace="support",
|
|
129
|
+
top_k=5,
|
|
130
|
+
max_tokens=1500,
|
|
131
|
+
)
|
|
132
|
+
print(ctx.context)
|
|
133
|
+
|
|
134
|
+
# Export portable .rag binary snapshot for browser/mobile clients
|
|
135
|
+
Path("knowledge.rag").write_bytes(rag.export_snapshot(namespace="support"))
|
|
136
|
+
rag.destroy(wipe_storage=False)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Recipe 2: Hydrate `knowledge.rag` in a Mobile Browser (npm Companion)
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
import { createOfflineRag, IndexedDBStorage } from 'offline-rag-lite';
|
|
143
|
+
|
|
144
|
+
const rag = createOfflineRag({
|
|
145
|
+
storage: new IndexedDBStorage({ dbName: 'support-kb' }),
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
const bytes = new Uint8Array(await (await fetch('/assets/knowledge.rag')).arrayBuffer());
|
|
149
|
+
await rag.importSnapshot(bytes, { replace: true });
|
|
150
|
+
|
|
151
|
+
const { context } = await rag.buildChatContext('ERR-404', { namespace: 'support' });
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
### Recipe 3: Offline BM25-Only Mode (No Embedder Required)
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
from offline_rag_lite import OfflineRag, MemoryStorage
|
|
158
|
+
|
|
159
|
+
rag = OfflineRag(storage=MemoryStorage()) # embed=None -> pure BM25 lexical mode
|
|
160
|
+
rag.add_documents([
|
|
161
|
+
{"id": "ticket-9", "text": "Flight confirmation ZX-9918 departs at 08:30."},
|
|
162
|
+
])
|
|
163
|
+
hits = rag.search("ZX-9918", top_k=3)
|
|
164
|
+
print(hits[0].id, hits[0].bm25_score)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
## Complete API Reference
|
|
170
|
+
|
|
171
|
+
### `OfflineRag(...)` Constructor
|
|
172
|
+
|
|
173
|
+
| Name | Type | Default | Description |
|
|
174
|
+
| --- | --- | --- | --- |
|
|
175
|
+
| `storage` | `Optional[StorageAdapter]` | `MemoryStorage()` | Backing store (`MemoryStorage` or `SQLiteStorage`) |
|
|
176
|
+
| `embed` | `Optional[EmbedFunction]` | `None` | External `Callable[[List[str]], Sequence[Sequence[float]]]` callback |
|
|
177
|
+
| `chunk_size` | `int` | `512` | Maximum characters per chunk in `add_documents()` |
|
|
178
|
+
| `overlap` | `int` | `64` | Character overlap between adjacent chunks |
|
|
179
|
+
| `quantization` | `str` | `"int8"` | Quantization mode (`"int8"` or `"float32"`) |
|
|
180
|
+
| `max_cache_entries` | `int` | `100` | Bounded LRU query cache size (`0` disables caching) |
|
|
181
|
+
| `default_namespace` | `str` | `"default"` | Default namespace when omitted |
|
|
182
|
+
| `fallback_to_lexical` | `bool` | `True` | Fall back to BM25 lexical search if `embed()` raises |
|
|
183
|
+
|
|
184
|
+
### `OfflineRag` Methods
|
|
185
|
+
|
|
186
|
+
| Name | Type | Default | Description |
|
|
187
|
+
| --- | --- | --- | --- |
|
|
188
|
+
| `add_documents(docs)` | `(docs: Sequence[Dict[str, Any]]) -> List[str]` | — | Chunks, tokenizes, optionally embeds, and upserts documents |
|
|
189
|
+
| `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` |
|
|
190
|
+
| `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>` |
|
|
191
|
+
| `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 |
|
|
192
|
+
| `import_snapshot(data, replace=False)` | `(data: bytes \| bytearray \| memoryview, replace=False) -> int` | `replace=False` | Verifies SHA-256 checksum and imports chunks |
|
|
193
|
+
| `clear_cache()` | `() -> None` | — | Clears the bounded LRU query cache |
|
|
194
|
+
| `delete_namespace(namespace)` | `(namespace: str) -> int` | — | Deletes all chunks in `namespace` and invalidates cache |
|
|
195
|
+
| `count(namespace=None)` | `(namespace: Optional[str] = None) -> int` | all namespaces | Returns stored chunk count |
|
|
196
|
+
| `destroy(wipe_storage=False)` | `(wipe_storage: bool = False) -> None` | `wipe_storage=False` | Zeroes tracked Int8 `array('b')` buffers, clears cache, optionally deletes SQLite file |
|
|
197
|
+
|
|
198
|
+
### Storage Adapters & Standalone Helpers
|
|
199
|
+
|
|
200
|
+
| Name | Type | Default | Description |
|
|
201
|
+
| --- | --- | --- | --- |
|
|
202
|
+
| `MemoryStorage()` | `StorageAdapter` | — | In-memory store with Int8 buffer zeroing on `destroy()` |
|
|
203
|
+
| `SQLiteStorage(path=":memory:", use_fts5=True)` | `StorageAdapter` | `":memory:"`, `use_fts5=True` | SQLite persistence with `FTS5` BM25 auto-detection and pure-Python fallback |
|
|
204
|
+
| `chunk_text(text, chunk_size=512, overlap=64)` | `(str, int, int) -> List[str]` | `512`, `64` | Sentence/paragraph-aware Markdown/text chunker |
|
|
205
|
+
| `build_chat_context(results, ...)` | `(Sequence[SearchResult], ...) -> ChatContextResult` | `max_tokens=1500` | Standalone token-budgeted, deduplicated context formatter |
|
|
206
|
+
| `encode_snapshot(chunks, quantization="int8")` | `(Sequence[StoredChunk], str) -> bytes` | `"int8"` | Low-level `.rag` v1 binary encoder |
|
|
207
|
+
| `decode_snapshot(data)` | `(bytes \| bytearray \| memoryview) -> DecodedSnapshot` | — | Low-level `.rag` v1 decoder with SHA-256 verification (`SnapshotError`) |
|
|
208
|
+
| `quantize_int8` / `dequantize_int8` | `(Sequence[float]) -> Tuple[array, float]` | — | Symmetric Int8 quantization and reconstruction |
|
|
209
|
+
| `cosine_similarity_int8` / `dot_product_int8` | `(Sequence[int], ...) -> float` | — | Fast Int8 cosine similarity and scaled dot product |
|
|
210
|
+
| `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 |
|
|
211
|
+
|
|
212
|
+
---
|
|
213
|
+
|
|
214
|
+
## When NOT to Use (Non-Goals)
|
|
215
|
+
|
|
216
|
+
- **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.
|
|
217
|
+
- **Bundled ML embedding weights:** Keeps zero runtime dependencies by delegating embeddings to your own `embed()` callback.
|
|
218
|
+
- **Multi-writer cloud replication:** Built for single-device SQLite persistence and portable `.rag` snapshot distribution.
|
|
219
|
+
|
|
220
|
+
## License
|
|
221
|
+
|
|
222
|
+
MIT © [Kotcherla Murali Krishna](https://github.com/mkkotcherla)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "offline-rag-lite"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Zero-runtime-dependency hybrid BM25 + Int8 vector RAG engine for offline mobile chat, PWAs, and local-first apps with portable .rag snapshots."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Kotcherla Murali Krishna" }
|
|
14
|
+
]
|
|
15
|
+
keywords = [
|
|
16
|
+
"rag",
|
|
17
|
+
"offline",
|
|
18
|
+
"bm25",
|
|
19
|
+
"vector-search",
|
|
20
|
+
"int8",
|
|
21
|
+
"quantization",
|
|
22
|
+
"rrf",
|
|
23
|
+
"sqlite",
|
|
24
|
+
"local-first",
|
|
25
|
+
"zero-dependency",
|
|
26
|
+
]
|
|
27
|
+
classifiers = [
|
|
28
|
+
"Development Status :: 4 - Beta",
|
|
29
|
+
"Intended Audience :: Developers",
|
|
30
|
+
"License :: OSI Approved :: MIT License",
|
|
31
|
+
"Operating System :: OS Independent",
|
|
32
|
+
"Programming Language :: Python :: 3",
|
|
33
|
+
"Programming Language :: Python :: 3.9",
|
|
34
|
+
"Programming Language :: Python :: 3.10",
|
|
35
|
+
"Programming Language :: Python :: 3.11",
|
|
36
|
+
"Programming Language :: Python :: 3.12",
|
|
37
|
+
"Programming Language :: Python :: 3.13",
|
|
38
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
39
|
+
"Topic :: Text Processing :: Indexing",
|
|
40
|
+
]
|
|
41
|
+
dependencies = []
|
|
42
|
+
|
|
43
|
+
[project.urls]
|
|
44
|
+
Homepage = "https://github.com/mkkotcherla/offline-rag-lite"
|
|
45
|
+
Repository = "https://github.com/mkkotcherla/offline-rag-lite"
|
|
46
|
+
Issues = "https://github.com/mkkotcherla/offline-rag-lite/issues"
|
|
47
|
+
|
|
48
|
+
[tool.setuptools]
|
|
49
|
+
package-dir = { "" = "src" }
|
|
50
|
+
|
|
51
|
+
[tool.setuptools.packages.find]
|
|
52
|
+
where = ["src"]
|
|
53
|
+
|
|
54
|
+
[tool.setuptools.package-data]
|
|
55
|
+
offline_rag_lite = ["py.typed"]
|
|
56
|
+
|
|
57
|
+
[tool.pytest.ini_options]
|
|
58
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""offline-rag-lite: Zero-dependency hybrid BM25 + Int8 vector RAG engine."""
|
|
2
|
+
|
|
3
|
+
from .bm25 import score_bm25, tokenize
|
|
4
|
+
from .chunker import chunk_text
|
|
5
|
+
from .context import build_chat_context
|
|
6
|
+
from .engine import OfflineRag
|
|
7
|
+
from .quantize import (
|
|
8
|
+
cosine_similarity_float32,
|
|
9
|
+
cosine_similarity_int8,
|
|
10
|
+
dequantize_int8,
|
|
11
|
+
dot_product_int8,
|
|
12
|
+
quantize_int8,
|
|
13
|
+
)
|
|
14
|
+
from .snapshot import (
|
|
15
|
+
QUANT_FLOAT32,
|
|
16
|
+
QUANT_INT8,
|
|
17
|
+
SNAPSHOT_HEADER_BYTES,
|
|
18
|
+
SNAPSHOT_MAGIC,
|
|
19
|
+
SNAPSHOT_VERSION,
|
|
20
|
+
DecodedSnapshot,
|
|
21
|
+
SnapshotError,
|
|
22
|
+
decode_snapshot,
|
|
23
|
+
encode_snapshot,
|
|
24
|
+
)
|
|
25
|
+
from .storage import MemoryStorage, SQLiteStorage, StorageAdapter
|
|
26
|
+
from .types import ChatContextResult, EmbedFunction, SearchResult, StoredChunk
|
|
27
|
+
|
|
28
|
+
__version__ = "0.1.0"
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"OfflineRag",
|
|
32
|
+
"chunk_text",
|
|
33
|
+
"build_chat_context",
|
|
34
|
+
"MemoryStorage",
|
|
35
|
+
"SQLiteStorage",
|
|
36
|
+
"StorageAdapter",
|
|
37
|
+
"encode_snapshot",
|
|
38
|
+
"decode_snapshot",
|
|
39
|
+
"DecodedSnapshot",
|
|
40
|
+
"SnapshotError",
|
|
41
|
+
"SNAPSHOT_MAGIC",
|
|
42
|
+
"SNAPSHOT_VERSION",
|
|
43
|
+
"SNAPSHOT_HEADER_BYTES",
|
|
44
|
+
"QUANT_FLOAT32",
|
|
45
|
+
"QUANT_INT8",
|
|
46
|
+
"quantize_int8",
|
|
47
|
+
"dequantize_int8",
|
|
48
|
+
"dot_product_int8",
|
|
49
|
+
"cosine_similarity_int8",
|
|
50
|
+
"cosine_similarity_float32",
|
|
51
|
+
"tokenize",
|
|
52
|
+
"score_bm25",
|
|
53
|
+
"StoredChunk",
|
|
54
|
+
"SearchResult",
|
|
55
|
+
"ChatContextResult",
|
|
56
|
+
"EmbedFunction",
|
|
57
|
+
"__version__",
|
|
58
|
+
]
|