parent
27082c02d5
commit
cf992cd45b
4 changed files with 167 additions and 0 deletions
0
app/rag/__init__.py
Normal file
0
app/rag/__init__.py
Normal file
58
app/rag/ingest.py
Normal file
58
app/rag/ingest.py
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
"""Load and chunk the policy markdown corpus.
|
||||||
|
|
||||||
|
Scalability note: documents are split with source + section metadata preserved on every
|
||||||
|
chunk, so the corpus can grow (more files, larger files) without changing the ingestion
|
||||||
|
code — only the chunk count grows. Swapping the in-memory FAISS store for a managed vector
|
||||||
|
DB (pgvector, Pinecone, etc.) for a larger corpus is a change confined to vectorstore.py;
|
||||||
|
this module never needs to know about the storage backend.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
||||||
|
|
||||||
|
from app.config import CHUNK_OVERLAP, CHUNK_SIZE, POLICY_DOCS_DIR
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Chunk:
|
||||||
|
content: str
|
||||||
|
source: str
|
||||||
|
chunk_id: int
|
||||||
|
|
||||||
|
|
||||||
|
def load_markdown_files(docs_dir: Path = POLICY_DOCS_DIR) -> list[tuple[str, str]]:
|
||||||
|
"""Return a list of (filename, raw_text) for every .md file in docs_dir."""
|
||||||
|
docs_dir = Path(docs_dir)
|
||||||
|
files = sorted(docs_dir.glob("*.md"))
|
||||||
|
return [(f.name, f.read_text(encoding="utf-8")) for f in files]
|
||||||
|
|
||||||
|
|
||||||
|
def chunk_documents(
|
||||||
|
documents: list[tuple[str, str]],
|
||||||
|
chunk_size: int = CHUNK_SIZE,
|
||||||
|
chunk_overlap: int = CHUNK_OVERLAP,
|
||||||
|
) -> list[Chunk]:
|
||||||
|
splitter = RecursiveCharacterTextSplitter(
|
||||||
|
chunk_size=chunk_size,
|
||||||
|
chunk_overlap=chunk_overlap,
|
||||||
|
separators=["\n## ", "\n### ", "\n\n", "\n", " "],
|
||||||
|
)
|
||||||
|
chunks: list[Chunk] = []
|
||||||
|
for filename, text in documents:
|
||||||
|
for i, piece in enumerate(splitter.split_text(text)):
|
||||||
|
chunks.append(Chunk(content=piece, source=filename, chunk_id=i))
|
||||||
|
return chunks
|
||||||
|
|
||||||
|
|
||||||
|
def corpus_fingerprint(docs_dir: Path = POLICY_DOCS_DIR) -> str:
|
||||||
|
"""Hash of file names + contents, used to decide whether the index must be rebuilt."""
|
||||||
|
docs_dir = Path(docs_dir)
|
||||||
|
hasher = hashlib.sha256()
|
||||||
|
for f in sorted(docs_dir.glob("*.md")):
|
||||||
|
hasher.update(f.name.encode("utf-8"))
|
||||||
|
hasher.update(f.read_bytes())
|
||||||
|
return hasher.hexdigest()
|
||||||
83
app/rag/vectorstore.py
Normal file
83
app/rag/vectorstore.py
Normal file
|
|
@ -0,0 +1,83 @@
|
||||||
|
"""FAISS-backed vector store wrapper.
|
||||||
|
|
||||||
|
This is the one module that knows about the storage backend. Everything else in the RAG
|
||||||
|
subgraph talks to it through `load_or_build_index` / `similarity_search`, so a future move
|
||||||
|
to a different vector database only touches this file.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.config import INDEX_DIR, POLICY_DOCS_DIR, RAG_TOP_K
|
||||||
|
from app.rag.ingest import chunk_documents, corpus_fingerprint, load_markdown_files
|
||||||
|
|
||||||
|
_FINGERPRINT_FILE = "corpus.fingerprint"
|
||||||
|
|
||||||
|
_embeddings_cache = {}
|
||||||
|
|
||||||
|
|
||||||
|
def get_embeddings():
|
||||||
|
"""Lazily construct (and cache) the local sentence-transformers embedding model."""
|
||||||
|
from app.config import EMBEDDING_MODEL
|
||||||
|
|
||||||
|
if "embeddings" not in _embeddings_cache:
|
||||||
|
from langchain_huggingface import HuggingFaceEmbeddings
|
||||||
|
|
||||||
|
_embeddings_cache["embeddings"] = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
|
||||||
|
return _embeddings_cache["embeddings"]
|
||||||
|
|
||||||
|
|
||||||
|
def _build_index(docs_dir: Path, embeddings):
|
||||||
|
from langchain_community.vectorstores import FAISS
|
||||||
|
from langchain_core.documents import Document
|
||||||
|
|
||||||
|
documents = load_markdown_files(docs_dir)
|
||||||
|
chunks = chunk_documents(documents)
|
||||||
|
lc_docs = [
|
||||||
|
Document(page_content=c.content, metadata={"source": c.source, "chunk_id": c.chunk_id})
|
||||||
|
for c in chunks
|
||||||
|
]
|
||||||
|
return FAISS.from_documents(lc_docs, embeddings)
|
||||||
|
|
||||||
|
|
||||||
|
def load_or_build_index(
|
||||||
|
docs_dir: Path = POLICY_DOCS_DIR, index_dir: Path = INDEX_DIR, force_rebuild: bool = False
|
||||||
|
):
|
||||||
|
"""Load a cached FAISS index from disk, rebuilding it if the corpus changed."""
|
||||||
|
from langchain_community.vectorstores import FAISS
|
||||||
|
|
||||||
|
docs_dir = Path(docs_dir)
|
||||||
|
index_dir = Path(index_dir)
|
||||||
|
embeddings = get_embeddings()
|
||||||
|
fingerprint_path = index_dir / _FINGERPRINT_FILE
|
||||||
|
current_fingerprint = corpus_fingerprint(docs_dir)
|
||||||
|
|
||||||
|
index_is_fresh = (
|
||||||
|
not force_rebuild
|
||||||
|
and (index_dir / "index.faiss").exists()
|
||||||
|
and fingerprint_path.exists()
|
||||||
|
and fingerprint_path.read_text(encoding="utf-8").strip() == current_fingerprint
|
||||||
|
)
|
||||||
|
|
||||||
|
if index_is_fresh:
|
||||||
|
return FAISS.load_local(
|
||||||
|
str(index_dir), embeddings, allow_dangerous_deserialization=True
|
||||||
|
)
|
||||||
|
|
||||||
|
store = _build_index(docs_dir, embeddings)
|
||||||
|
index_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
store.save_local(str(index_dir))
|
||||||
|
fingerprint_path.write_text(current_fingerprint, encoding="utf-8")
|
||||||
|
return store
|
||||||
|
|
||||||
|
|
||||||
|
def similarity_search(store, query: str, k: int = RAG_TOP_K) -> list[dict]:
|
||||||
|
results = store.similarity_search_with_score(query, k=k)
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"content": doc.page_content,
|
||||||
|
"source": doc.metadata.get("source", "unknown"),
|
||||||
|
"score": float(score),
|
||||||
|
}
|
||||||
|
for doc, score in results
|
||||||
|
]
|
||||||
26
scripts/build_index.py
Normal file
26
scripts/build_index.py
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
"""Standalone helper to (re)build the FAISS index without launching the UI.
|
||||||
|
|
||||||
|
python scripts/build_index.py [--force]
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from app.rag.vectorstore import load_or_build_index # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--force", action="store_true", help="Rebuild even if the corpus is unchanged.")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
store = load_or_build_index(force_rebuild=args.force)
|
||||||
|
print(f"Index ready with {store.index.ntotal} vectors.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Loading…
Add table
Reference in a new issue