# 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"
