offline-rag-lite 0.1.0__py3-none-any.whl
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/__init__.py +58 -0
- offline_rag_lite/bm25.py +74 -0
- offline_rag_lite/chunker.py +116 -0
- offline_rag_lite/context.py +112 -0
- offline_rag_lite/engine.py +341 -0
- offline_rag_lite/py.typed +0 -0
- offline_rag_lite/quantize.py +90 -0
- offline_rag_lite/snapshot.py +228 -0
- offline_rag_lite/storage.py +267 -0
- offline_rag_lite/types.py +38 -0
- offline_rag_lite-0.1.0.dist-info/LICENSE +21 -0
- offline_rag_lite-0.1.0.dist-info/METADATA +248 -0
- offline_rag_lite-0.1.0.dist-info/RECORD +15 -0
- offline_rag_lite-0.1.0.dist-info/WHEEL +5 -0
- offline_rag_lite-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -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
|
+
]
|
offline_rag_lite/bm25.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import re
|
|
5
|
+
from typing import Dict, List, Sequence, Tuple
|
|
6
|
+
|
|
7
|
+
# Matches Unicode word/digit sequences including hyphen/underscore identifiers (e.g. ERR-404, SKU_123)
|
|
8
|
+
_TOKEN_RE = re.compile(r"[^\W_]+(?:[-_][^\W_]+)*", re.UNICODE)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def tokenize(text: str) -> List[str]:
|
|
12
|
+
"""Tokenize text while preserving exact codes, IDs, and their sub-parts."""
|
|
13
|
+
matches = _TOKEN_RE.findall(text.lower())
|
|
14
|
+
if not matches:
|
|
15
|
+
return []
|
|
16
|
+
|
|
17
|
+
tokens: List[str] = []
|
|
18
|
+
for m in matches:
|
|
19
|
+
tokens.append(m)
|
|
20
|
+
if "-" in m or "_" in m:
|
|
21
|
+
parts = [p for p in re.split(r"[-_]+", m) if p]
|
|
22
|
+
if len(parts) > 1:
|
|
23
|
+
tokens.extend(parts)
|
|
24
|
+
return tokens
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def score_bm25(
|
|
28
|
+
query: str,
|
|
29
|
+
docs: Sequence[Tuple[str, Sequence[str]]],
|
|
30
|
+
k1: float = 1.5,
|
|
31
|
+
b: float = 0.75,
|
|
32
|
+
) -> Dict[str, float]:
|
|
33
|
+
"""Compute Okapi BM25 scores for a query against tokenized documents."""
|
|
34
|
+
scores: Dict[str, float] = {}
|
|
35
|
+
query_tokens = tokenize(query)
|
|
36
|
+
if not query_tokens or not docs:
|
|
37
|
+
return scores
|
|
38
|
+
|
|
39
|
+
unique_query_tokens = list(dict.fromkeys(query_tokens))
|
|
40
|
+
n_docs = len(docs)
|
|
41
|
+
|
|
42
|
+
total_len = 0
|
|
43
|
+
doc_freq: Dict[str, int] = {}
|
|
44
|
+
for _, tokens in docs:
|
|
45
|
+
total_len += len(tokens)
|
|
46
|
+
for tok in set(tokens):
|
|
47
|
+
doc_freq[tok] = doc_freq.get(tok, 0) + 1
|
|
48
|
+
|
|
49
|
+
avgdl = (total_len / n_docs) if total_len > 0 else 1.0
|
|
50
|
+
|
|
51
|
+
for doc_id, tokens in docs:
|
|
52
|
+
dl = len(tokens)
|
|
53
|
+
if dl == 0:
|
|
54
|
+
continue
|
|
55
|
+
|
|
56
|
+
tf: Dict[str, int] = {}
|
|
57
|
+
for tok in tokens:
|
|
58
|
+
tf[tok] = tf.get(tok, 0) + 1
|
|
59
|
+
|
|
60
|
+
score = 0.0
|
|
61
|
+
for q_tok in unique_query_tokens:
|
|
62
|
+
freq = tf.get(q_tok, 0)
|
|
63
|
+
if freq == 0:
|
|
64
|
+
continue
|
|
65
|
+
df = doc_freq.get(q_tok, 0)
|
|
66
|
+
idf = math.log(1.0 + (n_docs - df + 0.5) / (df + 0.5))
|
|
67
|
+
numerator = freq * (k1 + 1.0)
|
|
68
|
+
denominator = freq + k1 * (1.0 - b + b * (dl / avgdl))
|
|
69
|
+
score += idf * (numerator / denominator)
|
|
70
|
+
|
|
71
|
+
if score > 0.0:
|
|
72
|
+
scores[doc_id] = score
|
|
73
|
+
|
|
74
|
+
return scores
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import List
|
|
5
|
+
|
|
6
|
+
DEFAULT_CHUNK_SIZE = 512
|
|
7
|
+
DEFAULT_OVERLAP = 64
|
|
8
|
+
|
|
9
|
+
_SENTENCE_SPLIT_RE = re.compile(r"(?<=[.!?])\s+|\n+")
|
|
10
|
+
_PARAGRAPH_SPLIT_RE = re.compile(r"\n{2,}")
|
|
11
|
+
_WHITESPACE_RE = re.compile(r"\s+")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def chunk_text(
|
|
15
|
+
text: str,
|
|
16
|
+
chunk_size: int = DEFAULT_CHUNK_SIZE,
|
|
17
|
+
overlap: int = DEFAULT_OVERLAP,
|
|
18
|
+
) -> List[str]:
|
|
19
|
+
"""Split text or Markdown into sentence- and paragraph-aware chunks without breaking words."""
|
|
20
|
+
if chunk_size <= 0:
|
|
21
|
+
raise ValueError("chunk_size must be a positive integer")
|
|
22
|
+
if overlap < 0 or overlap >= chunk_size:
|
|
23
|
+
raise ValueError("overlap must be >= 0 and < chunk_size")
|
|
24
|
+
|
|
25
|
+
normalized = text.replace("\r\n", "\n").strip()
|
|
26
|
+
if not normalized:
|
|
27
|
+
return []
|
|
28
|
+
if len(normalized) <= chunk_size:
|
|
29
|
+
return [normalized]
|
|
30
|
+
|
|
31
|
+
units = _split_into_units(normalized, chunk_size)
|
|
32
|
+
chunks: List[str] = []
|
|
33
|
+
current = ""
|
|
34
|
+
|
|
35
|
+
for unit in units:
|
|
36
|
+
candidate = _join_units(current, unit) if current else unit
|
|
37
|
+
if len(candidate) <= chunk_size:
|
|
38
|
+
current = candidate
|
|
39
|
+
continue
|
|
40
|
+
|
|
41
|
+
if current:
|
|
42
|
+
chunks.append(current.strip())
|
|
43
|
+
|
|
44
|
+
tail = _extract_overlap_tail(current, overlap) if overlap > 0 and current else ""
|
|
45
|
+
with_overlap = _join_units(tail, unit) if tail else unit
|
|
46
|
+
|
|
47
|
+
if len(with_overlap) <= chunk_size:
|
|
48
|
+
current = with_overlap
|
|
49
|
+
else:
|
|
50
|
+
current = unit
|
|
51
|
+
|
|
52
|
+
if current.strip():
|
|
53
|
+
chunks.append(current.strip())
|
|
54
|
+
|
|
55
|
+
return chunks
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _join_units(a: str, b: str) -> str:
|
|
59
|
+
if a.endswith("\n") or b.startswith("\n"):
|
|
60
|
+
return a + b
|
|
61
|
+
return f"{a} {b}"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _split_into_units(text: str, max_len: int) -> List[str]:
|
|
65
|
+
units: List[str] = []
|
|
66
|
+
paragraphs = _PARAGRAPH_SPLIT_RE.split(text)
|
|
67
|
+
|
|
68
|
+
for raw_para in paragraphs:
|
|
69
|
+
para = raw_para.strip()
|
|
70
|
+
if not para:
|
|
71
|
+
continue
|
|
72
|
+
if len(para) <= max_len:
|
|
73
|
+
units.append(para)
|
|
74
|
+
continue
|
|
75
|
+
|
|
76
|
+
sentences = [s.strip() for s in _SENTENCE_SPLIT_RE.split(para) if s.strip()]
|
|
77
|
+
for sentence in sentences:
|
|
78
|
+
if len(sentence) <= max_len:
|
|
79
|
+
units.append(sentence)
|
|
80
|
+
else:
|
|
81
|
+
units.extend(_split_by_words(sentence, max_len))
|
|
82
|
+
|
|
83
|
+
return units
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _split_by_words(text: str, max_len: int) -> List[str]:
|
|
87
|
+
words = [w for w in _WHITESPACE_RE.split(text) if w]
|
|
88
|
+
segments: List[str] = []
|
|
89
|
+
buf = ""
|
|
90
|
+
|
|
91
|
+
for word in words:
|
|
92
|
+
if not buf:
|
|
93
|
+
buf = word
|
|
94
|
+
continue
|
|
95
|
+
if len(buf) + 1 + len(word) <= max_len:
|
|
96
|
+
buf = f"{buf} {word}"
|
|
97
|
+
else:
|
|
98
|
+
segments.append(buf)
|
|
99
|
+
buf = word
|
|
100
|
+
|
|
101
|
+
if buf:
|
|
102
|
+
segments.append(buf)
|
|
103
|
+
return segments
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _extract_overlap_tail(text: str, overlap: int) -> str:
|
|
107
|
+
if overlap <= 0 or len(text) <= overlap:
|
|
108
|
+
return text.strip()
|
|
109
|
+
start = len(text) - overlap
|
|
110
|
+
slice_text = text[start:]
|
|
111
|
+
if start > 0 and text[start - 1].isspace():
|
|
112
|
+
return slice_text.strip()
|
|
113
|
+
match = re.search(r"\s", slice_text)
|
|
114
|
+
if not match:
|
|
115
|
+
return ""
|
|
116
|
+
return slice_text[match.start() + 1 :].strip()
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import re
|
|
5
|
+
from typing import Callable, List, Optional, Sequence
|
|
6
|
+
|
|
7
|
+
from .types import ChatContextResult, SearchResult
|
|
8
|
+
|
|
9
|
+
DEFAULT_MAX_TOKENS = 1500
|
|
10
|
+
DEFAULT_SEPARATOR = "\n\n---\n\n"
|
|
11
|
+
DEFAULT_TAG_NAME = "retrieved_context"
|
|
12
|
+
|
|
13
|
+
_WS_RE = re.compile(r"\s+")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _default_estimate_tokens(text: str) -> int:
|
|
17
|
+
return math.ceil(len(text) / 4)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _normalize_for_dedup(text: str) -> str:
|
|
21
|
+
return _WS_RE.sub(" ", text.lower()).strip()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _is_duplicate_or_heavily_overlapping(candidate: str, existing: Sequence[str]) -> bool:
|
|
25
|
+
norm_cand = _normalize_for_dedup(candidate)
|
|
26
|
+
if not norm_cand:
|
|
27
|
+
return True
|
|
28
|
+
|
|
29
|
+
cand_words = set(norm_cand.split(" "))
|
|
30
|
+
for prev in existing:
|
|
31
|
+
norm_prev = _normalize_for_dedup(prev)
|
|
32
|
+
if norm_cand == norm_prev or norm_cand in norm_prev:
|
|
33
|
+
return True
|
|
34
|
+
prev_words = set(norm_prev.split(" "))
|
|
35
|
+
union = len(cand_words | prev_words)
|
|
36
|
+
if union > 0 and (len(cand_words & prev_words) / union) >= 0.85:
|
|
37
|
+
return True
|
|
38
|
+
return False
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _trim_leading_overlap(
|
|
42
|
+
text: str, previous_texts: Sequence[str], min_overlap_chars: int = 24
|
|
43
|
+
) -> str:
|
|
44
|
+
for prev in previous_texts:
|
|
45
|
+
max_check = min(len(prev), len(text), 256)
|
|
46
|
+
for overlap_len in range(max_check, min_overlap_chars - 1, -1):
|
|
47
|
+
if prev.endswith(text[:overlap_len]):
|
|
48
|
+
trimmed = text[overlap_len:].lstrip()
|
|
49
|
+
if trimmed:
|
|
50
|
+
return trimmed
|
|
51
|
+
return text
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _sanitize_boundary_tag(text: str, tag_name: str) -> str:
|
|
55
|
+
pattern = re.compile(rf"</{re.escape(tag_name)}>", re.IGNORECASE)
|
|
56
|
+
return pattern.sub(f"<\\/{tag_name}>", text)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def build_chat_context(
|
|
60
|
+
results: Sequence[SearchResult],
|
|
61
|
+
max_tokens: int = DEFAULT_MAX_TOKENS,
|
|
62
|
+
estimate_tokens: Optional[Callable[[str], int]] = None,
|
|
63
|
+
separator: str = DEFAULT_SEPARATOR,
|
|
64
|
+
tag_name: str = DEFAULT_TAG_NAME,
|
|
65
|
+
) -> ChatContextResult:
|
|
66
|
+
"""Select top-K chunks within a token budget, deduplicate overlaps, and wrap in boundary tags."""
|
|
67
|
+
estimator = estimate_tokens or _default_estimate_tokens
|
|
68
|
+
open_tag = f"<{tag_name}>"
|
|
69
|
+
close_tag = f"</{tag_name}>"
|
|
70
|
+
wrapper_tokens = estimator(f"{open_tag}\n\n{close_tag}")
|
|
71
|
+
sep_tokens = estimator(separator)
|
|
72
|
+
|
|
73
|
+
selected: List[SearchResult] = []
|
|
74
|
+
selected_texts: List[str] = []
|
|
75
|
+
used_tokens = wrapper_tokens
|
|
76
|
+
truncated = False
|
|
77
|
+
|
|
78
|
+
for result in results:
|
|
79
|
+
safe_raw = _sanitize_boundary_tag(result.text, tag_name)
|
|
80
|
+
if _is_duplicate_or_heavily_overlapping(safe_raw, selected_texts):
|
|
81
|
+
continue
|
|
82
|
+
|
|
83
|
+
safe_text = _trim_leading_overlap(safe_raw, selected_texts)
|
|
84
|
+
chunk_tokens = estimator(safe_text) + (sep_tokens if selected else 0)
|
|
85
|
+
|
|
86
|
+
if used_tokens + chunk_tokens > max_tokens:
|
|
87
|
+
truncated = True
|
|
88
|
+
continue
|
|
89
|
+
|
|
90
|
+
used_tokens += chunk_tokens
|
|
91
|
+
selected.append(
|
|
92
|
+
SearchResult(
|
|
93
|
+
id=result.id,
|
|
94
|
+
namespace=result.namespace,
|
|
95
|
+
text=safe_text,
|
|
96
|
+
metadata=result.metadata,
|
|
97
|
+
score=result.score,
|
|
98
|
+
bm25_score=result.bm25_score,
|
|
99
|
+
vector_score=result.vector_score,
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
selected_texts.append(safe_text)
|
|
103
|
+
|
|
104
|
+
body = separator.join(selected_texts)
|
|
105
|
+
context = f"{open_tag}\n{body}\n{close_tag}" if body else f"{open_tag}{close_tag}"
|
|
106
|
+
|
|
107
|
+
return ChatContextResult(
|
|
108
|
+
context=context,
|
|
109
|
+
chunks=selected,
|
|
110
|
+
estimated_tokens=used_tokens if body else estimator(context),
|
|
111
|
+
truncated=truncated,
|
|
112
|
+
)
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import uuid
|
|
5
|
+
from array import array
|
|
6
|
+
from collections import OrderedDict
|
|
7
|
+
from typing import Any, Callable, Dict, List, Optional, Sequence
|
|
8
|
+
|
|
9
|
+
from .bm25 import score_bm25, tokenize
|
|
10
|
+
from .chunker import DEFAULT_CHUNK_SIZE, DEFAULT_OVERLAP, chunk_text
|
|
11
|
+
from .context import (
|
|
12
|
+
DEFAULT_MAX_TOKENS,
|
|
13
|
+
DEFAULT_SEPARATOR,
|
|
14
|
+
DEFAULT_TAG_NAME,
|
|
15
|
+
build_chat_context,
|
|
16
|
+
)
|
|
17
|
+
from .quantize import cosine_similarity_float32, cosine_similarity_int8, quantize_int8
|
|
18
|
+
from .snapshot import decode_snapshot, encode_snapshot
|
|
19
|
+
from .storage import MemoryStorage, StorageAdapter
|
|
20
|
+
from .types import ChatContextResult, EmbedFunction, SearchResult, StoredChunk
|
|
21
|
+
|
|
22
|
+
DEFAULT_RRF_K = 60
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _LRUCache:
|
|
26
|
+
def __init__(self, max_entries: int = 100) -> None:
|
|
27
|
+
self._max_entries = max(0, max_entries)
|
|
28
|
+
self._data: OrderedDict[str, List[SearchResult]] = OrderedDict()
|
|
29
|
+
|
|
30
|
+
def get(self, key: str) -> Optional[List[SearchResult]]:
|
|
31
|
+
if self._max_entries == 0 or key not in self._data:
|
|
32
|
+
return None
|
|
33
|
+
self._data.move_to_end(key)
|
|
34
|
+
return self._data[key]
|
|
35
|
+
|
|
36
|
+
def set(self, key: str, value: List[SearchResult]) -> None:
|
|
37
|
+
if self._max_entries == 0:
|
|
38
|
+
return
|
|
39
|
+
if key in self._data:
|
|
40
|
+
self._data.move_to_end(key)
|
|
41
|
+
elif len(self._data) >= self._max_entries:
|
|
42
|
+
self._data.popitem(last=False)
|
|
43
|
+
self._data[key] = value
|
|
44
|
+
|
|
45
|
+
def clear(self) -> None:
|
|
46
|
+
self._data.clear()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _matches_filter(metadata: Dict[str, Any], flt: Optional[Dict[str, Any]]) -> bool:
|
|
50
|
+
if not flt:
|
|
51
|
+
return True
|
|
52
|
+
for k, expected in flt.items():
|
|
53
|
+
if metadata.get(k) != expected:
|
|
54
|
+
return False
|
|
55
|
+
return True
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class OfflineRag:
|
|
59
|
+
"""Zero-dependency hybrid BM25 + Int8 vector RAG engine."""
|
|
60
|
+
|
|
61
|
+
def __init__(
|
|
62
|
+
self,
|
|
63
|
+
storage: Optional[StorageAdapter] = None,
|
|
64
|
+
embed: Optional[EmbedFunction] = None,
|
|
65
|
+
chunk_size: int = DEFAULT_CHUNK_SIZE,
|
|
66
|
+
overlap: int = DEFAULT_OVERLAP,
|
|
67
|
+
quantization: str = "int8",
|
|
68
|
+
max_cache_entries: int = 100,
|
|
69
|
+
default_namespace: str = "default",
|
|
70
|
+
fallback_to_lexical: bool = True,
|
|
71
|
+
) -> None:
|
|
72
|
+
if quantization not in ("int8", "float32"):
|
|
73
|
+
raise ValueError(f"Unsupported quantization mode: {quantization}")
|
|
74
|
+
self._storage: StorageAdapter = storage if storage is not None else MemoryStorage()
|
|
75
|
+
self._embed = embed
|
|
76
|
+
self._chunk_size = chunk_size
|
|
77
|
+
self._overlap = overlap
|
|
78
|
+
self._quantization = quantization
|
|
79
|
+
self._default_namespace = default_namespace
|
|
80
|
+
self._fallback_to_lexical = fallback_to_lexical
|
|
81
|
+
self._cache = _LRUCache(max_cache_entries)
|
|
82
|
+
self._tracked_int8: List[array] = []
|
|
83
|
+
self._destroyed = False
|
|
84
|
+
|
|
85
|
+
def _assert_alive(self) -> None:
|
|
86
|
+
if self._destroyed:
|
|
87
|
+
raise RuntimeError("OfflineRag instance has been destroyed")
|
|
88
|
+
|
|
89
|
+
def _try_embed(self, texts: List[str]) -> Optional[Sequence[Sequence[float]]]:
|
|
90
|
+
if self._embed is None or not texts:
|
|
91
|
+
return None
|
|
92
|
+
try:
|
|
93
|
+
return self._embed(texts)
|
|
94
|
+
except Exception:
|
|
95
|
+
if self._fallback_to_lexical:
|
|
96
|
+
return None
|
|
97
|
+
raise
|
|
98
|
+
|
|
99
|
+
def add_documents(self, docs: Sequence[Dict[str, Any]]) -> List[str]:
|
|
100
|
+
"""Chunk, tokenize, optionally embed, and store documents."""
|
|
101
|
+
self._assert_alive()
|
|
102
|
+
if not docs:
|
|
103
|
+
return []
|
|
104
|
+
|
|
105
|
+
pending: List[Dict[str, Any]] = []
|
|
106
|
+
for idx, doc in enumerate(docs):
|
|
107
|
+
text = str(doc["text"])
|
|
108
|
+
ns = str(doc.get("namespace", self._default_namespace))
|
|
109
|
+
base_id = str(doc["id"]) if doc.get("id") else f"doc-{uuid.uuid4().hex[:8]}-{idx}"
|
|
110
|
+
base_meta = dict(doc.get("metadata") or {})
|
|
111
|
+
|
|
112
|
+
pieces = chunk_text(text, chunk_size=self._chunk_size, overlap=self._overlap)
|
|
113
|
+
for c_idx, piece in enumerate(pieces):
|
|
114
|
+
pending.append(
|
|
115
|
+
{
|
|
116
|
+
"id": base_id if len(pieces) == 1 else f"{base_id}#{c_idx}",
|
|
117
|
+
"namespace": ns,
|
|
118
|
+
"text": piece,
|
|
119
|
+
"metadata": {
|
|
120
|
+
**base_meta,
|
|
121
|
+
"sourceId": base_id,
|
|
122
|
+
"chunkIndex": c_idx,
|
|
123
|
+
"chunkCount": len(pieces),
|
|
124
|
+
},
|
|
125
|
+
}
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
if not pending:
|
|
129
|
+
return []
|
|
130
|
+
|
|
131
|
+
vectors = self._try_embed([p["text"] for p in pending])
|
|
132
|
+
stored: List[StoredChunk] = []
|
|
133
|
+
|
|
134
|
+
for idx, p in enumerate(pending):
|
|
135
|
+
chunk = StoredChunk(
|
|
136
|
+
id=p["id"],
|
|
137
|
+
namespace=p["namespace"],
|
|
138
|
+
text=p["text"],
|
|
139
|
+
metadata=p["metadata"],
|
|
140
|
+
bm25_tokens=tokenize(p["text"]),
|
|
141
|
+
)
|
|
142
|
+
if vectors is not None and idx < len(vectors) and len(vectors[idx]) > 0:
|
|
143
|
+
vec = vectors[idx]
|
|
144
|
+
if self._quantization == "int8":
|
|
145
|
+
q_vec, scale = quantize_int8(vec)
|
|
146
|
+
self._tracked_int8.append(q_vec)
|
|
147
|
+
chunk.vector_int8 = q_vec
|
|
148
|
+
chunk.vector_scale = scale
|
|
149
|
+
else:
|
|
150
|
+
chunk.vector_float32 = array("f", vec)
|
|
151
|
+
stored.append(chunk)
|
|
152
|
+
|
|
153
|
+
self._storage.upsert(stored)
|
|
154
|
+
self._cache.clear()
|
|
155
|
+
return [c.id for c in stored]
|
|
156
|
+
|
|
157
|
+
def search(
|
|
158
|
+
self,
|
|
159
|
+
query: str,
|
|
160
|
+
top_k: int = 5,
|
|
161
|
+
namespace: Optional[str] = None,
|
|
162
|
+
rrf_k: int = DEFAULT_RRF_K,
|
|
163
|
+
metadata_filter: Optional[Dict[str, Any]] = None,
|
|
164
|
+
mode: str = "hybrid",
|
|
165
|
+
) -> List[SearchResult]:
|
|
166
|
+
"""Run hybrid BM25 + Int8 vector RRF search strictly scoped to a namespace."""
|
|
167
|
+
self._assert_alive()
|
|
168
|
+
if top_k <= 0 or not query.strip():
|
|
169
|
+
return []
|
|
170
|
+
|
|
171
|
+
ns = namespace if namespace is not None else self._default_namespace
|
|
172
|
+
cache_key = json.dumps(
|
|
173
|
+
{
|
|
174
|
+
"query": query,
|
|
175
|
+
"top_k": top_k,
|
|
176
|
+
"namespace": ns,
|
|
177
|
+
"rrf_k": rrf_k,
|
|
178
|
+
"filter": metadata_filter,
|
|
179
|
+
"mode": mode,
|
|
180
|
+
},
|
|
181
|
+
sort_keys=True,
|
|
182
|
+
)
|
|
183
|
+
cached = self._cache.get(cache_key)
|
|
184
|
+
if cached is not None:
|
|
185
|
+
return list(cached)
|
|
186
|
+
|
|
187
|
+
all_in_ns = self._storage.get_all(ns)
|
|
188
|
+
candidates = (
|
|
189
|
+
[c for c in all_in_ns if _matches_filter(c.metadata, metadata_filter)]
|
|
190
|
+
if metadata_filter
|
|
191
|
+
else all_in_ns
|
|
192
|
+
)
|
|
193
|
+
if not candidates:
|
|
194
|
+
return []
|
|
195
|
+
|
|
196
|
+
candidate_ids = {c.id for c in candidates}
|
|
197
|
+
|
|
198
|
+
# 1. Lexical BM25 scoring (SQLite FTS5 if available, otherwise pure-Python BM25)
|
|
199
|
+
bm25_scores: Dict[str, float] = {}
|
|
200
|
+
if mode != "vector":
|
|
201
|
+
backend_scores = self._storage.lexical_search(query, ns)
|
|
202
|
+
if backend_scores is not None:
|
|
203
|
+
bm25_scores = {
|
|
204
|
+
cid: sc for cid, sc in backend_scores.items() if cid in candidate_ids
|
|
205
|
+
}
|
|
206
|
+
else:
|
|
207
|
+
bm25_scores = score_bm25(query, [(c.id, c.bm25_tokens) for c in candidates])
|
|
208
|
+
|
|
209
|
+
# 2. Vector similarity scoring (Int8 or Float32)
|
|
210
|
+
vector_scores: Dict[str, float] = {}
|
|
211
|
+
if mode != "lexical":
|
|
212
|
+
has_any_vectors = any(
|
|
213
|
+
(c.vector_int8 is not None and len(c.vector_int8) > 0)
|
|
214
|
+
or (c.vector_float32 is not None and len(c.vector_float32) > 0)
|
|
215
|
+
for c in candidates
|
|
216
|
+
)
|
|
217
|
+
if has_any_vectors:
|
|
218
|
+
embedded = self._try_embed([query])
|
|
219
|
+
if embedded is not None and len(embedded) > 0 and len(embedded[0]) > 0:
|
|
220
|
+
q_vec = embedded[0]
|
|
221
|
+
q_int8, _ = quantize_int8(q_vec)
|
|
222
|
+
q_f32 = array("f", q_vec)
|
|
223
|
+
for c in candidates:
|
|
224
|
+
if c.vector_int8 is not None and len(c.vector_int8) == len(q_int8):
|
|
225
|
+
vector_scores[c.id] = cosine_similarity_int8(q_int8, c.vector_int8)
|
|
226
|
+
elif c.vector_float32 is not None and len(c.vector_float32) == len(q_f32):
|
|
227
|
+
vector_scores[c.id] = cosine_similarity_float32(q_f32, c.vector_float32)
|
|
228
|
+
# Zero temporary query buffer
|
|
229
|
+
for i in range(len(q_int8)):
|
|
230
|
+
q_int8[i] = 0
|
|
231
|
+
|
|
232
|
+
# 3. Reciprocal Rank Fusion (RRF)
|
|
233
|
+
bm25_ranked = [cid for cid, _ in sorted(bm25_scores.items(), key=lambda kv: -kv[1])]
|
|
234
|
+
vector_ranked = [cid for cid, _ in sorted(vector_scores.items(), key=lambda kv: -kv[1])]
|
|
235
|
+
|
|
236
|
+
rrf_scores: Dict[str, float] = {}
|
|
237
|
+
if bm25_ranked and vector_ranked:
|
|
238
|
+
for rank, cid in enumerate(bm25_ranked, start=1):
|
|
239
|
+
rrf_scores[cid] = rrf_scores.get(cid, 0.0) + 1.0 / (rrf_k + rank)
|
|
240
|
+
for rank, cid in enumerate(vector_ranked, start=1):
|
|
241
|
+
rrf_scores[cid] = rrf_scores.get(cid, 0.0) + 1.0 / (rrf_k + rank)
|
|
242
|
+
elif bm25_ranked:
|
|
243
|
+
for rank, cid in enumerate(bm25_ranked, start=1):
|
|
244
|
+
rrf_scores[cid] = 1.0 / (rrf_k + rank)
|
|
245
|
+
elif vector_ranked:
|
|
246
|
+
for rank, cid in enumerate(vector_ranked, start=1):
|
|
247
|
+
rrf_scores[cid] = 1.0 / (rrf_k + rank)
|
|
248
|
+
else:
|
|
249
|
+
return []
|
|
250
|
+
|
|
251
|
+
by_id = {c.id: c for c in candidates}
|
|
252
|
+
ordered = sorted(
|
|
253
|
+
rrf_scores.items(),
|
|
254
|
+
key=lambda kv: (
|
|
255
|
+
-kv[1],
|
|
256
|
+
-(bm25_scores.get(kv[0], 0.0) + vector_scores.get(kv[0], 0.0)),
|
|
257
|
+
),
|
|
258
|
+
)[:top_k]
|
|
259
|
+
|
|
260
|
+
results = [
|
|
261
|
+
SearchResult(
|
|
262
|
+
id=by_id[cid].id,
|
|
263
|
+
namespace=by_id[cid].namespace,
|
|
264
|
+
text=by_id[cid].text,
|
|
265
|
+
metadata=by_id[cid].metadata,
|
|
266
|
+
score=score,
|
|
267
|
+
bm25_score=bm25_scores.get(cid, 0.0),
|
|
268
|
+
vector_score=vector_scores.get(cid, 0.0),
|
|
269
|
+
)
|
|
270
|
+
for cid, score in ordered
|
|
271
|
+
]
|
|
272
|
+
|
|
273
|
+
self._cache.set(cache_key, results)
|
|
274
|
+
return list(results)
|
|
275
|
+
|
|
276
|
+
def build_chat_context(
|
|
277
|
+
self,
|
|
278
|
+
query: str,
|
|
279
|
+
top_k: int = 5,
|
|
280
|
+
namespace: Optional[str] = None,
|
|
281
|
+
max_tokens: int = DEFAULT_MAX_TOKENS,
|
|
282
|
+
estimate_tokens: Optional[Callable[[str], int]] = None,
|
|
283
|
+
separator: str = DEFAULT_SEPARATOR,
|
|
284
|
+
tag_name: str = DEFAULT_TAG_NAME,
|
|
285
|
+
) -> ChatContextResult:
|
|
286
|
+
"""Search and wrap top-K deduplicated chunks into a token-budgeted <retrieved_context>."""
|
|
287
|
+
results = self.search(query=query, top_k=top_k, namespace=namespace)
|
|
288
|
+
return build_chat_context(
|
|
289
|
+
results,
|
|
290
|
+
max_tokens=max_tokens,
|
|
291
|
+
estimate_tokens=estimate_tokens,
|
|
292
|
+
separator=separator,
|
|
293
|
+
tag_name=tag_name,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
def export_snapshot(
|
|
297
|
+
self,
|
|
298
|
+
namespace: Optional[str] = None,
|
|
299
|
+
quantization: Optional[str] = None,
|
|
300
|
+
) -> bytes:
|
|
301
|
+
"""Export the index to a portable `.rag` binary snapshot."""
|
|
302
|
+
self._assert_alive()
|
|
303
|
+
chunks = self._storage.get_all(namespace)
|
|
304
|
+
return encode_snapshot(chunks, quantization=quantization or self._quantization)
|
|
305
|
+
|
|
306
|
+
def import_snapshot(self, data: bytes | bytearray | memoryview, replace: bool = False) -> int:
|
|
307
|
+
"""Import a portable `.rag` binary snapshot (verifying SHA-256 checksum)."""
|
|
308
|
+
self._assert_alive()
|
|
309
|
+
decoded = decode_snapshot(data)
|
|
310
|
+
if replace:
|
|
311
|
+
self._storage.clear()
|
|
312
|
+
for c in decoded.chunks:
|
|
313
|
+
if c.vector_int8 is not None:
|
|
314
|
+
self._tracked_int8.append(c.vector_int8)
|
|
315
|
+
self._storage.upsert(decoded.chunks)
|
|
316
|
+
self._cache.clear()
|
|
317
|
+
return len(decoded.chunks)
|
|
318
|
+
|
|
319
|
+
def clear_cache(self) -> None:
|
|
320
|
+
self._cache.clear()
|
|
321
|
+
|
|
322
|
+
def delete_namespace(self, namespace: str) -> int:
|
|
323
|
+
self._assert_alive()
|
|
324
|
+
deleted = self._storage.delete_namespace(namespace)
|
|
325
|
+
self._cache.clear()
|
|
326
|
+
return deleted
|
|
327
|
+
|
|
328
|
+
def count(self, namespace: Optional[str] = None) -> int:
|
|
329
|
+
self._assert_alive()
|
|
330
|
+
return self._storage.count(namespace)
|
|
331
|
+
|
|
332
|
+
def destroy(self, wipe_storage: bool = False) -> None:
|
|
333
|
+
if self._destroyed:
|
|
334
|
+
return
|
|
335
|
+
self._destroyed = True
|
|
336
|
+
self._cache.clear()
|
|
337
|
+
for buf in self._tracked_int8:
|
|
338
|
+
for i in range(len(buf)):
|
|
339
|
+
buf[i] = 0
|
|
340
|
+
self._tracked_int8.clear()
|
|
341
|
+
self._storage.destroy(wipe_storage=wipe_storage)
|
|
File without changes
|