initial commit: retrieval + agent artifacts
This commit is contained in:
@@ -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}")
|
||||
Reference in New Issue
Block a user