|
| 1 | +import pytest |
| 2 | +from sqlalchemy import create_engine |
| 3 | +from sqlalchemy.orm import sessionmaker |
| 4 | + |
| 5 | +from local_rag_backend.core.services.etl import ETLService |
| 6 | +from local_rag_backend.core.services.rag import RagService |
| 7 | +from local_rag_backend.infrastructure.embeddings import openai as openai_embedder_mod |
| 8 | +from local_rag_backend.infrastructure.embeddings.openai import OpenAIEmbedder |
| 9 | +from local_rag_backend.infrastructure.persistence.faiss.faiss_ import FaissVectorStorage |
| 10 | +from local_rag_backend.infrastructure.persistence.sqlalchemy.base import Base |
| 11 | +from local_rag_backend.infrastructure.persistence.sqlalchemy.sql_ import ( |
| 12 | + HistorySqlStorage, |
| 13 | + SqlDocumentStorage, |
| 14 | +) |
| 15 | +from local_rag_backend.infrastructure.retrieval.dense_faiss import DenseFaissRetriever |
| 16 | +from local_rag_backend.infrastructure.retrieval.hybrid import HybridRetriever |
| 17 | +from local_rag_backend.infrastructure.retrieval.sparse_bm25 import SparseBM25Retriever |
| 18 | +from local_rag_backend.settings import settings |
| 19 | +from local_rag_backend.utils import get_corpus_and_ids |
| 20 | + |
| 21 | + |
| 22 | +class _DummyEmbeddingItem: |
| 23 | + def __init__(self, embedding): |
| 24 | + self.embedding = embedding |
| 25 | + |
| 26 | + |
| 27 | +class _DummyEmbeddingsResp: |
| 28 | + def __init__(self, vectors): |
| 29 | + self.data = [_DummyEmbeddingItem(v) for v in vectors] |
| 30 | + |
| 31 | + |
| 32 | +class _DummyEmbeddingsAPI: |
| 33 | + def create(self, model, input): |
| 34 | + # Tiny deterministic 4D embedding; good enough for FAISS L2. |
| 35 | + vecs = [] |
| 36 | + for t in input: |
| 37 | + t = str(t) |
| 38 | + vecs.append( |
| 39 | + [ |
| 40 | + float(len(t)), |
| 41 | + float(sum(ord(c) for c in t) % 17), |
| 42 | + float(t.count("a")), |
| 43 | + float(t.count("z")), |
| 44 | + ] |
| 45 | + ) |
| 46 | + return _DummyEmbeddingsResp(vecs) |
| 47 | + |
| 48 | + |
| 49 | +class _DummyOpenAI: |
| 50 | + def __init__(self, api_key): |
| 51 | + self.embeddings = _DummyEmbeddingsAPI() |
| 52 | + |
| 53 | + |
| 54 | +class _DummyGen: |
| 55 | + def __init__(self, *a, **k): |
| 56 | + pass |
| 57 | + |
| 58 | + def generate(self, question, contexts): |
| 59 | + return f"answer:{question}:{len(contexts)}" |
| 60 | + |
| 61 | + |
| 62 | +@pytest.mark.integration |
| 63 | +def test_dense_and_hybrid_end_to_end(tmp_path, monkeypatch): |
| 64 | + # Settings |
| 65 | + db_path = tmp_path / "app.db" |
| 66 | + index_path = tmp_path / "idx.faiss" |
| 67 | + id_map_path = tmp_path / "id.pkl" |
| 68 | + |
| 69 | + monkeypatch.setattr(settings, "sqlite_url", f"sqlite:///{db_path}", raising=False) |
| 70 | + monkeypatch.setattr(settings, "index_path", str(index_path), raising=False) |
| 71 | + monkeypatch.setattr(settings, "id_map_path", str(id_map_path), raising=False) |
| 72 | + monkeypatch.setattr(settings, "openai_api_key", "k", raising=False) |
| 73 | + monkeypatch.setattr(settings, "openai_embedding_model", "dummy-4", raising=False) |
| 74 | + monkeypatch.setattr(openai_embedder_mod, "_MODEL_DIM", {"dummy-4": 4}, raising=False) |
| 75 | + monkeypatch.setattr(openai_embedder_mod, "OpenAI", _DummyOpenAI, raising=True) |
| 76 | + |
| 77 | + # DB setup |
| 78 | + engine = create_engine(settings.sqlite_url, connect_args={"check_same_thread": False}) |
| 79 | + SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False) |
| 80 | + Base.metadata.create_all(bind=engine) |
| 81 | + |
| 82 | + doc_repo = SqlDocumentStorage(session_factory=SessionLocal) |
| 83 | + history_repo = HistorySqlStorage(session_factory=SessionLocal) |
| 84 | + |
| 85 | + embedder = OpenAIEmbedder(model="dummy-4") |
| 86 | + vec_repo = FaissVectorStorage(index_path=str(index_path), id_map_path=str(id_map_path), dim=embedder.dim) |
| 87 | + |
| 88 | + etl = ETLService(doc_repo, vec_repo, embedder) |
| 89 | + ids = etl.ingest(["alpha alpha alpha", "zzzz zzzz zzzz"]) |
| 90 | + assert len(list(ids)) == 2 |
| 91 | + |
| 92 | + dense = DenseFaissRetriever(embedder=embedder, faiss_index=vec_repo, doc_repo=doc_repo) |
| 93 | + docs, scores = dense.retrieve("alpha", k=1) |
| 94 | + assert len(docs) == 1 |
| 95 | + assert docs[0].content.startswith("alpha") |
| 96 | + assert len(scores) == 1 |
| 97 | + |
| 98 | + # Hybrid: ensure sparse is wired and returns something too. |
| 99 | + corpus, doc_ids = get_corpus_and_ids(doc_repo) |
| 100 | + sparse = SparseBM25Retriever(documents=corpus, doc_ids=doc_ids, doc_repo=doc_repo) |
| 101 | + hybrid = HybridRetriever(dense=dense, sparse=sparse, alpha=0.5) |
| 102 | + |
| 103 | + svc = RagService(retriever=hybrid, generator=_DummyGen(), history_storage=history_repo) |
| 104 | + resp = svc.ask("alpha", top_k=1) |
| 105 | + assert resp["answer"].startswith("answer:alpha:1") |
| 106 | + assert resp["docs"] |
0 commit comments