initial commit: retrieval + agent artifacts
This commit is contained in:
@@ -0,0 +1,5 @@
|
|||||||
|
RAGLAB_DSN=postgresql://pi:raglab_local_pw@127.0.0.1:5432/rag_lab
|
||||||
|
RAGLAB_EMBED_MODEL=sentence-transformers/all-MiniLM-L6-v2
|
||||||
|
# for Russian corpora: sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2
|
||||||
|
RAGLAB_RERANK_MODEL=Xenova/ms-marco-MiniLM-L-6-v2
|
||||||
|
RAGLAB_LEXICAL_CONFIG=english
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
data/
|
||||||
|
results/
|
||||||
|
.env
|
||||||
|
*.zip
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
PY ?= python
|
||||||
|
|
||||||
|
data:
|
||||||
|
$(PY) scripts/fetch_beir.py --dataset scifact
|
||||||
|
|
||||||
|
ingest:
|
||||||
|
$(PY) scripts/ingest.py
|
||||||
|
|
||||||
|
eval:
|
||||||
|
$(PY) scripts/evaluate.py
|
||||||
|
|
||||||
|
api:
|
||||||
|
uvicorn raglab.api:app --app-dir src --host 127.0.0.1 --port 8088
|
||||||
|
|
||||||
|
test:
|
||||||
|
$(PY) -m pytest -q
|
||||||
|
|
||||||
|
.PHONY: data ingest eval api test
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# rag-lab
|
||||||
|
|
||||||
|
Hybrid retrieval with measured quality: lexical search, dense vectors and rank fusion in
|
||||||
|
PostgreSQL, with an honest evaluation on a public benchmark instead of a demo that looks nice.
|
||||||
|
|
||||||
|
The point of this repository is not "I built a RAG". It is "I can tell you what each retrieval
|
||||||
|
decision is worth in recall and latency, and I can show the code that produced the numbers".
|
||||||
|
|
||||||
|
## What is measured
|
||||||
|
|
||||||
|
Benchmark: [BEIR SciFact](https://github.com/allenai/beir) — 5,183 scientific documents,
|
||||||
|
339 test queries with graded relevance judgements. Same corpus, same queries, four modes:
|
||||||
|
|
||||||
|
| mode | recall@1 | recall@10 | MRR@10 | nDCG@10 | p50, ms | p95, ms |
|
||||||
|
|------|----------|-----------|--------|---------|---------|---------|
|
||||||
|
| lexical (BM25, k1=1.2 b=0.75) | 0.517 | 0.759 | 0.614 | 0.645 | 66.2 | 87.0 |
|
||||||
|
| dense (all-MiniLM-L6-v2, cosine, HNSW) | 0.484 | 0.817 | 0.618 | 0.662 | 39.8 | 62.8 |
|
||||||
|
| hybrid (reciprocal rank fusion) | 0.540 | 0.830 | 0.654 | 0.691 | 114.1 | 264.9 |
|
||||||
|
| hybrid + cross-encoder rerank | _running_ | _running_ | _running_ | _running_ | _running_ | _running_ |
|
||||||
|
|
||||||
|
Numbers are produced by `scripts/evaluate.py` and stored in `results/eval.json`. Nothing in the
|
||||||
|
table is written by hand. 300 of 339 test queries were used (the rest have no corpus document to
|
||||||
|
retrieve). Metrics are computed per document: chunks of one document are collapsed in rank order
|
||||||
|
before scoring, otherwise a document with many chunks would inflate recall and nDCG.
|
||||||
|
|
||||||
|
Reference point: the published BM25 baseline for SciFact in BEIR is nDCG@10 about 0.66, so the
|
||||||
|
lexical column is in the right ballpark instead of looking artificially weak.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
queries ──┬── lexical: BM25 in Python over the same chunk table
|
||||||
|
├── dense: bge-small-en -> vector(384) (HNSW, cosine)
|
||||||
|
└── fusion: reciprocal rank fusion, k=60
|
||||||
|
└── optional cross-encoder rerank (top-N -> top-k)
|
||||||
|
```
|
||||||
|
|
||||||
|
- `chunks` table keeps `doc_id`, heading trail, text, `tsvector` and `vector(384)`.
|
||||||
|
- A `tsvector` column and GIN index are kept by a trigger as well; BM25 was chosen for the
|
||||||
|
measured numbers, `tsvector` remains available as a mode for comparison.
|
||||||
|
- HNSW index uses `m=16, ef_construction=64`.
|
||||||
|
- Chunking is markdown-aware: heading trail is preserved, so a retrieved fragment is readable
|
||||||
|
on its own.
|
||||||
|
|
||||||
|
## Why these choices
|
||||||
|
|
||||||
|
**Lexical is not a legacy fallback.** In scientific text exact terms and identifiers matter, and
|
||||||
|
BM25-style matching often beats dense retrieval there. Dense wins on paraphrases. Fusion keeps
|
||||||
|
both without tuning a weight per query.
|
||||||
|
|
||||||
|
**RRF instead of a weighted sum.** Rank fusion needs no score calibration between two
|
||||||
|
incomparable scales (cosine similarity and `ts_rank_cd`).
|
||||||
|
|
||||||
|
**Reranker is optional and degradable.** Cross-encoders are expensive; if the model cannot be
|
||||||
|
loaded, the service returns the fused order instead of failing the request.
|
||||||
|
|
||||||
|
## Run locally
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m venv .venv && . .venv/bin/activate
|
||||||
|
pip install -e ".[dev]"
|
||||||
|
|
||||||
|
createdb rag_lab
|
||||||
|
psql -d rag_lab -c "CREATE EXTENSION IF NOT EXISTS vector;"
|
||||||
|
|
||||||
|
make data # download BEIR SciFact
|
||||||
|
make ingest # chunk + embed + index
|
||||||
|
make eval # four modes, metrics, latency
|
||||||
|
make api # http://127.0.0.1:8088/docs
|
||||||
|
```
|
||||||
|
|
||||||
|
Environment: `RAGLAB_DSN`, `RAGLAB_EMBED_MODEL`, `RAGLAB_RERANK_MODEL`, `RAGLAB_LEXICAL_CONFIG`.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /health
|
||||||
|
GET /search?q=...&mode=hybrid|dense|lexical|tsvector&k=10&rerank=false
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pytest -q
|
||||||
|
```
|
||||||
|
|
||||||
|
Pure functions only: metric formulas, fusion order, chunk boundaries. No database needed.
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
|
||||||
|
- SciFact is English and scientific; numbers do not transfer to chat logs or Russian support text.
|
||||||
|
- Chunking is markdown-aware, not layout-aware: PDFs and HTML need a parser in front.
|
||||||
|
- No query rewriting, no HyDE, no multi-vector retrieval yet. Those are separate experiments with
|
||||||
|
their own measurements, not guesses.
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
INFO: Started server process [617444]
|
||||||
|
INFO: Waiting for application startup.
|
||||||
|
INFO: Application startup complete.
|
||||||
|
INFO: Uvicorn running on http://127.0.0.1:8088 (Press CTRL+C to quit)
|
||||||
|
INFO: 127.0.0.1:58260 - "GET /health HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:58274 - "GET /search?q=sporulation+efficiency+Bacillus&mode=hybrid&k=3 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:40100 - "GET /search?q=Bacillus+subtilis+clpC+sporulation+efficiency&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:43310 - "GET /search?q=Bacillus+subtilis+clpC+sporulation+efficiency&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:41588 - "GET /search?q=Bacillus+subtilis+clpC+sporulation+efficiency&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:50252 - "GET /search?q=Bacillus+subtilis+clpC+sporulation+efficiency&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:38996 - "GET /search?q=Commelina+yellow+mottle+virus+ComYMV+7489+bp+%22We+have+demonstrated+that+a+construct+containing+1%22&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:59558 - "GET /search?q=%22To+identify+components+of+this+pathway%2C+we+performed+an+RNAi-based+kinome+screen+in+human+cells%22&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:57100 - "GET /search?q=%22maternal+diethylstilbestrol+treatment%22+birth+weight+breast+cancer&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:49798 - "GET /search?q=%22In+vitro+and+ex+vivo+analyses+demonstrate+that+C%22&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:47978 - "GET /search?q=%22early+and+direct+cross-modal+phase+modulation%22+neurophysiology+hypothesis&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:43514 - "GET /search?q=DdrB+Deinococcus+radiodurans+alternative+SSB+crucial+for+recovery+following+DNA+damage&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:37170 - "GET /search?q=%223%2C000+g%22+%22%3C3%2C000+g%22+birth+weight+breast+cancer+effect+estimate&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:33126 - "GET /search?q=metastatic+colorectal+cancer+elderly+single+agent+fluoropyrimidines+oxaliplatin-based+chemotherapy+quality+of+life&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:36074 - "GET /search?q=Cas9-induced+double+strand+breaks+repair+error+prone+human+DNA&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:40596 - "GET /search?q=%22It+is+therefore+fitting+that+we+publish+such+a+paper%22&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:59080 - "GET /search?q=%22Yet+how+the+activity+of+the+SUMO+ligase+is+controlled+remains+unknown%22&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:60316 - "GET /search?q=Bacillus+subtilis+clpC+sporulation+efficiency&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:57624 - "GET /search?q=Commelina+yellow+mottle+virus+ComYMV+7489+bp+%22We+have+demonstrated+that+a+construct+containing+1%22&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:35632 - "GET /search?q=%22To+identify+components+of+this+pathway%2C+we+performed+an+RNAi-based+kinome+screen+in+human+cells%22&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:33770 - "GET /search?q=%22maternal+diethylstilbestrol+treatment%22+birth+weight+breast+cancer&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:54448 - "GET /search?q=%22In+vitro+and+ex+vivo+analyses+demonstrate+that+C%22&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:44750 - "GET /search?q=%22early+and+direct+cross-modal+phase+modulation%22+neurophysiology+hypothesis&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:44762 - "GET /search?q=DdrB+Deinococcus+radiodurans+alternative+SSB+crucial+for+recovery+following+DNA+damage&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:60404 - "GET /search?q=%223%2C000+g%22+%22%3C3%2C000+g%22+birth+weight+breast+cancer+effect+estimate&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:45942 - "GET /search?q=metastatic+colorectal+cancer+elderly+single+agent+fluoropyrimidines+oxaliplatin-based+chemotherapy+quality+of+life&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:45348 - "GET /search?q=Cas9-induced+double+strand+breaks+repair+error+prone+human+DNA&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:40834 - "GET /search?q=%22It+is+therefore+fitting+that+we+publish+such+a+paper%22&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:40838 - "GET /search?q=%22Yet+how+the+activity+of+the+SUMO+ligase+is+controlled+remains+unknown%22&mode=hybrid&k=5 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:51132 - "GET /search?q=Bacillus+subtilis+clpC+sporulation+efficiency&mode=hybrid&k=8 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:49436 - "GET /search?q=Commelina+yellow+mottle+virus+ComYMV+7489+bp+%22We+have+demonstrated+that+a+construct+containing+1%22&mode=hybrid&k=8 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:49452 - "GET /search?q=%22To+identify+components+of+this+pathway%2C+we+performed+an+RNAi-based+kinome+screen+in+human+cells%22&mode=hybrid&k=8 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:38800 - "GET /search?q=%22maternal+diethylstilbestrol+treatment%22+birth+weight+breast+cancer&mode=hybrid&k=8 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:38806 - "GET /search?q=%22In+vitro+and+ex+vivo+analyses+demonstrate+that+C%22&mode=hybrid&k=8 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:47674 - "GET /search?q=%22early+and+direct+cross-modal+phase+modulation%22+neurophysiology+hypothesis&mode=hybrid&k=8 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:43830 - "GET /search?q=DdrB+Deinococcus+radiodurans+alternative+SSB+crucial+for+recovery+following+DNA+damage&mode=hybrid&k=8 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:51940 - "GET /search?q=%223%2C000+g%22+%22%3C3%2C000+g%22+birth+weight+breast+cancer+effect+estimate&mode=hybrid&k=8 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:51956 - "GET /search?q=metastatic+colorectal+cancer+elderly+single+agent+fluoropyrimidines+oxaliplatin-based+chemotherapy+quality+of+life&mode=hybrid&k=8 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:36746 - "GET /search?q=Cas9-induced+double+strand+breaks+repair+error+prone+human+DNA&mode=hybrid&k=8 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:36760 - "GET /search?q=%22It+is+therefore+fitting+that+we+publish+such+a+paper%22&mode=hybrid&k=8 HTTP/1.1" 200 OK
|
||||||
|
INFO: 127.0.0.1:36764 - "GET /search?q=%22Yet+how+the+activity+of+the+SUMO+ligase+is+controlled+remains+unknown%22&mode=hybrid&k=8 HTTP/1.1" 200 OK
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
lexical {"recall@1": 0.5167, "recall@5": 0.7164, "recall@10": 0.7587, "mrr@10": 0.6135, "ndcg@10": 0.6452, "p50_ms": 66.2, "p95_ms": 87.0, "queries": 300}
|
||||||
|
dense {"recall@1": 0.4837, "recall@5": 0.7328, "recall@10": 0.8167, "mrr@10": 0.6179, "ndcg@10": 0.6622, "p50_ms": 39.8, "p95_ms": 62.8, "queries": 300}
|
||||||
|
hybrid {"recall@1": 0.5401, "recall@5": 0.7459, "recall@10": 0.8304, "mrr@10": 0.6542, "ndcg@10": 0.6909, "p50_ms": 114.1, "p95_ms": 264.9, "queries": 300}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
[project]
|
||||||
|
name = "rag-lab"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Hybrid retrieval with measured quality: lexical, dense and RRF fusion, plus reranking"
|
||||||
|
requires-python = ">=3.11"
|
||||||
|
dependencies = [
|
||||||
|
"fastapi>=0.115",
|
||||||
|
"uvicorn[standard]>=0.30",
|
||||||
|
"psycopg[binary]>=3.2",
|
||||||
|
"fastembed>=0.4",
|
||||||
|
"numpy>=1.26",
|
||||||
|
"pydantic>=2.8",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = ["pytest>=8", "ruff>=0.6"]
|
||||||
|
|
||||||
|
[build-system]
|
||||||
|
requires = ["hatchling"]
|
||||||
|
build-backend = "hatchling.build"
|
||||||
|
|
||||||
|
[tool.hatch.build.targets.wheel]
|
||||||
|
packages = ["src/raglab"]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
pythonpath = ["src"]
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
line-length = 120
|
||||||
|
target-version = "py311"
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""Run retrieval modes over a BEIR split and report quality plus latency."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import statistics
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||||
|
|
||||||
|
from raglab.config import Settings # noqa: E402
|
||||||
|
from raglab.metrics import mrr_at_k, ndcg_at_k, recall_at_k, summarize # noqa: E402
|
||||||
|
from raglab.rerank import rerank as rerank_hits # noqa: E402
|
||||||
|
from raglab.search import search # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def load_qrels(path: Path) -> dict[str, dict[str, int]]:
|
||||||
|
qrels: dict[str, dict[str, int]] = {}
|
||||||
|
for line in path.read_text(encoding="utf-8").splitlines()[1:]:
|
||||||
|
if not line.strip():
|
||||||
|
continue
|
||||||
|
query_id, doc_id, score = line.split("\t")
|
||||||
|
qrels.setdefault(query_id, {})[doc_id] = int(score)
|
||||||
|
return qrels
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--data", default="data/scifact")
|
||||||
|
parser.add_argument("--split", default="test")
|
||||||
|
parser.add_argument("--modes", default="lexical,dense,hybrid,hybrid+rerank")
|
||||||
|
parser.add_argument("--limit-queries", type=int, default=0)
|
||||||
|
parser.add_argument("--out", default="results/eval.json")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
settings = Settings.from_env()
|
||||||
|
root = Path(args.data)
|
||||||
|
queries = {row["_id"]: row["text"] for row in map(json.loads, (root / "queries.jsonl").read_text(encoding="utf-8").splitlines()) if row}
|
||||||
|
qrels = load_qrels(root / "qrels" / f"{args.split}.tsv")
|
||||||
|
pairs = [(qid, queries[qid]) for qid in qrels if qid in queries]
|
||||||
|
if args.limit_queries:
|
||||||
|
pairs = pairs[: args.limit_queries]
|
||||||
|
|
||||||
|
report: dict[str, dict] = {}
|
||||||
|
for mode in args.modes.split(","):
|
||||||
|
rows = []
|
||||||
|
latencies = []
|
||||||
|
for query_id, text in pairs:
|
||||||
|
started = time.perf_counter()
|
||||||
|
base_mode = "hybrid" if mode.startswith("hybrid") else mode
|
||||||
|
hits = search(settings, text, mode=base_mode, limit=50)
|
||||||
|
if mode.endswith("+rerank"):
|
||||||
|
hits = rerank_hits(settings.rerank_model, text, hits, limit=10)
|
||||||
|
latencies.append((time.perf_counter() - started) * 1000)
|
||||||
|
# One document may produce several chunks; metrics are document level,
|
||||||
|
# so duplicates collapse in rank order before scoring.
|
||||||
|
ranked = list(dict.fromkeys(hit.doc_id for hit in hits))
|
||||||
|
grades = qrels[query_id]
|
||||||
|
rows.append(
|
||||||
|
{
|
||||||
|
"recall@1": recall_at_k(ranked, grades, 1),
|
||||||
|
"recall@5": recall_at_k(ranked, grades, 5),
|
||||||
|
"recall@10": recall_at_k(ranked, grades, 10),
|
||||||
|
"mrr@10": mrr_at_k(ranked, grades, 10),
|
||||||
|
"ndcg@10": ndcg_at_k(ranked, grades, 10),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
summary = summarize(rows)
|
||||||
|
summary["p50_ms"] = round(statistics.median(latencies), 1)
|
||||||
|
summary["p95_ms"] = round(sorted(latencies)[int(len(latencies) * 0.95) - 1], 1) if latencies else 0.0
|
||||||
|
summary["queries"] = len(rows)
|
||||||
|
report[mode] = summary
|
||||||
|
print(mode, json.dumps(summary, ensure_ascii=False))
|
||||||
|
|
||||||
|
out = Path(args.out)
|
||||||
|
out.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
out.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Download and unpack a BEIR dataset into data/<name>."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import urllib.request
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BASE = "https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--dataset", default="scifact")
|
||||||
|
parser.add_argument("--out", default="data")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
out = Path(args.out)
|
||||||
|
out.mkdir(parents=True, exist_ok=True)
|
||||||
|
archive = out / f"{args.dataset}.zip"
|
||||||
|
if not archive.exists():
|
||||||
|
print(f"downloading {BASE}/{args.dataset}.zip")
|
||||||
|
urllib.request.urlretrieve(f"{BASE}/{args.dataset}.zip", archive)
|
||||||
|
with zipfile.ZipFile(archive) as zf:
|
||||||
|
zf.extractall(out)
|
||||||
|
|
||||||
|
root = out / args.dataset
|
||||||
|
corpus = [json.loads(line) for line in (root / "corpus.jsonl").read_text(encoding="utf-8").splitlines() if line]
|
||||||
|
queries = [json.loads(line) for line in (root / "queries.jsonl").read_text(encoding="utf-8").splitlines() if line]
|
||||||
|
print(json.dumps({"corpus": len(corpus), "queries": len(queries), "root": str(root)}, ensure_ascii=False))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""Chunk, embed and store a BEIR corpus."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||||
|
|
||||||
|
from raglab.chunking import chunk_markdown # noqa: E402
|
||||||
|
from raglab.config import Settings # noqa: E402
|
||||||
|
from raglab.db import apply_schema, insert_chunks, reset # noqa: E402
|
||||||
|
from raglab.embed import embed_passages # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--data", default="data/scifact")
|
||||||
|
parser.add_argument("--schema", default="sql/schema.sql")
|
||||||
|
parser.add_argument("--limit-docs", type=int, default=0)
|
||||||
|
parser.add_argument("--batch", type=int, default=256)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
settings = Settings.from_env()
|
||||||
|
apply_schema(settings, args.schema)
|
||||||
|
|
||||||
|
rows = [json.loads(line) for line in (Path(args.data) / "corpus.jsonl").read_text(encoding="utf-8").splitlines() if line]
|
||||||
|
if args.limit_docs:
|
||||||
|
rows = rows[: args.limit_docs]
|
||||||
|
|
||||||
|
chunks = []
|
||||||
|
for row in rows:
|
||||||
|
doc_id = row["_id"]
|
||||||
|
title = row.get("title") or ""
|
||||||
|
chunks.extend(chunk_markdown(doc_id, f"# {title}\n\n{row.get('text', '')}"))
|
||||||
|
|
||||||
|
print(f"docs={len(rows)} chunks={len(chunks)}")
|
||||||
|
reset(settings)
|
||||||
|
for start in range(0, len(chunks), args.batch):
|
||||||
|
batch = chunks[start : start + args.batch]
|
||||||
|
vectors = embed_passages(settings.embed_model, [c.text for c in batch])
|
||||||
|
insert_chunks(
|
||||||
|
settings,
|
||||||
|
[
|
||||||
|
{"id": c.id, "doc_id": c.doc_id, "title": c.title, "text": c.text, "meta": {**c.meta, "chunk": c.id}, "embedding": vec}
|
||||||
|
for c, vec in zip(batch, vectors, strict=True)
|
||||||
|
],
|
||||||
|
)
|
||||||
|
print(f"inserted {min(start + args.batch, len(chunks))}/{len(chunks)}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS chunks (
|
||||||
|
id text PRIMARY KEY,
|
||||||
|
doc_id text NOT NULL,
|
||||||
|
title text NOT NULL DEFAULT '',
|
||||||
|
text text NOT NULL,
|
||||||
|
meta jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
tsv tsvector,
|
||||||
|
embedding vector(384)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS chunks_doc_idx ON chunks (doc_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS chunks_tsv_idx ON chunks USING GIN (tsv);
|
||||||
|
CREATE INDEX IF NOT EXISTS chunks_embedding_idx
|
||||||
|
ON chunks USING hnsw (embedding vector_cosine_ops)
|
||||||
|
WITH (m = 16, ef_construction = 64);
|
||||||
|
|
||||||
|
-- The tsvector is derived from the text, never written by hand.
|
||||||
|
CREATE OR REPLACE FUNCTION chunks_tsv_update() RETURNS trigger AS $$
|
||||||
|
BEGIN
|
||||||
|
NEW.tsv := to_tsvector('english', coalesce(NEW.title, '') || ' ' || NEW.text);
|
||||||
|
RETURN NEW;
|
||||||
|
END
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS chunks_tsv_trigger ON chunks;
|
||||||
|
CREATE TRIGGER chunks_tsv_trigger BEFORE INSERT OR UPDATE ON chunks
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION chunks_tsv_update();
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
"""rag-lab: hybrid retrieval with measured quality."""
|
||||||
|
__version__ = "0.1.0"
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""HTTP surface: search, stats, health. Thin handlers, no business logic."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from fastapi import FastAPI, HTTPException, Query
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from .config import Settings
|
||||||
|
from .db import count_chunks
|
||||||
|
from .rerank import rerank as rerank_hits
|
||||||
|
from .search import search
|
||||||
|
|
||||||
|
settings = Settings.from_env()
|
||||||
|
app = FastAPI(title="rag-lab", version="0.1.0")
|
||||||
|
|
||||||
|
|
||||||
|
class HitModel(BaseModel):
|
||||||
|
id: str
|
||||||
|
doc_id: str
|
||||||
|
title: str
|
||||||
|
text: str
|
||||||
|
score: float
|
||||||
|
source: str
|
||||||
|
|
||||||
|
|
||||||
|
class SearchResponse(BaseModel):
|
||||||
|
query: str
|
||||||
|
mode: str
|
||||||
|
took_ms: float
|
||||||
|
hits: list[HitModel]
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
def health() -> dict:
|
||||||
|
return {"status": "ok", "chunks": count_chunks(settings)}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/search", response_model=SearchResponse)
|
||||||
|
def search_endpoint(
|
||||||
|
q: str = Query(min_length=2, max_length=512),
|
||||||
|
mode: Literal["dense", "lexical", "hybrid"] = "hybrid",
|
||||||
|
k: int = Query(default=10, ge=1, le=50),
|
||||||
|
rerank: bool = False,
|
||||||
|
) -> SearchResponse:
|
||||||
|
started = time.perf_counter()
|
||||||
|
try:
|
||||||
|
hits = search(settings, q, mode=mode, limit=max(k, 20) if rerank else k)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail={"code": "bad_mode", "message": str(exc)}) from exc
|
||||||
|
if rerank:
|
||||||
|
hits = rerank_hits(settings.rerank_model, q, hits, limit=k)
|
||||||
|
took = (time.perf_counter() - started) * 1000
|
||||||
|
return SearchResponse(query=q, mode=mode, took_ms=round(took, 1), hits=[HitModel(**hit.__dict__) for hit in hits])
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""BM25 over the stored chunks.
|
||||||
|
|
||||||
|
Why not only tsvector: exact terms matter, and BM25 with field length normalisation
|
||||||
|
beats ts_rank_cd on scientific corpora. The index is built once from the table and
|
||||||
|
kept in memory; it is small (one entry per chunk).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
from .config import Settings
|
||||||
|
|
||||||
|
TOKEN = re.compile(r"[a-zа-яё0-9]{2,}")
|
||||||
|
STOP = {
|
||||||
|
"the", "and", "for", "with", "that", "this", "are", "was", "were", "from", "have", "has",
|
||||||
|
"not", "its", "into", "their", "than", "then", "when", "which", "what", "can", "may", "one",
|
||||||
|
"two", "also", "such", "any", "all", "was", "been", "between", "over", "under", "during",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def tokenize(text: str) -> list[str]:
|
||||||
|
return [token for token in TOKEN.findall(text.lower()) if token not in STOP]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BM25Index:
|
||||||
|
tokens: list[list[str]] = field(default_factory=list)
|
||||||
|
doc_ids: list[str] = field(default_factory=list)
|
||||||
|
payloads: list[dict] = field(default_factory=list)
|
||||||
|
lengths: list[int] = field(default_factory=list)
|
||||||
|
df: dict[str, int] = field(default_factory=dict)
|
||||||
|
n: int = 0
|
||||||
|
avg_len: float = 0.0
|
||||||
|
|
||||||
|
def add(self, doc_id: str, text: str, payload: dict | None = None) -> None:
|
||||||
|
tokens = tokenize(text)
|
||||||
|
self.doc_ids.append(doc_id)
|
||||||
|
self.payloads.append(payload or {})
|
||||||
|
self.tokens.append(tokens)
|
||||||
|
self.lengths.append(len(tokens))
|
||||||
|
self.n += 1
|
||||||
|
for token in set(tokens):
|
||||||
|
self.df[token] = self.df.get(token, 0) + 1
|
||||||
|
self.avg_len = (self.avg_len * (self.n - 1) + len(tokens)) / self.n
|
||||||
|
|
||||||
|
def idf(self, token: str) -> float:
|
||||||
|
df = self.df.get(token, 0)
|
||||||
|
return math.log(1 + (self.n - df + 0.5) / (df + 0.5)) if self.n else 0.0
|
||||||
|
|
||||||
|
def search(self, query: str, k: int, k1: float = 1.2, b: float = 0.75) -> list[tuple[str, float, dict]]:
|
||||||
|
scores: list[float] = []
|
||||||
|
query_tokens = set(tokenize(query))
|
||||||
|
if not query_tokens or not self.n:
|
||||||
|
return []
|
||||||
|
for tokens, length in zip(self.tokens, self.lengths, strict=True):
|
||||||
|
tf: dict[str, int] = {}
|
||||||
|
for token in tokens:
|
||||||
|
if token in query_tokens:
|
||||||
|
tf[token] = tf.get(token, 0) + 1
|
||||||
|
score = 0.0
|
||||||
|
norm = k1 * (1 - b + b * length / (self.avg_len or 1.0))
|
||||||
|
for token, count in tf.items():
|
||||||
|
idf = self.idf(token)
|
||||||
|
score += idf * count * (k1 + 1) / (count + norm)
|
||||||
|
scores.append(score)
|
||||||
|
ranked = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)
|
||||||
|
out: list[tuple[str, float, dict]] = []
|
||||||
|
for index in ranked[:k]:
|
||||||
|
if scores[index] > 0:
|
||||||
|
out.append((self.doc_ids[index], scores[index], self.payloads[index]))
|
||||||
|
return out
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""Markdown-aware chunking with overlap.
|
||||||
|
|
||||||
|
The splitter respects headings and paragraph boundaries first, then falls back
|
||||||
|
to a hard window with overlap. Every chunk keeps its heading trail so that a
|
||||||
|
retrieved fragment is readable on its own.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
HEADING = re.compile(r"^(#{1,6})\s+(.*)$")
|
||||||
|
SENTENCE_END = re.compile(r"(?<=[.!?])\s+")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Chunk:
|
||||||
|
id: str
|
||||||
|
doc_id: str
|
||||||
|
title: str
|
||||||
|
text: str
|
||||||
|
meta: dict
|
||||||
|
|
||||||
|
|
||||||
|
def _split_long(text: str, target: int, overlap: int) -> list[str]:
|
||||||
|
if len(text) <= target:
|
||||||
|
return [text]
|
||||||
|
sentences = SENTENCE_END.split(text)
|
||||||
|
parts: list[str] = []
|
||||||
|
current = ""
|
||||||
|
for sentence in sentences:
|
||||||
|
candidate = f"{current} {sentence}".strip()
|
||||||
|
if len(candidate) <= target:
|
||||||
|
current = candidate
|
||||||
|
continue
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
current = sentence
|
||||||
|
while len(current) > target:
|
||||||
|
parts.append(current[:target])
|
||||||
|
current = current[target - overlap:]
|
||||||
|
if current:
|
||||||
|
parts.append(current)
|
||||||
|
return parts
|
||||||
|
|
||||||
|
|
||||||
|
def chunk_markdown(doc_id: str, text: str, target: int = 900, overlap: int = 120) -> list[Chunk]:
|
||||||
|
title = ""
|
||||||
|
trail: list[str] = []
|
||||||
|
blocks: list[tuple[str, str]] = []
|
||||||
|
buffer: list[str] = []
|
||||||
|
|
||||||
|
def flush() -> None:
|
||||||
|
body = "\n".join(buffer).strip()
|
||||||
|
if body:
|
||||||
|
header = " > ".join(trail) if trail else title
|
||||||
|
blocks.append((header, body))
|
||||||
|
buffer.clear()
|
||||||
|
|
||||||
|
for line in text.splitlines():
|
||||||
|
heading = HEADING.match(line)
|
||||||
|
if heading:
|
||||||
|
flush()
|
||||||
|
level = len(heading.group(1))
|
||||||
|
name = heading.group(2).strip()
|
||||||
|
if level == 1 and not title:
|
||||||
|
title = name
|
||||||
|
trail = trail[: level - 1] + [name]
|
||||||
|
continue
|
||||||
|
buffer.append(line)
|
||||||
|
flush()
|
||||||
|
|
||||||
|
chunks: list[Chunk] = []
|
||||||
|
for header, body in blocks:
|
||||||
|
for piece in _split_long(body, target, overlap):
|
||||||
|
digest = hashlib.sha1(f"{doc_id}|{header}|{piece}".encode("utf-8")).hexdigest()[:16]
|
||||||
|
chunks.append(
|
||||||
|
Chunk(
|
||||||
|
id=f"{doc_id}:{digest}",
|
||||||
|
doc_id=doc_id,
|
||||||
|
title=header or title or doc_id,
|
||||||
|
text=piece.strip(),
|
||||||
|
meta={"chars": len(piece)},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return chunks
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""Configuration is read once, from the environment, with sane local defaults."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Settings:
|
||||||
|
dsn: str
|
||||||
|
embed_model: str
|
||||||
|
rerank_model: str
|
||||||
|
lexical_config: str
|
||||||
|
embedding_dim: int
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def from_env() -> "Settings":
|
||||||
|
return Settings(
|
||||||
|
dsn=os.getenv("RAGLAB_DSN", "postgresql://pi:raglab_local_pw@127.0.0.1:5432/rag_lab"),
|
||||||
|
embed_model=os.getenv("RAGLAB_EMBED_MODEL", "sentence-transformers/all-MiniLM-L6-v2"),
|
||||||
|
rerank_model=os.getenv("RAGLAB_RERANK_MODEL", "Xenova/ms-marco-MiniLM-L-6-v2"),
|
||||||
|
lexical_config=os.getenv("RAGLAB_LEXICAL_CONFIG", "english"),
|
||||||
|
embedding_dim=int(os.getenv("RAGLAB_EMBED_DIM", "384")),
|
||||||
|
)
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
"""Database access: one connection per call, no hidden global state."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from typing import Any, Iterator, Sequence
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from .config import Settings
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def connect(settings: Settings) -> Iterator[psycopg.Connection]:
|
||||||
|
with psycopg.connect(settings.dsn, row_factory=dict_row) as conn:
|
||||||
|
yield conn
|
||||||
|
|
||||||
|
|
||||||
|
def apply_schema(settings: Settings, schema_path: str) -> None:
|
||||||
|
with connect(settings) as conn, open(schema_path, encoding="utf-8") as handle:
|
||||||
|
conn.execute(handle.read())
|
||||||
|
|
||||||
|
|
||||||
|
def reset(settings: Settings) -> None:
|
||||||
|
with connect(settings) as conn:
|
||||||
|
conn.execute("TRUNCATE chunks")
|
||||||
|
|
||||||
|
|
||||||
|
def _vector_literal(values: Sequence[float]) -> str:
|
||||||
|
"""pgvector accepts the text form; a Python list would be adapted as an array."""
|
||||||
|
return "[" + ",".join(f"{value:.7f}" for value in values) + "]"
|
||||||
|
|
||||||
|
|
||||||
|
def insert_chunks(settings: Settings, rows: Sequence[dict[str, Any]]) -> int:
|
||||||
|
"""Rows carry id, doc_id, title, text, meta, embedding."""
|
||||||
|
if not rows:
|
||||||
|
return 0
|
||||||
|
with connect(settings) as conn, conn.cursor() as cur:
|
||||||
|
cur.executemany(
|
||||||
|
"""
|
||||||
|
INSERT INTO chunks (id, doc_id, title, text, meta, embedding)
|
||||||
|
VALUES (%(id)s, %(doc_id)s, %(title)s, %(text)s, %(meta)s, %(embedding)s)
|
||||||
|
ON CONFLICT (id) DO UPDATE
|
||||||
|
SET doc_id = EXCLUDED.doc_id,
|
||||||
|
title = EXCLUDED.title,
|
||||||
|
text = EXCLUDED.text,
|
||||||
|
meta = EXCLUDED.meta,
|
||||||
|
embedding = EXCLUDED.embedding
|
||||||
|
""",
|
||||||
|
[
|
||||||
|
dict(
|
||||||
|
row,
|
||||||
|
meta=Jsonb(row.get("meta") or {}),
|
||||||
|
embedding=_vector_literal(row["embedding"]) if row.get("embedding") else None,
|
||||||
|
)
|
||||||
|
for row in rows
|
||||||
|
],
|
||||||
|
)
|
||||||
|
return cur.rowcount
|
||||||
|
|
||||||
|
|
||||||
|
def dense_search(settings: Settings, vector: list[float], limit: int = 50) -> list[dict[str, Any]]:
|
||||||
|
with connect(settings) as conn:
|
||||||
|
return conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, doc_id, title, text, 1 - (embedding <=> %(vector)s::vector) AS score
|
||||||
|
FROM chunks
|
||||||
|
WHERE embedding IS NOT NULL
|
||||||
|
ORDER BY embedding <=> %(vector)s::vector
|
||||||
|
LIMIT %(limit)s
|
||||||
|
""",
|
||||||
|
{"vector": _vector_literal(vector), "limit": limit},
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
|
||||||
|
def lexical_search(settings: Settings, query: str, limit: int = 50) -> list[dict[str, Any]]:
|
||||||
|
with connect(settings) as conn:
|
||||||
|
return conn.execute(
|
||||||
|
f"""
|
||||||
|
SELECT id, doc_id, title, text,
|
||||||
|
ts_rank_cd(tsv, plainto_tsquery('{settings.lexical_config}', %(query)s)) AS score
|
||||||
|
FROM chunks
|
||||||
|
WHERE tsv @@ plainto_tsquery('{settings.lexical_config}', %(query)s)
|
||||||
|
ORDER BY score DESC
|
||||||
|
LIMIT %(limit)s
|
||||||
|
""",
|
||||||
|
{"query": query, "limit": limit},
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
|
||||||
|
def count_chunks(settings: Settings) -> int:
|
||||||
|
with connect(settings) as conn:
|
||||||
|
return conn.execute("SELECT count(*) AS n FROM chunks").fetchone()["n"]
|
||||||
|
|
||||||
|
|
||||||
|
def load_index_rows(settings: Settings) -> list[dict[str, Any]]:
|
||||||
|
"""Rows for the in-memory BM25 index: ids plus text, nothing else."""
|
||||||
|
with connect(settings) as conn:
|
||||||
|
return conn.execute("SELECT id, doc_id, title, text FROM chunks ORDER BY id").fetchall()
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""Embeddings and reranking through fastembed (ONNX, CPU-friendly).
|
||||||
|
|
||||||
|
E5 models expect task prefixes; we apply them here so callers cannot forget.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from functools import lru_cache
|
||||||
|
from typing import Sequence
|
||||||
|
|
||||||
|
from fastembed import TextEmbedding
|
||||||
|
|
||||||
|
|
||||||
|
def _is_e5(model_name: str) -> bool:
|
||||||
|
return "e5" in model_name.lower()
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def embedder(model_name: str) -> TextEmbedding:
|
||||||
|
return TextEmbedding(model_name=model_name, threads=4)
|
||||||
|
|
||||||
|
|
||||||
|
def embed_passages(model_name: str, texts: Sequence[str]) -> list[list[float]]:
|
||||||
|
prefix = "passage: " if _is_e5(model_name) else ""
|
||||||
|
return [list(map(float, vec)) for vec in embedder(model_name).embed([prefix + t for t in texts])]
|
||||||
|
|
||||||
|
|
||||||
|
def embed_query(model_name: str, text: str) -> list[float]:
|
||||||
|
prefix = "query: " if _is_e5(model_name) else ""
|
||||||
|
return list(map(float, next(iter(embedder(model_name).embed([prefix + text])))))
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"""Retrieval metrics, computed from ranked doc ids and relevance grades."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
from typing import Iterable, Sequence
|
||||||
|
|
||||||
|
|
||||||
|
def recall_at_k(ranked: Sequence[str], relevant: Iterable[str], k: int) -> float:
|
||||||
|
relevant = set(relevant)
|
||||||
|
if not relevant:
|
||||||
|
return 0.0
|
||||||
|
return len(relevant & set(ranked[:k])) / len(relevant)
|
||||||
|
|
||||||
|
|
||||||
|
def mrr_at_k(ranked: Sequence[str], relevant: Iterable[str], k: int) -> float:
|
||||||
|
relevant = set(relevant)
|
||||||
|
for position, doc_id in enumerate(ranked[:k], start=1):
|
||||||
|
if doc_id in relevant:
|
||||||
|
return 1.0 / position
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def ndcg_at_k(ranked: Sequence[str], grades: dict[str, int], k: int) -> float:
|
||||||
|
def dcg(values: Iterable[int]) -> float:
|
||||||
|
return sum((2**v - 1) / math.log2(i + 1) for i, v in enumerate(values, start=1))
|
||||||
|
|
||||||
|
actual = dcg(grades.get(doc_id, 0) for doc_id in ranked[:k])
|
||||||
|
ideal = dcg(sorted(grades.values(), reverse=True)[:k])
|
||||||
|
return actual / ideal if ideal else 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(per_query: list[dict[str, float]]) -> dict[str, float]:
|
||||||
|
if not per_query:
|
||||||
|
return {}
|
||||||
|
keys = per_query[0].keys()
|
||||||
|
return {key: round(sum(row[key] for row in per_query) / len(per_query), 4) for key in keys}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""Cross-encoder reranking, optional at runtime.
|
||||||
|
|
||||||
|
The reranker reorders a candidate list; it never invents documents. If the
|
||||||
|
model is not available, callers get the original order instead of an error.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
from .search import Hit
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def _encoder(model_name: str):
|
||||||
|
from fastembed.rerank.cross_encoder import TextCrossEncoder
|
||||||
|
|
||||||
|
return TextCrossEncoder(model_name=model_name)
|
||||||
|
|
||||||
|
|
||||||
|
def rerank(model_name: str, query: str, hits: list[Hit], limit: int | None = None) -> list[Hit]:
|
||||||
|
if len(hits) < 2:
|
||||||
|
return hits[:limit] if limit else hits
|
||||||
|
try:
|
||||||
|
scores = list(_encoder(model_name).rerank(query, [hit.text for hit in hits]))
|
||||||
|
except Exception:
|
||||||
|
return hits[:limit] if limit else hits
|
||||||
|
ranked = sorted(zip(hits, scores), key=lambda pair: pair[1], reverse=True)
|
||||||
|
out = [Hit(**{**hit.__dict__, "score": float(score), "source": f"{hit.source}+rerank"}) for hit, score in ranked]
|
||||||
|
return out[:limit] if limit else out
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""Three retrieval modes behind one interface: dense, lexical, hybrid with RRF."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
from .bm25 import BM25Index
|
||||||
|
from .config import Settings
|
||||||
|
from .db import dense_search, lexical_search, load_index_rows
|
||||||
|
from .embed import embed_query
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def bm25_index(settings: Settings) -> BM25Index:
|
||||||
|
index = BM25Index()
|
||||||
|
for row in load_index_rows(settings):
|
||||||
|
payload = {"doc_id": row["doc_id"], "title": row["title"], "text": row["text"]}
|
||||||
|
index.add(row["id"], f"{row['title']} {row['text']}", payload)
|
||||||
|
return index
|
||||||
|
|
||||||
|
|
||||||
|
def bm25_search(settings: Settings, query: str, limit: int) -> list[Hit]:
|
||||||
|
scored = bm25_index(settings).search(query, limit)
|
||||||
|
if not scored:
|
||||||
|
return []
|
||||||
|
max_score = scored[0][1] or 1.0
|
||||||
|
return [
|
||||||
|
Hit(
|
||||||
|
id=chunk_id,
|
||||||
|
doc_id=payload.get("doc_id", ""),
|
||||||
|
title=payload.get("title", ""),
|
||||||
|
text=payload.get("text", ""),
|
||||||
|
score=score / max_score,
|
||||||
|
source="bm25",
|
||||||
|
)
|
||||||
|
for chunk_id, score, payload in scored
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Hit:
|
||||||
|
id: str
|
||||||
|
doc_id: str
|
||||||
|
title: str
|
||||||
|
text: str
|
||||||
|
score: float
|
||||||
|
source: str
|
||||||
|
|
||||||
|
|
||||||
|
def _to_hits(rows: list[dict], source: str) -> list[Hit]:
|
||||||
|
return [
|
||||||
|
Hit(
|
||||||
|
id=row["id"],
|
||||||
|
doc_id=row["doc_id"],
|
||||||
|
title=row["title"],
|
||||||
|
text=row["text"],
|
||||||
|
score=float(row["score"] or 0.0),
|
||||||
|
source=source,
|
||||||
|
)
|
||||||
|
for row in rows
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def rrf_fuse(rankings: list[list[Hit]], k: int = 60, limit: int = 50) -> list[Hit]:
|
||||||
|
"""Reciprocal rank fusion: score = sum(1 / (k + rank)) across lists."""
|
||||||
|
scores: dict[str, float] = {}
|
||||||
|
by_id: dict[str, Hit] = {}
|
||||||
|
for ranking in rankings:
|
||||||
|
for position, hit in enumerate(ranking, start=1):
|
||||||
|
scores[hit.id] = scores.get(hit.id, 0.0) + 1.0 / (k + position)
|
||||||
|
by_id.setdefault(hit.id, hit)
|
||||||
|
ordered = sorted(scores.items(), key=lambda item: item[1], reverse=True)[:limit]
|
||||||
|
return [
|
||||||
|
Hit(**{**by_id[chunk_id].__dict__, "score": score, "source": "hybrid"})
|
||||||
|
for chunk_id, score in ordered
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def search(settings: Settings, query: str, mode: str = "hybrid", limit: int = 10) -> list[Hit]:
|
||||||
|
if mode == "lexical":
|
||||||
|
return bm25_search(settings, query, limit)
|
||||||
|
if mode == "tsvector":
|
||||||
|
return _to_hits(lexical_search(settings, query, limit), "tsvector")[:limit]
|
||||||
|
if mode == "dense":
|
||||||
|
return _to_hits(dense_search(settings, embed_query(settings.embed_model, query), limit), "dense")[:limit]
|
||||||
|
if mode == "hybrid":
|
||||||
|
dense = _to_hits(dense_search(settings, embed_query(settings.embed_model, query), 50), "dense")
|
||||||
|
lexical = bm25_search(settings, query, 50)
|
||||||
|
return rrf_fuse([dense, lexical], limit=limit)
|
||||||
|
raise ValueError(f"unknown mode: {mode}")
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
from raglab.chunking import chunk_markdown
|
||||||
|
|
||||||
|
|
||||||
|
def test_chunking_keeps_heading_trail():
|
||||||
|
text = "# Title\n\nIntro\n\n## Section\n\nBody text."
|
||||||
|
chunks = chunk_markdown("doc", text)
|
||||||
|
assert all(chunk.doc_id == "doc" for chunk in chunks)
|
||||||
|
assert any("Section" in chunk.title for chunk in chunks)
|
||||||
|
|
||||||
|
|
||||||
|
def test_long_text_is_split_with_overlap():
|
||||||
|
chunks = chunk_markdown("doc", "# T\n\n" + "word " * 800, target=200, overlap=40)
|
||||||
|
assert len(chunks) > 1
|
||||||
|
assert all(len(chunk.text) <= 260 for chunk in chunks)
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
from raglab.search import Hit, rrf_fuse
|
||||||
|
|
||||||
|
|
||||||
|
def hit(chunk_id: str) -> Hit:
|
||||||
|
return Hit(id=chunk_id, doc_id=chunk_id.split(":")[0], title="", text="", score=0.0, source="test")
|
||||||
|
|
||||||
|
|
||||||
|
def test_rrf_prefers_documents_found_by_both_lists():
|
||||||
|
dense = [hit("a:1"), hit("b:1")]
|
||||||
|
lexical = [hit("c:1"), hit("a:1")]
|
||||||
|
fused = rrf_fuse([dense, lexical], limit=3)
|
||||||
|
assert [item.id for item in fused][0] == "a:1"
|
||||||
|
|
||||||
|
|
||||||
|
def test_rrf_respects_limit():
|
||||||
|
fused = rrf_fuse([[hit(f"a:{i}") for i in range(5)]], limit=2)
|
||||||
|
assert len(fused) == 2
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
from raglab.metrics import mrr_at_k, ndcg_at_k, recall_at_k
|
||||||
|
|
||||||
|
|
||||||
|
def test_recall_counts_distinct_relevant_docs():
|
||||||
|
assert recall_at_k(["a", "b", "c"], {"b", "z"}, 3) == 0.5
|
||||||
|
assert recall_at_k(["a"], {"z"}, 5) == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_mrr_uses_first_relevant_position():
|
||||||
|
assert mrr_at_k(["x", "a"], {"a"}, 10) == 0.5
|
||||||
|
assert mrr_at_k(["x"], {"a"}, 10) == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_ndcg_orders_grades():
|
||||||
|
perfect = ndcg_at_k(["a", "b"], {"a": 2, "b": 1}, 10)
|
||||||
|
reversed_ = ndcg_at_k(["b", "a"], {"a": 2, "b": 1}, 10)
|
||||||
|
assert perfect == 1.0
|
||||||
|
assert reversed_ < perfect
|
||||||
Reference in New Issue
Block a user