"""Generate a synthetic Q&A testset from document chunks using RAGAS.""" from __future__ import annotations from langchain_community.chat_models import ChatOllama from langchain_community.embeddings import OllamaEmbeddings from langchain_core.documents import Document as LCDocument from ragas.embeddings import LangchainEmbeddingsWrapper from ragas.llms import LangchainLLMWrapper from ragas.testset import TestsetGenerator from askme.config import settings def _make_llm() -> LangchainLLMWrapper: # num_gpu=0 keeps the judge on CPU so it doesn't contend with the # GPU-resident RAG model; gemma4:12b is too large for the 8GB GPU anyway. llm = ChatOllama( model=settings.ragas_judge_model, base_url=settings.ollama_host, num_gpu=0, ) return LangchainLLMWrapper(llm) def _make_embeddings() -> LangchainEmbeddingsWrapper: base_url = settings.ollama_host # Force CPU (num_gpu=0): qwen2.5:7b fully occupies the 8GB GPU, so eval # embeddings must run on CPU like the ingest path (see rag.py) or they # contend for VRAM and fall back unpredictably. emb = OllamaEmbeddings(model=settings.embedding_model, base_url=base_url, num_gpu=0) return LangchainEmbeddingsWrapper(emb) def generate_testset(docs: list[str], n: int) -> list[dict]: """Generate n synthetic Q&A pairs from the provided document texts. Args: docs: Raw text chunks (e.g. extracted from notebooks/scripts). n: Number of Q&A pairs to generate. Returns: List of dicts with keys: question, ground_truth, contexts. """ lc_docs = [LCDocument(page_content=d) for d in docs] generator = TestsetGenerator(llm=_make_llm(), embedding_model=_make_embeddings()) testset = generator.generate_with_langchain_docs(lc_docs, testset_size=n) return [ { "question": row["user_input"], "ground_truth": row["reference"], "contexts": row.get("reference_contexts") or [], } for row in testset.to_pandas().to_dict(orient="records") ]