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
This commit is contained in:
Łukasz Boryń 2026-11-03 12:32:01 +01:00
commit 0e0bae4b9b
64 changed files with 10445 additions and 0 deletions

36
.gitignore vendored Normal file
View File

@ -0,0 +1,36 @@
# ==== Data (it contains large files which should never be tracked) ===========
data/*
# ==== Secrets ================================================================
.env
.env.local
.env.*.local
# ==== Python
__pycache__/*
.venv/
build/
.cache
.mypy_cache/
.ruff_cache/
.pytest_cache
.coverage
htmlcov/
# ==== Jupyter notebooks ======================================================
.ipynb_checkpoints/
*.ipynb_checkpoints
# ==== OS files ===============================================================
.Thumbs.db
# ==== Python cache ===========================================================
src/askme/__pycache__
*.pyc
*.pyo
# ==== Agent handoff notes ==================================================
HANDOFF.md
# Claude Code session lock
.claude/scheduled_tasks.lock

1
.gitinit Normal file
View File

@ -0,0 +1 @@
data/

1
.jjignore Normal file
View File

@ -0,0 +1 @@
data/

55
AGENTS.md Normal file
View File

@ -0,0 +1,55 @@
## Knowledge — read before you code
This project keeps an agent-first wiki at [`OKF/`](OKF/index.md)
(open-knowledge-format). Before extending or modifying askme:
1. Read [`OKF/index.md`](OKF/index.md), then the pages it flags for your
task — at minimum `SUMMARY.md`; `ARCHITECTURE.md` before structural
work.
2. Use the canonical vocabulary from `OKF/CONTEXT.md` (not written yet)
in code, tests, and commit messages. Don't coin synonyms.
3. Non-trivial changes start from a blueprint in `OKF/blueprints/` — write one
(blueprint skill) before implementing; cite its number in the commit.
4. Learned something that contradicts the wiki? Update the wiki in the
same change (supersede, don't delete) or append to
`OKF/learnings/` (the matching theme page).
## Behavioral guardrails
- State assumptions explicitly; name the simpler approach you are
rejecting; surface tradeoffs. Push back when warranted — if something
is unclear, stop and ask rather than guess.
- Do exactly what the task requires, nothing more. No speculative
abstractions, no drive-by refactors.
- A green test suite is a claim, not a proof — verify against the
blueprint's stated check before calling work done.
## Simplicity & rigor
- **Think before coding** — when multiple interpretations exist, present
them; don't pick silently.
- **Three sieves before a line stays**: real (not speculative — no error
handling for impossible scenarios, no unrequested flexibility or
configurability), good (nameably better for the next reader), minimal
(leanest form — stdlib/existing code before new). Burden is on keeping,
not cutting. Exceptions that always pass *good*: input validation,
error handling that prevents data loss, security, accessibility,
explicitly requested behaviour.
- **Surgical changes** — match existing style; notice unrelated dead code
and mention it, don't delete it; clean up only your own mess (remove
orphans your change created, not pre-existing dead code); every changed
line should trace to the request.
- **Goal-driven execution** — turn the task into a verifiable check
before starting: "add validation" → "write tests for invalid inputs,
then make them pass"; "fix the bug" → "write a test that reproduces
it, then make it pass". For multi-step work, state a brief plan, each
step naming its own verify. Strong success criteria let you loop
independently; weak ones ("make it work") need constant clarification.
## Repo conventions — askme
- Python, managed by `uv` (`pyproject.toml`).
- Tests: `tests/test_<source_file>.py`, one test file per source file; `just test` (`uv run --extra dev --extra eval pytest tests/`) must pass before committing.
- VCS: Jujutsu — commit with `jj describe` / `jj commit`, not `git commit`.
- Commit style: `<type>(<scope>): <this change will...>` with `* bullet` sub-changes.
- Task runner: `just` — model config (LLM, embedding, eval models) lives in justfile variables.

6
CLAUDE.md Normal file
View File

@ -0,0 +1,6 @@
# CLAUDE.md — askme
Read [`AGENTS.md`](AGENTS.md) first — it carries the full behavioral
contract (knowledge, guardrails, simplicity & rigor, repo conventions).
This file exists only because some tooling looks for `CLAUDE.md` by name;
it adds nothing AGENTS.md doesn't already say.

54
Dockerfile Normal file
View File

@ -0,0 +1,54 @@
# ==== Set base to build development and production image =====================
# System deps: nbconvert needs pandoc, neo4j driver needs libssl
# This should be something very small you should limit memory usage
FROM python:3.12-slim AS base
# Add system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
git \
build-essential \
pandoc \
libssl-dev \
&& rm -rf /var/lib/apt/lists/*
# Install uv
RUN command -v uv >/dev/null 2>&1 || \
curl -LsSf https://astral.sh/uv/install.sh | sh
ENV PATH="/root/.local/bin:$PATH"
WORKDIR /usr/askme
# Configure uv
ENV UV_LINK_MODE=copy \
UV_COMPILE_BYTECODE=1 \
UV_PYHTON_DOWNLOADS=never \
UV_PROJECT_ENVIRONMENT=/opt/venv
# ==== Set Production image with core dependencies only =======================
FROM base AS production
COPY pyproject.toml uv.lock ./
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --frozen --no-dev --extra eval --no-install-project 2>/dev/null || \
uv sync --no-dev --extra eval --no-install-project
COPY . .
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --frozen --no-dev --extra eval 2>/dev/null || uv sync --no-dev --extra eval
ENV PATH="/opt/venv/bin:$PATH"
ENTRYPOINT []
CMD ["uv", "run", "uvicorn", "askme.api.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

102
OKF/ROADMAP.md Normal file
View File

@ -0,0 +1,102 @@
---
type: Roadmap
purpose: Carry only what is still ahead — phases, their verify steps, and live risk.
answers:
- "What is askme building next, and how is each phase verified?"
cites:
- justfile
- src/askme/evaluation/compare.py
- src/askme/rag.py
- docker-compose.yml
---
# askme — roadmap
<!-- chart owns this content; scribe only places the page. Carries
what is *ahead* — a shipped phase keeps its verify evidence, a
spent risk is deleted. Migrated from the root Roadmap.md on
2026-11-03; findings moved to learnings/. -->
## Locked decisions
TODO(chart) — the why-register: `decisions/index.md` (not written yet).
Settled so far, pending a decisions/ entry each:
- **Fully local.** Models run in Ollama or a local llama.cpp router; no
corpus text goes to an external API — this rules out a hosted RAGAS judge.
- **Testsets are private.** Real testsets live in `data/` (gitignored); the
repo ships only `eval/*.example.json`.
- **Model config lives in the justfile** (`LLM_MODEL`, `EMBEDDING_MODEL`,
`EMBEDDING_DIM`, `EVAL_MODELS`); `config.py` keeps fallback defaults.
- **Embedding is fixed per store** — guarded by `askme_meta.json`
(`src/askme/rag.py:_check_embedding_meta`).
- **Publication by snapshot.** Git history contains private testsets, so a
cleaned snapshot becomes a fresh `askme-public` repo; this repo stays
private.
## Phases
1. **Validate the knowledge graph** — shipped (ingest of 821 docs,
2026-06-17; retrieval eval 10/10). Open: confirm which model built the
graph — see Risks.
2. **Test coverage** — test file per source file exists (`tests/`).
Open: measure and close gaps to ~70%.
**Verify:** `uv run --extra dev pytest tests/ --cov` ≥ 70%.
3. **Query quality** — open. Shipped: one prompt budget for every query
path and `num_ctx` 16384 (was 4096, silently truncating).
- [x] `naive` vs `hybrid`, qwen2.5:7b as generator and judge, n=20,
pinned keywords (2026-11-03): naive faithfulness 0.830 / relevancy
0.801 / context_precision 0.454 vs hybrid 0.668 / 0.781 / 0.268. The
current graph hurts retrieval → re-ingest is justified. gemma-4 as
second judge agrees on every metric (naive 0.637 / 0.822 / 0.549 vs
hybrid 0.528 / 0.801 / 0.484). Tables: `results/2026-11-03-eval.md`.
- [ ] Re-ingest (justified by the item above): first ~10 notebooks
into a separate store with qwen2.5:7b at 16k, inspect entities, then
the full archive (hours to days). Consider feeding extraction prose and
markdown rather than every code line.
- [ ] Analyse low-faithfulness questions (thin-coverage topics).
- [ ] Tune chunk size/overlap; compare query modes per question type.
- [ ] Re-ranking if retrieval recall is the bottleneck (LightRAG warns
"Rerank is enabled but no rerank model is configured").
- [ ] Query rewrite / synonym expansion (retrieval is vocabulary-sensitive).
**Verify:** eval-compare scores move with a fixed judge.
4. **Usability** — shipped: `/health`, `/collections`, `just serve`,
usage guide. Open: streaming `/query` responses.
5. **Incremental ingestion** — shipped: manifest + `just ingest-new`.
**Verify (still to run):** re-ingest of an unchanged archive inserts 0 docs.
6. **Generator × judge comparison** — built (`just eval-compare`).
- [ ] 2×2 pilot, n=20: qwen2.5:7b × gemma-4-12b-qat (running 2026-11-03).
- [ ] Decide: full n=50, `pinned` keyword run, more models.
**Verify:** `data/eval_compare/<run>/comparison.md` written with all cells.
7. **Ingest tuning per run** — model is selectable (`LLM_MODEL`); open:
expose `LLM_TIMEOUT` and `MAX_ASYNC` as justfile variables. Parallelism
above the Ollama container's `OLLAMA_NUM_PARALLEL` only queues.
8. **Publication** — open.
- [ ] Audit tracked files for private content.
- [x] Snapshot to `~/Documents/askme-public`, single initial commit.
Re-sync with `jj file list | grep -v '^results/' | rsync -a
--files-from=- ./ ../askme-public/` — `results/` stays private.
- [ ] Create and push the GitHub repo (explicit go-ahead first).
**Verify:** grep of the snapshot finds no testset questions or notebook
names.
9. **Rootless docker** — open: migrate askme and the other projects' volumes,
then disable rootful docker.
## Risks & gotchas
- **The knowledge graph is low quality** (checked 2026-11-03: 22,144
entities, 33% `UNKNOWN`, 1.2% `gene`, hubs are `adata` and plotting
calls, extraction-example garbage such as `Tokyo2023World…`). Likely
cause: truncated extraction prompts (`num_ctx` 4096 at ingest) and/or the
`qwen2.5:3b` swap. Hybrid retrieval runs through these entities — the
probable reason for low context_precision (0.29–0.37 in the pilot).
Phase 3 measures it before any re-ingest.
- **Silent CPU fallback** — Ollama runs on CPU without error if CUDA fails
inside the container; check `size_vram` via `/api/ps`. See learnings/operations.md.
- **Eval wall-clock** — judging is ~90% of matrix cost; a 4×4 × 50 matrix
is ~2 days on 8 GB.
## Out of scope
- Hosted LLM judges or LLMs (violates fully-local).
- PDF ingestion, multi-user isolation, web UI — backlog, unscheduled.

30
OKF/SUMMARY.md Normal file
View File

@ -0,0 +1,30 @@
---
type: Summary
purpose: Say what this project is and where to read next, for an agent landing cold.
answers:
- "What is askme, and where should an agent start reading?"
cites:
- README.md
- justfile
- src/askme/rag.py:create_rag
- src/askme/evaluation/compare.py
---
# askme — summary
**What**: fully local question answering over a collection of analysis
notebooks (`.ipynb`, `.Rmd`, `.py`, `.R`). Ingestion builds a LightRAG
knowledge graph; queries are answered from it. Includes local RAGAS
evaluation, up to a generator × judge comparison matrix.
**Stack**: Python 3.12 (`uv`), LightRAG over Neo4j (graph) and Qdrant
(vectors), Ollama for LLM and embeddings, optional llama.cpp router for
eval models; Docker Compose; `just` as task runner.
**Run it**: `just up` → `just ingest` → `just query "..."`; tests with
`just test`; evaluation with `just eval-compare`.
**Read next**: [README.md](../README.md) for setup and configuration,
[guides/usage.md](guides/usage.md) for every command,
[ROADMAP.md](ROADMAP.md) for what is ahead,
[learnings/index.md](learnings/index.md) before touching ingest, GPU or eval code.

8
OKF/guides/index.md Normal file
View File

@ -0,0 +1,8 @@
---
type: Index
---
# askme — guides
- [usage.md](usage.md) — command reference: stack, ingest, query, API,
evaluation, tests, teardown.

146
OKF/guides/usage.md Normal file
View File

@ -0,0 +1,146 @@
---
type: Guide
purpose: Give the full command reference for running askme day to day.
answers:
- "Which command starts, ingests, queries, evaluates or tears down askme?"
cites:
- justfile
- src/askme/api/main.py
---
# askme — Usage Guide
LightRAG-powered Q&A over bioinformatics notebooks (scanpy, scRNA-seq, spatial transcriptomics).
## Prerequisites
- Docker + Docker Compose
- `just` (command runner)
- Sufficient disk for models (~5GB for qwen2.5:7b + nomic-embed-text)
---
## 1. Start the stack
```bash
just up
```
This starts Neo4j, Qdrant, Ollama, and the askme API container. Ollama models are pulled automatically on first start.
---
## 2. Ingest notebooks
### Full ingest
```bash
just ingest
```
Walks `data/notebook_archive/`, extracts text from `.ipynb`, `.Rmd`, `.py`, and `.R` files, deduplicates, and inserts into LightRAG. Entity extraction via LLM runs during insert — expect several hours for 700+ files.
```bash
just ingest --dry-run # list files that would be ingested without inserting
just ingest my-folder # ingest from data/my-folder/ instead
```
### Incremental ingest (new/changed files only)
```bash
just ingest-new
```
Uses `data/ingest_manifest.json` to track which files have been ingested. Only processes files that are new or whose content has changed since the last run.
### Re-ingesting from scratch
If you need to wipe and start over:
```bash
just clean-stores # wipes Neo4j, Qdrant, and LightRAG KV store (keeps Ollama models)
just up
just ingest
```
---
## 3. Query
### CLI
```bash
just query "What preprocessing steps are used for scRNA-seq data?"
```
Query modes (default: `hybrid`):
| Mode | Description |
|---|---|
| `hybrid` | Combines local and global graph traversal (recommended) |
| `local` | Answers from local entity neighbourhood |
| `global` | Answers from high-level graph summaries |
| `naive` | Direct vector similarity, no graph traversal |
```bash
docker compose exec askme uv run askme-query "What is UMAP?" --mode local
```
### API
```bash
just serve # starts FastAPI on port 8000 with reload
```
```bash
curl -X POST http://localhost:8000/query \
-H "Content-Type: application/json" \
-d '{"question": "How is cell clustering performed?", "mode": "hybrid"}'
```
Response:
```json
{
"answer": "...",
"sources": [
{"file": "notebooks/clustering.ipynb", "excerpt": "..."}
]
}
```
### Utility endpoints
```bash
curl http://localhost:8000/health # check Neo4j, Qdrant, Ollama reachability
curl http://localhost:8000/collections # chunk, entity, relationship counts in Qdrant
```
---
## 4. Evaluate
```bash
just eval
just eval --testset-size 20 --output data/eval_report.json
```
Generates a synthetic testset from ingested content, queries LightRAG, and scores with RAGAS (faithfulness, answer relevancy, context precision). Results are printed as a table and optionally saved as JSON.
---
## 5. Run tests
```bash
uv run pytest tests/
uv run pytest tests/ --cov=askme --cov-report=term-missing
```
---
## 6. Teardown
```bash
just down # stop all containers (preserves volumes)
just clean-stores # stop + wipe Neo4j, Qdrant, LightRAG KV store
just clean-all # stop + wipe everything including Ollama models
```

44
OKF/index.md Normal file
View File

@ -0,0 +1,44 @@
---
okf_version: "0.1"
---
# askme — OKF index
Open-knowledge-format wiki. Agents: read this page first, then the pages
your task needs. Humans welcome too.
## Pages
- [SUMMARY.md](SUMMARY.md) — what this project is; start here cold.
- ARCHITECTURE.md — modules, seams, main flows. TODO(scribe): not yet written.
- CONTEXT.md — canonical domain glossary. TODO(model-domain): not yet written.
- [ROADMAP.md](ROADMAP.md) — phased plan with verify steps.
- [learnings/index.md](learnings/index.md) — gotchas and debunked claims: operations, evaluation.
## Guides
- [guides/index.md](guides/index.md) — guide list. [guides/usage.md](guides/usage.md) — every command: stack, ingest, query, API, eval, teardown.
A page is listed when planned, written when its producer has something to
say — CONTEXT and ROADMAP wait for model-domain and chart.
## Modules & analyses
- None planned. The taxonomy scan's `analyses/` candidates come from the
private, gitignored notebook archive and are rejected for good; module
pages wait until ARCHITECTURE.md needs to shed.
## Decisions
- `decisions/index.md` — TODO(scribe): the why-register; link it here
once the first decision lands.
## Blueprints
- `blueprints/` — TODO(scribe): list blueprints here as blueprint writes
them (`NNN — title — status`).
## Ferries
- `ferries/` — TODO(scribe): one line per ferry
(`<topic> — n/m resolved → MAP.md`).

View File

@ -0,0 +1,92 @@
---
type: Learnings
purpose: Keep debunked beliefs about evaluating askme with local RAGAS judges.
answers:
- "Which beliefs about evaluating askme were debunked, and what replaced them?"
cites:
- src/askme/evaluation/local_eval.py
- src/askme/evaluation/compare.py
---
# askme — learnings: evaluation
- **Believed:** every generator answers from the same retrieved context.
**True:** LightRAG builds prompts up to 30000 tokens; Ollama
(`OLLAMA_CONTEXT_LENGTH=16384`) silently truncated them and the router
(32k) rejected some with HTTP 400. Eval queries now cap the prompt at
12000 tokens. **Source:** pilot log 2026-11-03,
`src/askme/evaluation/compare.py:_PROMPT_TOKEN_CAP`.
- **Believed:** capping `max_total_tokens` alone shrinks the prompt evenly.
**True:** LightRAG gives chunks only what entities (default 6000),
relations (8000) and the system prompt leave over; a 12000 cap left 0
chunks in 37 of 39 answers. Entity/relation budgets must shrink with it
(now 2000/3000 → 4 chunks per answer). **Source:** pilot log
2026-11-03, `lightrag/operate.py` `available_chunk_tokens`.
- **Believed:** RAGAS works with a 7B local model. **True:** the
LangchainLLMWrapper + TestsetGenerator path aborted or hung three ways on
qwen2.5:7b. The instructor judge (`llm_factory` with an OpenAI-compatible
client, metrics' `.ascore()` called directly) works. **Source:**
`src/askme/evaluation/local_eval.py`, RAGAS issue #1214.
- **Believed:** the answering model drives the scores. **True:** the judge
dominates. Same qwen2.5:7b answers, N=10: faithfulness 0.913 (gemma3:4b),
0.967 (gemma2:9b), 0.634 (qwen2.5:7b); context_precision 1.0 vs 0.5 by
judge alone. Use local-judge scores relatively, with a fixed judge.
**Source:** `data/local_eval_*.json`, 2026-06-18.
- **Believed:** bigger judges are stricter. **True:** gemma2:9b was more
lenient than gemma3:4b; leniency tracked the gemma family, not size.
**Source:** same runs.
- **Believed:** a reasoning model (qwen3.5:9b) makes a better judge.
**True:** unbounded `<think>` output blew every token/time budget (two
N=50 crashes), and Ollama's `/v1` ignored both ways to disable thinking.
**Source:** `data/local_eval_q35.log`, 2026-06-20.
- **Believed:** the first N chars of LightRAG's context dump are a fair
judge context. **True:** the ~27k-token dump starts with entity triples;
truncating kept no source chunks and zeroed context_precision. Use the
retrieved chunks. **Source:** commit `fix(eval/local): trim to the
document-chunks section`.
- **Believed:** interleaving answer and judge calls is fine. **True:** the
two models thrashed the 8 GB GPU and wedged runs; generate everything
first, then judge, one model resident at a time. **Source:** commit
`fix(eval/local): two-phase scoring`.
- **Believed:** retrieval matches meaning. **True:** it is
vocabulary-sensitive — a question phrased without the corpus's own term
missed the right entities. **Source:** commit `fix(eval): reword Hotspot
retrieval question`, 2026-06-18.
- **Believed:** gemma-4-12b is too slow to judge on 8 GB (~80 s/call).
**True:** unverified — that run may have been on CPU (see the CDI entry);
re-measure on the router. **Source:** 2026-11-03 pilot pending.
- **Believed:** a test asserting the prompt cap is passed proves the fix.
**True:** it passed while 37 of 39 answers had no source chunks; the
effect was only visible in the live log. Before a multi-hour run, run 2
questions live and check chunk counts per answer. **Source:**
2026-11-03 pilot.
- **Believed:** swapping LightRAG's LLM per query needs a second LightRAG
instance. **True:** `QueryParam.model_func` overrides both keyword
extraction and answer synthesis for one query; preset
`hl_keywords`/`ll_keywords` skip extraction (pinned mode). **Source:**
`lightrag/operate.py` `get_keywords_from_query`, 2026-11-02.
- **Believed:** gemma-4-12b-qat is a plain instruct model. **True:** the
router returns `reasoning_content` before the answer — it thinks, like
the qwen3.5 judge that failed above. Answering takes ~1–2 min/question
on the router with a 12000-token prompt (qwen2.5:7b on Ollama GPU:
~15 s). **Source:** 2026-11-03 smoke run and pilot log.
- **Believed:** turning a reasoning model's thinking off is optional for
judging. **True:** gemma-4-12b-qat reasoned inside the faithfulness
structured output until `max_tokens` (10000) and the exception ended the
whole pilot. Fixed twice: `reasoning = off` in its router preset, and
judge failures now leave one metric `None` (counted as "failed" in
comparison.md) instead of ending the run. **Source:** pilot crash
2026-11-03, `src/askme/evaluation/compare.py:judge_samples`.
- **Believed:** LightRAG's graph modes (hybrid) retrieve better than plain
vector search. **True:** on this graph, `naive` beat `hybrid` on every
metric — context_precision 0.454 vs 0.268, faithfulness 0.830 vs 0.668
(qwen2.5:7b judge, n=20; run-to-run noise ~±0.06). A low-quality graph
is worse than no graph. **Source:** `just eval-compare 20 pinned …
--mode naive|hybrid`, 2026-11-03.
- **Believed:** judges agree roughly on the same answers. **True:** in the
2×2 pilot, gemma-4 gave qwen's answers faithfulness 0.495 where qwen gave
0.729, and context_precision ranged 0.29–0.67 by judge; self-judging was
not consistently lenient (gemma scored itself 0.64, qwen scored gemma
0.82). Only answer_relevancy was stable (~0.77–0.83). **Source:**
pilot-2x2-n20 comparison, 2026-11-03.

17
OKF/learnings/index.md Normal file
View File

@ -0,0 +1,17 @@
---
type: Learnings
purpose: Point to where each theme of askme's debunked beliefs lives.
answers:
- "Where are askme's learnings kept, by theme?"
cites:
- docker-compose.yml
- src/askme/evaluation/compare.py
---
# askme — learnings
Append-only. Each entry: believed / true / source. Hardware: RTX 5060
Laptop 8 GB. Migrated from the root Roadmap.md on 2026-11-03.
- [operations.md](operations.md) — stack, Docker, GPU, LightRAG runtime.
- [evaluation.md](evaluation.md) — RAGAS, judges, eval-compare.

View File

@ -0,0 +1,73 @@
---
type: Learnings
purpose: Keep debunked beliefs about running askme's stack, GPU and LightRAG runtime.
answers:
- "Which beliefs about operating askme's stack were debunked, and what replaced them?"
cites:
- docker-compose.yml
- src/askme/rag.py
---
# askme — learnings: operations
- **Believed:** `just down` is safe any time. **True:** stopping mid-ingest
corrupts LightRAG's JSON KV files (`JSONDecodeError` on next boot). Wait
for ingest or drain with `just process-pending` first; recovery is
`just clean-stores` + re-ingest. **Source:** 2026-06 ingest.
- **Believed:** `docker compose restart` picks up env changes. **True:** it
does not — use `just down && just up`. **Source:** 2026-06 ingest tuning.
- **Believed:** `nvidia-smi` working in a container means CUDA works there.
**True:** with the legacy `driver: nvidia` hook on driver 610, `cuInit`
failed with 999 while `nvidia-smi` worked; Ollama silently ran on CPU.
CDI (`nvidia-ctk cdi generate`) fixed it. **Source:** commit
`fix(ollama): pass the GPU via CDI`, 2026-11-03.
- **Believed:** `OLLAMA_KEEP_ALIVE=-1` is needed to keep ingest fast.
**True:** it pins the model on the GPU forever and blocks other GPU
servers; `5m` stays warm across ingest calls. **Source:** commit
`feat(ollama): release the GPU when idle`, 2026-11-02.
- **Believed:** LightRAG's caches are safe when comparing models.
**True:** cache keys ignore the model, so a second generator would get
the first one's cached answers and keywords. `create_rag(cache=False)`
for comparisons. **Source:** `lightrag/operate.py` `compute_args_hash`.
- **Believed:** `settings.chunk_overlap` was applied. **True:** it was dead
config until passed to LightRAG; the 4000-char embed cap also dropped
chunk tails silently (now logged). **Source:** 2026-06-17 review.
- **Believed:** LightRAG takes storage URLs from askme's settings.
**True:** its Neo4j/Qdrant backends read `QDRANT_URL`, `NEO4J_URI` etc.
straight from `os.environ` and refuse to start without them; a host
process (outside compose) must export them — `just eval-compare` does.
**Source:** `lightrag/utils.py` `check_storage_env_vars`, 2026-11-03.
- **Believed:** the askme container can reach a llama.cpp router on the
host. **True:** the router binds `127.0.0.1:8080`, which the container's
localhost does not reach; eval-compare therefore runs on the host, where
Ollama, Neo4j, Qdrant and the router are all on localhost. **Source:**
`templates/llama-router.service` in llm-config, 2026-11-02.
- **Believed:** host processes can write to `data/`. **True:** the
container runs as root, so everything it writes under the bind-mounted
`data/` is root-owned; `sudo chown -R $USER: data/rag_storage` after an
in-container ingest. **Source:** `askme_meta.json` write, 2026-11-02.
- **Believed:** `pkill -f askme-eval-compare` stops only the eval.
**True:** the pattern also matches the shell running pkill and kills it;
match the interpreter: `pkill -f "python.*askme-eval-compare"`.
**Source:** 2026-11-03 session.
- **Believed:** `just eval-compare n=20` sets `n`. **True:** just recipe
arguments are positional; `n=20` became the first parameter's value.
Pass values in order (`just eval-compare 20`). **Source:** `just
--dry-run`, 2026-11-02.
- **Believed:** normal queries (`just query`, the API) answer from the
whole retrieved context. **True:** `rag.py` set Ollama's `num_ctx` to
4096 while LightRAG builds prompts up to 30000 tokens; Ollama cut the
rest silently. Now every query path caps the prompt at 12000 tokens
(entities 2000, relations 3000, rest for chunks) and `num_ctx` is 16384.
Query-time only — the stores were not re-ingested. The 2026-06 eval-local
numbers came through the old path. **Source:** `src/askme/rag.py`
`make_query_param`, 2026-11-03. Open: whether ingest-time entity
extraction was truncated too (its log is gone).
- **Believed:** the ingested graph holds domain knowledge (genes, cell
types, methods). **True:** 33% of 22,144 entities are `UNKNOWN`, genes are
1.2%, the best-connected nodes are `adata` and plotting calls, and some
entities are copied from LightRAG's extraction examples
(`Tokyo2023World…`) — signs of lost instructions (truncated prompt) or a
too-small model. Code-heavy notebooks also yield variable names as
entities. **Source:** Cypher entity-type count and random sample,
2026-11-03.

135
README.md Normal file
View File

@ -0,0 +1,135 @@
# askme
Local question answering over your own analysis notebooks (`.ipynb`, `.Rmd`,
`.py`, `.R`). askme builds a [LightRAG](https://github.com/HKUDS/LightRAG)
knowledge graph from the notebooks and answers questions grounded in them —
fully local: models run in Ollama, nothing leaves the machine.
Built for bioinformatics notebooks (scanpy, scRNA-seq, spatial
transcriptomics), but nothing in the pipeline is domain-specific.
## Stack
| Service | Role |
|---|---|
| Ollama | LLM (default `qwen2.5:7b`) and embeddings (`nomic-embed-text`) |
| Neo4j | knowledge graph |
| Qdrant | vectors for chunks, entities, relations |
| askme | ingestion, query CLI, FastAPI server, evaluation |
## Requirements
- Docker with Docker Compose, and [`just`](https://github.com/casey/just)
- [`uv`](https://docs.astral.sh/uv/) on the host (tests and `just eval-compare` run there)
- NVIDIA GPU (developed on 8 GB) with the NVIDIA Container Toolkit, GPU
passed to containers via CDI. Generate the spec once, and again after
every driver update — otherwise Ollama silently falls back to CPU:
```bash
sudo nvidia-ctk cdi generate --output=/etc/cdi/nvidia.yaml
```
- Disk: ~5 GB of models, plus the stores (grow with your notebook collection)
Docker access: either your user is in the `docker` group (root-equivalent),
you prefix docker commands with `sudo`, or you run rootless Docker.
## Quick start
```bash
just up # Neo4j, Qdrant, Ollama, askme; pulls models
mkdir -p data/notebook_archive # put your notebooks here
just ingest # build the graph (slow: hours for hundreds of files)
just query "How are low-quality cells filtered?"
```
`data/` is gitignored — your notebooks, stores and testsets stay local.
Full command reference: [`OKF/guides/usage.md`](OKF/guides/usage.md), or `just --list`.
## Configuration
Model choices are justfile variables, overridable via environment or `.env`:
| Variable | Default | Notes |
|---|---|---|
| `LLM_MODEL` | `qwen2.5:7b` | builds the graph and answers queries |
| `EMBEDDING_MODEL` | `nomic-embed-text` | fixed once data is ingested |
| `EMBEDDING_DIM` | `768` | must match the embedding model |
| `OLLAMA_KEEP_ALIVE` | `5m` | how long an idle model stays on the GPU |
| `EVAL_MODELS` | `qwen2.5:7b gemma3:4b gemma2:9b llamacpp:gemma-4-12b-qat` | models compared by `just eval-compare` |
| `LLAMACPP_URL` | `http://localhost:8080` | optional llama.cpp router for `llamacpp:<id>` models |
The embedding model and dimension are recorded in
`data/rag_storage/askme_meta.json` on first use; askme refuses to run against
stores built with a different embedding. To switch: `just clean-stores`, then
re-ingest.
**One GPU, one model.** Stop other GPU model servers (e.g. a llama.cpp
router) before ingesting — a second resident model makes loads fail or spill
to CPU.
## Evaluation
Evaluation needs a testset of questions about *your* notebooks. Write your own
in `data/` (gitignored), following the examples:
- `data/testset.json` — `{question, reference}` pairs for RAGAS; format in
[`eval/testset.example.json`](eval/testset.example.json)
- `data/retrieval_testset.json` — `{question, expected}` term pairs for the
retrieval eval; format in
[`eval/retrieval_testset.example.json`](eval/retrieval_testset.example.json)
| Command | Measures |
|---|---|
| `just eval-retrieval` | retrieval term recall, no LLM judge |
| `just eval-local <judge> --n N` | RAGAS faithfulness / answer relevancy / context precision with a local judge |
| `just eval-compare [n] [keywords] [generators] [judges]` | full generator × judge RAGAS matrix |
`eval-compare` has every generator answer the testset through the same
knowledge graph, then every judge score every generator. It runs on the host,
keeps one model on the GPU at a time, writes results as they finish (rerun
with `--out <dir>` to resume), and renders `comparison.md` with one matrix per
metric. Self-judged cells are flagged — local judges are noticeably lenient
on their own answers, and judge choice moves absolute scores more than
generator choice, so read the matrix comparatively.
```bash
just eval-compare 20 # 20 questions, every EVAL_MODELS model in both roles
just eval-compare 20 pinned # retrieval keywords extracted once by LLM_MODEL,
# so only answer synthesis differs
```
Models are Ollama tags, or `llamacpp:<model-id>` for a model served by a
llama.cpp router (OpenAI-compatible).
### What shapes the scores
Code-level knobs (embedding, chunking, judges, generators, memory, context
budget, query mode, retrieval depth, rerank, keyword mode, temperature) are
marked in the source: `grep -rn "#ADJUST" justfile docker-compose.yml src`.
Two more choices live outside the code:
- **Testset and n.** Scores are means over your questions, so they inherit
the testset's coverage: questions on topics the notebooks barely cover pull
faithfulness down, and questions phrased in the notebooks' own vocabulary
retrieve better than paraphrases. Small n is noisy — with n=20 one question
moves a mean by 0.05. Compare runs only on the same questions and n.
- **Metrics.** *Faithfulness* — are the answer's claims supported by the
retrieved text (catches invention). *Answer relevancy* — does the answer
address the question (catches evasive or noncommittal answers; uses the
embedding model). *Context precision* — are the retrieved chunks that
support the reference answer ranked high (judges retrieval, not the
answer). A model can be faithful yet unhelpful, or relevant yet invented —
read the three together.
## Development
```bash
just test # unit tests, host, no containers
```
Agent and contributor conventions: [`AGENTS.md`](AGENTS.md).
## License
Apache 2.0 — see [`LICENSE`](LICENSE).

125
docker-compose.yml Normal file
View File

@ -0,0 +1,125 @@
services:
# ===== Main askme RAG application ==========================================
askme:
build: .
container_name: askme
volumes:
- .:/usr/askme # live code reload
- ./data:/usr/askme/data # notebooks, processed text, indexes
environment:
- PYTHONPATH=/usr/askme
- DATA_DIR=/usr/askme/data
- NEO4J_URI=neo4j://neo4j:7687
- NEO4J_USERNAME=neo4j
- NEO4J_PASSWORD=${NEO4J_PASSWORD:-askme_neo4j}
- QDRANT_URL=http://qdrant:6333
- OLLAMA_HOST=http://ollama:11434
- LLM_MODEL=${LLM_MODEL:-qwen2.5:7b}
- LLM_TIMEOUT=900
- EMBEDDING_TIMEOUT=300
- EMBEDDING_MODEL=${EMBEDDING_MODEL:-nomic-embed-text}
env_file:
- .env
ports:
- "8000:8000"
depends_on:
neo4j:
condition: service_healthy
qdrant:
condition: service_started
ollama-init:
condition: service_completed_successfully
restart: unless-stopped
# ==== Neo4j – graph storage for LightRAG knowledge graph ===================
neo4j:
image: neo4j:5-community
container_name: askme-neo4j
environment:
- NEO4J_AUTH=neo4j/${NEO4J_PASSWORD:-askme_neo4j}
- NEO4J_PLUGINS=["apoc"]
- NEO4J_dbms_memory_heap_max__size=2G
- NEO4J_dbms_memory_pagecache_size=1G
ports:
- "7474:7474" # Neo4j Browser UI
- "7687:7687" # Bolt protocol
volumes:
- neo4j_data:/data
- neo4j_logs:/logs
healthcheck:
test: ["CMD", "cypher-shell", "-u", "neo4j", "-p", "${NEO4J_PASSWORD:-askme_neo4j}", "RETURN 1"]
interval: 15s
timeout: 10s
retries: 10
restart: unless-stopped
# ==== Qdrant – vector storage for dense retrieval ==========================
qdrant:
image: qdrant/qdrant:latest
container_name: askme-qdrant
ports:
- "6333:6333" # REST API
- "6334:6334" # gRPC
volumes:
- qdrant_data:/qdrant/storage
restart: unless-stopped
# ==== Ollama – local LLM server (Qwen2.5-7B + embedding model) =============
ollama:
image: ollama/ollama:latest
container_name: askme-ollama
environment:
# #ADJUST memory: parallel request slots per loaded model; each costs KV-cache
# VRAM — too many spill the model to CPU (much slower). Speed, not scores.
- OLLAMA_NUM_PARALLEL=2
- OLLAMA_KEEP_ALIVE=${OLLAMA_KEEP_ALIVE:-5m} # long enough to stay warm across ingest calls; frees the GPU when idle
# #ADJUST context management: default window for requests that set none (eval
# generators and judges via /v1). Longer prompts are truncated silently; larger
# windows cost VRAM.
- OLLAMA_CONTEXT_LENGTH=16384 # default ctx for the RAGAS judge (LightRAG pins its own 4096)
- GGML_CUDA_FORCE_CUBLAS=1
ports:
- "11434:11434"
volumes:
- ollama_models:/root/.ollama
healthcheck:
test: ["CMD", "ollama", "list"]
interval: 10s
timeout: 10s
retries: 12
start_period: 20s
# GPU passthrough via CDI — requires NVIDIA Container Toolkit on host and a
# generated spec: `sudo nvidia-ctk cdi generate --output=/etc/cdi/nvidia.yaml`
# (re-run after driver updates). The legacy `driver: nvidia` hook left CUDA
# failing with cuInit 999 inside the container on driver 610.
deploy:
resources:
reservations:
devices:
- driver: cdi
device_ids: ["nvidia.com/gpu=all"]
capabilities: [gpu]
restart: unless-stopped
# ==== Pull required models once on first start ==============================
ollama-init:
image: ollama/ollama:latest
container_name: askme-ollama-init
depends_on:
ollama:
condition: service_healthy
environment:
- OLLAMA_HOST=http://ollama:11434
entrypoint: ["/bin/sh", "-c"]
command:
- |
ollama pull ${LLM_MODEL:-qwen2.5:7b} &&
ollama pull ${EMBEDDING_MODEL:-nomic-embed-text}
restart: "no"
volumes:
neo4j_data:
neo4j_logs:
qdrant_data:
ollama_models:

View File

@ -0,0 +1,5 @@
[
{"question": "How are cells clustered into communities?", "expected": "leiden"},
{"question": "How is total-count normalization applied to expression data?", "expected": "normalize_total"},
{"question": "How is dimensionality reduced before building the neighbor graph?", "expected": "pca"}
]

14
eval/testset.example.json Normal file
View File

@ -0,0 +1,14 @@
[
{
"question": "How are raw counts normalized before clustering?",
"reference": "Counts are scaled to a fixed total per cell and then log-transformed (log1p)."
},
{
"question": "Which method is used to reduce dimensionality before building the neighbor graph?",
"reference": "Principal component analysis (PCA) on the highly variable genes."
},
{
"question": "How are low-quality cells filtered?",
"reference": "Cells with too few detected genes or a high fraction of mitochondrial reads are removed."
}
]

207
justfile Normal file
View File

@ -0,0 +1,207 @@
# askme – LightRAG over bioinformatics notebooks
# Usage: just <recipe>
set dotenv-load := true
set shell := ["bash", "-cu"]
# ── Model config ──────────────────────────────────────────────────────────────
# Single source of truth for models; override via env or .env.
# Embedding model/dim are fixed once data is ingested — changing them requires
# `just clean-stores` and a re-ingest (askme refuses mismatched stores).
# #ADJUST answer generator + graph builder: this model extracts entities at ingest
# (changing it there needs a re-ingest; a weaker model yields generic entities and a
# poorer graph) and writes every answer at query time (style, faithfulness).
export LLM_MODEL := env("LLM_MODEL", "qwen2.5:7b")
# #ADJUST embedding type: decides which chunks/entities vector search finds, so it
# drives context_precision and, through the context, faithfulness. Fixed per store —
# changing it needs `just clean-stores` and a full re-ingest; DIM must match the model.
export EMBEDDING_MODEL := env("EMBEDDING_MODEL", "nomic-embed-text")
export EMBEDDING_DIM := env("EMBEDDING_DIM", "768")
# How long Ollama keeps an idle model on the GPU (applied on `just up`).
# Stop other GPU model servers (e.g. `systemctl --user stop llama-router`) before ingesting.
# #ADJUST memory: longer keeps a model resident (no reload between calls) but blocks
# the GPU for other models; too short forces reloads. Affects speed, not scores — unless
# memory pressure pushes a model onto the CPU.
export OLLAMA_KEEP_ALIVE := env("OLLAMA_KEEP_ALIVE", "5m")
# Optional llama.cpp router for eval models addressed as "llamacpp:<model-id>"
export LLAMACPP_URL := env("LLAMACPP_URL", "http://localhost:8080")
# Models compared by `just eval-compare` (as generators and as judges).
# Bare tag = Ollama; "llamacpp:<id>" = llama.cpp router model.
# #ADJUST judges + answer generators: rows (generators) and columns (judges) of the
# eval-compare matrix. Judge choice moves absolute scores more than generator choice
# (gemma judges lenient, qwen strict); self-judged cells are inflated.
eval_models := env("EVAL_MODELS", "qwen2.5:7b gemma3:4b gemma2:9b llamacpp:gemma-4-12b-qat")
# Forward the model config into the askme container
dce := "docker compose exec -e LLM_MODEL -e EMBEDDING_MODEL -e EMBEDDING_DIM"
# Default: list available recipes
default:
@just --list
# ── Stack lifecycle ────────────────────────────────────────────────────────────
# Start all services (pulls models on first run)
up:
docker compose up -d
# Start and stream logs
up-attached:
docker compose up
# Stop all services
down:
docker compose down
# Rebuild askme image and restart
build:
docker compose build askme
docker compose up -d --no-deps askme
# Restart a single service (default: askme)
restart service="askme":
docker compose restart {{ service }}
# Show running services and health
ps:
docker compose ps
# ── Logs ───────────────────────────────────────────────────────────────────────
# Stream logs for all services (or pass a service name)
logs service="":
docker compose logs -f --tail=100 {{ service }}
# ── Models ────────────────────────────────────────────────────────────────────
# Manually pull/update Ollama models (re-runs ollama-init)
pull-models:
docker compose run --rm ollama-init
# List models currently loaded in Ollama
list-models:
docker compose exec ollama ollama list
# ── Ingestion ─────────────────────────────────────────────────────────────────
# Run ingestion pipeline (optional: path relative to data/, extra flags forwarded)
ingest path="notebook_archive" *flags="":
{{ dce }} askme uv run askme-ingest --source /usr/askme/data/{{ path }} {{ flags }}
# Incremental ingest — skips files unchanged since last run (uses manifest)
ingest-new path="notebook_archive":
{{ dce }} askme uv run askme-ingest \
--source /usr/askme/data/{{ path }} \
--manifest /usr/askme/data/ingest_manifest.json
# Process pending/failed documents (use when a previous ingest was interrupted)
process-pending:
{{ dce }} askme uv run python scripts/process_pending.py
# ── Querying ──────────────────────────────────────────────────────────────────
# Start the FastAPI server (reload on code changes)
serve:
{{ dce }} askme uv run uvicorn askme.api.main:app --host 0.0.0.0 --port 8000 --reload
# Run a one-off query from the CLI
query q:
{{ dce }} askme uv run askme-query "{{ q }}"
# ── Evaluation ────────────────────────────────────────────────────────────────
# Evaluate RAG faithfulness with RAGAS (optional: --testset-size N --output path)
eval *args:
{{ dce }} askme uv run askme-eval {{ args }}
# RAGAS eval with an independent CPU judge model (e.g. gemma4:12b). Pilot small:
# just eval-judge gemma4:12b --testset-size 5
eval-judge model="gemma4:12b" *args:
{{ dce }} -e RAGAS_JUDGE_MODEL={{ model }} askme uv run askme-eval {{ args }}
# Local retrieval term-recall eval (no LLM judge)
eval-retrieval *args:
{{ dce }} askme uv run askme-eval-retrieval {{ args }}
# Fully-local RAGAS triad (instructor judge). Pilot small; gemma4:12b is CPU-slow:
# just eval-local gemma4:12b --n 5
eval-local model="gemma4:12b" *args:
{{ dce }} -e RAGAS_JUDGE_MODEL={{ model }} askme uv run askme-eval-local {{ args }}
# Generator x judge RAGAS matrix. Runs on the host (reaches Ollama, the stores
# and the llama.cpp router on localhost). Reuse --out <dir> to resume a run:
# just eval-compare 20 # n=20, per-generator keywords
# just eval-compare 20 pinned # keywords extracted once by LLM_MODEL
# just eval-compare 5 per-generator "gemma3:4b" "qwen2.5:7b" # one generator, one judge
# #ADJUST keyword mode: per-generator lets each model extract its own retrieval
# keywords (realistic, but rows see different contexts); pinned uses LLM_MODEL's keywords
# for every row, so only answer synthesis differs between generators.
eval-compare n="10" keywords="per-generator" generators=eval_models judges=eval_models *args:
DATA_DIR=data RAG_WORKING_DIR=data/rag_storage \
QDRANT_URL=http://localhost:6333 NEO4J_URI=bolt://localhost:7687 NEO4J_USERNAME=neo4j \
NEO4J_PASSWORD="${NEO4J_PASSWORD:-askme_neo4j}" uv run askme-eval-compare \
--generators "{{ generators }}" --judges "{{ judges }}" \
--n {{ n }} --keywords {{ keywords }} {{ args }}
# ── Shells ────────────────────────────────────────────────────────────────────
# Open a shell inside a container (default: askme)
shell service="askme":
docker compose exec {{ service }} bash
# Open Neo4j cypher shell
neo4j-shell:
docker compose exec neo4j cypher-shell -u neo4j -p ${NEO4J_PASSWORD:-askme_neo4j}
# Open Ollama CLI shell
ollama-shell:
docker compose exec ollama bash
# ── Data management ───────────────────────────────────────────────────────────
# Wipe vector + graph stores + LightRAG registry (keeps models). Use when re-ingesting from scratch
clean-stores:
docker compose down
docker volume rm askme_neo4j_data askme_neo4j_logs askme_qdrant_data || true
sudo rm -rf data/rag_storage
# Full teardown: stop everything and remove all volumes (including models)
clean-all:
@echo "WARNING: This will delete ALL volumes including downloaded models."
@read -p "Are you sure? [y/N] " confirm && [ "$$confirm" = "y" ]
docker compose down -v
# ── Tests ─────────────────────────────────────────────────────────────────────
# Run unit tests (host, no container needed)
test:
uv run --extra dev --extra eval pytest tests/
# End-to-end smoke test: insert one doc, query it
smoke-test:
{{ dce }} askme uv run python scripts/smoke_test.py
# Run any script inside the askme container: just run scripts/test_extract.py
run script:
{{ dce }} askme uv run python {{ script }}
# ── Health checks ─────────────────────────────────────────────────────────────
# Check all services are reachable
check:
@echo "Neo4j..."; curl -sf http://localhost:7474 > /dev/null && echo " OK" || echo " FAIL"
@echo "Qdrant..."; curl -sf http://localhost:6333/healthz > /dev/null && echo " OK" || echo " FAIL"
@echo "Ollama..."; curl -sf http://localhost:11434/api/tags > /dev/null && echo " OK" || echo " FAIL"
# ── Info ──────────────────────────────────────────────────────────────────────
# Show service URLs
urls:
@echo "askme API → http://localhost:8000"
@echo "Neo4j UI → http://localhost:7474"
@echo "Qdrant UI → http://localhost:6333/dashboard"
@echo "Ollama API → http://localhost:11434"

155
pyproject.toml Normal file
View File

@ -0,0 +1,155 @@
[project]
name = "askme"
version = "0.0.1"
description = "LightRAG-powered Q&A over provided jupyter, Rmd notebooks and other scripts"
requires-python = ">=3.12"
dependencies = [
# lightRAG deps
"lightrag-hku>=1.0",
# LLM / Embeddings
# if not needed these will be removed
"ollama>=0.4", # Ollama Python client (required by lightrag llm/ollama)
"openai>=1.0", # OpenAI-compatible client
"anthropic>=0.40", # optional fallback
# Vector store
"qdrant-client>=1.12",
# Graph store
"neo4j>=5.0",
# Notebook ingestion
"nbconvert>=7.0",
"nbformat>=5.0",
# Deduplication (MinHash)
"datasketch>=1.6",
# API
"fastapi>=0.115",
"uvicorn[standard]>=0.32",
"pydantic>=2.0",
"pydantic-settings>=2.0",
# Utilities
"python-dotenv>=1.0",
"tqdm>=4.0",
"rich>=13.0",
"typer>=0.13",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"pytest-asyncio>=0.24",
"pytest-cov>=5.0",
"ruff>=0.8",
"mypy>=1.13",
"ipykernel>=6.0",
"jupyterlab>=4.0",
"notebook>=7.0",
]
eval = [
# RAG evaluation
"ragas>=0.4,<0.5", # code targets the 0.4 API (ragas.metrics.collections)
"rapidfuzz>=3.0", # required by ragas 0.4 testset transforms, not pulled transitively
"datasets>=3.0",
]
[project.scripts]
askme-ingest = "askme.ingestion.cli:main"
askme-query = "askme.api.cli:main"
askme-eval = "askme.evaluation.cli:main"
askme-eval-retrieval = "askme.evaluation.retrieval:main"
askme-eval-local = "askme.evaluation.local_eval:main"
askme-eval-compare = "askme.evaluation.compare:main"
[tool.hatch.build.targets.wheel]
packages = ["src/askme"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.ruff]
line-length = 90
target-version = "py312"
preview = true
exclude = [
".git",
".jj",
"__pycache__",
"_bin/*",
"_build/*",
".venv",
".mypy_cache",
".pytype",
".svn",
"__pypackages__",
]
extend-exclude = ["*.ipynb"]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
skip-magic-trailing-comma = false
line-ending = "auto"
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"UP", # pyupgrade
"ARG", # flake8-unused-arguments
"SIM", # flake8-simplify
"TCH", # flake8-type-checking
"PTH", # flake8-use-pathlib
"NPY", # numpy-specific rules
]
ignore = [
"E501", # line too long (handled by formatter)
]
[tool.ruff.lint.isort]
known-first-party = ["askme"]
[tool.ruff.lint.flake8-implicit-str-concat]
allow-multiline = false
[tool.mypy]
python_version = "3.12"
warn_return_any = true
warn_unused_ignores = true
disallow_untyped_defs = true
ignore_missing_imports = true
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
addopts = [
"-ra",
"--strict-markers",
"-q",
]
markers = [
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
"integration: marks tests as integration tests",
]
[tool.coverage.run]
source = ["askme"]
branch = true
omit = ["tests/*", "*/__pycache__/*"]
[tool.coverage.report]
exclude_lines = [
"pragma: no cover",
"def __repr__",
"raise NotImplementedError",
"if TYPE_CHECKING:",
]

View File

@ -0,0 +1,60 @@
"""
One-shot script to process any pending/failed documents in LightRAG.
Use when a previous ingest was interrupted before entity extraction completed.
Run inside the container: uv run python scripts/process_pending.py
"""
from __future__ import annotations
import asyncio
import logging
import sys
from lightrag.base import DocStatus
from askme.rag import create_rag
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
stream=sys.stderr,
)
log = logging.getLogger(__name__)
async def main() -> None:
rag = create_rag()
await rag.initialize_storages()
pending = await rag.doc_status.get_docs_by_status(DocStatus.PENDING)
processing = await rag.doc_status.get_docs_by_status(DocStatus.PROCESSING)
log.info("Found %d pending, %d processing docs", len(pending), len(processing))
if not pending and not processing:
log.info("Nothing to process.")
await rag.finalize_storages()
return
await rag.apipeline_process_enqueue_documents()
poll_interval = 30
while True:
pending = await rag.doc_status.get_docs_by_status(DocStatus.PENDING)
processing = await rag.doc_status.get_docs_by_status(DocStatus.PROCESSING)
if not pending and not processing:
break
log.info(
"Waiting: %d pending, %d processing — checking again in %ds",
len(pending),
len(processing),
poll_interval,
)
await asyncio.sleep(poll_interval)
await rag.finalize_storages()
log.info("Done.")
if __name__ == "__main__":
asyncio.run(main())

38
scripts/smoke_test.py Normal file
View File

@ -0,0 +1,38 @@
"""
Smoke test: insert one sentence, query it, verify the full pipeline works.
Run inside the askme container: uv run python scripts/smoke_test.py
"""
import asyncio
import os
from askme.rag import create_rag, make_query_param
TEXT = (
"Scanpy is a scalable toolkit for analyzing single-cell gene expression data. "
"It includes preprocessing, visualization, clustering, and trajectory inference."
)
QUERY = "What is scanpy used for?"
async def main() -> None:
os.makedirs("/usr/askme/data/rag_storage", exist_ok=True)
print("Initializing LightRAG...")
rag = create_rag()
await rag.initialize_storages()
print("Inserting test document...")
await rag.ainsert(TEXT)
print(f"\nQuerying: {QUERY!r}\n")
response = await rag.aquery(QUERY, param=make_query_param(mode="hybrid"))
print("Response:", response)
await rag.finalize_storages()
print("\nSmoke test passed.")
if __name__ == "__main__":
asyncio.run(main())

24
scripts/test_extract.py Normal file
View File

@ -0,0 +1,24 @@
"""Quick sanity check for the extractor — prints stats only, no content."""
from pathlib import Path
from askme.ingestion.extract import extract, supported_suffixes
archive = Path("/usr/askme/data/notebook_archive")
_SKIP = {"site-packages", "__pycache__", "x86_64-pc-linux-gnu-library"}
for suffix in sorted(supported_suffixes()):
files = [
p for p in archive.rglob("*")
if p.suffix.lower() == suffix
and not any(s in p.parts for s in _SKIP)
]
if not files:
print(f"{suffix}: no files found")
continue
sample = files[0]
try:
text = extract(sample)
lines = text.splitlines() if text else []
print(f"{suffix}: {len(files)} files | sample '{sample.name}' → {len(text)} chars, {len(lines)} lines")
except Exception as e:
print(f"{suffix}: ERROR on '{sample.name}': {e}")

45
scripts/test_filter.py Normal file
View File

@ -0,0 +1,45 @@
"""
Test the filter pipeline: walk the archive, apply path filter + dedup.
Prints stats only — no file content is shown.
"""
from pathlib import Path
from askme.config import settings
from askme.ingestion.extract import extract
from askme.ingestion.filter import Deduplicator, filter_paths
archive = Path("/usr/askme/data/notebook_archive")
all_paths = list(archive.rglob("*"))
kept = filter_paths(all_paths)
print(f"Total files found : {len(all_paths)}")
print(f"After path filter : {len(kept)}")
# Count by type
by_suffix: dict[str, int] = {}
for p in kept:
by_suffix[p.suffix.lower()] = by_suffix.get(p.suffix.lower(), 0) + 1
for suffix, count in sorted(by_suffix.items()):
print(f" {suffix:8s} {count}")
# Run deduplication
dedup = Deduplicator(threshold=settings.minhash_threshold)
duplicates = 0
errors = 0
for path in kept:
try:
text = extract(path)
if not text or not text.strip():
continue
if dedup.is_duplicate(path, text):
duplicates += 1
except Exception as e:
errors += 1
print(f"\nAfter dedup (threshold={settings.minhash_threshold}):")
print(f" Unique documents : {dedup.seen_count}")
print(f" Duplicates found : {duplicates}")
print(f" Errors : {errors}")

0
src/askme/__init__.py Normal file
View File

View File

41
src/askme/api/cli.py Normal file
View File

@ -0,0 +1,41 @@
"""askme-query CLI — query LightRAG directly from the terminal."""
from __future__ import annotations
import asyncio
import typer
from askme.api.main import _parse_sources
from askme.rag import create_rag, make_query_param
app = typer.Typer(add_completion=False)
async def _run(question: str, mode: str) -> None:
rag = create_rag()
await rag.initialize_storages()
try:
param = make_query_param(mode=mode)
raw: str = await rag.aquery(question, param=param)
answer, sources = _parse_sources(raw)
typer.echo(answer)
if sources:
typer.echo("\nSources:")
for src in sources:
typer.echo(f" {src.file}: {src.excerpt}")
finally:
await rag.finalize_storages()
@app.command()
def query(
question: str = typer.Argument(..., help="Question to ask"),
mode: str = typer.Option("hybrid", help="Query mode: hybrid|local|global|naive"),
) -> None:
"""Query the RAG knowledge base and print the answer with source references."""
asyncio.run(_run(question, mode))
def main() -> None:
app()

162
src/askme/api/main.py Normal file
View File

@ -0,0 +1,162 @@
"""FastAPI application exposing a single /query endpoint."""
from __future__ import annotations
import re
from contextlib import asynccontextmanager
from typing import TYPE_CHECKING, Any, Literal
if TYPE_CHECKING:
from collections.abc import AsyncIterator
import httpx
from fastapi import FastAPI
from neo4j import AsyncGraphDatabase
from pydantic import BaseModel
from askme.config import settings
from askme.rag import create_rag, make_query_param
class QueryRequest(BaseModel):
question: str
mode: Literal["local", "global", "hybrid", "naive"] = "hybrid"
class Source(BaseModel):
file: str
excerpt: str
class QueryResponse(BaseModel):
answer: str
sources: list[Source]
def _parse_sources(raw: str) -> tuple[str, list[Source]]:
"""Split answer text from an optional '## Sources' section.
LightRAG may append source references after the answer in the form:
## Sources
- path/to/file.ipynb: excerpt text...
Returns the clean answer and a list of Source objects.
"""
parts = re.split(r"\n#{1,3}\s*Sources\b", raw, maxsplit=1, flags=re.IGNORECASE)
answer = parts[0].strip()
sources: list[Source] = []
if len(parts) == 2:
for line in parts[1].splitlines():
line = line.strip().lstrip("-").strip()
if ":" in line:
file_part, _, excerpt_part = line.partition(":")
sources.append(
Source(file=file_part.strip(), excerpt=excerpt_part.strip())
)
return answer, sources
_rag: Any = None
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
global _rag
_rag = create_rag()
await _rag.initialize_storages()
yield
await _rag.finalize_storages()
app = FastAPI(title="askme", lifespan=lifespan)
class ServiceStatus(BaseModel):
status: str # "ok" or "error: <msg>"
class HealthResponse(BaseModel):
status: str # "ok" or "degraded"
services: dict[str, str]
class CollectionsResponse(BaseModel):
chunks: int
entities: int
relationships: int
async def _check_neo4j() -> str:
try:
driver = AsyncGraphDatabase.driver(
settings.neo4j_uri,
auth=(settings.neo4j_username, settings.neo4j_password),
)
await driver.verify_connectivity()
await driver.close()
return "ok"
except Exception as e:
return f"error: {e}"
async def _check_qdrant() -> str:
try:
async with httpx.AsyncClient(timeout=5) as client:
r = await client.get(f"{settings.qdrant_url}/collections")
r.raise_for_status()
return "ok"
except Exception as e:
return f"error: {e}"
async def _check_ollama() -> str:
try:
async with httpx.AsyncClient(timeout=5) as client:
r = await client.get(f"{settings.ollama_host}/api/tags")
r.raise_for_status()
return "ok"
except Exception as e:
return f"error: {e}"
async def _collection_count(name: str) -> int:
try:
async with httpx.AsyncClient(timeout=5) as client:
r = await client.get(f"{settings.qdrant_url}/collections/{name}")
r.raise_for_status()
return int(r.json()["result"]["points_count"])
except Exception:
return 0
@app.get("/health", response_model=HealthResponse)
async def health() -> HealthResponse:
services = {
"neo4j": await _check_neo4j(),
"qdrant": await _check_qdrant(),
"ollama": await _check_ollama(),
}
status = "ok" if all(v == "ok" for v in services.values()) else "degraded"
return HealthResponse(status=status, services=services)
@app.get("/collections", response_model=CollectionsResponse)
async def collections() -> CollectionsResponse:
embed = settings.embedding_model.replace("-", "_")
dim = settings.embedding_dim
prefix = f"lightrag_vdb_{{name}}_{embed}_{dim}d"
return CollectionsResponse(
chunks=await _collection_count(prefix.format(name="chunks")),
entities=await _collection_count(prefix.format(name="entities")),
relationships=await _collection_count(prefix.format(name="relationships")),
)
@app.post("/query", response_model=QueryResponse)
async def query(req: QueryRequest) -> QueryResponse:
param = make_query_param(mode=req.mode)
raw: str = await _rag.aquery(req.question, param=param)
answer, sources = _parse_sources(raw)
return QueryResponse(answer=answer, sources=sources)

70
src/askme/backends.py Normal file
View File

@ -0,0 +1,70 @@
"""Model specs spanning the two local backends: Ollama and the llama.cpp router.
A spec is a bare Ollama tag ("gemma2:9b"), or prefixed with its backend
("ollama:gemma2:9b", "llamacpp:gemma-4-12b-qat"). Both backends speak the
OpenAI API, so generators and judges are reached the same way.
"""
from __future__ import annotations
from dataclasses import dataclass
from lightrag.llm.openai import openai_complete_if_cache
from openai import AsyncOpenAI
from askme.config import settings
from askme.gpu import unload_llamacpp_model, unload_ollama_model
_BACKENDS = ("ollama", "llamacpp")
@dataclass(frozen=True)
class ModelSpec:
backend: str
model: str
label: str
def parse_spec(spec: str) -> ModelSpec:
prefix, _, rest = spec.partition(":")
if prefix in _BACKENDS and rest:
return ModelSpec(prefix, rest, spec)
return ModelSpec("ollama", spec, spec)
def _base_url(spec: ModelSpec) -> str:
host = settings.ollama_host if spec.backend == "ollama" else settings.llamacpp_url
return f"{host}/v1"
def openai_client(spec: ModelSpec) -> AsyncOpenAI:
"""OpenAI-compatible client for the spec's backend.
timeout caps each call so a dropped response (happens under VRAM pressure)
fails fast and retries instead of wedging forever. Set high (900s) because
reasoning models on a large-context call can take >5min on a partial-CPU
8GB box; 300s timed them out.
"""
return AsyncOpenAI(base_url=_base_url(spec), api_key="local", timeout=900.0, max_retries=2)
def lightrag_model_func(spec: ModelSpec):
"""LightRAG `QueryParam.model_func` answering (and extracting keywords) with `spec`."""
# #ADJUST sampling temperature: not set, so each model's default applies (often
# 0.7–1.0) — answers vary run to run and so do scores. Pass temperature=0 here for
# repeatable generators; it also applies to keyword extraction.
async def _complete(prompt: str, **kwargs) -> str:
return await openai_complete_if_cache(
spec.model, prompt, base_url=_base_url(spec), api_key="local", **kwargs
)
return _complete
async def release(spec: ModelSpec) -> None:
"""Free the GPU memory held by `spec` on its backend."""
if spec.backend == "ollama":
await unload_ollama_model(spec.model)
else:
await unload_llamacpp_model(spec.model)

64
src/askme/config.py Normal file
View File

@ -0,0 +1,64 @@
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
# Ollama
ollama_host: str = "http://localhost:11434"
# #ADJUST answer generator + graph builder — fallback for LLM_MODEL (justfile).
llm_model: str = "qwen2.5:7b"
# #ADJUST embedding type — fallback for EMBEDDING_MODEL/DIM (justfile); fixed per store.
embedding_model: str = "nomic-embed-text"
embedding_dim: int = 768 # nomic-embed-text output dimension
llm_timeout: int | None = None
# llama.cpp router (OpenAI-compatible) — optional second backend for eval
# models, addressed as "llamacpp:<model-id>"
llamacpp_url: str = "http://localhost:8080"
# Neo4j
neo4j_uri: str = "neo4j://localhost:7687"
neo4j_username: str = "neo4j"
neo4j_password: str = "askme_neo4j"
# Qdrant
qdrant_url: str = "http://localhost:6333"
# Storage
data_dir: str = "/usr/askme/data"
rag_working_dir: str = "/usr/askme/data/rag_storage"
# Ingestion
# #ADJUST chunking: smaller chunks give more precise retrieval but split context
# across pieces (more chunks needed per answer); larger ones carry more context but
# risk the 4000-char embedding cut. Overlap keeps statements spanning a border
# findable. Ingest-time: changing either needs a re-ingest.
chunk_size: int = 1200
chunk_overlap: int = 200
minhash_threshold: float = 0.95
# LightRAG runtime
# #ADJUST memory: concurrent LLM calls; above OLLAMA_NUM_PARALLEL they only queue,
# and each slot costs KV-cache VRAM. Speed only, unless it spills the model to CPU.
max_async: int = 2 # match OLLAMA_NUM_PARALLEL=2 — safe sweet spot on RTX 5060 8GB
# #ADJUST query mode: hybrid (graph neighbourhood + global summaries), local
# (entity neighbourhood), global (relation summaries), naive (plain vector search on
# chunks). Decides what text is retrieved at all — context_precision and, through
# the context, faithfulness. Query-time: no re-ingest.
default_query_mode: str = "hybrid"
# RAGAS judge — an independent local model (different family from the LLM
# that built the graph) scores the eval. Runs on CPU (num_gpu=0) so it does
# not contend with the GPU-resident RAG model. gemma4:12b is too large for
# the 8GB GPU but fits comfortably in CPU RAM.
# #ADJUST judges: the single judge of `just eval` / `just eval-local`; the judge sets
# the absolute score level (see OKF/learnings/evaluation.md).
ragas_judge_model: str = "qwen2.5:7b"
model_config = {
"env_file": ".env",
"env_file_encoding": "utf-8",
"extra": "ignore",
}
settings = Settings()

View File

122
src/askme/evaluation/cli.py Normal file
View File

@ -0,0 +1,122 @@
"""askme-eval CLI — generate a testset and evaluate RAG faithfulness."""
from __future__ import annotations
import json
import random
import time
from pathlib import Path
import typer
from rich.console import Console
from rich.table import Table
from askme.config import settings
from askme.evaluation.evaluate import run_eval
from askme.evaluation.generate import generate_testset
from askme.ingestion.extract import extract
from askme.ingestion.filter import filter_paths
app = typer.Typer(add_completion=False)
console = Console()
def _sample_docs(source_dir: Path, n: int) -> list[str]:
"""Return up to n extracted texts from source_dir, chosen randomly."""
candidates = filter_paths(list(source_dir.rglob("*")))
random.shuffle(candidates)
docs: list[str] = []
for path in candidates:
if len(docs) >= n:
break
try:
text = extract(path)
except Exception:
continue
if text:
docs.append(text)
return docs
def _load_doc_cache(cache: Path, source: Path, n: int) -> list[str] | None:
"""Return cached sampled docs if the cache matches source + sample size."""
if not cache.exists():
return None
data = json.loads(cache.read_text())
if data.get("source") == str(source) and data.get("doc_sample") == n:
return data["docs"]
return None
@app.command()
def eval_cmd(
source: Path = typer.Option(
Path("/usr/askme/data/notebook_archive"),
"--source",
help="Directory of notebooks/scripts to sample from",
),
testset_size: int = typer.Option(
50, "--testset-size", help="Number of Q&A pairs to generate"
),
output: Path = typer.Option(
Path("eval_report.json"), "--output", help="Path for JSON report"
),
doc_sample: int = typer.Option(
25,
"--doc-sample",
help="Number of source docs to sample for testset generation",
),
refresh: bool = typer.Option(
False, "--refresh", help="Re-sample source docs, ignoring any cache"
),
) -> None:
"""Evaluate RAG faithfulness using RAGAS synthetic testset."""
cache = output.with_suffix(".docsample.json")
cached = _load_doc_cache(cache, source, doc_sample) if not refresh else None
if cached is not None:
console.print(f"[bold]Reusing {len(cached)} cached docs[/bold] ({cache})")
docs = cached
else:
console.print(f"[bold]Sampling {doc_sample} docs from[/bold] {source}")
docs = _sample_docs(source, doc_sample)
if docs:
cache.write_text(
json.dumps(
{"source": str(source), "doc_sample": doc_sample, "docs": docs}
)
)
if not docs:
typer.echo("No documents found — check --source path.", err=True)
raise typer.Exit(1)
start = time.monotonic()
console.print(f"[bold]Generating {testset_size} Q&A pairs…[/bold]")
testset = generate_testset(docs, n=testset_size)
console.print("[bold]Evaluating…[/bold]")
scores = run_eval(testset, samples_path=output.with_suffix(".samples.json"))
elapsed = round(time.monotonic() - start, 1)
table = Table(title="RAGAS Evaluation Results")
table.add_column("Metric", style="cyan")
table.add_column("Score", style="green")
for metric in ("faithfulness", "answer_relevancy", "context_precision"):
table.add_row(metric, f"{scores[metric]:.3f}")
console.print(table)
console.print(f"Judge: [bold]{settings.ragas_judge_model}[/bold] | "
f"{testset_size} questions | {elapsed}s")
# Self-describing report: scores + run metadata (judge, size, wall-clock).
report = {
**scores,
"judge_model": settings.ragas_judge_model,
"testset_size": testset_size,
"elapsed_seconds": elapsed,
}
output.write_text(json.dumps(report, indent=2))
console.print(f"Report saved to [bold]{output}[/bold]")
def main() -> None:
app()

View File

@ -0,0 +1,356 @@
"""Generator x judge RAGAS matrix over the ingested knowledge graph.
Every generator answers the testset through LightRAG (the graph itself stays
the one built at ingest), then every judge scores every generator's answers
with the local RAGAS triad (faithfulness, answer relevancy, context precision).
Keywords: in "per-generator" mode each generator also extracts the retrieval
keywords (realistic: the whole query path runs on that model), so context
differences feed into the scores. In "pinned" mode the configured LLM extracts
them once and every generator retrieves the same contexts — only answer
synthesis differs.
Only one model is on the GPU at a time: all generation runs before judging and
each model is released after its phase. Results are written as they finish and
reused on rerun, so a crashed multi-hour run resumes where it stopped.
"""
from __future__ import annotations
import asyncio
import json
import time
from datetime import datetime
from pathlib import Path
import typer
from ragas.embeddings import OpenAIEmbeddings
from ragas.llms import llm_factory
from ragas.metrics.collections import (
AnswerRelevancy,
ContextPrecisionWithReference,
Faithfulness,
)
from rich.console import Console
from askme.backends import (
ModelSpec,
lightrag_model_func,
openai_client,
parse_spec,
release,
)
from askme.config import settings
from askme.rag import create_rag, make_query_param
app = typer.Typer(add_completion=False)
console = Console()
# #ADJUST memory: parallel calls per model (match OLLAMA_NUM_PARALLEL); higher only
# queues or adds KV-cache VRAM. Speed only.
_CONCURRENCY = 2
# ~3000 tokens of source text: fits a 16k judge context with room for the
# answer and the statement-extraction output.
# #ADJUST context management: how much retrieved source text the judge sees. Too low
# hides supporting text (faithfulness and context_precision drop); too high overflows
# small judge windows.
_CONTEXT_CHAR_CAP = 12000
_METRICS = ("faithfulness", "answer_relevancy", "context_precision")
def _contexts(raw: dict, cap: int = _CONTEXT_CHAR_CAP) -> list[str]:
"""Retrieved chunk texts in rank order, truncated to `cap` chars in total."""
out, left = [], cap
for chunk in raw.get("data", {}).get("chunks", []):
if left <= 0:
break
text = chunk["content"][:left]
out.append(text)
left -= len(text)
return out
def _keywords(raw: dict) -> tuple[list[str], list[str]]:
kw = raw.get("metadata", {}).get("keywords", {})
return kw.get("high_level", []), kw.get("low_level", [])
async def generate_samples(
rag,
gen: ModelSpec,
testset: list[dict],
mode: str,
pinned: dict[str, tuple[list[str], list[str]]] | None = None,
) -> list[dict]:
"""Answer every question with `gen`, recording contexts and keywords used."""
semaphore = asyncio.Semaphore(_CONCURRENCY)
model_func = lightrag_model_func(gen)
async def _one(item: dict) -> dict:
hl, ll = (pinned or {}).get(item["question"], ([], []))
param = make_query_param(
mode=mode,
model_func=model_func,
hl_keywords=list(hl),
ll_keywords=list(ll),
)
async with semaphore:
raw = await rag.aquery_llm(item["question"], param=param)
used_hl, used_ll = _keywords(raw)
return {
"question": item["question"],
"reference": item["reference"],
"answer": raw.get("llm_response", {}).get("content") or "",
"contexts": _contexts(raw),
"hl_keywords": used_hl,
"ll_keywords": used_ll,
}
return list(await asyncio.gather(*(_one(i) for i in testset)))
async def _pin_keywords(rag, testset: list[dict], mode: str) -> dict:
"""Extract retrieval keywords once with the configured LLM."""
semaphore = asyncio.Semaphore(_CONCURRENCY)
async def _one(item: dict) -> tuple[str, tuple[list[str], list[str]]]:
async with semaphore:
raw = await rag.aquery_data(item["question"], param=make_query_param(mode=mode))
return item["question"], _keywords(raw)
return dict(await asyncio.gather(*(_one(i) for i in testset)))
async def judge_samples(judge: ModelSpec, samples: list[dict]) -> list[dict]:
"""Score samples with the RAGAS triad, `judge` as the schema-enforced LLM.
max_tokens is generous: faithfulness extracts one statement per answer
claim, and reasoning models emit a long <think> block before the JSON.
"""
# #ADJUST sampling temperature: judges run at their model default, so the same
# answer can score differently across runs; temperature=0 would make judging
# repeatable.
# #ADJUST judges: judge output budget — too low truncates faithfulness statement
# lists (and reasoning judges' thinking), failing or zeroing the metric.
llm = llm_factory(judge.model, provider="openai", client=openai_client(judge), max_tokens=10000)
embedder = parse_spec(settings.embedding_model)
embeddings = OpenAIEmbeddings(client=openai_client(embedder), model=embedder.model)
faith = Faithfulness(llm=llm)
relev = AnswerRelevancy(llm=llm, embeddings=embeddings)
prec = ContextPrecisionWithReference(llm=llm)
semaphore = asyncio.Semaphore(_CONCURRENCY)
async def _one(s: dict) -> dict:
calls = {
"faithfulness": lambda: faith.ascore(
user_input=s["question"], response=s["answer"], retrieved_contexts=s["contexts"]
),
"answer_relevancy": lambda: relev.ascore(
user_input=s["question"], response=s["answer"]
),
"context_precision": lambda: prec.ascore(
user_input=s["question"], reference=s["reference"], retrieved_contexts=s["contexts"]
),
}
row: dict = {"question": s["question"], "errors": {}}
async with semaphore:
for metric, call in calls.items():
# One failed judge call (e.g. output cut at max_tokens) leaves this
# metric None instead of ending a multi-hour run.
try:
row[metric] = (await call()).value
except Exception as e: # noqa: BLE001 — any judge failure is recorded
row[metric] = None
row["errors"][metric] = f"{type(e).__name__}: {e}"[:500]
return row
return list(await asyncio.gather(*(_one(s) for s in samples)))
def _slug(label: str) -> str:
return label.replace("/", "_").replace(":", "_")
def _mean(results: list[dict], key: str) -> float | None:
vals = [r[key] for r in results if r[key] is not None]
return sum(vals) / len(vals) if vals else None
def _keyword_overlap(samples: dict[str, list[dict]], baseline: str) -> dict[str, float]:
"""Mean Jaccard overlap of each generator's keywords with the baseline's."""
def _set(s: dict) -> set[str]:
return {k.lower() for k in s["hl_keywords"] + s["ll_keywords"]}
base = {s["question"]: _set(s) for s in samples[baseline]}
overlap = {}
for label, rows in samples.items():
vals = []
for s in rows:
a, b = _set(s), base.get(s["question"], set())
vals.append(len(a & b) / len(a | b) if a | b else 1.0)
overlap[label] = sum(vals) / len(vals) if vals else 0.0
return overlap
def comparison_markdown(
generators: list[str],
judges: list[str],
scores: dict[tuple[str, str], dict],
keyword_overlap: dict[str, float],
) -> str:
"""One generator x judge table per metric; self-judged cells marked with *."""
lines = ["# RAGAS generator x judge comparison", ""]
for metric in _METRICS:
lines += [f"## {metric}", "", "| generator \\ judge | " + " | ".join(judges) + " |"]
lines.append("|---" * (len(judges) + 1) + "|")
for g in generators:
cells = []
for j in judges:
report = scores.get((g, j), {})
v = report.get(metric)
cell = "n/a" if v is None else f"{v:.3f}"
cell += "*" if g == j else ""
failed = report.get("failed", {}).get(metric, 0)
cells.append(cell + (f" ({failed} failed)" if failed else ""))
lines.append(f"| {g} | " + " | ".join(cells) + " |")
lines.append("")
lines += [
"\\* self-judged: the judge scored its own answers. Expect inflated scores;",
"the gap to other judges in the same row measures that bias.",
"",
f"## Keyword overlap with {generators[0]}",
"",
"Mean Jaccard overlap of extracted retrieval keywords (1.0 = identical retrieval input).",
"",
"| generator | overlap |",
"|---|---|",
]
lines += [f"| {g} | {keyword_overlap.get(g, 0.0):.3f} |" for g in generators]
return "\n".join(lines) + "\n"
def run_matrix(
generators: list[ModelSpec],
judges: list[ModelSpec],
testset: list[dict],
mode: str,
keywords: str,
out: Path,
) -> str:
"""Run the full matrix into `out`, reusing finished files; return the markdown."""
samples_dir, scores_dir = out / "samples", out / "scores"
samples_dir.mkdir(parents=True, exist_ok=True)
scores_dir.mkdir(parents=True, exist_ok=True)
async def _generate_all() -> None:
todo = [g for g in generators if not (samples_dir / f"{_slug(g.label)}.json").exists()]
if not todo:
return
rag = create_rag(cache=False)
await rag.initialize_storages()
try:
pinned = None
if keywords == "pinned":
kw_path = out / "keywords.json"
if kw_path.exists():
pinned = json.loads(kw_path.read_text())
else:
pinned = await _pin_keywords(rag, testset, mode)
kw_path.write_text(json.dumps(pinned, indent=2))
await release(parse_spec(settings.llm_model))
for g in todo:
console.print(f"[bold]generate[/bold] {g.label}")
start = time.monotonic()
rows = await generate_samples(rag, g, testset, mode, pinned)
path = samples_dir / f"{_slug(g.label)}.json"
path.write_text(json.dumps(rows, indent=2))
console.print(f" {len(rows)} answers in {time.monotonic() - start:.0f}s")
await release(g)
finally:
await rag.finalize_storages()
async def _judge_all() -> None:
for j in judges:
judged = False
for g in generators:
path = scores_dir / f"{_slug(g.label)}__{_slug(j.label)}.json"
if path.exists():
continue
console.print(f"[bold]judge[/bold] {j.label} ← {g.label}")
rows = json.loads((samples_dir / f"{_slug(g.label)}.json").read_text())
start = time.monotonic()
results = await judge_samples(j, rows)
report = {
"generator": g.label,
"judge": j.label,
**{m: _mean(results, m) for m in _METRICS},
"failed": {m: sum(r[m] is None for r in results) for m in _METRICS},
"elapsed_seconds": round(time.monotonic() - start, 1),
"results": results,
}
path.write_text(json.dumps(report, indent=2))
judged = True
if judged:
await release(j)
asyncio.run(_generate_all())
asyncio.run(_judge_all())
scores = {}
for g in generators:
for j in judges:
path = scores_dir / f"{_slug(g.label)}__{_slug(j.label)}.json"
scores[(g.label, j.label)] = json.loads(path.read_text())
samples = {
g.label: json.loads((samples_dir / f"{_slug(g.label)}.json").read_text())
for g in generators
}
overlap = _keyword_overlap(samples, generators[0].label)
return comparison_markdown(
[g.label for g in generators], [j.label for j in judges], scores, overlap
)
@app.command()
def eval_compare(
generators: str = typer.Option(..., "--generators", help="Space-separated model specs"),
judges: str = typer.Option(..., "--judges", help="Space-separated model specs"),
n: int = typer.Option(10, "--n", help="Number of testset questions"),
mode: str = typer.Option("hybrid", "--mode", help="local/global/hybrid/naive"),
keywords: str = typer.Option(
"per-generator", "--keywords", help="per-generator | pinned (configured LLM extracts)"
),
testset: Path = typer.Option(
None, "--testset", help="JSON list of {question, reference}; default <data_dir>/testset.json"
),
out: Path = typer.Option(
None, "--out", help="Run directory (reuse one to resume); default <data_dir>/eval_compare/<ts>"
),
) -> None:
"""Score every generator's answers with every judge (local RAGAS triad)."""
if keywords not in ("per-generator", "pinned"):
raise typer.BadParameter("--keywords must be per-generator or pinned")
testset = testset or Path(settings.data_dir) / "testset.json"
if not testset.exists():
console.print(
f"[red]No testset at {testset}.[/red] Write your own questions about your "
"ingested notebooks — see eval/testset.example.json for the format."
)
raise typer.Exit(1)
ts = json.loads(testset.read_text())[:n]
out = out or Path(settings.data_dir) / "eval_compare" / datetime.now().strftime("%Y%m%d-%H%M%S")
gens = [parse_spec(s) for s in generators.split()]
judge_specs = [parse_spec(s) for s in judges.split()]
console.print(
f"[bold]Matrix[/bold]: {len(gens)} generators x {len(judge_specs)} judges, "
f"{len(ts)} questions, keywords={keywords} → {out}"
)
out.mkdir(parents=True, exist_ok=True)
md = run_matrix(gens, judge_specs, ts, mode, keywords, out)
(out / "comparison.md").write_text(md)
console.print(md)
def main() -> None:
app()

View File

@ -0,0 +1,106 @@
"""Run RAGAS faithfulness evaluation against the LightRAG knowledge base."""
from __future__ import annotations
import asyncio
import json
import re
from pathlib import Path
from ragas import EvaluationDataset, SingleTurnSample, evaluate
from ragas.metrics.collections import (
answer_relevancy,
context_precision,
faithfulness,
)
from askme.evaluation.generate import _make_embeddings, _make_llm
from askme.rag import create_rag, make_query_param
_SOURCES_RE = re.compile(r"\n#{1,3}\s*Sources\b", re.IGNORECASE)
# Concurrent queries — match OLLAMA_NUM_PARALLEL=2 (proven VRAM-safe budget).
_QUERY_CONCURRENCY = 2
# Per-query ceiling so one hung aquery fails fast instead of stalling the eval.
_QUERY_TIMEOUT = 900
def _strip_sources(text: str) -> tuple[str, list[str]]:
"""Return (answer_text, [context_excerpts]) from a LightRAG response."""
match = _SOURCES_RE.search(text)
if match:
answer = text[: match.start()].strip()
contexts = [
line.strip().lstrip("-").strip()
for line in text[match.end() :].splitlines()
if line.strip().lstrip("-").strip()
]
return answer, contexts
return text.strip(), []
async def _query_all(
testset: list[dict],
) -> list[SingleTurnSample]:
rag = create_rag()
await rag.initialize_storages()
semaphore = asyncio.Semaphore(_QUERY_CONCURRENCY)
async def _query_one(item: dict) -> SingleTurnSample:
async with semaphore:
param = make_query_param(mode="hybrid")
raw: str = await asyncio.wait_for(
rag.aquery(item["question"], param=param), timeout=_QUERY_TIMEOUT
)
answer, contexts = _strip_sources(raw)
# Fall back to ground-truth contexts when RAG returns none
retrieved = contexts or item.get("contexts", [])
return SingleTurnSample(
user_input=item["question"],
response=answer,
retrieved_contexts=retrieved,
reference=item.get("ground_truth", ""),
)
try:
# gather preserves input order regardless of completion order
return list(await asyncio.gather(*(_query_one(item) for item in testset)))
finally:
await rag.finalize_storages()
def run_eval(testset: list[dict], samples_path: Path | None = None) -> dict:
"""Query LightRAG for every item in testset and evaluate with RAGAS.
Args:
testset: List of dicts with keys: question, ground_truth, contexts.
samples_path: If given, the queried samples are written here before the
(expensive, failure-prone) metrics phase, so a metrics-phase error
doesn't discard the query results.
Returns:
Dict with keys: faithfulness, answer_relevancy, context_precision
(float scores 0-1) plus a 'samples' key with per-item breakdowns.
"""
samples = asyncio.run(_query_all(testset))
if samples_path is not None:
samples_path.write_text(
json.dumps([s.model_dump() for s in samples], indent=2)
)
dataset = EvaluationDataset(samples=samples)
result = evaluate(
dataset,
metrics=[faithfulness, answer_relevancy, context_precision],
llm=_make_llm(),
embeddings=_make_embeddings(),
raise_exceptions=False,
)
scores = result.to_pandas()[
["faithfulness", "answer_relevancy", "context_precision"]
]
return {
"faithfulness": float(scores["faithfulness"].mean()),
"answer_relevancy": float(scores["answer_relevancy"].mean()),
"context_precision": float(scores["context_precision"].mean()),
"samples": scores.to_dict(orient="records"),
}

View File

@ -0,0 +1,55 @@
"""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")
]

View File

@ -0,0 +1,228 @@
"""Fully-local RAGAS faithfulness/relevancy/precision via instructor + Ollama.
The legacy RAGAS path (LangchainLLMWrapper + synthetic TestsetGenerator) aborts
on local models with RagasOutputParserException — the model emits JSON that
doesn't match the metric schema. This module uses the path the RAGAS maintainers
recommend for local models (issue #1214): build the judge with `llm_factory`
(instructor adapter, mode=JSON) so output is *schema-enforced*, and call the
modern `ragas.metrics.collections` metrics' `.ascore()` directly — no synthetic
generation, no langchain wrapper. The judge is an independent local model
(gemma4:12b, different family from the qwen LLM that built the graph) served via
Ollama's OpenAI-compatible /v1 endpoint; embeddings reuse the local nomic model.
"""
from __future__ import annotations
import asyncio
import json
import time
from pathlib import Path
import typer
from openai import AsyncOpenAI
from rich.console import Console
from rich.table import Table
from ragas.embeddings import OpenAIEmbeddings
from ragas.llms import llm_factory
from ragas.metrics.collections import (
AnswerRelevancy,
ContextPrecisionWithReference,
Faithfulness,
)
from askme.config import settings
from askme.rag import create_rag, make_query_param
app = typer.Typer(add_completion=False)
console = Console()
# Judge calls are heavy (CPU model); bound concurrency to the proven VRAM/CPU budget.
_CONCURRENCY = 2
# LightRAG's only_need_context dump is ~27k tokens, ordered Entities ->
# Relations -> Document Chunks -> Reference List. The chunks are the actual
# source text the answer should be grounded in (what faithfulness and
# context_precision need); the entity/relation triples are KG summaries. Start
# at the chunks section and cap to ~12000 chars (~3000 tokens) — fits the judge's
# 16k ctx with room for the answer + statement-extraction output.
# #ADJUST context management: judge's view of the retrieved source text (eval-local);
# too low hides supporting text and lowers faithfulness/context_precision.
_CONTEXT_CHAR_CAP = 12000
_CHUNKS_MARKER = "Document Chunks"
def _trim_context(text: str) -> str:
"""Prefer the document-chunks section, bounded to the judge's window."""
i = text.find(_CHUNKS_MARKER)
if i != -1:
text = text[i:]
return text[:_CONTEXT_CHAR_CAP]
def _client() -> AsyncOpenAI:
"""OpenAI-compatible client pointed at the local Ollama server.
timeout caps each judge call so a dropped Ollama response (happens under
VRAM pressure) fails fast and retries instead of wedging forever. Set high
(900s) because reasoning judges (qwen3.5) on a real large-context call can
take >5min on this partial-CPU 8GB box; 300s timed them out and crashed.
"""
return AsyncOpenAI(
base_url=f"{settings.ollama_host}/v1",
api_key="ollama",
timeout=900.0,
max_retries=2,
)
def _make_judge():
"""Schema-enforcing instructor judge LLM (independent local model).
max_tokens is generous: faithfulness extracts one statement per answer
claim, so the structured output is long. Reasoning judges (e.g. qwen3.5)
also emit a long <think> block before the JSON — both consume output
tokens, so the default 4096 truncated them ("incomplete due to max_tokens").
Kept under the 16k judge ctx so prompt + output still fit.
"""
return llm_factory(
settings.ragas_judge_model,
provider="openai",
client=_client(),
# #ADJUST judges: judge output budget; too low truncates faithfulness statements.
max_tokens=10000,
)
def _make_modern_embeddings() -> OpenAIEmbeddings:
"""Local nomic embeddings via Ollama's /v1 endpoint (for answer_relevancy)."""
return OpenAIEmbeddings(client=_client(), model=settings.embedding_model)
async def _retrieve(rag, question: str, mode: str) -> tuple[str, list[str]]:
"""Return (generated answer, retrieved context) from LightRAG."""
answer: str = await rag.aquery(question, param=make_query_param(mode=mode))
ctx_param = make_query_param(mode=mode)
ctx_param.only_need_context = True
context: str = await rag.aquery(question, param=ctx_param)
return answer, [_trim_context(context)]
async def _eval_all(testset: list[dict], mode: str) -> list[dict]:
semaphore = asyncio.Semaphore(_CONCURRENCY)
# Phase 1 — retrieve every answer+context with the GPU RAG model (qwen).
# Done fully before judging so qwen and the judge don't ping-pong on the
# 8GB GPU (that thrash dropped responses and wedged the run).
rag = create_rag()
await rag.initialize_storages()
async def _retrieve_one(item: dict) -> dict:
async with semaphore:
answer, ctx = await _retrieve(rag, item["question"], mode)
return {"item": item, "answer": answer, "ctx": ctx}
try:
retrieved = await asyncio.gather(*(_retrieve_one(i) for i in testset))
finally:
await rag.finalize_storages()
# Phase 2 — judge everything with the independent model (qwen now idle).
judge = _make_judge()
faith = Faithfulness(llm=judge)
relev = AnswerRelevancy(llm=judge, embeddings=_make_modern_embeddings())
prec = ContextPrecisionWithReference(llm=judge)
async def _judge_one(r: dict) -> dict:
item, answer, ctx = r["item"], r["answer"], r["ctx"]
async with semaphore:
f = await faith.ascore(
user_input=item["question"], response=answer, retrieved_contexts=ctx
)
rl = await relev.ascore(user_input=item["question"], response=answer)
c = await prec.ascore(
user_input=item["question"],
reference=item["reference"],
retrieved_contexts=ctx,
)
return {
"question": item["question"],
"faithfulness": f.value,
"answer_relevancy": rl.value,
"context_precision": c.value,
}
return list(await asyncio.gather(*(_judge_one(r) for r in retrieved)))
def run_local_eval(testset: list[dict], mode: str = "hybrid") -> dict:
"""Score the faithfulness/relevancy/precision triad fully locally.
Args:
testset: List of dicts with keys: question, reference.
mode: LightRAG query mode.
Returns:
Dict with mean faithfulness, answer_relevancy, context_precision, the
question count n, and a per-question results breakdown.
"""
results = asyncio.run(_eval_all(testset, mode))
def _mean(key: str) -> float:
vals = [r[key] for r in results if r[key] is not None]
return sum(vals) / len(vals) if vals else 0.0
return {
"faithfulness": _mean("faithfulness"),
"answer_relevancy": _mean("answer_relevancy"),
"context_precision": _mean("context_precision"),
"n": len(results),
"results": results,
}
@app.command()
def eval_local(
n: int = typer.Option(5, "--n", help="Number of testset questions to score"),
mode: str = typer.Option("hybrid", "--mode", help="local/global/hybrid/naive"),
testset: Path = typer.Option(
None,
"--testset",
help="JSON list of {question, reference}; default is <data_dir>/testset.json",
),
output: Path = typer.Option(
Path("local_eval_report.json"), "--output", help="Path for JSON report"
),
) -> None:
"""Score faithfulness/relevancy/precision fully locally (instructor judge)."""
testset = testset or Path(settings.data_dir) / "testset.json"
if not testset.exists():
console.print(
f"[red]No testset at {testset}.[/red] Write your own questions about your "
"ingested notebooks — see eval/testset.example.json for the format."
)
raise typer.Exit(1)
ts = json.loads(testset.read_text())
ts = ts[:n]
console.print(
f"[bold]Local RAGAS[/bold]: {len(ts)} questions, judge={settings.ragas_judge_model}"
)
start = time.monotonic()
scores = run_local_eval(ts, mode)
elapsed = round(time.monotonic() - start, 1)
table = Table(title="Local RAGAS (instructor judge)")
table.add_column("Metric", style="cyan")
table.add_column("Score", style="green")
for metric in ("faithfulness", "answer_relevancy", "context_precision"):
table.add_row(metric, f"{scores[metric]:.3f}")
console.print(table)
console.print(f"Judge: [bold]{settings.ragas_judge_model}[/bold] | "
f"{scores['n']} questions | {elapsed}s")
report = {**scores, "judge_model": settings.ragas_judge_model, "elapsed_seconds": elapsed}
output.write_text(json.dumps(report, indent=2))
console.print(f"Report saved to [bold]{output}[/bold]")
def main() -> None:
app()

View File

@ -0,0 +1,111 @@
"""Local, LLM-judge-free retrieval evaluation for the LightRAG knowledge base.
Measures whether retrieval surfaces the right content: for each question, run
LightRAG in context-only mode (no answer generation) and check that a known
distinctive term for that question appears in the retrieved context. Fully
local — no RAGAS, no structured-output judge (qwen2.5:7b cannot drive those).
"""
from __future__ import annotations
import asyncio
import json
from pathlib import Path
import typer
from rich.console import Console
from rich.table import Table
from askme.config import settings
from askme.rag import create_rag, make_query_param
app = typer.Typer(add_completion=False)
console = Console()
# Concurrent retrievals — match OLLAMA_NUM_PARALLEL=2 (keyword extraction per
# query is one small LLM call; the rest is CPU embedding + graph/vector search).
_RETRIEVAL_CONCURRENCY = 2
def _hit(context: str, expected: str) -> bool:
"""True when the expected term appears in the retrieved context."""
return expected.lower() in context.lower()
async def _retrieve_all(testset: list[dict], mode: str) -> list[str]:
"""Return the context-only retrieval string for each question."""
rag = create_rag()
await rag.initialize_storages()
semaphore = asyncio.Semaphore(_RETRIEVAL_CONCURRENCY)
async def _one(item: dict) -> str:
async with semaphore:
param = make_query_param(mode=mode)
param.only_need_context = True
return await rag.aquery(item["question"], param=param)
try:
return list(await asyncio.gather(*(_one(item) for item in testset)))
finally:
await rag.finalize_storages()
def run_retrieval_eval(testset: list[dict], mode: str = "hybrid") -> dict:
"""Retrieve context for each question and score term-recall.
Args:
testset: List of dicts with keys: question, expected.
mode: LightRAG query mode (local/global/hybrid/naive).
Returns:
Dict with keys: hit_rate (float 0-1), n (int), results (per-question
question/expected/hit breakdown).
"""
contexts = asyncio.run(_retrieve_all(testset, mode))
results = [
{"question": q["question"], "expected": q["expected"], "hit": _hit(ctx, q["expected"])}
for q, ctx in zip(testset, contexts)
]
hits = sum(r["hit"] for r in results)
return {"hit_rate": hits / len(results), "n": len(results), "results": results}
@app.command()
def eval_retrieval(
mode: str = typer.Option("hybrid", "--mode", help="local/global/hybrid/naive"),
testset: Path = typer.Option(
None,
"--testset",
help="JSON list of {question, expected}; default is <data_dir>/retrieval_testset.json",
),
output: Path = typer.Option(
Path("retrieval_report.json"), "--output", help="Path for JSON report"
),
) -> None:
"""Evaluate retrieval term-recall against the LightRAG knowledge base."""
testset = testset or Path(settings.data_dir) / "retrieval_testset.json"
if not testset.exists():
console.print(
f"[red]No testset at {testset}.[/red] Pair questions about your ingested "
"notebooks with a term correct retrieval must surface — see "
"eval/retrieval_testset.example.json for the format."
)
raise typer.Exit(1)
ts = json.loads(testset.read_text())
console.print(f"[bold]Retrieval eval[/bold]: {len(ts)} questions, mode={mode}")
scores = run_retrieval_eval(ts, mode)
table = Table(title=f"Retrieval term-recall (hit-rate {scores['hit_rate']:.0%})")
table.add_column("Hit", style="green")
table.add_column("Expected", style="cyan")
table.add_column("Question")
for r in scores["results"]:
table.add_row("✓" if r["hit"] else "✗", r["expected"], r["question"])
console.print(table)
output.write_text(json.dumps(scores, indent=2))
console.print(f"Report saved to [bold]{output}[/bold]")
def main() -> None:
app()

18
src/askme/gpu.py Normal file
View File

@ -0,0 +1,18 @@
"""GPU residency control for the 8GB card shared by generator and judges."""
import httpx
import ollama
from askme.config import settings
async def unload_ollama_model(model: str) -> None:
"""Evict `model` from Ollama now instead of waiting for OLLAMA_KEEP_ALIVE."""
client = ollama.AsyncClient(host=settings.ollama_host)
await client.generate(model=model, keep_alive=0)
async def unload_llamacpp_model(model: str) -> None:
"""Evict `model` from the llama.cpp router."""
async with httpx.AsyncClient() as client:
await client.post(f"{settings.llamacpp_url}/models/unload", json={"model": model})

View File

View File

@ -0,0 +1,3 @@
from askme.ingestion.ingest import main
__all__ = ["main"]

View File

@ -0,0 +1,132 @@
"""
Text extraction from notebook formats.
Supports:
- .ipynb (Jupyter notebooks) — extracts markdown + code cells with headers
- .Rmd (R Markdown) — strips YAML front-matter, keeps prose + code blocks
- .py (Python scripts) — returns source as-is, strips shebangs
- .R (R scripts) — returns source as-is
Each extractor returns a plain string ready for LightRAG ingestion.
The path is never read here — callers pass content or a Path object.
"""
from __future__ import annotations
import json
import re
import subprocess
from pathlib import Path
# ── Jupyter notebooks (.ipynb) ────────────────────────────────────────────────
def extract_ipynb(path: Path) -> str:
"""
Convert a Jupyter notebook to a readable text document.
Strategy:
- Markdown cells → included as-is (prose, explanations)
- Code cells → wrapped in a fenced block with language tag
- Raw cells → skipped
- Output cells → skipped (noisy, hurts chunking and entity extraction)
The notebook filename is prepended so LightRAG can attribute entities.
"""
nb = json.loads(path.read_text(encoding="utf-8", errors="replace"))
lang = (
nb.get("metadata", {})
.get("kernelspec", {})
.get("language", "python")
.lower()
)
parts: list[str] = [f"# Notebook: {path.name}\n"]
for i, cell in enumerate(nb.get("cells", []), start=1):
cell_type = cell.get("cell_type", "")
source = "".join(cell.get("source", []))
if not source.strip():
continue
if cell_type == "markdown":
parts.append(source)
elif cell_type == "code":
parts.append(f"```{lang}\n{source}\n```")
return "\n\n".join(parts)
# ── R Markdown (.Rmd) ─────────────────────────────────────────────────────────
_YAML_FRONT_MATTER = re.compile(r"^---\s*\n.*?\n---\s*\n", re.DOTALL)
_RMD_CODE_FENCE = re.compile(r"```\{[^}]+\}", re.MULTILINE)
def extract_rmd(path: Path) -> str:
"""
Extract text from an R Markdown file.
- Strips YAML front matter
- Keeps prose sections as-is
- Normalises code fences: ```{r ...} → ```r (readable but not executed)
"""
text = path.read_text(encoding="utf-8", errors="replace")
# Remove YAML front matter
text = _YAML_FRONT_MATTER.sub("", text, count=1)
# Normalise code fence headers: ```{r chunk-name, echo=FALSE} → ```r
text = _RMD_CODE_FENCE.sub(
lambda m: "```" + re.search(r"\{(\w+)", m.group()).group(1),
text,
)
return f"# Notebook: {path.name}\n\n{text.strip()}"
# ── Python scripts (.py) ──────────────────────────────────────────────────────
_SHEBANG = re.compile(r"^#!.*\n")
def extract_py(path: Path) -> str:
text = path.read_text(encoding="utf-8", errors="replace")
text = _SHEBANG.sub("", text, count=1)
return f"# Script: {path.name}\n\n{text.strip()}"
# ── R scripts (.R) ────────────────────────────────────────────────────────────
def extract_r(path: Path) -> str:
text = path.read_text(encoding="utf-8", errors="replace")
return f"# Script: {path.name}\n\n{text.strip()}"
# ── Dispatcher ────────────────────────────────────────────────────────────────
_EXTRACTORS = {
".ipynb": extract_ipynb,
".rmd": extract_rmd,
".py": extract_py,
".r": extract_r,
}
# Tiktoken special tokens that appear literally in some notebooks and cause
# ValueError when LightRAG tokenises chunks for gleaning context limits.
_TIKTOKEN_SPECIAL = re.compile(r"<\|[a-z_]+\|>")
def extract(path: Path) -> str | None:
"""
Extract text from a supported file. Returns None for unsupported types.
Raises on read/parse errors so callers can decide whether to skip or abort.
"""
extractor = _EXTRACTORS.get(path.suffix.lower())
if extractor is None:
return None
text = extractor(path)
return _TIKTOKEN_SPECIAL.sub("", text)
def supported_suffixes() -> frozenset[str]:
return frozenset(_EXTRACTORS)

View File

@ -0,0 +1,113 @@
"""
File filtering and deduplication for the ingestion pipeline.
Two responsibilities:
1. filter_paths() — decide which files are worth ingesting at all
(skip venvs, build artifacts, checkpoints)
2. Deduplicator — MinHash-based near-duplicate detection across files
(same analysis copy-pasted across projects won't be ingested twice)
"""
from __future__ import annotations
from pathlib import Path
from datasketch import MinHash, MinHashLSH
from askme.ingestion.extract import supported_suffixes
# ── Path filter ───────────────────────────────────────────────────────────────
# Directory names that signal the path is inside a venv / package library
# rather than original research code. Any path component matching one of
# these strings is skipped.
_VENV_MARKERS: frozenset[str] = frozenset(
{
"site-packages",
"dist-packages",
"__pycache__",
".ipynb_checkpoints",
"x86_64-pc-linux-gnu-library", # R library tree
"node_modules",
}
)
def is_venv_path(path: Path) -> bool:
"""Return True if any component of the path looks like a venv/library."""
return any(marker in path.parts for marker in _VENV_MARKERS)
def filter_paths(paths: list[Path]) -> list[Path]:
"""
Return only paths that are:
- A supported file type (.ipynb, .rmd, .py, .r)
- Not inside a venv, package library, or checkpoint directory
- Non-empty files
"""
kept = []
for p in paths:
if p.suffix.lower() not in supported_suffixes():
continue
if is_venv_path(p):
continue
if p.stat().st_size == 0:
continue
kept.append(p)
return kept
# ── MinHash deduplication ─────────────────────────────────────────────────────
_NUM_PERM = 128 # number of permutations — controls accuracy vs speed tradeoff
def _minhash(text: str) -> MinHash:
"""Compute a MinHash signature from a text using word shingles."""
m = MinHash(num_perm=_NUM_PERM)
# Use 5-word shingles for semantic similarity
words = text.lower().split()
for i in range(max(1, len(words) - 4)):
shingle = " ".join(words[i : i + 5])
m.update(shingle.encode("utf-8"))
return m
class Deduplicator:
"""
Tracks seen documents and detects near-duplicates using MinHash LSH.
Usage:
dedup = Deduplicator(threshold=0.85)
for path, text in documents:
if dedup.is_duplicate(path, text):
continue # skip
# ingest this document
"""
def __init__(self, threshold: float = 0.85) -> None:
self._lsh = MinHashLSH(threshold=threshold, num_perm=_NUM_PERM)
self._seen: dict[str, Path] = {} # key → original path
def is_duplicate(self, path: Path, text: str) -> bool:
"""
Returns True if this text is a near-duplicate of a previously seen document.
Registers the document if it is new.
"""
key = str(path)
m = _minhash(text)
results = self._lsh.query(m)
if results:
original = self._seen[results[0]]
return True
# New document — register it
self._lsh.insert(key, m)
self._seen[key] = path
return False
@property
def seen_count(self) -> int:
return len(self._seen)

View File

@ -0,0 +1,213 @@
"""
Ingestion pipeline: walk a directory, extract text, deduplicate, insert into LightRAG.
Usage (inside the askme container):
uv run python -m askme.ingestion.ingest data/notebook_archive/
uv run python -m askme.ingestion.ingest data/notebook_archive/ --dry-run
"""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import logging
import sys
from pathlib import Path
from lightrag.base import DocStatus
from askme.config import settings
from askme.ingestion.extract import extract
from askme.ingestion.filter import Deduplicator, filter_paths
from askme.rag import create_rag
log = logging.getLogger(__name__)
# ── Manifest ──────────────────────────────────────────────────────────────────
def _file_hash(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def load_manifest(manifest_path: Path) -> dict[str, str]:
if manifest_path.exists():
return json.loads(manifest_path.read_text())
return {}
def save_manifest(manifest: dict[str, str], manifest_path: Path) -> None:
manifest_path.parent.mkdir(parents=True, exist_ok=True)
manifest_path.write_text(json.dumps(manifest, indent=2))
async def ingest_directory(
root: Path,
dry_run: bool = False,
manifest_path: Path | None = None,
) -> None:
manifest: dict[str, str] = {}
if manifest_path is not None:
manifest = load_manifest(manifest_path)
log.info("Manifest loaded: %d previously ingested files", len(manifest))
all_paths = list(root.rglob("*"))
candidates = filter_paths(all_paths)
log.info("Found %d candidate files (from %d total)", len(candidates), len(all_paths))
dedup = Deduplicator(threshold=settings.minhash_threshold)
# Extract and deduplicate up-front so we know total work before inserting
docs: list[tuple[Path, str, str]] = [] # (path, text, hash)
skipped_extract = 0
skipped_dedup = 0
skipped_manifest = 0
for path in candidates:
file_hash = _file_hash(path)
if manifest_path is not None and manifest.get(str(path)) == file_hash:
skipped_manifest += 1
continue
try:
text = extract(path)
except Exception as exc:
log.warning("Extract failed for %s: %s", path, exc)
skipped_extract += 1
continue
if text is None:
skipped_extract += 1
continue
if dedup.is_duplicate(path, text):
log.debug("Duplicate skipped: %s", path)
skipped_dedup += 1
continue
docs.append((path, text, file_hash))
log.info(
"After filtering: %d to ingest, %d manifest hits, %d extract errors, %d duplicates skipped",
len(docs),
skipped_manifest,
skipped_extract,
skipped_dedup,
)
if dry_run:
log.info("Dry run — no documents inserted.")
for path, _, _ in docs:
print(path)
return
rag = create_rag()
await rag.initialize_storages()
sem = asyncio.Semaphore(settings.max_async)
inserted = 0
failed = 0
async def _insert(path: Path, text: str, file_hash: str) -> None:
nonlocal inserted, failed
async with sem:
try:
await rag.ainsert(text, file_paths=str(path))
inserted += 1
if manifest_path is not None:
manifest[str(path)] = file_hash
if inserted % 50 == 0:
log.info("Progress: %d / %d inserted", inserted, len(docs))
if manifest_path is not None:
save_manifest(manifest, manifest_path)
except Exception as exc:
log.warning("Insert failed for %s: %s", path, exc)
failed += 1
await asyncio.gather(*(_insert(p, t, h) for p, t, h in docs))
# Wait for LightRAG's internal worker to finish entity extraction on all docs
# ainsert queues extraction work; finalize_storages kills the worker prematurely
# if called before the queue is drained.
poll_interval = 30
while True:
pending = await rag.doc_status.get_docs_by_status(DocStatus.PENDING)
processing = await rag.doc_status.get_docs_by_status(DocStatus.PROCESSING)
if not pending and not processing:
break
log.info(
"Waiting for entity extraction: %d pending, %d processing — checking again in %ds",
len(pending),
len(processing),
poll_interval,
)
await asyncio.sleep(poll_interval)
await rag.finalize_storages()
if manifest_path is not None:
save_manifest(manifest, manifest_path)
log.info(
"Done. Inserted: %d, failed: %d, manifest hits: %d, duplicates skipped: %d, extract errors: %d",
inserted,
failed,
skipped_manifest,
skipped_dedup,
skipped_extract,
)
def main() -> None:
parser = argparse.ArgumentParser(description="Ingest notebooks into LightRAG")
parser.add_argument(
"root",
nargs="?",
type=Path,
help="Root directory to walk (positional)",
)
parser.add_argument(
"--source",
type=Path,
dest="source",
help="Root directory to walk (alias for positional root)",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="List files that would be ingested without inserting anything",
)
parser.add_argument(
"--manifest",
type=Path,
default=None,
help="Path to manifest JSON for incremental ingestion (skip unchanged files)",
)
parser.add_argument(
"--log-level",
default="INFO",
choices=["DEBUG", "INFO", "WARNING", "ERROR"],
)
args = parser.parse_args()
logging.basicConfig(
level=args.log_level,
format="%(asctime)s %(levelname)s %(message)s",
stream=sys.stderr,
)
root = args.source or args.root
if root is None:
parser.error("Provide a root directory (positional or --source)")
if not root.is_dir():
log.error("Not a directory: %s", root)
sys.exit(1)
asyncio.run(ingest_directory(root, dry_run=args.dry_run, manifest_path=args.manifest))
if __name__ == "__main__":
main()

171
src/askme/rag.py Normal file
View File

@ -0,0 +1,171 @@
import json
import logging
from pathlib import Path
import numpy as np
from lightrag import LightRAG, QueryParam
from lightrag.llm.ollama import ollama_embed, ollama_model_complete
from lightrag.utils import EmbeddingFunc
from askme.config import settings
logger = logging.getLogger(__name__)
# #ADJUST embedding type / chunking: texts are cut here before embedding (the
# nomic-embed-text 2048-token limit); text past the cut is stored but not vector-searchable.
# Raise only with an embedding model that has a longer context.
_EMBED_CHAR_CAP = 4000
# #ADJUST context management: prompt budget for every query and its split. LightRAG's
# defaults (30000 total, 6000 entities, 8000 relations) overflow the LLM window, which
# Ollama truncates silently. Entities and relations are knowledge-graph summaries;
# chunks (source text) get what is left after them and the ~2k system prompt —
# shifting budget toward chunks grounds answers in the notebooks (faithfulness),
# toward the graph gives broader but less verifiable answers.
PROMPT_TOKEN_CAP = 12000
_ENTITY_TOKENS = 2000
_RELATION_TOKENS = 3000
# #ADJUST context management / memory: Ollama window — must hold the prompt cap plus
# the answer, or prompts are cut silently. Each token of window costs KV-cache VRAM
# per parallel slot (qwen2.5:7b at 16384 x 2 slots: ~6.1 GB, fits 8 GB).
_NUM_CTX = 16384
# Dimensions for known embedding models — tied to the model, not config
_EMBEDDING_DIMS: dict[str, int] = {
"nomic-embed-text": 768,
"bge-m3": 1024,
"all-minilm": 384,
}
def _embedding_dim() -> int:
for model, dim in _EMBEDDING_DIMS.items():
if model in settings.embedding_model:
return dim
return settings.embedding_dim # fallback to config
class EmbeddingMismatchError(RuntimeError):
"""Configured embedding differs from the one the stores were built with."""
def _check_embedding_meta(working_dir: Path, model: str, dim: int) -> None:
"""Record the embedding on first use; refuse a different one afterwards.
Stored vectors are only comparable with query vectors from the same model
and dimension — a silent switch returns garbage or crashes on dim mismatch.
"""
meta_path = working_dir / "askme_meta.json"
wanted = {"embedding_model": model, "embedding_dim": dim}
if not meta_path.exists():
working_dir.mkdir(parents=True, exist_ok=True)
meta_path.write_text(json.dumps(wanted, indent=2))
return
stored = json.loads(meta_path.read_text())
if stored != wanted:
raise EmbeddingMismatchError(
f"Stores were built with {stored['embedding_model']} "
f"(dim {stored['embedding_dim']}) but {model} (dim {dim}) is configured. "
"Restore the original embedding settings or re-ingest after `just clean-stores`."
)
def _make_embedding_func() -> EmbeddingFunc:
dim = _embedding_dim()
async def _embed(texts: list[str]) -> np.ndarray:
# Call the raw function directly — ollama_embed is wrapped with
# embedding_dim=1024 (bge-m3 default), which would fail for nomic-embed-text.
# Force CPU inference (num_gpu=0) so the embedding model doesn't compete
# with the LLM for the ~8GB GPU VRAM.
# Truncate to nomic-embed-text's hard 2048-token context (num_ctx is
# ignored by the model — verified). Dense notebook text (gene names,
# numbers) packs ~2.9 chars/token, so 6000 chars overflowed 2048 tokens
# and triggered Ollama "input exceeds context length" 400 errors.
# 4000 chars stays safely under the limit for the densest content.
# chunk_token_size keeps chunks small enough that this rarely fires;
# when it does, the dropped tail is absent from the vector while the
# full chunk is still stored — log it so the retrieval gap isn't silent.
over = sum(len(t) > _EMBED_CHAR_CAP for t in texts)
if over:
logger.warning(
"Truncated %d/%d text(s) to %d chars for embedding; "
"dropped tails are not vector-searchable.",
over,
len(texts),
_EMBED_CHAR_CAP,
)
truncated = [t[:_EMBED_CHAR_CAP] for t in texts]
return await ollama_embed.func(
truncated,
embed_model=settings.embedding_model,
host=settings.ollama_host,
timeout=settings.llm_timeout,
options={"num_gpu": 0},
)
return EmbeddingFunc(
embedding_dim=dim,
max_token_size=2048,
func=_embed,
model_name=settings.embedding_model,
)
def create_rag(cache: bool = True) -> LightRAG:
_check_embedding_meta(
Path(settings.rag_working_dir), settings.embedding_model, _embedding_dim()
)
return LightRAG(
working_dir=settings.rag_working_dir,
llm_model_max_async=settings.max_async,
# Chunking — make config authoritative (else LightRAG uses its own
# 1200/100 defaults and settings.chunk_overlap is silently ignored).
chunk_token_size=settings.chunk_size,
chunk_overlap_token_size=settings.chunk_overlap,
# LLM
llm_model_func=ollama_model_complete,
llm_model_name=settings.llm_model,
llm_model_kwargs={
"host": settings.ollama_host,
"timeout": settings.llm_timeout,
"options": {"num_ctx": _NUM_CTX},
},
# Embeddings — cap CPU embed fan-out (default 8 oversubscribes the CPU)
# and batch larger to cut Ollama round-trips on the slowest stage.
embedding_func=_make_embedding_func(),
# #ADJUST memory: embedding concurrency and batch size — CPU load and ingest
# speed only, no effect on scores.
embedding_func_max_async=2,
embedding_batch_num=32,
# Semantic query-response cache: reuse a prior answer when a new query
# is ≥0.95 cosine-similar, skipping retrieval+generation. use_llm_check
# off so a hit costs no extra LLM call.
# cache=False for model comparisons: LightRAG's cache keys ignore the model.
enable_llm_cache=cache,
embedding_cache_config={
"enabled": cache,
"similarity_threshold": 0.95,
"use_llm_check": False,
},
# Storage backends
graph_storage="Neo4JStorage",
vector_storage="QdrantVectorDBStorage",
kv_storage="JsonKVStorage",
doc_status_storage="JsonDocStatusStorage",
)
# #ADJUST retrieval depth: LightRAG defaults apply — top_k=40 entities/relations,
# chunk_top_k=20 chunks, cosine cutoff 0.2 (COSINE_THRESHOLD env). More candidates raise
# recall but dilute the prompt (lower context_precision); fewer sharpen it but can miss
# the supporting chunk. Query-time: pass top_k/chunk_top_k here, no re-ingest.
# #ADJUST rerank: enable_rerank defaults True but no rerank model is configured, so
# chunks keep vector-similarity order (LightRAG warns on every query). A local reranker
# would put the most relevant chunks first — more of them survive the prompt budget.
def make_query_param(**kwargs) -> QueryParam:
mode = kwargs.pop("mode", settings.default_query_mode)
kwargs.setdefault("max_total_tokens", PROMPT_TOKEN_CAP)
kwargs.setdefault("max_entity_tokens", _ENTITY_TOKENS)
kwargs.setdefault("max_relation_tokens", _RELATION_TOKENS)
return QueryParam(mode=mode, **kwargs)

36
tests/conftest.py Normal file
View File

@ -0,0 +1,36 @@
"""Shared pytest fixtures for askme tests."""
from __future__ import annotations
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
import pytest
@pytest.fixture
def sample_chunks() -> list[str]:
"""Small text chunks representative of notebook content."""
return [
"# Notebook: scanpy_tutorial.ipynb\n\nScanpy is a Python library for "
"single-cell analysis. It provides tools for preprocessing, "
"visualization, clustering, and trajectory inference.",
"# Script: preprocess.py\n\nimport scanpy as sc\n\nadata = sc.read_h5ad('data.h5ad')\n"
"sc.pp.normalize_total(adata)\nsc.pp.log1p(adata)",
]
@pytest.fixture
def mock_rag(tmp_path: Path) -> MagicMock:
"""LightRAG mock with async stubs for storage and query methods."""
rag = MagicMock()
rag.initialize_storages = AsyncMock()
rag.finalize_storages = AsyncMock()
rag.ainsert = AsyncMock()
rag.aquery = AsyncMock(
return_value=(
"Scanpy is used for single-cell RNA-seq analysis.\n\n"
"## Sources\n- scanpy_tutorial.ipynb: Scanpy is a Python library"
)
)
return rag

4
tests/fixtures/sample.R vendored Normal file
View File

@ -0,0 +1,4 @@
library(Seurat)
data <- Read10X(data.dir = "data/")
seurat_obj <- CreateSeuratObject(counts = data)

20
tests/fixtures/sample.Rmd vendored Normal file
View File

@ -0,0 +1,20 @@
---
title: "Single-cell Analysis"
author: "Test"
output: html_document
---
# Analysis
This notebook analyses single-cell RNA-seq data using Seurat.
```{r setup, echo=FALSE, message=FALSE}
library(Seurat)
data <- Read10X(data.dir = "data/")
```
Some prose between chunks.
```{r clustering, fig.width=8}
seurat_obj <- FindClusters(seurat_obj, resolution = 0.5)
```

61
tests/fixtures/sample.ipynb vendored Normal file
View File

@ -0,0 +1,61 @@
{
"nbformat": 4,
"nbformat_minor": 5,
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": ["# Single-cell Analysis\n\nThis notebook demonstrates scanpy usage."],
"outputs": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": ["import scanpy as sc\nadata = sc.read_h5ad('data.h5ad')"],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": ["AnnData object with 1000 cells\n"]
}
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": ["sc.pp.normalize_total(adata)"],
"outputs": [
{
"output_type": "execute_result",
"execution_count": 1,
"data": {
"text/plain": ["'done'"]
},
"metadata": {}
}
]
},
{
"cell_type": "raw",
"metadata": {},
"source": ["raw cell — should be skipped"],
"outputs": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [""],
"outputs": []
}
]
}

6
tests/fixtures/sample.py vendored Normal file
View File

@ -0,0 +1,6 @@
#!/usr/bin/env python3
import scanpy as sc
adata = sc.read_h5ad("data.h5ad")
sc.pp.normalize_total(adata)
sc.pp.log1p(adata)

95
tests/test_backends.py Normal file
View File

@ -0,0 +1,95 @@
"""Tests for src/askme/backends.py."""
from __future__ import annotations
import asyncio
from unittest.mock import AsyncMock, patch
import pytest
from askme.backends import (
ModelSpec,
lightrag_model_func,
openai_client,
parse_spec,
release,
)
@pytest.mark.parametrize(
"spec,backend,model",
[
("qwen2.5:7b", "ollama", "qwen2.5:7b"),
("ollama:gemma3:4b", "ollama", "gemma3:4b"),
("llamacpp:gemma-4-12b-qat", "llamacpp", "gemma-4-12b-qat"),
],
)
def test_parse_spec(spec, backend, model):
"""
Scenario: one model list mixes Ollama tags and router ids
Given a spec string (bare tag, ollama: or llamacpp: prefix)
When parse_spec runs
Then backend and model are split, and the label keeps the original spec
"""
parsed = parse_spec(spec)
assert (parsed.backend, parsed.model, parsed.label) == (backend, model, spec)
def test_parse_spec_bare_tag_with_colon_stays_ollama():
"""
Scenario: Ollama tags contain colons themselves
Given "gemma2:9b" (no backend prefix)
When parse_spec runs
Then it is an Ollama model named "gemma2:9b", not backend "gemma2"
"""
assert parse_spec("gemma2:9b") == ModelSpec("ollama", "gemma2:9b", "gemma2:9b")
@pytest.mark.parametrize(
"spec,url",
[
("qwen2.5:7b", "http://localhost:11434/v1"),
("llamacpp:gemma-4-12b-qat", "http://localhost:8080/v1"),
],
)
def test_openai_client_targets_backend(spec, url):
"""
Scenario: both backends speak the OpenAI API
Given a model spec
When openai_client builds a client
Then its base_url is that backend's /v1 endpoint
"""
assert str(openai_client(parse_spec(spec)).base_url).rstrip("/") == url
def test_lightrag_model_func_binds_model_and_backend():
"""
Scenario: a generator overrides LightRAG's LLM for one query
Given llamacpp:gemma-4-12b-qat
When the returned model_func is called like LightRAG calls it
Then openai_complete_if_cache gets that model, the router base_url and the call args
"""
with patch("askme.backends.openai_complete_if_cache", new=AsyncMock(return_value="a")) as c:
func = lightrag_model_func(parse_spec("llamacpp:gemma-4-12b-qat"))
out = asyncio.run(func("prompt", keyword_extraction=True))
assert out == "a"
args, kwargs = c.call_args
assert args == ("gemma-4-12b-qat", "prompt")
assert kwargs["base_url"] == "http://localhost:8080/v1"
assert kwargs["keyword_extraction"] is True
@pytest.mark.parametrize(
"spec,target",
[("qwen2.5:7b", "unload_ollama_model"), ("llamacpp:gemma-4-12b-qat", "unload_llamacpp_model")],
)
def test_release_unloads_from_its_backend(spec, target):
"""
Scenario: free the GPU before the next model loads
Given a model spec
When release() runs
Then the matching backend's unload is awaited with the bare model name
"""
with patch(f"askme.backends.{target}", new=AsyncMock()) as unload:
asyncio.run(release(parse_spec(spec)))
unload.assert_awaited_once_with(parse_spec(spec).model)

220
tests/test_cli.py Normal file
View File

@ -0,0 +1,220 @@
"""Tests for askme CLI entrypoints (api/cli.py and evaluation/cli.py)."""
from __future__ import annotations
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
from typer.testing import CliRunner
from askme.api.cli import app as query_app
from askme.evaluation.cli import app as eval_app
runner = CliRunner()
# ── askme-query ───────────────────────────────────────────────────────────────
RAW_RESPONSE = (
"Scanpy is used for single-cell RNA-seq analysis.\n\n"
"## Sources\n"
"- notebooks/tutorial.ipynb: Scanpy is a Python library\n"
)
def _mock_rag(raw: str = RAW_RESPONSE):
rag = AsyncMock()
rag.initialize_storages = AsyncMock()
rag.finalize_storages = AsyncMock()
rag.aquery = AsyncMock(return_value=raw)
return rag
def test_query_prints_answer():
with patch("askme.api.cli.create_rag", return_value=_mock_rag()):
result = runner.invoke(query_app, ["What is scanpy?"])
assert result.exit_code == 0
assert "Scanpy is used for single-cell RNA-seq analysis." in result.output
def test_query_prints_sources():
with patch("askme.api.cli.create_rag", return_value=_mock_rag()):
result = runner.invoke(query_app, ["What is scanpy?"])
assert "Sources:" in result.output
assert "notebooks/tutorial.ipynb" in result.output
def test_query_no_sources_section():
with patch("askme.api.cli.create_rag", return_value=_mock_rag("Just an answer.")):
result = runner.invoke(query_app, ["What is scanpy?"])
assert result.exit_code == 0
assert "Sources:" not in result.output
def test_query_mode_option():
mock = _mock_rag()
with patch("askme.api.cli.create_rag", return_value=mock):
result = runner.invoke(query_app, ["question", "--mode", "local"])
assert result.exit_code == 0
call_args = mock.aquery.call_args
param = call_args.kwargs.get("param") or call_args.args[1]
assert param.mode == "local"
# ── askme-eval ────────────────────────────────────────────────────────────────
FAKE_SCORES = {
"faithfulness": 0.9,
"answer_relevancy": 0.85,
"context_precision": 0.8,
"samples": [],
}
FAKE_TESTSET = [
{
"question": "What is scanpy?",
"ground_truth": "Scanpy is for single-cell analysis.",
"contexts": ["Scanpy is a Python library."],
}
]
def test_eval_exits_zero(tmp_path: Path, sample_chunks):
report = tmp_path / "report.json"
with (
patch("askme.evaluation.cli._sample_docs", return_value=sample_chunks),
patch("askme.evaluation.cli.generate_testset", return_value=FAKE_TESTSET),
patch("askme.evaluation.cli.run_eval", return_value=FAKE_SCORES),
):
result = runner.invoke(
eval_app,
["--testset-size", "1", "--output", str(report)],
)
assert result.exit_code == 0
def test_eval_writes_json_report(tmp_path: Path, sample_chunks):
import json
report = tmp_path / "report.json"
with (
patch("askme.evaluation.cli._sample_docs", return_value=sample_chunks),
patch("askme.evaluation.cli.generate_testset", return_value=FAKE_TESTSET),
patch("askme.evaluation.cli.run_eval", return_value=FAKE_SCORES),
):
runner.invoke(eval_app, ["--testset-size", "1", "--output", str(report)])
assert report.exists()
data = json.loads(report.read_text())
assert "faithfulness" in data
def test_eval_exits_one_when_no_docs(tmp_path: Path):
report = tmp_path / "report.json"
with patch("askme.evaluation.cli._sample_docs", return_value=[]):
result = runner.invoke(
eval_app,
["--testset-size", "1", "--output", str(report)],
)
assert result.exit_code == 1
def test_eval_default_testset_size_is_50(tmp_path: Path, sample_chunks):
"""
Scenario: a full eval defaults to 50 questions
When eval runs with no --testset-size
Then generate_testset is asked for 50 Q&A pairs
"""
report = tmp_path / "report.json"
with (
patch("askme.evaluation.cli._sample_docs", return_value=sample_chunks),
patch("askme.evaluation.cli.generate_testset", return_value=FAKE_TESTSET) as mock_gen,
patch("askme.evaluation.cli.run_eval", return_value=FAKE_SCORES),
):
runner.invoke(eval_app, ["--output", str(report)])
assert mock_gen.call_args.kwargs.get("n") == 50
def test_eval_report_records_elapsed_seconds(tmp_path: Path, sample_chunks):
"""
Scenario: the eval report records how long the run took
When eval finishes
Then the JSON report carries an elapsed_seconds number (CPU-judge runs are
long; the duration is part of the result)
"""
import json
report = tmp_path / "report.json"
with (
patch("askme.evaluation.cli._sample_docs", return_value=sample_chunks),
patch("askme.evaluation.cli.generate_testset", return_value=FAKE_TESTSET),
patch("askme.evaluation.cli.run_eval", return_value=FAKE_SCORES),
):
runner.invoke(eval_app, ["--testset-size", "1", "--output", str(report)])
data = json.loads(report.read_text())
assert isinstance(data["elapsed_seconds"], (int, float))
def test_eval_reuses_cached_doc_sample(tmp_path: Path, sample_chunks):
"""
Scenario: second run reuses the cached doc sample
Given a doc-sample cache matching the source and sample size
When eval runs without --refresh
Then the extract/filter sampling is skipped (cache is used)
"""
import json
report = tmp_path / "report.json"
source = tmp_path / "notebooks"
source.mkdir()
cache = report.with_suffix(".docsample.json")
cache.write_text(
json.dumps({"source": str(source), "doc_sample": 25, "docs": sample_chunks})
)
with (
patch("askme.evaluation.cli._sample_docs") as mock_sample,
patch("askme.evaluation.cli.generate_testset", return_value=FAKE_TESTSET),
patch("askme.evaluation.cli.run_eval", return_value=FAKE_SCORES),
):
result = runner.invoke(
eval_app,
["--source", str(source), "--testset-size", "1", "--output", str(report)],
)
assert result.exit_code == 0
mock_sample.assert_not_called()
def test_eval_refresh_ignores_cache(tmp_path: Path, sample_chunks):
"""
Scenario: --refresh forces re-sampling even when a cache exists
Given a doc-sample cache
When eval runs with --refresh
Then _sample_docs is called again (cache ignored, then rewritten)
"""
import json
report = tmp_path / "report.json"
source = tmp_path / "notebooks"
source.mkdir()
cache = report.with_suffix(".docsample.json")
cache.write_text(
json.dumps({"source": str(source), "doc_sample": 25, "docs": sample_chunks})
)
with (
patch("askme.evaluation.cli._sample_docs", return_value=sample_chunks) as mock_sample,
patch("askme.evaluation.cli.generate_testset", return_value=FAKE_TESTSET),
patch("askme.evaluation.cli.run_eval", return_value=FAKE_SCORES),
):
result = runner.invoke(
eval_app,
[
"--source", str(source),
"--refresh",
"--testset-size", "1",
"--output", str(report),
],
)
assert result.exit_code == 0
mock_sample.assert_called_once()

298
tests/test_compare.py Normal file
View File

@ -0,0 +1,298 @@
"""Tests for src/askme/evaluation/compare.py."""
from __future__ import annotations
import asyncio
import json
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
from typer.testing import CliRunner
from askme.backends import parse_spec
from askme.evaluation.compare import (
_contexts,
app,
comparison_markdown,
generate_samples,
judge_samples,
run_matrix,
)
runner = CliRunner()
def _raw(answer: str, chunks: list[str], hl=("hl",), ll=("ll",)) -> dict:
"""Shape of LightRAG's aquery_llm / aquery_data result."""
return {
"data": {"chunks": [{"content": c} for c in chunks]},
"metadata": {"keywords": {"high_level": list(hl), "low_level": list(ll)}},
"llm_response": {"content": answer},
}
def test_contexts_are_chunk_texts_capped():
"""
Scenario: judge context is the retrieved source text, bounded
Given retrieved chunks totalling more than the cap
When _contexts runs with cap=10
Then whole chunks are kept until the cap, the last one truncated
"""
raw = _raw("a", ["aaaaaa", "bbbbbb", "cccccc"])
assert _contexts(raw, cap=10) == ["aaaaaa", "bbbb"]
def test_generate_samples_records_answer_contexts_and_keywords():
"""
Scenario: per-generator keywords (default)
Given a generator and one question
When generate_samples runs
Then the query uses that generator's model_func with no preset keywords,
and the sample holds answer, contexts and the extracted keywords
"""
rag = MagicMock()
rag.aquery_llm = AsyncMock(return_value=_raw("ans", ["ctx"], hl=["h"], ll=["l"]))
gen = parse_spec("gemma3:4b")
with patch("askme.evaluation.compare.lightrag_model_func", return_value="FUNC"):
samples = asyncio.run(
generate_samples(rag, gen, [{"question": "q", "reference": "r"}], "hybrid")
)
param = rag.aquery_llm.call_args.kwargs["param"]
assert param.model_func == "FUNC"
assert param.max_total_tokens == 12000
assert param.hl_keywords == [] and param.ll_keywords == []
assert samples == [
{
"question": "q",
"reference": "r",
"answer": "ans",
"contexts": ["ctx"],
"hl_keywords": ["h"],
"ll_keywords": ["l"],
}
]
def test_generate_samples_caps_context_for_every_generator():
"""
Scenario: every generator sees the same, complete context
Given LightRAG's default 30000-token prompt budget
When generate_samples queries
Then the prompt budget is capped at 12000 tokens
(fits Ollama's 16k and the router's 32k windows, so no backend
silently truncates or rejects the prompt)
"""
rag = MagicMock()
rag.aquery_llm = AsyncMock(return_value=_raw("a", ["c"]))
with patch("askme.evaluation.compare.lightrag_model_func"):
asyncio.run(
generate_samples(rag, parse_spec("x"), [{"question": "q", "reference": "r"}], "hybrid")
)
param = rag.aquery_llm.call_args.kwargs["param"]
assert param.max_total_tokens == 12000
def test_generate_samples_leaves_room_for_source_chunks():
"""
Scenario: the capped prompt still carries notebook text
Given LightRAG fills chunks only with what entities, relations and the
~2k-token system prompt leave of max_total_tokens
When generate_samples queries
Then entity + relation budgets leave at least 4000 tokens for chunks
(with the 6000/8000 defaults a 12000 cap left none: 19/20
answers had no source text, so faithfulness was unmeasurable)
"""
rag = MagicMock()
rag.aquery_llm = AsyncMock(return_value=_raw("a", ["c"]))
with patch("askme.evaluation.compare.lightrag_model_func"):
asyncio.run(
generate_samples(rag, parse_spec("x"), [{"question": "q", "reference": "r"}], "hybrid")
)
p = rag.aquery_llm.call_args.kwargs["param"]
system_prompt = 2000
assert p.max_total_tokens - p.max_entity_tokens - p.max_relation_tokens - system_prompt >= 4000
def test_generate_samples_uses_pinned_keywords():
"""
Scenario: pinned keywords isolate answer synthesis
Given keywords already extracted for the question by the base model
When generate_samples runs with them
Then the query carries those keywords, so retrieval is identical across generators
"""
rag = MagicMock()
rag.aquery_llm = AsyncMock(return_value=_raw("ans", ["ctx"], hl=["H"], ll=["L"]))
pinned = {"q": (["H"], ["L"])}
with patch("askme.evaluation.compare.lightrag_model_func"):
asyncio.run(
generate_samples(
rag, parse_spec("gemma3:4b"), [{"question": "q", "reference": "r"}],
"hybrid", pinned,
)
)
param = rag.aquery_llm.call_args.kwargs["param"]
assert (param.hl_keywords, param.ll_keywords) == (["H"], ["L"])
def _fake_matrix_deps(events: list):
"""Patch generation/judging/release, recording the order of GPU-relevant calls."""
rag = MagicMock()
rag.initialize_storages = AsyncMock()
rag.finalize_storages = AsyncMock()
async def gen(_rag, spec, testset, mode, pinned=None):
events.append(("gen", spec.label))
return [{"question": t["question"], "hl_keywords": [], "ll_keywords": []} for t in testset]
async def judge(spec, samples):
events.append(("judge", spec.label))
return [{"question": s["question"], "faithfulness": 1.0,
"answer_relevancy": 0.5, "context_precision": 0.0} for s in samples]
async def rel(spec):
events.append(("release", spec.label))
return [
patch("askme.evaluation.compare.create_rag", return_value=rag),
patch("askme.evaluation.compare.generate_samples", side_effect=gen),
patch("askme.evaluation.compare.judge_samples", side_effect=judge),
patch("askme.evaluation.compare.release", side_effect=rel),
]
def _run(tmp_path: Path, events: list, **kw):
patches = _fake_matrix_deps(events)
for p in patches:
p.start()
try:
return run_matrix(
[parse_spec("g1"), parse_spec("g2")],
[parse_spec("j1"), parse_spec("g1")],
[{"question": "q", "reference": "r"}],
"hybrid",
"per-generator",
tmp_path,
**kw,
)
finally:
for p in patches:
p.stop()
def test_run_matrix_generates_all_before_judging_and_frees_gpu(tmp_path: Path):
"""
Scenario: one model on the 8GB GPU at a time
Given 2 generators and 2 judges
When run_matrix runs
Then every generator answers before any judge runs, each model is
released after its phase, and every judge scores every generator
"""
events: list = []
_run(tmp_path, events)
assert events == [
("gen", "g1"), ("release", "g1"),
("gen", "g2"), ("release", "g2"),
("judge", "j1"), ("judge", "j1"), ("release", "j1"),
("judge", "g1"), ("judge", "g1"), ("release", "g1"),
]
assert len(list((tmp_path / "scores").glob("*.json"))) == 4
def test_run_matrix_resumes_from_existing_files(tmp_path: Path):
"""
Scenario: a long run crashed part-way
Given samples and scores already written by a previous run
When run_matrix runs again on the same directory
Then nothing is regenerated or re-judged
"""
_run(tmp_path, [])
events: list = []
_run(tmp_path, events)
assert [e for e in events if e[0] != "release"] == []
def test_comparison_markdown_flags_self_judging():
"""
Scenario: a model judging its own answers
Given scores for g1 judged by j1 and by g1
When comparison_markdown renders the matrix
Then each metric has a generator x judge table, and the g1/g1 cell is
marked as self-judged with a note on the bias
"""
scores = {
("g1", "j1"): {"faithfulness": 0.5, "answer_relevancy": 0.6, "context_precision": 0.7},
("g1", "g1"): {"faithfulness": 0.9, "answer_relevancy": 0.8, "context_precision": 0.7},
}
md = comparison_markdown(["g1"], ["j1", "g1"], scores, keyword_overlap={"g1": 1.0})
assert "## faithfulness" in md
assert "| g1 | 0.500 | 0.900* |" in md
assert "self-judged" in md
def test_cli_writes_comparison(tmp_path: Path):
"""
Scenario: one command runs the matrix and writes the report
Given a testset file and generator/judge lists
When askme-eval-compare runs
Then it exits 0 and comparison.md exists in the output dir
"""
testset = tmp_path / "ts.json"
testset.write_text(json.dumps([{"question": "q", "reference": "r"}] * 3))
out = tmp_path / "run"
with patch("askme.evaluation.compare.run_matrix", return_value="# md\n") as rm:
result = runner.invoke(
app,
["--generators", "g1 g2", "--judges", "j1", "--n", "2",
"--testset", str(testset), "--out", str(out)],
)
assert result.exit_code == 0, result.output
assert (out / "comparison.md").read_text() == "# md\n"
generators, judges, ts = rm.call_args.args[:3]
assert [g.label for g in generators] == ["g1", "g2"]
assert [j.label for j in judges] == ["j1"]
assert len(ts) == 2
def test_judge_samples_survives_a_failing_metric():
"""
Scenario: a judge fails one metric on one question
Given faithfulness raises (e.g. "output incomplete due to max_tokens")
When judge_samples scores the sample
Then faithfulness is None with the error recorded, and the other
metrics are still scored — one bad call must not end a
multi-hour run
"""
ok = MagicMock(value=0.5)
faith = MagicMock(ascore=AsyncMock(side_effect=RuntimeError("max_tokens")))
relev = MagicMock(ascore=AsyncMock(return_value=ok))
prec = MagicMock(ascore=AsyncMock(return_value=ok))
with (
patch("askme.evaluation.compare.llm_factory"),
patch("askme.evaluation.compare.OpenAIEmbeddings"),
patch("askme.evaluation.compare.Faithfulness", return_value=faith),
patch("askme.evaluation.compare.AnswerRelevancy", return_value=relev),
patch("askme.evaluation.compare.ContextPrecisionWithReference", return_value=prec),
):
[row] = asyncio.run(
judge_samples(
parse_spec("j"),
[{"question": "q", "reference": "r", "answer": "a", "contexts": ["c"]}],
)
)
assert row["faithfulness"] is None
assert "max_tokens" in row["errors"]["faithfulness"]
assert row["answer_relevancy"] == 0.5 and row["context_precision"] == 0.5
def test_comparison_markdown_shows_failed_counts():
"""
Scenario: some judge calls failed in a cell
Given a cell whose report counts 2 failed faithfulness calls
When comparison_markdown renders it
Then the cell reads "0.500 (2 failed)" so a mean over fewer questions is visible
"""
scores = {("g1", "j1"): {"faithfulness": 0.5, "answer_relevancy": 0.6,
"context_precision": 0.7, "failed": {"faithfulness": 2}}}
md = comparison_markdown(["g1"], ["j1"], scores, keyword_overlap={"g1": 1.0})
assert "| g1 | 0.500 (2 failed) |" in md

173
tests/test_evaluate.py Normal file
View File

@ -0,0 +1,173 @@
"""Tests for src/askme/evaluation/evaluate.py."""
from __future__ import annotations
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import pandas as pd
import pytest
from askme.evaluation.evaluate import _query_all, _strip_sources, run_eval
def _mock_rag_with_aquery(aquery: AsyncMock) -> MagicMock:
rag = MagicMock()
rag.initialize_storages = AsyncMock()
rag.finalize_storages = AsyncMock()
rag.aquery = aquery
return rag
def test_query_all_runs_with_bounded_concurrency():
"""
Scenario: testset questions are queried concurrently, capped at 2
Given a 4-question testset and a slow aquery
When _query_all runs
Then at most 2 queries are ever in flight at once (not serial, not all)
"""
inflight = 0
max_inflight = 0
async def slow_aquery(question, param=None):
nonlocal inflight, max_inflight
inflight += 1
max_inflight = max(max_inflight, inflight)
await asyncio.sleep(0.05)
inflight -= 1
return "answer"
testset = [{"question": f"q{i}", "ground_truth": "", "contexts": []} for i in range(4)]
rag = _mock_rag_with_aquery(AsyncMock(side_effect=slow_aquery))
with patch("askme.evaluation.evaluate.create_rag", return_value=rag):
samples = asyncio.run(_query_all(testset))
assert max_inflight == 2
assert [s.user_input for s in samples] == ["q0", "q1", "q2", "q3"]
def test_query_all_times_out_a_hung_query():
"""
Scenario: a hung query fails fast instead of stalling the whole eval
Given an aquery that never returns within the per-query timeout
When _query_all runs
Then it raises TimeoutError rather than blocking indefinitely
"""
async def hung_aquery(question, param=None):
await asyncio.sleep(10)
return "never"
testset = [{"question": "q", "ground_truth": "", "contexts": []}]
rag = _mock_rag_with_aquery(AsyncMock(side_effect=hung_aquery))
with (
patch("askme.evaluation.evaluate.create_rag", return_value=rag),
patch("askme.evaluation.evaluate._QUERY_TIMEOUT", 0.05),
):
with pytest.raises((asyncio.TimeoutError, TimeoutError)):
asyncio.run(_query_all(testset))
# ── _strip_sources ────────────────────────────────────────────────────────────
def test_strip_sources_no_section():
answer, contexts = _strip_sources("Scanpy clusters cells.")
assert answer == "Scanpy clusters cells."
assert contexts == []
def test_strip_sources_with_section():
raw = "Answer text.\n\n## Sources\n- file.py: some excerpt\n- other.ipynb: more"
answer, contexts = _strip_sources(raw)
assert answer == "Answer text."
assert len(contexts) == 2
assert "file.py" in contexts[0]
# ── run_eval ──────────────────────────────────────────────────────────────────
TESTSET = [
{
"question": "What is scanpy?",
"ground_truth": "Scanpy is for single-cell analysis.",
"contexts": ["Scanpy is a Python library for single-cell analysis."],
}
]
def _mock_eval_result() -> MagicMock:
df = pd.DataFrame(
[{"faithfulness": 0.9, "answer_relevancy": 0.85, "context_precision": 0.8}]
)
result = MagicMock()
result.to_pandas.return_value = df
return result
def test_run_eval_persists_samples_before_metrics(tmp_path):
"""
Scenario: query samples survive a metrics-phase failure
Given the RAGAS evaluate() step raises (missing dep, embedding OOM)
When run_eval has already queried the testset
Then the samples were written to disk before metrics ran, so the
expensive query phase is not lost
"""
import json
samples_file = tmp_path / "samples.json"
mock_rag = MagicMock()
mock_rag.initialize_storages = AsyncMock()
mock_rag.finalize_storages = AsyncMock()
mock_rag.aquery = AsyncMock(return_value="Scanpy is for single-cell analysis.")
with (
patch("askme.evaluation.evaluate.create_rag", return_value=mock_rag),
patch("askme.evaluation.evaluate._make_llm"),
patch("askme.evaluation.evaluate._make_embeddings"),
patch("askme.evaluation.evaluate.evaluate", side_effect=RuntimeError("boom")),
):
with pytest.raises(RuntimeError):
run_eval(TESTSET, samples_path=samples_file)
assert samples_file.exists()
data = json.loads(samples_file.read_text())
assert data[0]["user_input"] == "What is scanpy?"
def test_run_eval_returns_score_keys():
mock_rag = MagicMock()
mock_rag.initialize_storages = AsyncMock()
mock_rag.finalize_storages = AsyncMock()
mock_rag.aquery = AsyncMock(return_value="Scanpy is used for single-cell analysis.")
with (
patch("askme.evaluation.evaluate.create_rag", return_value=mock_rag),
patch("askme.evaluation.evaluate._make_llm"),
patch("askme.evaluation.evaluate._make_embeddings"),
patch("askme.evaluation.evaluate.evaluate", return_value=_mock_eval_result()),
):
result = run_eval(TESTSET)
assert "faithfulness" in result
assert "answer_relevancy" in result
assert "context_precision" in result
assert "samples" in result
def test_run_eval_scores_are_floats():
mock_rag = MagicMock()
mock_rag.initialize_storages = AsyncMock()
mock_rag.finalize_storages = AsyncMock()
mock_rag.aquery = AsyncMock(return_value="Scanpy is used for single-cell analysis.")
with (
patch("askme.evaluation.evaluate.create_rag", return_value=mock_rag),
patch("askme.evaluation.evaluate._make_llm"),
patch("askme.evaluation.evaluate._make_embeddings"),
patch("askme.evaluation.evaluate.evaluate", return_value=_mock_eval_result()),
):
result = run_eval(TESTSET)
assert isinstance(result["faithfulness"], float)
assert 0.0 <= result["faithfulness"] <= 1.0

190
tests/test_extract.py Normal file
View File

@ -0,0 +1,190 @@
"""Tests for src/askme/ingestion/extract.py."""
from __future__ import annotations
from pathlib import Path
import pytest
from askme.ingestion.extract import (
extract,
extract_ipynb,
extract_py,
extract_r,
extract_rmd,
supported_suffixes,
)
FIXTURES = Path(__file__).parent / "fixtures"
# ── extract_ipynb ─────────────────────────────────────────────────────────────
def test_ipynb_includes_filename():
result = extract_ipynb(FIXTURES / "sample.ipynb")
assert "sample.ipynb" in result
def test_ipynb_includes_markdown_cell():
result = extract_ipynb(FIXTURES / "sample.ipynb")
assert "Single-cell Analysis" in result
assert "scanpy usage" in result
def test_ipynb_includes_code_cell():
result = extract_ipynb(FIXTURES / "sample.ipynb")
assert "import scanpy as sc" in result
assert "```python" in result
def test_ipynb_excludes_stream_output():
result = extract_ipynb(FIXTURES / "sample.ipynb")
assert "AnnData object" not in result
def test_ipynb_excludes_execute_result_output():
result = extract_ipynb(FIXTURES / "sample.ipynb")
assert "'done'" not in result
def test_ipynb_skips_raw_cells():
result = extract_ipynb(FIXTURES / "sample.ipynb")
assert "raw cell" not in result
def test_ipynb_skips_empty_cells():
# Empty code cell should not add a blank fenced block
result = extract_ipynb(FIXTURES / "sample.ipynb")
assert "```python\n\n```" not in result
def test_ipynb_invalid_json_raises():
tmp = Path("/tmp/bad.ipynb")
tmp.write_text("not valid json{{{")
with pytest.raises(Exception):
extract_ipynb(tmp)
# ── extract_rmd ───────────────────────────────────────────────────────────────
def test_rmd_includes_filename():
result = extract_rmd(FIXTURES / "sample.Rmd")
assert "sample.Rmd" in result
def test_rmd_strips_yaml_front_matter():
result = extract_rmd(FIXTURES / "sample.Rmd")
assert "title:" not in result
assert "author:" not in result
assert "output:" not in result
def test_rmd_keeps_prose():
result = extract_rmd(FIXTURES / "sample.Rmd")
assert "Seurat" in result
assert "single-cell" in result
def test_rmd_normalises_code_fences():
result = extract_rmd(FIXTURES / "sample.Rmd")
assert "```r" in result
assert "```{r" not in result
# ── extract_py ────────────────────────────────────────────────────────────────
def test_py_includes_filename():
result = extract_py(FIXTURES / "sample.py")
assert "sample.py" in result
def test_py_strips_shebang():
result = extract_py(FIXTURES / "sample.py")
assert "#!/usr/bin/env" not in result
def test_py_keeps_code():
result = extract_py(FIXTURES / "sample.py")
assert "import scanpy" in result
assert "normalize_total" in result
# ── extract_r ────────────────────────────────────────────────────────────────
def test_r_includes_filename():
result = extract_r(FIXTURES / "sample.R")
assert "sample.R" in result
def test_r_keeps_code():
result = extract_r(FIXTURES / "sample.R")
assert "library(Seurat)" in result
assert "Read10X" in result
# ── extract dispatcher ────────────────────────────────────────────────────────
def test_extract_ipynb(tmp_path):
src = FIXTURES / "sample.ipynb"
dst = tmp_path / "nb.ipynb"
dst.write_bytes(src.read_bytes())
result = extract(dst)
assert result is not None
assert "nb.ipynb" in result
def test_extract_rmd(tmp_path):
src = FIXTURES / "sample.Rmd"
dst = tmp_path / "nb.Rmd"
dst.write_bytes(src.read_bytes())
result = extract(dst)
assert result is not None
def test_extract_py(tmp_path):
dst = tmp_path / "script.py"
dst.write_text("x = 1\n")
result = extract(dst)
assert result is not None
assert "script.py" in result
def test_extract_r(tmp_path):
dst = tmp_path / "script.R"
dst.write_text("x <- 1\n")
result = extract(dst)
assert result is not None
def test_extract_unsupported_returns_none(tmp_path):
dst = tmp_path / "data.csv"
dst.write_text("a,b,c\n1,2,3\n")
assert extract(dst) is None
def test_extract_case_insensitive_suffix(tmp_path):
src = FIXTURES / "sample.ipynb"
dst = tmp_path / "nb.IPYNB"
dst.write_bytes(src.read_bytes())
result = extract(dst)
assert result is not None
# ── supported_suffixes ────────────────────────────────────────────────────────
def test_supported_suffixes_contains_expected():
suffixes = supported_suffixes()
assert ".ipynb" in suffixes
assert ".rmd" in suffixes
assert ".py" in suffixes
assert ".r" in suffixes
def test_supported_suffixes_returns_frozenset():
assert isinstance(supported_suffixes(), frozenset)

110
tests/test_filter.py Normal file
View File

@ -0,0 +1,110 @@
"""Tests for src/askme/ingestion/filter.py."""
from __future__ import annotations
from pathlib import Path
import pytest
from askme.ingestion.filter import Deduplicator, filter_paths, is_venv_path
# ── is_venv_path ──────────────────────────────────────────────────────────────
def test_is_venv_path_site_packages(tmp_path):
p = tmp_path / "site-packages" / "numpy" / "core.py"
assert is_venv_path(p) is True
def test_is_venv_path_pycache(tmp_path):
p = tmp_path / "project" / "__pycache__" / "module.cpython-312.pyc"
assert is_venv_path(p) is True
def test_is_venv_path_checkpoints(tmp_path):
p = tmp_path / "notebooks" / ".ipynb_checkpoints" / "nb-checkpoint.ipynb"
assert is_venv_path(p) is True
def test_is_venv_path_normal(tmp_path):
p = tmp_path / "notebooks" / "analysis.ipynb"
assert is_venv_path(p) is False
# ── filter_paths ──────────────────────────────────────────────────────────────
def test_filter_paths_keeps_supported(tmp_path):
f = tmp_path / "nb.ipynb"
f.write_text('{"cells": [], "nbformat": 4, "nbformat_minor": 5, "metadata": {}}')
result = filter_paths([f])
assert f in result
def test_filter_paths_skips_unsupported_suffix(tmp_path):
f = tmp_path / "data.csv"
f.write_text("a,b\n1,2\n")
assert filter_paths([f]) == []
def test_filter_paths_skips_venv(tmp_path):
venv = tmp_path / "site-packages" / "pkg" / "module.py"
venv.parent.mkdir(parents=True)
venv.write_text("x = 1")
assert filter_paths([venv]) == []
def test_filter_paths_skips_empty_file(tmp_path):
f = tmp_path / "empty.py"
f.write_text("")
assert filter_paths([f]) == []
def test_filter_paths_mixed(tmp_path):
good = tmp_path / "nb.py"
good.write_text("import scanpy")
bad_suffix = tmp_path / "data.csv"
bad_suffix.write_text("a,b")
empty = tmp_path / "empty.R"
empty.write_text("")
result = filter_paths([good, bad_suffix, empty])
assert result == [good]
# ── Deduplicator ──────────────────────────────────────────────────────────────
def test_deduplicator_new_document_not_duplicate(tmp_path):
dedup = Deduplicator()
p = tmp_path / "a.py"
assert dedup.is_duplicate(p, "import scanpy as sc\nadata = sc.read_h5ad('x')") is False
def test_deduplicator_exact_duplicate(tmp_path):
dedup = Deduplicator()
text = "import scanpy as sc\n" * 20 # enough tokens for MinHash
p1 = tmp_path / "a.py"
p2 = tmp_path / "b.py"
dedup.is_duplicate(p1, text)
assert dedup.is_duplicate(p2, text) is True
def test_deduplicator_distinct_documents_not_duplicate(tmp_path):
dedup = Deduplicator()
p1 = tmp_path / "a.py"
p2 = tmp_path / "b.py"
dedup.is_duplicate(p1, "import scanpy as sc\nadata = sc.read_h5ad('x.h5ad')" * 10)
assert (
dedup.is_duplicate(p2, "library(Seurat)\ndata <- Read10X(data.dir='data/')" * 10)
is False
)
def test_deduplicator_seen_count(tmp_path):
dedup = Deduplicator()
assert dedup.seen_count == 0
dedup.is_duplicate(tmp_path / "a.py", "import scanpy" * 20)
assert dedup.seen_count == 1
dedup.is_duplicate(tmp_path / "b.py", "library(Seurat)" * 20)
assert dedup.seen_count == 2

110
tests/test_generate.py Normal file
View File

@ -0,0 +1,110 @@
"""Tests for src/askme/evaluation/generate.py."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pandas as pd
from askme.evaluation.generate import _make_embeddings, _make_llm, generate_testset
def test_make_llm_uses_cpu_judge_model(monkeypatch):
"""
Scenario: RAGAS runs on an independent CPU judge
Given ragas_judge_model="gemma4:12b"
When _make_llm builds the judge LLM
Then it constructs ChatOllama for that model with num_gpu=0 (CPU, so it
doesn't fight the GPU-resident RAG model)
"""
monkeypatch.setattr("askme.evaluation.generate.settings.ragas_judge_model", "gemma4:12b")
with (
patch("askme.evaluation.generate.ChatOllama") as mock_ollama,
patch("askme.evaluation.generate.LangchainLLMWrapper"),
):
_make_llm()
kwargs = mock_ollama.call_args.kwargs
assert kwargs["model"] == "gemma4:12b"
assert kwargs["num_gpu"] == 0
def test_make_embeddings_forces_cpu():
"""
Scenario: eval embeddings stay off the GPU
Given _make_embeddings() builds the eval embedder
When it is constructed
Then num_gpu=0 is passed (qwen2.5:7b owns the 8GB GPU)
"""
with patch("askme.evaluation.generate.OllamaEmbeddings") as mock_emb:
_make_embeddings()
_, kwargs = mock_emb.call_args
assert kwargs.get("num_gpu") == 0
def _fake_testset_df() -> pd.DataFrame:
return pd.DataFrame(
[
{
"user_input": "What does scanpy do?",
"reference": "Scanpy is used for single-cell analysis.",
"reference_contexts": ["Scanpy is a Python library..."],
}
]
)
def _make_mock_generator(df: pd.DataFrame) -> MagicMock:
testset = MagicMock()
testset.to_pandas.return_value = df
gen = MagicMock()
gen.generate_with_langchain_docs.return_value = testset
return gen
def test_generate_testset_returns_list(sample_chunks):
df = _fake_testset_df()
mock_gen = _make_mock_generator(df)
with (
patch("askme.evaluation.generate._make_llm"),
patch("askme.evaluation.generate._make_embeddings"),
patch("askme.evaluation.generate.TestsetGenerator", return_value=mock_gen),
):
result = generate_testset(sample_chunks, n=1)
assert isinstance(result, list)
assert len(result) == 1
def test_generate_testset_item_shape(sample_chunks):
df = _fake_testset_df()
mock_gen = _make_mock_generator(df)
with (
patch("askme.evaluation.generate._make_llm"),
patch("askme.evaluation.generate._make_embeddings"),
patch("askme.evaluation.generate.TestsetGenerator", return_value=mock_gen),
):
result = generate_testset(sample_chunks, n=1)
item = result[0]
assert "question" in item
assert "ground_truth" in item
assert "contexts" in item
assert isinstance(item["contexts"], list)
def test_generate_testset_passes_n(sample_chunks):
df = _fake_testset_df()
mock_gen = _make_mock_generator(df)
with (
patch("askme.evaluation.generate._make_llm"),
patch("askme.evaluation.generate._make_embeddings"),
patch("askme.evaluation.generate.TestsetGenerator", return_value=mock_gen),
):
generate_testset(sample_chunks, n=5)
mock_gen.generate_with_langchain_docs.assert_called_once()
_, kwargs = mock_gen.generate_with_langchain_docs.call_args
assert kwargs.get("testset_size") == 5

39
tests/test_gpu.py Normal file
View File

@ -0,0 +1,39 @@
"""Tests for src/askme/gpu.py."""
from __future__ import annotations
import asyncio
from unittest.mock import AsyncMock, patch
from askme.gpu import unload_llamacpp_model, unload_ollama_model
def test_unload_requests_zero_keep_alive():
"""
Scenario: free the GPU between eval phases
Given a model resident in Ollama
When unload_ollama_model("qwen2.5:7b") runs
Then Ollama is asked to generate with keep_alive=0 against settings.ollama_host
(Ollama's documented way to evict a model immediately)
"""
client = AsyncMock()
with patch("askme.gpu.ollama.AsyncClient", return_value=client) as ctor:
asyncio.run(unload_ollama_model("qwen2.5:7b"))
ctor.assert_called_once_with(host="http://localhost:11434")
client.generate.assert_awaited_once_with(model="qwen2.5:7b", keep_alive=0)
def test_unload_llamacpp_posts_to_router():
"""
Scenario: free the GPU held by the llama.cpp router
Given a model resident in the router
When unload_llamacpp_model("gemma-4-12b-qat") runs
Then POST <llamacpp_url>/models/unload is sent with that model id
"""
client = AsyncMock()
client.__aenter__.return_value = client
with patch("askme.gpu.httpx.AsyncClient", return_value=client):
asyncio.run(unload_llamacpp_model("gemma-4-12b-qat"))
client.post.assert_awaited_once_with(
"http://localhost:8080/models/unload", json={"model": "gemma-4-12b-qat"}
)

115
tests/test_ingest.py Normal file
View File

@ -0,0 +1,115 @@
"""Tests for src/askme/ingestion/ingest.py."""
from __future__ import annotations
import asyncio
import json
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from askme.ingestion.ingest import ingest_directory, load_manifest, save_manifest
@pytest.fixture
def notebook_dir(tmp_path: Path) -> Path:
"""Minimal directory with one supported file."""
nb = tmp_path / "sample.py"
nb.write_text("import scanpy as sc\nprint('hello')\n")
return tmp_path
@pytest.fixture
def mock_rag_instance():
rag = MagicMock()
rag.initialize_storages = AsyncMock()
rag.finalize_storages = AsyncMock()
rag.ainsert = AsyncMock()
# Return empty dicts so the post-insert wait loop exits immediately
rag.doc_status.get_docs_by_status = AsyncMock(return_value={})
return rag
def test_ainsert_called_with_file_path(notebook_dir, mock_rag_instance):
"""ainsert must receive file_paths= so LightRAG can cite the source."""
with patch("askme.ingestion.ingest.create_rag", return_value=mock_rag_instance):
asyncio.run(ingest_directory(notebook_dir, dry_run=False))
assert mock_rag_instance.ainsert.called
call_kwargs = mock_rag_instance.ainsert.call_args
file_paths = call_kwargs.kwargs.get("file_paths") or call_kwargs.args[1]
assert file_paths is not None
assert "sample.py" in file_paths
def test_dry_run_does_not_insert(notebook_dir, mock_rag_instance):
with patch("askme.ingestion.ingest.create_rag", return_value=mock_rag_instance):
asyncio.run(ingest_directory(notebook_dir, dry_run=True))
mock_rag_instance.ainsert.assert_not_called()
def test_extract_error_skipped(tmp_path, mock_rag_instance):
"""Files that fail extraction are skipped, not crashing the pipeline."""
bad = tmp_path / "bad.ipynb"
bad.write_text("not valid json{{{")
with patch("askme.ingestion.ingest.create_rag", return_value=mock_rag_instance):
# Should not raise
asyncio.run(ingest_directory(tmp_path, dry_run=False))
# ── Manifest ──────────────────────────────────────────────────────────────────
def test_load_manifest_missing_returns_empty(tmp_path):
assert load_manifest(tmp_path / "manifest.json") == {}
def test_save_and_load_manifest_roundtrip(tmp_path):
manifest = {"/path/to/file.py": "abc123", "/other/file.ipynb": "def456"}
path = tmp_path / "manifest.json"
save_manifest(manifest, path)
assert load_manifest(path) == manifest
def test_manifest_skips_unchanged_files(tmp_path, mock_rag_instance):
"""Files already in manifest with same hash should be skipped."""
f = tmp_path / "script.py"
f.write_text("import scanpy as sc\n")
import hashlib
file_hash = hashlib.sha256(f.read_bytes()).hexdigest()
manifest_path = tmp_path / "manifest.json"
save_manifest({str(f): file_hash}, manifest_path)
with patch("askme.ingestion.ingest.create_rag", return_value=mock_rag_instance):
asyncio.run(ingest_directory(tmp_path, dry_run=False, manifest_path=manifest_path))
mock_rag_instance.ainsert.assert_not_called()
def test_manifest_updated_after_insert(tmp_path, mock_rag_instance):
"""Manifest should be written with inserted file hash after successful ingest."""
f = tmp_path / "script.py"
f.write_text("import scanpy as sc\n")
manifest_path = tmp_path / "manifest.json"
with patch("askme.ingestion.ingest.create_rag", return_value=mock_rag_instance):
asyncio.run(ingest_directory(tmp_path, dry_run=False, manifest_path=manifest_path))
manifest = load_manifest(manifest_path)
assert str(f) in manifest
def test_manifest_not_updated_on_dry_run(tmp_path, mock_rag_instance):
"""Dry run should not update the manifest."""
f = tmp_path / "script.py"
f.write_text("import scanpy as sc\n")
manifest_path = tmp_path / "manifest.json"
with patch("askme.ingestion.ingest.create_rag", return_value=mock_rag_instance):
asyncio.run(ingest_directory(tmp_path, dry_run=True, manifest_path=manifest_path))
assert not manifest_path.exists()

181
tests/test_local_eval.py Normal file
View File

@ -0,0 +1,181 @@
"""Tests for src/askme/evaluation/local_eval.py."""
from __future__ import annotations
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
from typer.testing import CliRunner
from askme.evaluation.local_eval import _client, _make_judge, app, run_local_eval
runner = CliRunner()
def test_trim_context_prefers_chunks_then_caps():
"""
Scenario: the judge sees the document chunks, bounded to its window
Given LightRAG's ~27k-token dump (Entities -> Relations -> Document Chunks)
When _trim_context is applied before judging
Then it starts at the Document Chunks section (actual source text — what
context_precision and faithfulness need, not the KG entity triples)
and is capped to _CONTEXT_CHAR_CAP
"""
from askme.evaluation.local_eval import _CONTEXT_CHAR_CAP, _trim_context
dump = "Knowledge Graph Data (Entity): ...lots... Document Chunks: src " + "z" * 100_000
out = _trim_context(dump)
assert out.startswith("Document Chunks")
assert len(out) <= _CONTEXT_CHAR_CAP
# No chunks marker -> fall back to a plain cap
assert _trim_context("x" * 100_000) == "x" * _CONTEXT_CHAR_CAP
assert _trim_context("short") == "short"
def test_client_sets_a_timeout(monkeypatch):
"""
Scenario: a dropped Ollama response fails fast instead of wedging the run
When the OpenAI-compatible client is built
Then it carries an explicit timeout (Ollama drops in-flight responses
under load; without a timeout the judge call hangs indefinitely)
"""
monkeypatch.setattr(
"askme.evaluation.local_eval.settings.ollama_host", "http://ollama:11434"
)
with patch("askme.evaluation.local_eval.AsyncOpenAI") as mock_client:
_client()
assert mock_client.call_args.kwargs.get("timeout") is not None
def test_make_judge_uses_instructor_factory_at_ollama_v1(monkeypatch):
"""
Scenario: the judge is a schema-enforcing instructor LLM on Ollama
Given ragas_judge_model="gemma4:12b" and ollama_host
When _make_judge builds the judge
Then it points an OpenAI client at <ollama_host>/v1 and builds the LLM via
llm_factory(provider="openai") — the instructor path that enforces
the metric schema (fixes RagasOutputParserException)
"""
monkeypatch.setattr("askme.evaluation.local_eval.settings.ragas_judge_model", "gemma4:12b")
monkeypatch.setattr(
"askme.evaluation.local_eval.settings.ollama_host", "http://ollama:11434"
)
with (
patch("askme.evaluation.local_eval.AsyncOpenAI") as mock_client,
patch("askme.evaluation.local_eval.llm_factory") as mock_factory,
):
_make_judge()
assert mock_client.call_args.kwargs["base_url"] == "http://ollama:11434/v1"
assert mock_factory.call_args.args[0] == "gemma4:12b"
assert mock_factory.call_args.kwargs["provider"] == "openai"
# Generous max_tokens — faithfulness statement-extraction output is long;
# the default truncated it ("output incomplete due to max_tokens").
assert mock_factory.call_args.kwargs["max_tokens"] >= 2048
def _metric_returning(value: float) -> MagicMock:
"""A metric class whose instances' .ascore returns a fixed-value result."""
inst = MagicMock()
inst.ascore = AsyncMock(return_value=MagicMock(value=value))
cls = MagicMock(return_value=inst)
return cls
def test_run_local_eval_aggregates_triad_means():
"""
Scenario: the triad is scored per question and averaged
Given a 2-question testset and a RAG that answers
When run_local_eval runs with the three collections metrics
Then it returns mean faithfulness/answer_relevancy/context_precision and a
per-question breakdown
"""
testset = [
{"question": "q1", "reference": "r1"},
{"question": "q2", "reference": "r2"},
]
rag = MagicMock()
rag.initialize_storages = AsyncMock()
rag.finalize_storages = AsyncMock()
rag.aquery = AsyncMock(return_value="an answer")
with (
patch("askme.evaluation.local_eval.create_rag", return_value=rag),
patch("askme.evaluation.local_eval._make_judge"),
patch("askme.evaluation.local_eval._make_modern_embeddings"),
patch("askme.evaluation.local_eval.Faithfulness", _metric_returning(1.0)),
patch("askme.evaluation.local_eval.AnswerRelevancy", _metric_returning(0.8)),
patch(
"askme.evaluation.local_eval.ContextPrecisionWithReference",
_metric_returning(0.6),
),
):
scores = run_local_eval(testset)
assert scores["n"] == 2
assert scores["faithfulness"] == 1.0
assert scores["answer_relevancy"] == 0.8
assert scores["context_precision"] == 0.6
assert [r["question"] for r in scores["results"]] == ["q1", "q2"]
def test_eval_local_cli_writes_timed_report(tmp_path: Path):
"""
Scenario: the CLI writes a timed report with the triad means
When askme-eval-local runs
Then it exits 0 and the report holds the scores + elapsed_seconds + judge
"""
import json
report = tmp_path / "report.json"
fake = {
"faithfulness": 0.9,
"answer_relevancy": 0.8,
"context_precision": 0.7,
"n": 1,
"results": [{"question": "q", "faithfulness": 0.9, "answer_relevancy": 0.8, "context_precision": 0.7}],
}
testset = tmp_path / "testset.json"
testset.write_text(json.dumps([{"question": "q", "reference": "r"}]))
with patch("askme.evaluation.local_eval.run_local_eval", return_value=fake):
result = runner.invoke(
app, ["--n", "1", "--testset", str(testset), "--output", str(report)]
)
assert result.exit_code == 0
data = json.loads(report.read_text())
assert data["faithfulness"] == 0.9
assert isinstance(data["elapsed_seconds"], (int, float))
assert data["judge_model"]
def test_eval_local_cli_defaults_to_data_dir_testset(tmp_path: Path, monkeypatch):
"""
Scenario: the private testset lives in the data dir, not in code
Given settings.data_dir holds testset.json with one question
When askme-eval-local runs without --testset
Then that file's questions are scored
"""
import json
(tmp_path / "testset.json").write_text(json.dumps([{"question": "dq", "reference": "r"}]))
monkeypatch.setattr("askme.evaluation.local_eval.settings.data_dir", str(tmp_path))
fake = {"faithfulness": 1.0, "answer_relevancy": 1.0, "context_precision": 1.0, "n": 1, "results": []}
with patch("askme.evaluation.local_eval.run_local_eval", return_value=fake) as run:
result = runner.invoke(app, ["--output", str(tmp_path / "r.json")])
assert result.exit_code == 0
assert run.call_args.args[0] == [{"question": "dq", "reference": "r"}]
def test_eval_local_cli_missing_testset_points_to_example(tmp_path: Path, monkeypatch):
"""
Scenario: a fresh clone has no testset yet
Given no testset.json in settings.data_dir
When askme-eval-local runs without --testset
Then it exits non-zero and points the user at eval/testset.example.json
"""
monkeypatch.setattr("askme.evaluation.local_eval.settings.data_dir", str(tmp_path))
result = runner.invoke(app, ["--output", str(tmp_path / "r.json")])
assert result.exit_code != 0
assert "testset.example.json" in result.output

188
tests/test_main.py Normal file
View File

@ -0,0 +1,188 @@
"""Tests for src/askme/api/main.py."""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi.testclient import TestClient
from askme.api.main import _parse_sources, app
# ── _parse_sources ────────────────────────────────────────────────────────────
def test_parse_sources_no_section():
answer, sources = _parse_sources("Scanpy is used for single-cell analysis.")
assert answer == "Scanpy is used for single-cell analysis."
assert sources == []
def test_parse_sources_with_section():
raw = (
"Scanpy clusters cells.\n\n"
"## Sources\n"
"- notebooks/tutorial.ipynb: Scanpy is a Python library\n"
"- scripts/run.py: sc.pp.normalize_total(adata)\n"
)
answer, sources = _parse_sources(raw)
assert answer == "Scanpy clusters cells."
assert len(sources) == 2
assert sources[0].file == "notebooks/tutorial.ipynb"
assert "Scanpy" in sources[0].excerpt
assert sources[1].file == "scripts/run.py"
def test_parse_sources_case_insensitive():
raw = "Answer.\n\n### sources\n- file.py: some excerpt"
answer, sources = _parse_sources(raw)
assert answer == "Answer."
assert len(sources) == 1
# ── /query endpoint ───────────────────────────────────────────────────────────
@pytest.fixture
def client(mock_rag):
"""Test client with RAG initialisation patched out."""
with (
patch("askme.api.main.create_rag", return_value=mock_rag),
patch("askme.api.main._rag", mock_rag),
):
mock_rag.aquery = AsyncMock(
return_value=(
"Scanpy is used for single-cell analysis.\n\n"
"## Sources\n"
"- notebooks/tutorial.ipynb: Scanpy is a Python library\n"
)
)
with TestClient(app, raise_server_exceptions=True) as c:
yield c
def test_query_returns_answer(client):
resp = client.post("/query", json={"question": "What is scanpy?"})
assert resp.status_code == 200
data = resp.json()
assert "answer" in data
assert "sources" in data
assert isinstance(data["sources"], list)
def test_query_answer_stripped_of_sources_section(client):
resp = client.post("/query", json={"question": "What is scanpy?"})
data = resp.json()
assert "## Sources" not in data["answer"]
assert "## sources" not in data["answer"].lower()
def test_query_sources_populated(client):
resp = client.post("/query", json={"question": "What is scanpy?"})
sources = resp.json()["sources"]
assert len(sources) == 1
assert sources[0]["file"] == "notebooks/tutorial.ipynb"
def test_query_mode_forwarded(client, mock_rag):
client.post("/query", json={"question": "q", "mode": "local"})
call_kwargs = mock_rag.aquery.call_args
param = call_kwargs.kwargs.get("param") or call_kwargs.args[1]
assert param.mode == "local"
def test_query_invalid_mode_returns_422(client):
resp = client.post("/query", json={"question": "q", "mode": "invalid"})
assert resp.status_code == 422
# ── /health ───────────────────────────────────────────────────────────────────
def _all_ok_patches():
mock_driver = MagicMock()
mock_driver.verify_connectivity = AsyncMock()
mock_driver.close = AsyncMock()
mock_neo4j = MagicMock(return_value=mock_driver)
mock_resp = MagicMock()
mock_resp.raise_for_status = MagicMock()
mock_resp.json = MagicMock(return_value={"result": {"points_count": 10}})
mock_http = MagicMock()
mock_http.__aenter__ = AsyncMock(return_value=mock_http)
mock_http.__aexit__ = AsyncMock(return_value=False)
mock_http.get = AsyncMock(return_value=mock_resp)
return mock_neo4j, mock_http
def test_health_all_ok(mock_rag):
mock_neo4j, mock_http = _all_ok_patches()
with (
patch("askme.api.main.create_rag", return_value=mock_rag),
patch("askme.api.main._rag", mock_rag),
patch("askme.api.main.AsyncGraphDatabase.driver", mock_neo4j),
patch("askme.api.main.httpx.AsyncClient", return_value=mock_http),
):
with TestClient(app) as c:
resp = c.get("/health")
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "ok"
assert data["services"]["neo4j"] == "ok"
assert data["services"]["qdrant"] == "ok"
assert data["services"]["ollama"] == "ok"
def test_health_degraded_when_service_fails(mock_rag):
mock_driver = MagicMock()
mock_driver.verify_connectivity = AsyncMock(side_effect=Exception("connection refused"))
mock_driver.close = AsyncMock()
mock_neo4j = MagicMock(return_value=mock_driver)
mock_resp = MagicMock()
mock_resp.raise_for_status = MagicMock()
mock_http = MagicMock()
mock_http.__aenter__ = AsyncMock(return_value=mock_http)
mock_http.__aexit__ = AsyncMock(return_value=False)
mock_http.get = AsyncMock(return_value=mock_resp)
with (
patch("askme.api.main.create_rag", return_value=mock_rag),
patch("askme.api.main._rag", mock_rag),
patch("askme.api.main.AsyncGraphDatabase.driver", mock_neo4j),
patch("askme.api.main.httpx.AsyncClient", return_value=mock_http),
):
with TestClient(app) as c:
resp = c.get("/health")
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "degraded"
assert "error" in data["services"]["neo4j"]
# ── /collections ──────────────────────────────────────────────────────────────
def test_collections_returns_counts(mock_rag):
mock_resp = MagicMock()
mock_resp.raise_for_status = MagicMock()
mock_resp.json = MagicMock(return_value={"result": {"points_count": 42}})
mock_http = MagicMock()
mock_http.__aenter__ = AsyncMock(return_value=mock_http)
mock_http.__aexit__ = AsyncMock(return_value=False)
mock_http.get = AsyncMock(return_value=mock_resp)
with (
patch("askme.api.main.create_rag", return_value=mock_rag),
patch("askme.api.main._rag", mock_rag),
patch("askme.api.main.httpx.AsyncClient", return_value=mock_http),
):
with TestClient(app) as c:
resp = c.get("/collections")
assert resp.status_code == 200
data = resp.json()
assert data["chunks"] == 42
assert data["entities"] == 42
assert data["relationships"] == 42

196
tests/test_rag.py Normal file
View File

@ -0,0 +1,196 @@
"""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

130
tests/test_retrieval.py Normal file
View File

@ -0,0 +1,130 @@
"""Tests for src/askme/evaluation/retrieval.py."""
from __future__ import annotations
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
from typer.testing import CliRunner
from askme.evaluation.retrieval import _hit, app, run_retrieval_eval
runner = CliRunner()
def test_hit_is_case_insensitive_substring():
"""
Scenario: an expected term is found regardless of case
Given a retrieved context mentioning "CellChat"
Then _hit matches the expected term "cellchat"
"""
assert _hit("... uses CellChat to infer communication ...", "cellchat") is True
assert _hit("... only scanpy preprocessing here ...", "cellbender") is False
def test_run_retrieval_eval_scores_term_recall():
"""
Scenario: hit-rate reflects which expected terms were retrieved
Given two questions where retrieval surfaces one expected term but not
the other
When run_retrieval_eval scores them
Then hit_rate is 0.5 and each result carries its hit/miss
"""
testset = [
{"question": "ambient RNA?", "expected": "cellbender"},
{"question": "velocity?", "expected": "scvelo"},
]
async def fake_aquery(question, param=None):
return "cellbender removes ambient RNA" if "ambient" in question else "unrelated context"
rag = MagicMock()
rag.initialize_storages = AsyncMock()
rag.finalize_storages = AsyncMock()
rag.aquery = AsyncMock(side_effect=fake_aquery)
with patch("askme.evaluation.retrieval.create_rag", return_value=rag):
scores = run_retrieval_eval(testset)
assert scores["n"] == 2
assert scores["hit_rate"] == 0.5
by_term = {r["expected"]: r["hit"] for r in scores["results"]}
assert by_term["cellbender"] is True
assert by_term["scvelo"] is False
def test_run_retrieval_eval_requests_context_only():
"""
Scenario: retrieval eval never triggers answer generation
When run_retrieval_eval queries the RAG
Then every aquery is issued with only_need_context=True
"""
testset = [{"question": "q", "expected": "x"}]
rag = MagicMock()
rag.initialize_storages = AsyncMock()
rag.finalize_storages = AsyncMock()
rag.aquery = AsyncMock(return_value="x")
with patch("askme.evaluation.retrieval.create_rag", return_value=rag):
run_retrieval_eval(testset)
param = rag.aquery.call_args.kwargs["param"]
assert param.only_need_context is True
def test_eval_retrieval_cli_writes_report(tmp_path: Path):
"""
Scenario: the CLI runs the eval and writes a JSON report
When askme-eval-retrieval runs with a small testset
Then it exits 0 and the report holds the hit_rate
"""
import json
report = tmp_path / "retrieval_report.json"
testset = tmp_path / "ts.json"
testset.write_text(json.dumps([{"question": "ambient RNA?", "expected": "cellbender"}]))
fake = {"hit_rate": 1.0, "n": 1, "results": [
{"question": "ambient RNA?", "expected": "cellbender", "hit": True}
]}
with patch("askme.evaluation.retrieval.run_retrieval_eval", return_value=fake):
result = runner.invoke(
app, ["--testset", str(testset), "--output", str(report)]
)
assert result.exit_code == 0
assert json.loads(report.read_text())["hit_rate"] == 1.0
def test_eval_retrieval_cli_defaults_to_data_dir_testset(tmp_path: Path, monkeypatch):
"""
Scenario: the private retrieval testset lives in the data dir, not in code
Given settings.data_dir holds retrieval_testset.json
When askme-eval-retrieval runs without --testset
Then that file's questions are evaluated
"""
import json
ts = [{"question": "q", "expected": "t"}]
(tmp_path / "retrieval_testset.json").write_text(json.dumps(ts))
monkeypatch.setattr("askme.evaluation.retrieval.settings.data_dir", str(tmp_path))
fake = {"hit_rate": 1.0, "n": 1, "results": []}
with patch("askme.evaluation.retrieval.run_retrieval_eval", return_value=fake) as run:
result = runner.invoke(app, ["--output", str(tmp_path / "r.json")])
assert result.exit_code == 0
assert run.call_args.args[0] == ts
def test_eval_retrieval_cli_missing_testset_points_to_example(tmp_path: Path, monkeypatch):
"""
Scenario: a fresh clone has no retrieval testset yet
Given no retrieval_testset.json in settings.data_dir
When askme-eval-retrieval runs without --testset
Then it exits non-zero and points at eval/retrieval_testset.example.json
"""
monkeypatch.setattr("askme.evaluation.retrieval.settings.data_dir", str(tmp_path))
result = runner.invoke(app, ["--output", str(tmp_path / "r.json")])
assert result.exit_code != 0
assert "retrieval_testset.example.json" in result.output

4634
uv.lock generated Normal file

File diff suppressed because it is too large Load Diff