askme-public/tests/test_rag.py
Lukasz Boryn 0e0bae4b9b feat: initial public release of askme
* local question answering over analysis notebooks with LightRAG, Neo4j, Qdrant and Ollama
* RAGAS evaluation with a generator x judge comparison matrix, fully local
* docs in README and OKF
2026-11-03 17:50:52 +01:00

197 lines
7.0 KiB
Python

"""Tests for src/askme/rag.py."""
from __future__ import annotations
import asyncio
import json
from unittest.mock import patch
import numpy as np
import pytest
from askme.rag import (
EmbeddingMismatchError,
_check_embedding_meta,
_make_embedding_func,
create_rag,
make_query_param,
)
def _create_rag_kwargs(**create_kwargs) -> dict:
"""Build the RAG with LightRAG patched; return the kwargs it was called with."""
with (
patch("askme.rag.LightRAG") as mock_rag,
patch("askme.rag._check_embedding_meta"),
):
create_rag(**create_kwargs)
_, kwargs = mock_rag.call_args
return kwargs
def test_create_rag_matches_llm_and_embed_concurrency():
"""
Scenario: RAG built with bounded, matched concurrency
Given create_rag()
When the LightRAG instance is constructed
Then llm_model_max_async=2 and embedding_func_max_async=2 are passed
(match OLLAMA_NUM_PARALLEL=2; cap CPU embed fan-out)
"""
kwargs = _create_rag_kwargs()
assert kwargs["llm_model_max_async"] == 2
assert kwargs["embedding_func_max_async"] == 2
assert kwargs["embedding_batch_num"] == 32
def test_create_rag_wires_chunk_config():
"""
Scenario: chunk config is authoritative
Given settings.chunk_size=1200, chunk_overlap=200
When create_rag() builds LightRAG
Then chunk_token_size and chunk_overlap_token_size are passed through
(otherwise LightRAG silently uses its own 1200/100 defaults)
"""
kwargs = _create_rag_kwargs()
assert kwargs["chunk_token_size"] == 1200
assert kwargs["chunk_overlap_token_size"] == 200
def test_create_rag_enables_query_response_cache():
"""
Scenario: near-duplicate queries reuse cached answers
Given create_rag()
When LightRAG is constructed
Then embedding_cache_config is enabled with no extra LLM check
(skip full retrieval+generation on semantically-equal queries)
"""
cfg = _create_rag_kwargs()["embedding_cache_config"]
assert cfg["enabled"] is True
assert cfg["use_llm_check"] is False
def test_create_rag_without_cache_disables_both_caches():
"""
Scenario: comparing generators must not reuse another model's output
Given create_rag(cache=False)
When LightRAG is constructed
Then the LLM response cache and the semantic query cache are both off
(LightRAG's cache key ignores the model, so a cached answer or
keyword set from one generator would be served for the next)
"""
kwargs = _create_rag_kwargs(cache=False)
assert kwargs["enable_llm_cache"] is False
assert kwargs["embedding_cache_config"]["enabled"] is False
def test_embed_warns_on_oversize_truncation(caplog):
"""
Scenario: oversize chunk logs instead of silently dropping
Given a text longer than the 4000-char embed cap
When _embed runs
Then the text is truncated to 4000 chars AND a warning is logged
(so the retrieval-affecting data loss is no longer silent)
"""
captured: dict = {}
async def fake_func(texts, **kwargs):
captured["texts"] = texts
return np.zeros((len(texts), 768))
with patch("askme.rag.ollama_embed") as mock_oe:
mock_oe.func = fake_func
embed = _make_embedding_func().func
with caplog.at_level("WARNING"):
asyncio.run(embed(["x" * 5000]))
assert len(captured["texts"][0]) == 4000
assert any("truncat" in r.message.lower() for r in caplog.records)
def test_embedding_meta_written_on_first_use(tmp_path):
"""
Scenario: fresh storage records the embedding it was built with
Given a working dir with no askme_meta.json
When _check_embedding_meta runs with nomic-embed-text / 768
Then askme_meta.json stores that model and dim
"""
_check_embedding_meta(tmp_path, "nomic-embed-text", 768)
meta = json.loads((tmp_path / "askme_meta.json").read_text())
assert meta == {"embedding_model": "nomic-embed-text", "embedding_dim": 768}
def test_embedding_meta_match_passes(tmp_path):
"""
Scenario: same embedding as stored
Given askme_meta.json for nomic-embed-text / 768
When _check_embedding_meta runs with the same model and dim
Then no error is raised
"""
_check_embedding_meta(tmp_path, "nomic-embed-text", 768)
_check_embedding_meta(tmp_path, "nomic-embed-text", 768)
@pytest.mark.parametrize("model,dim", [("bge-m3", 1024), ("nomic-embed-text", 1024)])
def test_embedding_meta_mismatch_raises(tmp_path, model, dim):
"""
Scenario: embedding changed after ingest
Given askme_meta.json for nomic-embed-text / 768
When _check_embedding_meta runs with a different model or dim
Then EmbeddingMismatchError names both the stored and requested values
(stored vectors are incompatible with new query vectors)
"""
_check_embedding_meta(tmp_path, "nomic-embed-text", 768)
with pytest.raises(EmbeddingMismatchError, match="nomic-embed-text.*768"):
_check_embedding_meta(tmp_path, model, dim)
def test_create_rag_checks_embedding_meta(tmp_path):
"""
Scenario: every RAG entry point is guarded
Given create_rag()
When LightRAG is constructed
Then the embedding meta is checked against the working dir first
"""
with (
patch("askme.rag.LightRAG"),
patch("askme.rag._check_embedding_meta") as check,
patch("askme.rag.settings.rag_working_dir", str(tmp_path)),
):
create_rag()
check.assert_called_once_with(tmp_path, "nomic-embed-text", 768)
def test_make_query_param_caps_the_prompt_and_leaves_room_for_chunks():
"""
Scenario: every query path gets a prompt the LLM window can hold
Given LightRAG's defaults (30000 total, 6000 entities, 8000 relations)
When make_query_param builds a query
Then the total is capped at 12000, and entity + relation budgets
leave >= 4000 tokens for source chunks after a ~2000-token
system prompt
"""
p = make_query_param()
assert p.max_total_tokens == 12000
assert p.max_total_tokens - p.max_entity_tokens - p.max_relation_tokens - 2000 >= 4000
def test_make_query_param_budget_is_overridable():
"""
Scenario: a caller needs a different budget
Given an explicit max_total_tokens
When make_query_param builds a query
Then the explicit value wins over the default
"""
assert make_query_param(max_total_tokens=8000).max_total_tokens == 8000
def test_create_rag_window_holds_the_capped_prompt_plus_an_answer():
"""
Scenario: Ollama must not truncate query prompts
Given Ollama silently cuts prompts longer than num_ctx
When create_rag() configures the LLM
Then num_ctx >= the prompt cap + 2048 tokens for the answer
(at 4096 every normal query lost most of its retrieved context)
"""
num_ctx = _create_rag_kwargs()["llm_model_kwargs"]["options"]["num_ctx"]
assert num_ctx >= make_query_param().max_total_tokens + 2048