llavrag 0.3.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.
- llavrag/__init__.py +21 -0
- llavrag/__main__.py +3 -0
- llavrag/api.py +41 -0
- llavrag/backend.py +61 -0
- llavrag/cli.py +280 -0
- llavrag/config.py +88 -0
- llavrag/core/__init__.py +2 -0
- llavrag/core/cache.py +42 -0
- llavrag/core/chunk.py +34 -0
- llavrag/core/data.py +69 -0
- llavrag/core/dense.py +35 -0
- llavrag/core/engine.py +179 -0
- llavrag/core/expand.py +35 -0
- llavrag/core/fuse.py +12 -0
- llavrag/core/judge.py +71 -0
- llavrag/core/lexical.py +136 -0
- llavrag/core/net.py +28 -0
- llavrag/core/run.py +120 -0
- llavrag/core/score.py +63 -0
- llavrag/core/state.py +34 -0
- llavrag/core/text.py +134 -0
- llavrag/demo.py +281 -0
- llavrag/doctor.py +412 -0
- llavrag/embed.py +192 -0
- llavrag/engine.py +117 -0
- llavrag/examples/docs/org-chart.docx +0 -0
- llavrag/examples/docs/projects.txt +7 -0
- llavrag/examples/docs/rotterdam-pilot.pdf +0 -0
- llavrag/examples/docs/travel-policy.md +21 -0
- llavrag/examples/docs/vendors.html +14 -0
- llavrag/index.py +224 -0
- llavrag/ingest.py +505 -0
- llavrag/judge.py +426 -0
- llavrag/judges.py +179 -0
- llavrag/manifests/embedder.json +54 -0
- llavrag/manifests/judge.json +59 -0
- llavrag/mcp_server.py +126 -0
- llavrag/onepass.py +78 -0
- llavrag/pilot.py +185 -0
- llavrag/placement.py +245 -0
- llavrag/search.py +163 -0
- llavrag/textsafe.py +47 -0
- llavrag/weights.py +199 -0
- llavrag-0.3.0.dist-info/METADATA +694 -0
- llavrag-0.3.0.dist-info/RECORD +49 -0
- llavrag-0.3.0.dist-info/WHEEL +4 -0
- llavrag-0.3.0.dist-info/entry_points.txt +2 -0
- llavrag-0.3.0.dist-info/licenses/LICENSE +201 -0
- llavrag-0.3.0.dist-info/licenses/NOTICE +35 -0
llavrag/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""llavRAG local: self-hosted multi-hop retrieval. A 4B evidence judge scores every candidate passage over three rounds
|
|
2
|
+
that follow the evidence found so far (keyword + dense retrieval; retrieval core llavrag.core, "llav-retrieve" v0.3).
|
|
3
|
+
|
|
4
|
+
from llavrag import Searcher, build_index
|
|
5
|
+
build_index(["./docs"], index="default")
|
|
6
|
+
s = Searcher.open("default")
|
|
7
|
+
print(s.search("Who approves travel for the team that runs Project Kestrel?", top_k=5)["results"][0])
|
|
8
|
+
"""
|
|
9
|
+
__version__ = "0.3.0"
|
|
10
|
+
|
|
11
|
+
__all__ = ["Searcher", "build_index", "__version__"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def __getattr__(name): # keep `import llavrag` light: models load only when used
|
|
15
|
+
if name == "Searcher":
|
|
16
|
+
from .engine import Searcher
|
|
17
|
+
return Searcher
|
|
18
|
+
if name == "build_index":
|
|
19
|
+
from .api import build_index
|
|
20
|
+
return build_index
|
|
21
|
+
raise AttributeError(name)
|
llavrag/__main__.py
ADDED
llavrag/api.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Python API helpers (the CLI uses the same code)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def build_index(paths, index: str | os.PathLike | None = None, *, device: str | None = None, passage_chars: int = 1200,
|
|
10
|
+
embed_batch: int = 16, cjk: str = "bigram", code: bool = False, embed_device: str | None = None,
|
|
11
|
+
embed_bits: int | None = None, cpu_dtype: str | None = None, quiet: bool = False,
|
|
12
|
+
follow_symlinks: bool = False, max_file_mb: float | None = None) -> dict:
|
|
13
|
+
"""Index files/folders into an index (a name under ~/.llavrag/indexes or a directory). Returns the index manifest.
|
|
14
|
+
Re-running on the same folder only embeds passages that are new or changed. Symbolic links that leave a folder are
|
|
15
|
+
skipped unless follow_symlinks; files over max_file_mb (default $LLAVRAG_MAX_FILE_MB or 256) are skipped."""
|
|
16
|
+
from . import backend, config, weights
|
|
17
|
+
from .embed import Embedder
|
|
18
|
+
from .index import build
|
|
19
|
+
from .placement import plan_index
|
|
20
|
+
if isinstance(paths, (str, os.PathLike)):
|
|
21
|
+
paths = [paths]
|
|
22
|
+
if cjk == "jieba":
|
|
23
|
+
try:
|
|
24
|
+
import jieba # noqa: F401
|
|
25
|
+
except ImportError:
|
|
26
|
+
raise SystemExit("--cjk jieba needs jieba: pip install 'llavrag[cjk]'") from None
|
|
27
|
+
index_dir = config.resolve_index(str(index) if index is not None else None)
|
|
28
|
+
dev = backend.resolve(device or config.device())
|
|
29
|
+
embed_path = weights.ensure("embedder", quiet)
|
|
30
|
+
edev_req = None if embed_device in (None, "auto", "swap") else backend.resolve(embed_device)
|
|
31
|
+
plan = plan_index(dev, embed_path, embed_device=edev_req, embed_bits=embed_bits, cpu_dtype=cpu_dtype)
|
|
32
|
+
edev, ebits = plan.embed_device, (plan.embed_bits if plan.embed_bits < 16 else None)
|
|
33
|
+
if not quiet:
|
|
34
|
+
print(f"placement: embedder only, {edev} {'8-bit' if ebits else 'fp16'}" + "".join(f"; {n}" for n in plan.notes),
|
|
35
|
+
file=sys.stderr)
|
|
36
|
+
base = weights.manifest("embedder")["name"] if not os.environ.get("LLAVRAG_EMBED_PATH") else Path(embed_path).name
|
|
37
|
+
name = f"{base}@{edev}" + (f"-{ebits}bit" if ebits else "")
|
|
38
|
+
return build([Path(p) for p in paths], index_dir,
|
|
39
|
+
lambda: Embedder(embed_path, edev, bits=ebits, cpu_dtype=plan.cpu_dtype),
|
|
40
|
+
passage_chars=passage_chars, embed_batch=embed_batch, embedder_name=name, cjk=cjk, code=code,
|
|
41
|
+
follow_symlinks=follow_symlinks, max_file_mb=max_file_mb)
|
llavrag/backend.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Backend auto-detection: Apple Silicon -> MLX (GPU), NVIDIA -> PyTorch CUDA, otherwise PyTorch CPU (tiny tests).
|
|
2
|
+
`mps` (PyTorch on the Apple GPU) is available on request; it is what the reference dense server used."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.util
|
|
6
|
+
import platform
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _has(module: str) -> bool:
|
|
11
|
+
return importlib.util.find_spec(module) is not None
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def resolve(requested: str = "auto") -> str:
|
|
15
|
+
requested = (requested or "auto").lower()
|
|
16
|
+
if requested not in ("auto", "mlx", "cuda", "mps", "cpu", "mlx-cpu"):
|
|
17
|
+
raise SystemExit(f"unknown device {requested!r} (auto, mlx, cuda, mps, cpu)")
|
|
18
|
+
if requested != "auto":
|
|
19
|
+
return requested
|
|
20
|
+
if sys.platform == "darwin" and platform.machine() == "arm64" and _has("mlx") and _has("mlx_lm"):
|
|
21
|
+
return "mlx"
|
|
22
|
+
if _has("torch"):
|
|
23
|
+
import torch
|
|
24
|
+
if torch.cuda.is_available():
|
|
25
|
+
return "cuda"
|
|
26
|
+
return "cpu"
|
|
27
|
+
if _has("mlx"):
|
|
28
|
+
return "mlx-cpu"
|
|
29
|
+
raise SystemExit("no backend: install mlx + mlx-lm (Apple Silicon) or torch (NVIDIA / CPU)")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def describe(device: str) -> str:
|
|
33
|
+
if device in ("mlx", "mlx-cpu"):
|
|
34
|
+
import mlx.core as mx
|
|
35
|
+
return f"mlx {mx.__version__} ({'gpu' if device == 'mlx' else 'cpu'})"
|
|
36
|
+
import torch
|
|
37
|
+
if device == "cuda":
|
|
38
|
+
return f"torch {torch.__version__} cuda {torch.cuda.get_device_name(0)}"
|
|
39
|
+
return f"torch {torch.__version__} {device}"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
_CUDA_READY = False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def cuda_setup():
|
|
46
|
+
"""Per-process CUDA settings, applied once before the first model goes to the GPU:
|
|
47
|
+
LLAVRAG_CUDA_MEMORY_FRACTION (e.g. 0.95) caps PyTorch's allocator on GPU 0, so a model that does not fit raises an
|
|
48
|
+
out-of-memory error instead of spilling into shared system memory (WSL2 / Windows drivers do that silently)."""
|
|
49
|
+
global _CUDA_READY
|
|
50
|
+
if _CUDA_READY:
|
|
51
|
+
return
|
|
52
|
+
import os
|
|
53
|
+
import torch
|
|
54
|
+
frac = os.environ.get("LLAVRAG_CUDA_MEMORY_FRACTION")
|
|
55
|
+
if frac:
|
|
56
|
+
torch.cuda.set_per_process_memory_fraction(float(frac), 0)
|
|
57
|
+
_CUDA_READY = True
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def has_accelerate() -> bool:
|
|
61
|
+
return _has("accelerate")
|
llavrag/cli.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""llavrag command line: demo / doctor / index / search / pilot / mcp / download / info."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import textwrap
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import warnings
|
|
13
|
+
|
|
14
|
+
warnings.filterwarnings("ignore", category=SyntaxWarning) # optional jieba (CJK) regex literals on Python 3.12+
|
|
15
|
+
logging.getLogger("torch.distributed.elastic.multiprocessing.redirects").setLevel(logging.ERROR)
|
|
16
|
+
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
|
17
|
+
os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error")
|
|
18
|
+
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _common(p):
|
|
22
|
+
p.add_argument("--index", help="index name (under ~/.llavrag/indexes) or directory; default: $LLAVRAG_INDEX or 'default'")
|
|
23
|
+
p.add_argument("--device", default=None, help="auto | mlx | cuda | mps | cpu (default: $LLAVRAG_DEVICE or auto)")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _placement(p, judge=True):
|
|
27
|
+
if judge:
|
|
28
|
+
p.add_argument("--judge-device", default=None, help="force the judge's device (mlx, cuda, mps, cpu)")
|
|
29
|
+
p.add_argument("--judge-bits", type=int, choices=(16, 8), default=None,
|
|
30
|
+
help="16 = fp16 (exact parity; default when it fits), 8 = 8-bit")
|
|
31
|
+
p.add_argument("--embed-bits", type=int, choices=(16, 8), default=None, help="embedder precision (default: auto)")
|
|
32
|
+
p.add_argument("--cpu-dtype", choices=("float32", "bfloat16"), default=None,
|
|
33
|
+
help="dtype for a model placed on the CPU (default float32, bfloat16 when RAM is short)")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _judges(p):
|
|
37
|
+
p.add_argument("--judge", default=None,
|
|
38
|
+
help="judge backend: local (default) | local:DIR | https://URL of your own judge endpoint (http:// "
|
|
39
|
+
"only for localhost) | plugin:NAME")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def cmd_index(a):
|
|
43
|
+
from . import config
|
|
44
|
+
from .api import build_index
|
|
45
|
+
index_dir = config.resolve_index(a.index)
|
|
46
|
+
m = build_index(a.paths, a.index, device=a.device, passage_chars=a.passage_chars, embed_batch=a.embed_batch,
|
|
47
|
+
cjk=a.cjk, code=a.code, embed_device=a.embed_device, embed_bits=a.embed_bits, cpu_dtype=a.cpu_dtype,
|
|
48
|
+
follow_symlinks=a.follow_symlinks, max_file_mb=a.max_file_mb)
|
|
49
|
+
rate = f", {m['embedded'] / m['embed_s']:.1f} passages/s embedded" if m["embedded"] and m["embed_s"] else ""
|
|
50
|
+
print(f"indexed {len(m['files'])} files, {m['passages']} passages -> {index_dir} ({m['build_s']}s{rate})")
|
|
51
|
+
if m["skipped"]:
|
|
52
|
+
print(f"skipped {len(m['skipped'])} files (see {index_dir / 'llavrag-index.json'})")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _print_results(res, full: bool, width: int = 100):
|
|
56
|
+
print(f"\nQ: {res['question']}\n")
|
|
57
|
+
for r in res["results"]:
|
|
58
|
+
where = Path(r["source"]).name if r["source"] else "?"
|
|
59
|
+
if r.get("page"):
|
|
60
|
+
where += f" p.{r['page']}"
|
|
61
|
+
if r.get("line"):
|
|
62
|
+
where += f" line {r['line']}"
|
|
63
|
+
print(f"{r['rank']:>2}. p={r['p']:.3f} {r['title']} [{where}] (passage {r['passage_id']})")
|
|
64
|
+
text = " ".join(r["text"].split())
|
|
65
|
+
if not full and len(text) > 360:
|
|
66
|
+
text = text[:360].rsplit(" ", 1)[0] + " ..."
|
|
67
|
+
print(textwrap.indent(textwrap.fill(text, width - 6), " "))
|
|
68
|
+
sec = res["seconds"]
|
|
69
|
+
tier = " (one search pass: round 0 only)" if res.get("tier") == "one-pass" else ""
|
|
70
|
+
print(f"\n{res['judged_passages']} passages judged ({res['judgments']} judgments) in {res['wall_s']:.1f}s; "
|
|
71
|
+
f"judge {sec['judge']:.1f}s, dense {sec['dense']:.1f}s{tier}")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _where(r) -> str:
|
|
75
|
+
where = Path(r["source"]).name if r.get("source") else "?"
|
|
76
|
+
if r.get("page"):
|
|
77
|
+
where += f" p.{r['page']}"
|
|
78
|
+
return where
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _print_one_pass(res):
|
|
82
|
+
"""`--compare`: the round-0 ranking of the same run, marked against llavRAG's results."""
|
|
83
|
+
mine = {r["passage_id"] for r in res["results"]}
|
|
84
|
+
print(f"\nOne search pass (round 0 of the same run: the same judge, question alone), top {len(res['one_pass'])}:")
|
|
85
|
+
for r in res["one_pass"]:
|
|
86
|
+
print(f"{r['rank']:>2}. p={r['p']:.3f} {r['title']} [{_where(r)}]" + ("" if r["passage_id"] in mine else
|
|
87
|
+
" (not in llavRAG's list)"))
|
|
88
|
+
gone = [r for r in res["results"] if r["passage_id"] not in {x["passage_id"] for x in res["one_pass"]}]
|
|
89
|
+
for r in gone:
|
|
90
|
+
print(f" llavRAG adds: rank {r['rank']}, p={r['p']:.3f} {r['title']} [{_where(r)}]")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def cmd_search(a):
|
|
94
|
+
from . import config
|
|
95
|
+
from .engine import Searcher
|
|
96
|
+
questions = list(a.question)
|
|
97
|
+
if questions == ["-"]:
|
|
98
|
+
questions = [line.strip() for line in sys.stdin if line.strip()]
|
|
99
|
+
s = Searcher(config.resolve_index(a.index), device=a.device, embed_device=a.embed_device,
|
|
100
|
+
judge_batch=a.judge_batch, config_overrides={"top_k": a.top_k}, quiet=a.json, judge=a.judge,
|
|
101
|
+
judge_device=a.judge_device, judge_bits=a.judge_bits, embed_bits=a.embed_bits,
|
|
102
|
+
cpu_dtype=a.cpu_dtype)
|
|
103
|
+
try:
|
|
104
|
+
for q in questions:
|
|
105
|
+
if a.one_pass:
|
|
106
|
+
res = s.one_pass(q)
|
|
107
|
+
elif a.compare:
|
|
108
|
+
res = s.compare(q, log_states=a.log_states)
|
|
109
|
+
else:
|
|
110
|
+
res = s.search(q, log_states=a.log_states)
|
|
111
|
+
if a.json:
|
|
112
|
+
print(json.dumps(res, ensure_ascii=False))
|
|
113
|
+
sys.stdout.flush()
|
|
114
|
+
else:
|
|
115
|
+
_print_results(res, a.full)
|
|
116
|
+
if a.compare:
|
|
117
|
+
_print_one_pass(res)
|
|
118
|
+
finally:
|
|
119
|
+
s.close()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def cmd_mcp(a):
|
|
123
|
+
from .mcp_server import serve
|
|
124
|
+
serve(a)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def cmd_download(a):
|
|
128
|
+
from . import weights
|
|
129
|
+
kinds = ("judge", "embedder") if a.what == "all" else (a.what,)
|
|
130
|
+
if a.source and len(kinds) != 1:
|
|
131
|
+
raise SystemExit("--from needs one model: llavrag download judge|embedder --from DIR_OR_URL")
|
|
132
|
+
progress = weights.Progress(0 if a.source else sum(weights.missing_bytes(k) for k in kinds))
|
|
133
|
+
for k in kinds:
|
|
134
|
+
print(k, weights.ensure(k, source=a.source, progress=progress))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def cmd_info(a):
|
|
138
|
+
from . import __version__, backend, config, weights
|
|
139
|
+
print(f"llavrag {__version__}")
|
|
140
|
+
print(f"python {sys.version.split()[0]} on {sys.platform}")
|
|
141
|
+
try:
|
|
142
|
+
dev = backend.resolve(a.device or config.device())
|
|
143
|
+
print(f"backend: {dev} ({backend.describe(dev)})")
|
|
144
|
+
except SystemExit as e:
|
|
145
|
+
print(f"backend: none ({e})")
|
|
146
|
+
print(f"home: {config.home()}")
|
|
147
|
+
for k in ("judge", "embedder"):
|
|
148
|
+
m = weights.manifest(k)
|
|
149
|
+
env = os.environ.get(f"LLAVRAG_{weights.KINDS[k]}_PATH")
|
|
150
|
+
local = Path(env) if env else config.models_dir() / m["name"]
|
|
151
|
+
ok = (local / "config.json").exists()
|
|
152
|
+
print(f"{k}: {m['name']} -> {local} ({'present' if ok else 'not downloaded'})")
|
|
153
|
+
try:
|
|
154
|
+
from .placement import plan_index, plan_search, probe
|
|
155
|
+
dev = backend.resolve(a.device or config.device())
|
|
156
|
+
jp = os.environ.get("LLAVRAG_JUDGE_PATH") or config.models_dir() / weights.manifest("judge")["name"]
|
|
157
|
+
ep = os.environ.get("LLAVRAG_EMBED_PATH") or config.models_dir() / weights.manifest("embedder")["name"]
|
|
158
|
+
mem = probe(dev if dev in ("cuda", "mlx") else "cpu")
|
|
159
|
+
print(f"memory: {mem.kind}, {mem.accel_free_gb:.1f} GB usable of {mem.accel_total_gb:.1f} GB; free RAM "
|
|
160
|
+
f"{mem.ram_free_gb:.1f} GB")
|
|
161
|
+
ps = plan_search(dev, jp, ep, mem=mem)
|
|
162
|
+
print(f"search placement: {ps.describe()}" + "".join(f"\n - {n}" for n in ps.notes))
|
|
163
|
+
pi = plan_index(dev, ep, mem=mem)
|
|
164
|
+
print(f"index placement: embedder {pi.embed_device} {'fp16' if pi.embed_bits == 16 else '8-bit'}")
|
|
165
|
+
except SystemExit as e:
|
|
166
|
+
print(f"placement: {e}")
|
|
167
|
+
idx = config.resolve_index(a.index)
|
|
168
|
+
mf = idx / "llavrag-index.json"
|
|
169
|
+
if mf.exists():
|
|
170
|
+
from .index import FORMAT
|
|
171
|
+
m = json.loads(mf.read_text())
|
|
172
|
+
old = "" if m.get("format", 2) >= FORMAT else " -- built by llavrag 0.2: run `llavrag index` again"
|
|
173
|
+
print(f"index: {idx} ({len(m['files'])} files, {m['passages']} passages, built {m['created']}){old}")
|
|
174
|
+
else:
|
|
175
|
+
print(f"index: {idx} (not built)")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def cmd_pilot(a):
|
|
179
|
+
from .pilot import main as pilot_main
|
|
180
|
+
raise SystemExit(pilot_main(a))
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def cmd_doctor(a):
|
|
184
|
+
from .doctor import main as doctor_main
|
|
185
|
+
raise SystemExit(doctor_main(a))
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def cmd_demo(a):
|
|
189
|
+
from .demo import main as demo_main
|
|
190
|
+
raise SystemExit(demo_main(a))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def main(argv=None):
|
|
194
|
+
p = argparse.ArgumentParser(prog="llavrag", description="Self-hosted multi-hop retrieval with an evidence judge.")
|
|
195
|
+
p.add_argument("--version", action="version", version=f"llavrag {__import__('llavrag').__version__}")
|
|
196
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
197
|
+
pdemo = sub.add_parser("demo", help="first run: check the machine, get the models, index the sample folder and "
|
|
198
|
+
"answer a three-hop question (one search pass vs llavRAG, live)")
|
|
199
|
+
_common(pdemo)
|
|
200
|
+
pdemo.set_defaults(index="demo")
|
|
201
|
+
pdemo.add_argument("--yes", "-y", action="store_true", help="continue even if `llavrag doctor` reports a problem")
|
|
202
|
+
pdemo.add_argument("--verbose", action="store_true", help="show indexing and model-loading logs")
|
|
203
|
+
pdemo.set_defaults(func=cmd_demo)
|
|
204
|
+
ppil = sub.add_parser("pilot", help="score your own questions: one search pass vs llavRAG, against the files each "
|
|
205
|
+
"answer needs (JSONL: {\"question\": ..., \"expect\": [file, ...]})")
|
|
206
|
+
ppil.add_argument("questions", help="JSONL file, one {\"question\": str, \"expect\": [file names]} per line")
|
|
207
|
+
_common(ppil)
|
|
208
|
+
ppil.add_argument("-k", "--top-k", type=int, default=5, help="passages per question to look in (default 5)")
|
|
209
|
+
ppil.add_argument("--json", action="store_true", help="print the report as one JSON object")
|
|
210
|
+
ppil.add_argument("--chains", type=int, default=2, help="evidence chains to print for the biggest wins (default 2)")
|
|
211
|
+
ppil.add_argument("--embed-device", default=None)
|
|
212
|
+
_judges(ppil)
|
|
213
|
+
_placement(ppil)
|
|
214
|
+
ppil.set_defaults(func=cmd_pilot)
|
|
215
|
+
pdoc = sub.add_parser("doctor", help="check this machine: Python, backend, memory, disk, models, network; "
|
|
216
|
+
"verdict and expected time per question")
|
|
217
|
+
pdoc.add_argument("--device", default=None, help="auto | mlx | cuda | mps | cpu (default: $LLAVRAG_DEVICE or auto)")
|
|
218
|
+
pdoc.add_argument("--json", action="store_true", help="print the report as one JSON object")
|
|
219
|
+
pdoc.add_argument("--offline", action="store_true", help="skip the huggingface.co checks")
|
|
220
|
+
pdoc.set_defaults(func=cmd_doctor)
|
|
221
|
+
pi = sub.add_parser("index", help="index a folder (PDF, DOCX, MD, TXT, HTML; JSONL passages)")
|
|
222
|
+
pi.add_argument("paths", nargs="+")
|
|
223
|
+
_common(pi)
|
|
224
|
+
pi.add_argument("--embed-device", default=None, help="device for the embedder (default: same as --device)")
|
|
225
|
+
pi.add_argument("--passage-chars", type=int, default=1200, help="maximum passage size in characters")
|
|
226
|
+
pi.add_argument("--embed-batch", type=int, default=16)
|
|
227
|
+
pi.add_argument("--cjk", choices=("bigram", "jieba"), default="bigram",
|
|
228
|
+
help="lexical tokens for Chinese/Japanese/Korean runs: character bigrams (default) or jieba words "
|
|
229
|
+
"(pip install 'llavrag[cjk]')")
|
|
230
|
+
pi.add_argument("--code", action="store_true",
|
|
231
|
+
help="experimental: also index source code (.py .js .ts .go .rs .java .c .cpp .h .rb .php; .md as text)")
|
|
232
|
+
pi.add_argument("--follow-symlinks", action="store_true",
|
|
233
|
+
help="follow symbolic links, also to files and folders outside the indexed folder (default: links "
|
|
234
|
+
"that leave the folder are skipped and listed under 'skipped')")
|
|
235
|
+
pi.add_argument("--max-file-mb", type=float, default=None,
|
|
236
|
+
help="skip input files larger than this (default: $LLAVRAG_MAX_FILE_MB or 256)")
|
|
237
|
+
_placement(pi, judge=False)
|
|
238
|
+
pi.set_defaults(func=cmd_index)
|
|
239
|
+
ps = sub.add_parser("search", help="search the index; prints passages with probabilities and sources")
|
|
240
|
+
ps.add_argument("question", nargs="+", help="one or more questions ('-' = one per line on stdin)")
|
|
241
|
+
_common(ps)
|
|
242
|
+
ps.add_argument("-k", "--top-k", type=int, default=10)
|
|
243
|
+
ps.add_argument("--json", action="store_true", help="one JSON object per question on stdout")
|
|
244
|
+
ps.add_argument("--full", action="store_true", help="print whole passages")
|
|
245
|
+
ps.add_argument("--embed-device", default=None)
|
|
246
|
+
ps.add_argument("--judge-batch", type=int, default=None, help="sequences per judge forward pass (default 8)")
|
|
247
|
+
ps.add_argument("--log-states", action="store_true",
|
|
248
|
+
help="with --json: add every judge state with the passages judged under it and their probabilities")
|
|
249
|
+
mode = ps.add_mutually_exclusive_group()
|
|
250
|
+
mode.add_argument("--one-pass", action="store_true",
|
|
251
|
+
help="baseline: round 0 only (hybrid search scored by the same judge against the question alone, "
|
|
252
|
+
"as in search-once-and-rerank); about a third of the judge calls")
|
|
253
|
+
mode.add_argument("--compare", action="store_true",
|
|
254
|
+
help="full search plus the round-0 ranking of the same run (JSON: 'one_pass'): one pass vs "
|
|
255
|
+
"llavRAG from one run")
|
|
256
|
+
_judges(ps)
|
|
257
|
+
_placement(ps)
|
|
258
|
+
ps.set_defaults(func=cmd_search)
|
|
259
|
+
pm = sub.add_parser("mcp", help="run the stdio MCP server (tools: search, get_passage, list_sources)")
|
|
260
|
+
_common(pm)
|
|
261
|
+
pm.add_argument("--embed-device", default=None)
|
|
262
|
+
pm.add_argument("--lazy", action="store_true", help="load the models on the first search, not at start-up")
|
|
263
|
+
_judges(pm)
|
|
264
|
+
_placement(pm)
|
|
265
|
+
pm.set_defaults(func=cmd_mcp)
|
|
266
|
+
pd = sub.add_parser("download", help="download the model weights now (resumable, sha256-checked)")
|
|
267
|
+
pd.add_argument("what", nargs="?", default="all", choices=("all", "judge", "embedder"))
|
|
268
|
+
pd.add_argument("--from", dest="source", default=None, metavar="DIR_OR_URL",
|
|
269
|
+
help="take the files from a local directory (or another base URL) instead of the manifest URL; "
|
|
270
|
+
"sha256 is still checked")
|
|
271
|
+
pd.set_defaults(func=cmd_download)
|
|
272
|
+
pinfo = sub.add_parser("info", help="show backend, weights and index status")
|
|
273
|
+
_common(pinfo)
|
|
274
|
+
pinfo.set_defaults(func=cmd_info)
|
|
275
|
+
a = p.parse_args(argv)
|
|
276
|
+
a.func(a)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
if __name__ == "__main__":
|
|
280
|
+
main()
|
llavrag/config.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Paths and settings. Everything can be overridden with environment variables:
|
|
2
|
+
|
|
3
|
+
LLAVRAG_HOME base directory for weights and caches (default ~/.llavrag)
|
|
4
|
+
LLAVRAG_DEVICE auto | mlx | cuda | mps | cpu (default auto)
|
|
5
|
+
LLAVRAG_JUDGE_PATH local judge weights directory (skips download)
|
|
6
|
+
LLAVRAG_JUDGE_URL base URL the judge files are downloaded from (overrides the built-in manifest URL)
|
|
7
|
+
LLAVRAG_EMBED_PATH local Qwen3-Embedding-4B directory (skips download)
|
|
8
|
+
LLAVRAG_EMBED_URL base URL for the embedder files
|
|
9
|
+
LLAVRAG_INDEX default index for `index` / `search` / `mcp` (a name under ~/.llavrag/indexes or a path;
|
|
10
|
+
default: "default")
|
|
11
|
+
LLAVRAG_MAX_FILE_MB size cap per input file when indexing (default 256)
|
|
12
|
+
|
|
13
|
+
Folders that llavrag creates (the home directory, indexes, model folders) get mode 0700 and the files it writes there
|
|
14
|
+
mode 0600.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import os
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
DEFAULT_INDEX = "default"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def home() -> Path:
|
|
25
|
+
"""The base directory (not created here; private_dir() creates it 0700 when something is first written)."""
|
|
26
|
+
return Path(os.environ.get("LLAVRAG_HOME", Path.home() / ".llavrag")).expanduser()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def private_dir(path: Path) -> Path:
|
|
30
|
+
"""Create `path` and any missing parent folders with mode 0700 (only the user can list or read them). Folders that
|
|
31
|
+
already exist keep their mode."""
|
|
32
|
+
path = Path(path)
|
|
33
|
+
missing = []
|
|
34
|
+
p = path
|
|
35
|
+
while not p.is_dir():
|
|
36
|
+
missing.append(p)
|
|
37
|
+
if p.parent == p:
|
|
38
|
+
break
|
|
39
|
+
p = p.parent
|
|
40
|
+
for d in reversed(missing):
|
|
41
|
+
try:
|
|
42
|
+
d.mkdir(mode=0o700)
|
|
43
|
+
except FileExistsError:
|
|
44
|
+
pass
|
|
45
|
+
return path
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def open_private(path: Path, mode: str = "wb", encoding: str | None = None):
|
|
49
|
+
"""Open a file for writing with mode 0600 (also tightened if the file existed). mode: "wb", "ab", "w" or "a".
|
|
50
|
+
A symbolic link at `path` is refused (O_NOFOLLOW), so a planted link cannot redirect the write."""
|
|
51
|
+
flags = os.O_WRONLY | os.O_CREAT | (os.O_APPEND if mode.startswith("a") else os.O_TRUNC) | getattr(os, "O_NOFOLLOW", 0)
|
|
52
|
+
fd = os.open(path, flags, 0o600)
|
|
53
|
+
try:
|
|
54
|
+
os.fchmod(fd, 0o600)
|
|
55
|
+
except OSError:
|
|
56
|
+
pass
|
|
57
|
+
return os.fdopen(fd, mode, encoding=encoding) if "b" not in mode else os.fdopen(fd, mode)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def write_private(path: Path, data: str | bytes) -> None:
|
|
61
|
+
"""Write a whole file with mode 0600."""
|
|
62
|
+
if isinstance(data, str):
|
|
63
|
+
with open_private(path, "w", encoding="utf-8") as f:
|
|
64
|
+
f.write(data)
|
|
65
|
+
else:
|
|
66
|
+
with open_private(path, "wb") as f:
|
|
67
|
+
f.write(data)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def models_dir() -> Path:
|
|
71
|
+
return home() / "models"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def cache_dir() -> Path:
|
|
75
|
+
return home() / "cache"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def resolve_index(arg: str | None = None) -> Path:
|
|
79
|
+
"""A bare name (no path separator, not starting with . or ~) is an index under ~/.llavrag/indexes/; anything else
|
|
80
|
+
is a directory path."""
|
|
81
|
+
value = arg or os.environ.get("LLAVRAG_INDEX") or DEFAULT_INDEX
|
|
82
|
+
if os.sep in value or value.startswith((".", "~")) or (os.altsep and os.altsep in value):
|
|
83
|
+
return Path(value).expanduser().resolve()
|
|
84
|
+
return home() / "indexes" / value
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def device() -> str:
|
|
88
|
+
return os.environ.get("LLAVRAG_DEVICE", "auto").lower()
|
llavrag/core/__init__.py
ADDED
llavrag/core/cache.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Append-only JSONL caches for judge answers and dense results (thread-safe); keys are sha1 hex digests."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import threading
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def key(*parts) -> str:
|
|
11
|
+
h = hashlib.sha1()
|
|
12
|
+
for p in parts:
|
|
13
|
+
h.update((p if isinstance(p, str) else json.dumps(p, sort_keys=True, ensure_ascii=False)).encode())
|
|
14
|
+
h.update(b"\x00")
|
|
15
|
+
return h.hexdigest()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class JsonlCache:
|
|
19
|
+
def __init__(self, path: str | Path | None):
|
|
20
|
+
self.path = Path(path) if path else None
|
|
21
|
+
self.data: dict[str, object] = {}
|
|
22
|
+
self.lock = threading.Lock()
|
|
23
|
+
if self.path and self.path.exists():
|
|
24
|
+
for line in self.path.read_text().splitlines():
|
|
25
|
+
try:
|
|
26
|
+
k, v = json.loads(line)
|
|
27
|
+
self.data[k] = v
|
|
28
|
+
except ValueError:
|
|
29
|
+
continue # interrupted write
|
|
30
|
+
|
|
31
|
+
def get(self, k: str):
|
|
32
|
+
return self.data.get(k)
|
|
33
|
+
|
|
34
|
+
def put_many(self, items: dict[str, object]) -> None:
|
|
35
|
+
if not items:
|
|
36
|
+
return
|
|
37
|
+
with self.lock:
|
|
38
|
+
self.data.update(items)
|
|
39
|
+
if self.path:
|
|
40
|
+
with self.path.open("a") as f:
|
|
41
|
+
for k, v in items.items():
|
|
42
|
+
f.write(json.dumps([k, v], ensure_ascii=False) + "\n")
|
llavrag/core/chunk.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Document -> chunks (own code): a document up to max_chars is one chunk; a longer one is cut at sentence ends into the
|
|
2
|
+
smallest number of chunks <= max_chars, balanced in length (hard cut inside a sentence only if one sentence is too long)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
_SENT_END = re.compile(r"(?<=[.!?。!?;;])\s+|\n+")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def split_text(text: str, max_chars: int = 2048) -> list[str]:
|
|
12
|
+
text = text or ""
|
|
13
|
+
if len(text) <= max_chars:
|
|
14
|
+
return [text]
|
|
15
|
+
pieces: list[str] = []
|
|
16
|
+
for s in _SENT_END.split(text):
|
|
17
|
+
s = s.strip()
|
|
18
|
+
while len(s) > max_chars:
|
|
19
|
+
pieces.append(s[:max_chars])
|
|
20
|
+
s = s[max_chars:]
|
|
21
|
+
if s:
|
|
22
|
+
pieces.append(s)
|
|
23
|
+
n = math.ceil(len(text) / max_chars)
|
|
24
|
+
target = len(text) / n
|
|
25
|
+
chunks, cur = [], ""
|
|
26
|
+
for s in pieces:
|
|
27
|
+
if cur and (len(cur) + 1 + len(s) > max_chars or len(cur) >= target):
|
|
28
|
+
chunks.append(cur)
|
|
29
|
+
cur = s
|
|
30
|
+
else:
|
|
31
|
+
cur = f"{cur} {s}" if cur else s
|
|
32
|
+
if cur:
|
|
33
|
+
chunks.append(cur)
|
|
34
|
+
return chunks
|
llavrag/core/data.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Benchmark data in the HippoRAG-2 release format ({ds}.json + {ds}_corpus.json) and gold passages (own code)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def load(data_dir: str | Path, dataset: str) -> tuple[list[dict], list[dict]]:
|
|
9
|
+
d = Path(data_dir)
|
|
10
|
+
return json.loads((d / f"{dataset}.json").read_text()), json.loads((d / f"{dataset}_corpus.json").read_text())
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _maybe(v):
|
|
14
|
+
if isinstance(v, str) and v[:1] in "[{":
|
|
15
|
+
try:
|
|
16
|
+
return json.loads(v)
|
|
17
|
+
except ValueError:
|
|
18
|
+
import ast
|
|
19
|
+
return ast.literal_eval(v)
|
|
20
|
+
return v
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def question_id(rec: dict) -> str:
|
|
24
|
+
return str(rec.get("id") or rec.get("_id"))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def gold_passages(rec: dict, kind: str) -> list[tuple[str, str]]:
|
|
28
|
+
"""(title, text) of the supporting passages. kind: musique | 2wiki | hotpot (from the dataset name)."""
|
|
29
|
+
if kind == "musique":
|
|
30
|
+
return [(p["title"], p["paragraph_text"]) for p in _maybe(rec["paragraphs"]) if str(p.get("is_supporting")) in ("True", "true", "1")]
|
|
31
|
+
sup = {t for t, _ in _maybe(rec["supporting_facts"])}
|
|
32
|
+
joiner = " " if kind == "2wiki" else ""
|
|
33
|
+
out, seen = [], set()
|
|
34
|
+
for title, sents in _maybe(rec["context"]):
|
|
35
|
+
if title in sup and title not in seen:
|
|
36
|
+
seen.add(title)
|
|
37
|
+
out.append((title, joiner.join(sents)))
|
|
38
|
+
return out
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def kind_of(dataset: str) -> str:
|
|
42
|
+
d = dataset.lower()
|
|
43
|
+
return "musique" if d.startswith("musique") else "2wiki" if "2wiki" in d else "hotpot"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def gold_doc_ids(records: list[dict], corpus: list[dict], dataset: str) -> dict[str, list[int]]:
|
|
47
|
+
"""question id -> corpus indices of its gold passages (-1 if a gold passage is not in the corpus)."""
|
|
48
|
+
kind = kind_of(dataset)
|
|
49
|
+
by_pair = {}
|
|
50
|
+
by_title: dict[str, list[int]] = {}
|
|
51
|
+
for i, c in enumerate(corpus):
|
|
52
|
+
by_pair.setdefault((c["title"], c["text"]), i)
|
|
53
|
+
by_title.setdefault(c["title"], []).append(i)
|
|
54
|
+
norm = lambda s: " ".join(s.split())
|
|
55
|
+
by_npair = {}
|
|
56
|
+
for i, c in enumerate(corpus):
|
|
57
|
+
by_npair.setdefault((c["title"], norm(c["text"])), i)
|
|
58
|
+
out = {}
|
|
59
|
+
for r in records:
|
|
60
|
+
ids = []
|
|
61
|
+
for t, x in gold_passages(r, kind):
|
|
62
|
+
i = by_pair.get((t, x))
|
|
63
|
+
if i is None:
|
|
64
|
+
i = by_npair.get((t, norm(x)))
|
|
65
|
+
if i is None and len(by_title.get(t, [])) == 1:
|
|
66
|
+
i = by_title[t][0]
|
|
67
|
+
ids.append(-1 if i is None else i)
|
|
68
|
+
out[question_id(r)] = ids
|
|
69
|
+
return out
|