offline-rag-kit 0.1.2__tar.gz → 0.1.4__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_kit-0.1.2 → offline_rag_kit-0.1.4}/PKG-INFO +50 -3
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/README.md +49 -2
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/pyproject.toml +16 -1
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/src/offline_rag/__init__.py +1 -1
- offline_rag_kit-0.1.4/src/offline_rag/cli.py +181 -0
- offline_rag_kit-0.1.4/src/offline_rag/embeddings.py +177 -0
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/src/offline_rag/eval.py +25 -5
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/src/offline_rag/index.py +88 -14
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/src/offline_rag/ollama.py +1 -2
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/PKG-INFO +50 -3
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/SOURCES.txt +3 -0
- offline_rag_kit-0.1.4/tests/test_embeddings.py +178 -0
- offline_rag_kit-0.1.4/tests/test_eval.py +56 -0
- offline_rag_kit-0.1.4/tests/test_files.py +108 -0
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/tests/test_index.py +13 -2
- offline_rag_kit-0.1.2/src/offline_rag/cli.py +0 -107
- offline_rag_kit-0.1.2/tests/test_eval.py +0 -25
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/LICENSE +0 -0
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/setup.cfg +0 -0
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/dependency_links.txt +0 -0
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/entry_points.txt +0 -0
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/requires.txt +0 -0
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/src/offline_rag_kit.egg-info/top_level.txt +0 -0
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/tests/test_cli.py +0 -0
- {offline_rag_kit-0.1.2 → offline_rag_kit-0.1.4}/tests/test_ollama.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: offline-rag-kit
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.4
|
|
4
4
|
Summary: Privacy-first local document search with PDF citations and optional Ollama answers
|
|
5
5
|
Author: HugoDelgadoo
|
|
6
6
|
Maintainer: HugoDelgadoo
|
|
@@ -27,6 +27,8 @@ Dynamic: license-file
|
|
|
27
27
|
[](https://pypi.org/project/offline-rag-kit/)
|
|
28
28
|
[](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/LICENSE)
|
|
29
29
|
|
|
30
|
+
**English** | [Español](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/README.es.md)
|
|
31
|
+
|
|
30
32
|
**Privacy-first local document search with PDF citations and optional local AI answers.**
|
|
31
33
|
|
|
32
34
|
> **Status: v0.1 alpha — a working retrieval-first prototype, not yet a complete multimodal RAG system.**
|
|
@@ -60,6 +62,16 @@ offline-rag ingest "C:\Users\YourUser\Documents\knowledge"
|
|
|
60
62
|
offline-rag search "retention policy"
|
|
61
63
|
```
|
|
62
64
|
|
|
65
|
+
### Use it from any terminal, and where the index lives
|
|
66
|
+
|
|
67
|
+
- **Install once, use anywhere:** `pipx install offline-rag-kit` makes the `offline-rag` command available in every terminal. With plain `pip` inside a virtual environment it only works while that environment is active. If your terminal says `offline-rag` is not recognized, Python's scripts folder is not on your `PATH`; `pipx ensurepath` fixes that.
|
|
68
|
+
- **The index is saved in the folder where you run the command**, as `.offline-rag/index.sqlite3`. If you index in one folder and search from another, the second folder has no index and finds nothing. To always use the same index, give a fixed path with `--db`:
|
|
69
|
+
|
|
70
|
+
```powershell
|
|
71
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 ingest C:\Users\You\Documents
|
|
72
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 search "policy"
|
|
73
|
+
```
|
|
74
|
+
|
|
63
75
|
To ask questions using a local model, first [install Ollama](https://ollama.com/) and pull a model:
|
|
64
76
|
|
|
65
77
|
```powershell
|
|
@@ -73,15 +85,50 @@ The `ask` command uses a **local** Ollama server only. It cannot guarantee the m
|
|
|
73
85
|
|
|
74
86
|
```text
|
|
75
87
|
offline-rag [--db PATH] [--json] ingest FOLDER
|
|
76
|
-
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5]
|
|
88
|
+
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid] [--files]
|
|
89
|
+
offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
|
|
77
90
|
offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
|
|
78
91
|
[--ollama-host URL] [--allow-remote]
|
|
79
92
|
```
|
|
80
93
|
|
|
94
|
+
### Which files contain a word?
|
|
95
|
+
|
|
96
|
+
By default `search` prints the best matching **passages** (the same file can appear several times). To get a list of **files** instead, add `--files`: each file appears once, with its full path, how many passages match and, for PDFs, the pages.
|
|
97
|
+
|
|
98
|
+
```powershell
|
|
99
|
+
offline-rag search "policy" --files
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
```text
|
|
103
|
+
3 files contain 'policy':
|
|
104
|
+
C:\Users\You\Documents\notes\meeting.md (2 matching passages)
|
|
105
|
+
C:\Users\You\Documents\handbook.md (1 matching passage)
|
|
106
|
+
C:\Users\You\Documents\contract.pdf (2 matching passages; pages 1, 3)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Files containing **every** word are listed; if there are none, files containing at least one word are listed and the output says so. `--limit` (default 20, up to 100) caps the list, while the first line always shows the total. `--files` works only in the default lexical mode.
|
|
110
|
+
|
|
81
111
|
Re-running `ingest` is incremental: unchanged files (by content hash) are not re-parsed.
|
|
82
112
|
|
|
83
113
|
`ask` talks to `127.0.0.1:11434` by default. Set `OLLAMA_HOST` or `--ollama-host` to use another port. Non-loopback hosts are refused unless you pass `--allow-remote`, because retrieved passages would then leave your machine.
|
|
84
114
|
|
|
115
|
+
### Optional semantic search (local Ollama)
|
|
116
|
+
|
|
117
|
+
Plain `search` is lexical and works fully offline. To also match by meaning (for example "work from home" ~ "teletrabajo"), create embeddings **explicitly** with a local Ollama model, then choose a mode:
|
|
118
|
+
|
|
119
|
+
```powershell
|
|
120
|
+
ollama pull bge-m3 # a multilingual embedding model
|
|
121
|
+
offline-rag embed --model bge-m3 # explicit step; only embeds new passages
|
|
122
|
+
offline-rag search "work from home" --mode hybrid # BM25 + vectors fused (RRF)
|
|
123
|
+
offline-rag search "work from home" --mode vector # vectors only
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
- `ingest` never calls Ollama, and the default mode stays `lexical`. Semantic modes need Ollama running when you search, because the question must be embedded too.
|
|
127
|
+
- The index remembers which model made its vectors. Switching models needs `offline-rag embed --model NEW --rebuild`.
|
|
128
|
+
- Same privacy rule as `ask`: only loopback hosts are accepted unless you pass `--allow-remote`.
|
|
129
|
+
- Vectors are compared with a plain scan, which is fine for thousands of passages but slows down on very large collections. Embedding speed depends on your hardware and model.
|
|
130
|
+
- **Not yet measured with a real model.** Use `python -m offline_rag.eval --mode hybrid --model bge-m3` to see what it does on the bundled dataset.
|
|
131
|
+
|
|
85
132
|
`--json` (placed before the subcommand) prints a single JSON document on stdout, with the full passage text, page, bounding box and score for each hit. Errors and exit codes are unchanged and still go to stderr.
|
|
86
133
|
|
|
87
134
|
## Current capabilities and limitations
|
|
@@ -92,7 +139,7 @@ Re-running `ingest` is incremental: unchanged files (by content hash) are not re
|
|
|
92
139
|
| Lexical ranking with SQLite FTS5 (BM25) | Supported |
|
|
93
140
|
| PDF source pages and block bounding boxes | Supported |
|
|
94
141
|
| Local Ollama text generation | Optional, supported |
|
|
95
|
-
| Semantic / vector retrieval |
|
|
142
|
+
| Semantic / vector retrieval | Optional, via local Ollama embeddings (not yet benchmarked) |
|
|
96
143
|
| OCR, image understanding, audio transcription | Planned |
|
|
97
144
|
| Web dashboard / user authentication | Planned |
|
|
98
145
|
| Reliable claim-level grounding evaluation | Planned |
|
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
[](https://pypi.org/project/offline-rag-kit/)
|
|
6
6
|
[](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/LICENSE)
|
|
7
7
|
|
|
8
|
+
**English** | [Español](https://github.com/HugoDelgadoo/offline-rag-kit/blob/main/README.es.md)
|
|
9
|
+
|
|
8
10
|
**Privacy-first local document search with PDF citations and optional local AI answers.**
|
|
9
11
|
|
|
10
12
|
> **Status: v0.1 alpha — a working retrieval-first prototype, not yet a complete multimodal RAG system.**
|
|
@@ -38,6 +40,16 @@ offline-rag ingest "C:\Users\YourUser\Documents\knowledge"
|
|
|
38
40
|
offline-rag search "retention policy"
|
|
39
41
|
```
|
|
40
42
|
|
|
43
|
+
### Use it from any terminal, and where the index lives
|
|
44
|
+
|
|
45
|
+
- **Install once, use anywhere:** `pipx install offline-rag-kit` makes the `offline-rag` command available in every terminal. With plain `pip` inside a virtual environment it only works while that environment is active. If your terminal says `offline-rag` is not recognized, Python's scripts folder is not on your `PATH`; `pipx ensurepath` fixes that.
|
|
46
|
+
- **The index is saved in the folder where you run the command**, as `.offline-rag/index.sqlite3`. If you index in one folder and search from another, the second folder has no index and finds nothing. To always use the same index, give a fixed path with `--db`:
|
|
47
|
+
|
|
48
|
+
```powershell
|
|
49
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 ingest C:\Users\You\Documents
|
|
50
|
+
offline-rag --db C:\Users\You\my-index.sqlite3 search "policy"
|
|
51
|
+
```
|
|
52
|
+
|
|
41
53
|
To ask questions using a local model, first [install Ollama](https://ollama.com/) and pull a model:
|
|
42
54
|
|
|
43
55
|
```powershell
|
|
@@ -51,15 +63,50 @@ The `ask` command uses a **local** Ollama server only. It cannot guarantee the m
|
|
|
51
63
|
|
|
52
64
|
```text
|
|
53
65
|
offline-rag [--db PATH] [--json] ingest FOLDER
|
|
54
|
-
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5]
|
|
66
|
+
offline-rag [--db PATH] [--json] search "TERMS" [--limit 5] [--mode lexical|vector|hybrid] [--files]
|
|
67
|
+
offline-rag [--db PATH] [--json] embed [--model bge-m3] [--rebuild] [--ollama-host URL] [--allow-remote]
|
|
55
68
|
offline-rag [--db PATH] [--json] ask "QUESTION" [--limit 5] [--model llama3.2]
|
|
56
69
|
[--ollama-host URL] [--allow-remote]
|
|
57
70
|
```
|
|
58
71
|
|
|
72
|
+
### Which files contain a word?
|
|
73
|
+
|
|
74
|
+
By default `search` prints the best matching **passages** (the same file can appear several times). To get a list of **files** instead, add `--files`: each file appears once, with its full path, how many passages match and, for PDFs, the pages.
|
|
75
|
+
|
|
76
|
+
```powershell
|
|
77
|
+
offline-rag search "policy" --files
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
```text
|
|
81
|
+
3 files contain 'policy':
|
|
82
|
+
C:\Users\You\Documents\notes\meeting.md (2 matching passages)
|
|
83
|
+
C:\Users\You\Documents\handbook.md (1 matching passage)
|
|
84
|
+
C:\Users\You\Documents\contract.pdf (2 matching passages; pages 1, 3)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Files containing **every** word are listed; if there are none, files containing at least one word are listed and the output says so. `--limit` (default 20, up to 100) caps the list, while the first line always shows the total. `--files` works only in the default lexical mode.
|
|
88
|
+
|
|
59
89
|
Re-running `ingest` is incremental: unchanged files (by content hash) are not re-parsed.
|
|
60
90
|
|
|
61
91
|
`ask` talks to `127.0.0.1:11434` by default. Set `OLLAMA_HOST` or `--ollama-host` to use another port. Non-loopback hosts are refused unless you pass `--allow-remote`, because retrieved passages would then leave your machine.
|
|
62
92
|
|
|
93
|
+
### Optional semantic search (local Ollama)
|
|
94
|
+
|
|
95
|
+
Plain `search` is lexical and works fully offline. To also match by meaning (for example "work from home" ~ "teletrabajo"), create embeddings **explicitly** with a local Ollama model, then choose a mode:
|
|
96
|
+
|
|
97
|
+
```powershell
|
|
98
|
+
ollama pull bge-m3 # a multilingual embedding model
|
|
99
|
+
offline-rag embed --model bge-m3 # explicit step; only embeds new passages
|
|
100
|
+
offline-rag search "work from home" --mode hybrid # BM25 + vectors fused (RRF)
|
|
101
|
+
offline-rag search "work from home" --mode vector # vectors only
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
- `ingest` never calls Ollama, and the default mode stays `lexical`. Semantic modes need Ollama running when you search, because the question must be embedded too.
|
|
105
|
+
- The index remembers which model made its vectors. Switching models needs `offline-rag embed --model NEW --rebuild`.
|
|
106
|
+
- Same privacy rule as `ask`: only loopback hosts are accepted unless you pass `--allow-remote`.
|
|
107
|
+
- Vectors are compared with a plain scan, which is fine for thousands of passages but slows down on very large collections. Embedding speed depends on your hardware and model.
|
|
108
|
+
- **Not yet measured with a real model.** Use `python -m offline_rag.eval --mode hybrid --model bge-m3` to see what it does on the bundled dataset.
|
|
109
|
+
|
|
63
110
|
`--json` (placed before the subcommand) prints a single JSON document on stdout, with the full passage text, page, bounding box and score for each hit. Errors and exit codes are unchanged and still go to stderr.
|
|
64
111
|
|
|
65
112
|
## Current capabilities and limitations
|
|
@@ -70,7 +117,7 @@ Re-running `ingest` is incremental: unchanged files (by content hash) are not re
|
|
|
70
117
|
| Lexical ranking with SQLite FTS5 (BM25) | Supported |
|
|
71
118
|
| PDF source pages and block bounding boxes | Supported |
|
|
72
119
|
| Local Ollama text generation | Optional, supported |
|
|
73
|
-
| Semantic / vector retrieval |
|
|
120
|
+
| Semantic / vector retrieval | Optional, via local Ollama embeddings (not yet benchmarked) |
|
|
74
121
|
| OCR, image understanding, audio transcription | Planned |
|
|
75
122
|
| Web dashboard / user authentication | Planned |
|
|
76
123
|
| Reliable claim-level grounding evaluation | Planned |
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "offline-rag-kit"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.4"
|
|
8
8
|
description = "Privacy-first local document search with PDF citations and optional Ollama answers"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -31,3 +31,18 @@ offline-rag = "offline_rag.cli:main"
|
|
|
31
31
|
|
|
32
32
|
[tool.setuptools.packages.find]
|
|
33
33
|
where = ["src"]
|
|
34
|
+
|
|
35
|
+
[tool.ruff]
|
|
36
|
+
line-length = 120
|
|
37
|
+
target-version = "py310"
|
|
38
|
+
|
|
39
|
+
[tool.ruff.lint]
|
|
40
|
+
select = ["E", "F", "W", "I", "B", "UP"]
|
|
41
|
+
|
|
42
|
+
[tool.coverage.run]
|
|
43
|
+
source = ["src/offline_rag"]
|
|
44
|
+
branch = true
|
|
45
|
+
|
|
46
|
+
[tool.coverage.report]
|
|
47
|
+
show_missing = true
|
|
48
|
+
exclude_also = ["if __name__ == .__main__.:"]
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Command line interface for offline document search."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from .embeddings import DEFAULT_MODEL, embed_index, hybrid_search, indexed_model, ollama_embedder, vector_search
|
|
8
|
+
from .index import citation, ingest, search, search_files
|
|
9
|
+
from .ollama import answer_with_ollama
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
13
|
+
parser = argparse.ArgumentParser(
|
|
14
|
+
prog="offline-rag", description="Search private documents entirely on your machine."
|
|
15
|
+
)
|
|
16
|
+
parser.add_argument("--db", default=".offline-rag/index.sqlite3", help="Local SQLite index path")
|
|
17
|
+
parser.add_argument(
|
|
18
|
+
"--json", action="store_true", help="Print machine-readable JSON on stdout (errors stay on stderr)"
|
|
19
|
+
)
|
|
20
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
21
|
+
|
|
22
|
+
ing = commands.add_parser("ingest", help="Index PDFs, .txt and .md files recursively")
|
|
23
|
+
ing.add_argument("folder", help="Directory containing documents")
|
|
24
|
+
|
|
25
|
+
emb = commands.add_parser(
|
|
26
|
+
"embed", help="Create embeddings with local Ollama for semantic search (explicit, optional)"
|
|
27
|
+
)
|
|
28
|
+
emb.add_argument("--model", default=DEFAULT_MODEL, help="Ollama embedding model (ollama pull <model>)")
|
|
29
|
+
emb.add_argument("--rebuild", action="store_true", help="Discard existing embeddings first")
|
|
30
|
+
emb.add_argument("--ollama-host", help="Ollama URL (default: $OLLAMA_HOST or 127.0.0.1:11434)")
|
|
31
|
+
emb.add_argument("--allow-remote", action="store_true", help="Allow a non-loopback Ollama host")
|
|
32
|
+
|
|
33
|
+
for command in ("search", "ask"):
|
|
34
|
+
sub = commands.add_parser(command, help="Search locally" if command == "search" else "Ask local Ollama")
|
|
35
|
+
sub.add_argument("query", help="Question or search terms")
|
|
36
|
+
sub.add_argument(
|
|
37
|
+
"--limit", type=int, default=None,
|
|
38
|
+
help="Maximum results (default: 5 passages, or 20 files with --files)",
|
|
39
|
+
)
|
|
40
|
+
sub.add_argument(
|
|
41
|
+
"--mode", choices=("lexical", "vector", "hybrid"), default="lexical",
|
|
42
|
+
help="lexical (default, offline); vector/hybrid need 'offline-rag embed' and a running Ollama",
|
|
43
|
+
)
|
|
44
|
+
sub.add_argument("--ollama-host", help="Ollama URL (default: $OLLAMA_HOST or 127.0.0.1:11434)")
|
|
45
|
+
sub.add_argument(
|
|
46
|
+
"--allow-remote", action="store_true",
|
|
47
|
+
help="Allow a non-loopback Ollama host (text is sent to it)",
|
|
48
|
+
)
|
|
49
|
+
if command == "search":
|
|
50
|
+
sub.add_argument(
|
|
51
|
+
"--files", action="store_true",
|
|
52
|
+
help="List the files that contain the terms (full path, matches, pages) instead of passages",
|
|
53
|
+
)
|
|
54
|
+
if command == "ask":
|
|
55
|
+
sub.add_argument("--model", default="llama3.2", help="Ollama model used to write the answer")
|
|
56
|
+
return parser
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _hit_json(rank: int, hit: dict) -> dict:
|
|
60
|
+
return {
|
|
61
|
+
"rank": rank,
|
|
62
|
+
"citation": citation(hit),
|
|
63
|
+
"path": hit["path"],
|
|
64
|
+
"page": hit["page"] or None,
|
|
65
|
+
"bbox": [float(n) for n in hit["bbox"].split(",")] if hit["bbox"] else None,
|
|
66
|
+
"score": hit["score"],
|
|
67
|
+
"snippet": hit["snippet"],
|
|
68
|
+
"text": hit["body"],
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _dump(payload: dict) -> None:
|
|
73
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _format_pages(pages: list[int], shown: int = 10) -> str:
|
|
77
|
+
text = ", ".join(str(p) for p in pages[:shown])
|
|
78
|
+
return text + (f", … (+{len(pages) - shown})" if len(pages) > shown else "")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _print_files(query: str, result: dict) -> None:
|
|
82
|
+
total = result["total"]
|
|
83
|
+
if not total:
|
|
84
|
+
print("No files found.")
|
|
85
|
+
return
|
|
86
|
+
noun, verb = ("file", "contains") if total == 1 else ("files", "contain")
|
|
87
|
+
if result["match"] == "any":
|
|
88
|
+
print(f"No file contains all the words of {query!r}; {total} {noun} {verb} at least one of them:")
|
|
89
|
+
else:
|
|
90
|
+
print(f"{total} {noun} {verb} {query!r}:")
|
|
91
|
+
for item in result["files"]:
|
|
92
|
+
count = item["matches"]
|
|
93
|
+
detail = f"{count} matching passage{'s' if count != 1 else ''}"
|
|
94
|
+
if item["pages"]:
|
|
95
|
+
detail += f"; page{'s' if len(item['pages']) != 1 else ''} {_format_pages(item['pages'])}"
|
|
96
|
+
print(f" {item['path']} ({detail})")
|
|
97
|
+
if total > len(result["files"]):
|
|
98
|
+
print(f"Showing the first {len(result['files'])} of {total}. Use --limit to see more (up to 100).")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _retrieve(args) -> list[dict]:
|
|
102
|
+
limit = args.limit if args.limit is not None else 5
|
|
103
|
+
if args.mode == "lexical":
|
|
104
|
+
return search(args.query, args.db, limit)
|
|
105
|
+
model = indexed_model(args.db)
|
|
106
|
+
if model is None:
|
|
107
|
+
raise ValueError("This index has no embeddings. Run 'offline-rag embed' first.")
|
|
108
|
+
embedder = ollama_embedder(model, args.ollama_host, args.allow_remote)
|
|
109
|
+
run = vector_search if args.mode == "vector" else hybrid_search
|
|
110
|
+
return run(args.query, args.db, embedder, limit)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def main(argv: list[str] | None = None) -> None:
|
|
114
|
+
args = build_parser().parse_args(argv)
|
|
115
|
+
try:
|
|
116
|
+
if args.command == "ingest":
|
|
117
|
+
result = ingest(args.folder, args.db)
|
|
118
|
+
skipped = [{"path": str(p), "error": message} for p, message in result.skipped]
|
|
119
|
+
if args.json:
|
|
120
|
+
_dump({
|
|
121
|
+
"files": result.files, "passages": result.passages,
|
|
122
|
+
"unchanged": result.unchanged, "database": args.db, "skipped": skipped,
|
|
123
|
+
})
|
|
124
|
+
else:
|
|
125
|
+
for item in skipped:
|
|
126
|
+
print(f"Warning: skipped {item['path']}: {item['error']}", file=sys.stderr)
|
|
127
|
+
print(
|
|
128
|
+
f"Indexed {result.files} files ({result.unchanged} unchanged) and "
|
|
129
|
+
f"{result.passages} passages in {args.db}"
|
|
130
|
+
)
|
|
131
|
+
elif args.command == "embed":
|
|
132
|
+
embedder = ollama_embedder(args.model, args.ollama_host, args.allow_remote)
|
|
133
|
+
count = embed_index(args.db, embedder, args.model, rebuild=args.rebuild)
|
|
134
|
+
if args.json:
|
|
135
|
+
_dump({"embedded": count, "model": args.model, "database": args.db})
|
|
136
|
+
else:
|
|
137
|
+
print(f"Embedded {count} passages with {args.model} in {args.db}")
|
|
138
|
+
elif args.command == "search" and args.files:
|
|
139
|
+
if args.mode != "lexical":
|
|
140
|
+
raise ValueError("--files lists files that contain the words, so it only works with --mode lexical.")
|
|
141
|
+
limit = args.limit if args.limit is not None else 20
|
|
142
|
+
result = search_files(args.query, args.db, limit)
|
|
143
|
+
if args.json:
|
|
144
|
+
_dump({"query": args.query, **result})
|
|
145
|
+
else:
|
|
146
|
+
_print_files(args.query, result)
|
|
147
|
+
else:
|
|
148
|
+
hits = _retrieve(args)
|
|
149
|
+
if args.command == "search":
|
|
150
|
+
if args.json:
|
|
151
|
+
_dump({"query": args.query, "results": [_hit_json(i, h) for i, h in enumerate(hits, 1)]})
|
|
152
|
+
else:
|
|
153
|
+
if not hits:
|
|
154
|
+
print("No matching passages found.")
|
|
155
|
+
for rank, hit in enumerate(hits, start=1):
|
|
156
|
+
print(f"\n[{rank}] {citation(hit)}\n{hit['snippet']}")
|
|
157
|
+
else:
|
|
158
|
+
answer = answer_with_ollama(
|
|
159
|
+
args.query, hits, model=args.model,
|
|
160
|
+
host=args.ollama_host, allow_remote=args.allow_remote,
|
|
161
|
+
)
|
|
162
|
+
if args.json:
|
|
163
|
+
_dump({
|
|
164
|
+
"question": args.query,
|
|
165
|
+
"model": args.model,
|
|
166
|
+
"answer": answer,
|
|
167
|
+
"sources": [_hit_json(i, h) for i, h in enumerate(hits, 1)],
|
|
168
|
+
})
|
|
169
|
+
else:
|
|
170
|
+
print(answer)
|
|
171
|
+
if hits:
|
|
172
|
+
print("\nRetrieved evidence:")
|
|
173
|
+
for rank, hit in enumerate(hits, start=1):
|
|
174
|
+
print(f"[{rank}] {citation(hit)}")
|
|
175
|
+
except (OSError, ValueError, RuntimeError) as exc:
|
|
176
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
177
|
+
raise SystemExit(1) from exc
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
if __name__ == "__main__":
|
|
181
|
+
main()
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Optional semantic retrieval with embeddings from a local Ollama server.
|
|
2
|
+
|
|
3
|
+
Nothing here runs unless the user asks for it: ``offline-rag embed`` creates the vectors
|
|
4
|
+
(an explicit step), and ``search --mode vector|hybrid`` uses them. Only the Python standard
|
|
5
|
+
library is needed; vectors live in the same SQLite file as the passages.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import heapq
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import operator
|
|
14
|
+
import struct
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from contextlib import closing
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from urllib.error import HTTPError, URLError
|
|
19
|
+
from urllib.request import Request, urlopen
|
|
20
|
+
|
|
21
|
+
from .index import open_index, search
|
|
22
|
+
from .ollama import resolve_host
|
|
23
|
+
|
|
24
|
+
DEFAULT_MODEL = "bge-m3" # multilingual; pull it first with `ollama pull bge-m3`
|
|
25
|
+
Embedder = Callable[[list[str]], list[list[float]]]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def ollama_embedder(
|
|
29
|
+
model: str, host: str | None = None, allow_remote: bool = False, timeout: int = 180
|
|
30
|
+
) -> Embedder:
|
|
31
|
+
"""Return a function that embeds texts through Ollama's ``/api/embed`` endpoint."""
|
|
32
|
+
base_url = resolve_host(host, allow_remote) # refuses non-loopback hosts by default
|
|
33
|
+
|
|
34
|
+
def embed(texts: list[str]) -> list[list[float]]:
|
|
35
|
+
payload = json.dumps({"model": model, "input": texts, "truncate": True}).encode("utf-8")
|
|
36
|
+
request = Request(
|
|
37
|
+
f"{base_url}/api/embed",
|
|
38
|
+
data=payload,
|
|
39
|
+
headers={"Content-Type": "application/json"},
|
|
40
|
+
method="POST",
|
|
41
|
+
)
|
|
42
|
+
try:
|
|
43
|
+
with urlopen(request, timeout=timeout) as response:
|
|
44
|
+
data = json.load(response)
|
|
45
|
+
except HTTPError as exc:
|
|
46
|
+
detail = ""
|
|
47
|
+
try:
|
|
48
|
+
detail = json.load(exc).get("error", "")
|
|
49
|
+
except Exception:
|
|
50
|
+
pass
|
|
51
|
+
hint = f" Run: ollama pull {model}" if exc.code == 404 else ""
|
|
52
|
+
raise RuntimeError(f"Ollama returned HTTP {exc.code} for model {model!r}: {detail}.{hint}") from exc
|
|
53
|
+
except URLError as exc:
|
|
54
|
+
raise RuntimeError(
|
|
55
|
+
f"Cannot reach Ollama at {base_url}. Run 'ollama serve' and 'ollama pull {model}'."
|
|
56
|
+
) from exc
|
|
57
|
+
vectors = data.get("embeddings")
|
|
58
|
+
if (
|
|
59
|
+
not isinstance(vectors, list)
|
|
60
|
+
or len(vectors) != len(texts)
|
|
61
|
+
or not all(isinstance(v, list) and v for v in vectors)
|
|
62
|
+
):
|
|
63
|
+
raise RuntimeError("Unexpected response from Ollama's /api/embed endpoint.")
|
|
64
|
+
return vectors
|
|
65
|
+
|
|
66
|
+
return embed
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _normalize(vector: list[float]) -> list[float]:
|
|
70
|
+
norm = math.sqrt(sum(x * x for x in vector))
|
|
71
|
+
if norm == 0:
|
|
72
|
+
raise ValueError("The embedding model returned a zero vector.")
|
|
73
|
+
return [x / norm for x in vector]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _encode(vector: list[float]) -> bytes:
|
|
77
|
+
return struct.pack(f"<{len(vector)}f", *vector)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _decode(blob: bytes) -> tuple[float, ...]:
|
|
81
|
+
return struct.unpack(f"<{len(blob) // 4}f", blob)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def indexed_model(database: str | Path) -> str | None:
|
|
85
|
+
"""Model that produced the vectors in this index, or None if it has none."""
|
|
86
|
+
with closing(open_index(database)) as connection:
|
|
87
|
+
models = [row[0] for row in connection.execute("SELECT DISTINCT model FROM embeddings")]
|
|
88
|
+
if len(models) > 1:
|
|
89
|
+
raise ValueError(f"Index mixes embeddings from several models: {', '.join(sorted(models))}.")
|
|
90
|
+
return models[0] if models else None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def embed_index(
|
|
94
|
+
database: str | Path,
|
|
95
|
+
embedder: Embedder,
|
|
96
|
+
model: str,
|
|
97
|
+
batch_size: int = 16,
|
|
98
|
+
rebuild: bool = False,
|
|
99
|
+
) -> int:
|
|
100
|
+
"""Embed every passage that has no vector yet; return how many were embedded."""
|
|
101
|
+
with closing(open_index(database)) as connection:
|
|
102
|
+
if rebuild:
|
|
103
|
+
with connection:
|
|
104
|
+
connection.execute("DELETE FROM embeddings")
|
|
105
|
+
existing = [row[0] for row in connection.execute("SELECT DISTINCT model FROM embeddings")]
|
|
106
|
+
if existing and existing != [model]:
|
|
107
|
+
raise ValueError(
|
|
108
|
+
f"This index already has embeddings from {existing[0]!r}. "
|
|
109
|
+
f"Use --rebuild to replace them with {model!r}."
|
|
110
|
+
)
|
|
111
|
+
todo = connection.execute(
|
|
112
|
+
"""SELECT p.rowid AS id, p.body FROM passages p
|
|
113
|
+
LEFT JOIN embeddings e ON e.passage_rowid = p.rowid
|
|
114
|
+
WHERE e.passage_rowid IS NULL ORDER BY p.rowid"""
|
|
115
|
+
).fetchall()
|
|
116
|
+
dims = {row[0] for row in connection.execute("SELECT DISTINCT dim FROM embeddings")}
|
|
117
|
+
for start in range(0, len(todo), batch_size):
|
|
118
|
+
batch = todo[start:start + batch_size]
|
|
119
|
+
vectors = [_normalize(v) for v in embedder([row["body"] for row in batch])]
|
|
120
|
+
dims |= {len(v) for v in vectors}
|
|
121
|
+
if len(dims) > 1:
|
|
122
|
+
raise ValueError("The embedding model returned vectors of different sizes.")
|
|
123
|
+
with connection:
|
|
124
|
+
connection.executemany(
|
|
125
|
+
"INSERT OR REPLACE INTO embeddings (passage_rowid, model, dim, vector) VALUES (?, ?, ?, ?)",
|
|
126
|
+
((row["id"], model, len(v), _encode(v)) for row, v in zip(batch, vectors, strict=True)),
|
|
127
|
+
)
|
|
128
|
+
return len(todo)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def vector_search(query: str, database: str | Path, embedder: Embedder, limit: int = 5) -> list[dict]:
|
|
132
|
+
"""Rank passages by cosine similarity to the query (brute force over all vectors)."""
|
|
133
|
+
if limit < 1 or limit > 100:
|
|
134
|
+
raise ValueError("limit must be between 1 and 100")
|
|
135
|
+
with closing(open_index(database)) as connection:
|
|
136
|
+
stored = connection.execute("SELECT passage_rowid, dim, vector FROM embeddings").fetchall()
|
|
137
|
+
if not stored:
|
|
138
|
+
raise ValueError("This index has no embeddings. Run 'offline-rag embed' first.")
|
|
139
|
+
query_vector = _normalize(embedder([query])[0])
|
|
140
|
+
if len(query_vector) != stored[0]["dim"]:
|
|
141
|
+
raise ValueError("The query embedding does not match the indexed vectors: was the model changed?")
|
|
142
|
+
dot = operator.mul
|
|
143
|
+
scored = (
|
|
144
|
+
(sum(map(dot, query_vector, _decode(row["vector"]))), row["passage_rowid"]) for row in stored
|
|
145
|
+
)
|
|
146
|
+
top = heapq.nlargest(limit, scored)
|
|
147
|
+
hits = []
|
|
148
|
+
for score, rowid in top:
|
|
149
|
+
row = connection.execute(
|
|
150
|
+
"SELECT root, path, page, bbox, body FROM passages WHERE rowid = ?", (rowid,)
|
|
151
|
+
).fetchone()
|
|
152
|
+
if row:
|
|
153
|
+
body = row["body"]
|
|
154
|
+
hits.append({
|
|
155
|
+
"id": rowid, "root": row["root"], "path": row["path"], "page": row["page"],
|
|
156
|
+
"bbox": row["bbox"], "body": body, "score": score,
|
|
157
|
+
"snippet": body if len(body) <= 240 else body[:240].rstrip() + " …",
|
|
158
|
+
})
|
|
159
|
+
return hits
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def hybrid_search(
|
|
163
|
+
query: str, database: str | Path, embedder: Embedder, limit: int = 5, k: int = 60
|
|
164
|
+
) -> list[dict]:
|
|
165
|
+
"""Fuse BM25 and vector rankings with Reciprocal Rank Fusion."""
|
|
166
|
+
if limit < 1 or limit > 100:
|
|
167
|
+
raise ValueError("limit must be between 1 and 100")
|
|
168
|
+
pool = min(100, max(limit * 4, 20))
|
|
169
|
+
rankings = [search(query, database, pool), vector_search(query, database, embedder, pool)]
|
|
170
|
+
fused: dict[int, float] = {}
|
|
171
|
+
best: dict[int, dict] = {}
|
|
172
|
+
for hits in rankings:
|
|
173
|
+
for rank, hit in enumerate(hits, start=1):
|
|
174
|
+
fused[hit["id"]] = fused.get(hit["id"], 0.0) + 1.0 / (k + rank)
|
|
175
|
+
best.setdefault(hit["id"], hit) # the lexical hit comes first and has a highlighted snippet
|
|
176
|
+
ordered = sorted(fused, key=lambda i: (-fused[i], i))[:limit]
|
|
177
|
+
return [{**best[i], "score": fused[i]} for i in ordered]
|
|
@@ -14,18 +14,27 @@ import sys
|
|
|
14
14
|
import tempfile
|
|
15
15
|
from pathlib import Path
|
|
16
16
|
|
|
17
|
+
from .embeddings import DEFAULT_MODEL, embed_index, hybrid_search, ollama_embedder, vector_search
|
|
17
18
|
from .index import ingest, search
|
|
18
19
|
|
|
19
20
|
KS = (1, 3, 5)
|
|
20
21
|
|
|
21
22
|
|
|
22
|
-
def evaluate(corpus: Path, questions: list[dict]) -> dict:
|
|
23
|
+
def evaluate(corpus: Path, questions: list[dict], mode: str = "lexical", embedder=None, model: str = "") -> dict:
|
|
24
|
+
"""Run the questions. ``mode`` is lexical, vector or hybrid; the last two need ``embedder``."""
|
|
23
25
|
with tempfile.TemporaryDirectory() as tmp:
|
|
24
26
|
database = Path(tmp) / "eval.sqlite3"
|
|
25
27
|
ingest(corpus, database)
|
|
28
|
+
if mode != "lexical":
|
|
29
|
+
embed_index(database, embedder, model)
|
|
26
30
|
rows = []
|
|
27
31
|
for item in questions:
|
|
28
|
-
|
|
32
|
+
if mode == "lexical":
|
|
33
|
+
hits = search(item["q"], database, limit=max(KS))
|
|
34
|
+
elif mode == "vector":
|
|
35
|
+
hits = vector_search(item["q"], database, embedder, limit=max(KS))
|
|
36
|
+
else:
|
|
37
|
+
hits = hybrid_search(item["q"], database, embedder, limit=max(KS))
|
|
29
38
|
rank = next(
|
|
30
39
|
(
|
|
31
40
|
i
|
|
@@ -56,11 +65,21 @@ def main(argv: list[str] | None = None) -> None:
|
|
|
56
65
|
parser.add_argument("--corpus", default="eval/corpus", type=Path)
|
|
57
66
|
parser.add_argument("--questions", default="eval/questions.json", type=Path)
|
|
58
67
|
parser.add_argument("--json", action="store_true")
|
|
68
|
+
parser.add_argument(
|
|
69
|
+
"--mode", choices=("lexical", "vector", "hybrid"), default="lexical",
|
|
70
|
+
help="vector/hybrid embed the corpus with local Ollama first (needs 'ollama serve' and the model)",
|
|
71
|
+
)
|
|
72
|
+
parser.add_argument("--model", default=DEFAULT_MODEL, help="Ollama embedding model for vector/hybrid")
|
|
73
|
+
parser.add_argument("--ollama-host")
|
|
74
|
+
parser.add_argument("--allow-remote", action="store_true")
|
|
59
75
|
args = parser.parse_args(argv)
|
|
60
76
|
try:
|
|
61
77
|
questions = json.loads(args.questions.read_text(encoding="utf-8"))["questions"]
|
|
62
|
-
|
|
63
|
-
|
|
78
|
+
embedder = None
|
|
79
|
+
if args.mode != "lexical":
|
|
80
|
+
embedder = ollama_embedder(args.model, args.ollama_host, args.allow_remote)
|
|
81
|
+
report = evaluate(args.corpus, questions, args.mode, embedder, args.model)
|
|
82
|
+
except (OSError, ValueError, KeyError, RuntimeError) as exc:
|
|
64
83
|
print(f"Error: {exc}", file=sys.stderr)
|
|
65
84
|
raise SystemExit(1) from exc
|
|
66
85
|
if args.json:
|
|
@@ -68,7 +87,8 @@ def main(argv: list[str] | None = None) -> None:
|
|
|
68
87
|
return
|
|
69
88
|
print(f"{'subset':<12}{'n':>4}" + "".join(f"{'R@' + str(k):>8}" for k in KS) + f"{'MRR':>8}")
|
|
70
89
|
for name, st in [("overall", report["overall"]), *report["by_kind"].items()]:
|
|
71
|
-
|
|
90
|
+
recalls = "".join(f"{st[f'recall@{k}']:>8.3f}" for k in KS)
|
|
91
|
+
print(f"{name:<12}{st['questions']:>4}{recalls}{st['mrr']:>8.3f}")
|
|
72
92
|
missed = [r["q"] for r in report["rows"] if not r["rank"]]
|
|
73
93
|
if missed:
|
|
74
94
|
print("\nNot found in top 5:")
|