Skip to main content
Glama
README.md
πŸ‡΅πŸ‡± [Wersja polska](README.pl.md)

# RAG Pipeline β€” a local knowledge base

A local, GPU-accelerated retrieval pipeline for research papers, whole books, slide decks, notes and pasted text. Everything runs on your own machine β€” Qdrant, Redis, the models and a browser panel. Searchable by Claude through an MCP server, or by hand from the GUI.

## Features

- **Two kinds of knowledge libraries**
  - **shared, tagged** β€” libraries share one Qdrant collection (`kb_common`); search all of them at once or narrow to one library / a set of tags,
  - **isolated** β€” its own Qdrant collection (`kb_<id>`); search never leaves it, so knowledge is not diluted.
  - Each is **public** or **private**: private ones are skipped by default search and are only used when named explicitly.
- **Agent access control** β€” an MCP agent without a token sees public libraries only (private ones do not exist for it, not even by name). A token profile (`RAG_API_TOKEN`) defines which private libraries it may see; granular scope per library, or all, or none. Each profile has a `requires_unlock` flag β€” when set, the agent can only see its libraries after they are temporarily unlocked via `POST /libraries/{lib_id}/unlock` in the **DostΔ™p** tab. Without `requires_unlock`, the profile has persistent access to its libraries. This is tool-level protection, not OS-level isolation.
- **Browser panel** (`http://localhost:8100`) β€” create libraries, drag-and-drop files, paste text, edit tags and citation metadata, watch ingest progress, browse chunks, run searches with a per-stage trace, inspect service state and logs. Tabs: **Biblioteki** (libraries), **Szukaj** (search), **Zadania** (jobs queue with a notification pill showing pending/failed tasks), **DostΔ™p** (agent access profiles and library lock/unlock), **Debug** (GPU mode, ColPali unload, cache stats). Dark/light theme toggle.
- **Document types** β€” papers, books, textbooks, articles, notes, slide decks, atlases.
- **Per-document embed-figures** β€” `POST /documents/{lib}/{hash}/embed-figures` runs ColPali embedding for figures without re-parsing the document.
- **Per-document reingest** β€” `POST /documents/{lib}/{hash}/reingest?chunking=paragraph&full_pipeline=true` overrides chunking or pipeline settings without re-uploading.
- **Formats** β€” PDF, DOCX, PPTX, XLSX, HTML, Markdown, images (Docling) plus EPUB and TXT (small built-in parser).
- **Photos as documents** β€” an image file uploaded without the full pipeline is one entry searched by its title and description; the description is written by the user in the GUI or by an agent over MCP (it looks at the photo and stores what it sees). No OCR, no vision models.
- **Chunking** β€” `merged` by default: paragraphs of a section packed to ~1200 characters (papers too; one-element-per-chunk produced 29% of chunks under 60 characters). Reference lists are tagged and excluded from search unless `include_references` is set.
- **Multilingual embeddings** β€” BGE-M3 produces dense and sparse vectors in one pass (Polish + English); figures get a ColPali multivector in the full pipeline.
- **Hybrid search** β€” dense + sparse with RRF fusion in Qdrant. Modes: `normal` (fusion only) and `scholar` (CrossEncoder reranking, relevance cutoff, authors/DOI required, ColPali for figures with a relevance threshold, `COLPALI_MIN_SCORE`). When scholar drops relevant passages for lacking authors/DOI, the response says how many and from which documents.
- **Figures** β€” found by their real caption and by the image (ColPali). Icon-sized pictures (under ~1.2% of the page area, full pipeline only) are skipped. Small-VLM descriptions are off by default (`VLM_DESCRIPTIONS=1` brings them back as a labelled, non-embedded annotation).
- **Metadata** β€” DOI from the first 3 pages (title-checked), CrossRef, then DataCite (arXiv), then the PDF's own metadata. The year is never taken from the file's creation date.
- **Durable state in SQLite** β€” libraries, documents, SHA-256 dedup, per-document ingest log. Source files stay on disk, so re-ingesting needs no re-upload.
- **MCP server** β€” `list_libraries`, `create_library`, `search_library`, `ingest_document`, `ingest_text`, `read_context`, `get_page`, `ingest_status`, plus photo tools: `ingest_image`, `list_images`, `get_image`, `describe_image`. `get_page` returns an original PDF page as an image; results carry local links to figures and pages. `read_context` reads the chunks around a hit; `ingest_text` with a `note_key` replaces the note's previous version. AI-written text (`ingest_text`) always gets category `ai-note` and no authors, so `scholar` never returns it. Deleting libraries and changing visibility is GUI-only.

## Layout

| File | Role |
|---|---|
| `main.py` | API + GUI: libraries, ingest, documents, search, debug |
| `ingest.py` | parsing, chunking, embedding, upsert (RQ job `ingest_job`) |
| `embedder.py` | BGE-M3: dense + sparse in one forward pass |
| `textparse.py` | EPUB/TXT parser, paragraph packing |
| `state_store.py` | SQLite: libraries, documents, events |
| `meta_extract.py` | DOI β†’ CrossRef (PDF metadata) |
| `mcp_server.py` | MCP tools for Claude |
| `gpu.py` | GPU/CPU device selection shared by API and worker |
| `worker.py` | RQ worker entry point (`python worker.py`) |
| `requirements.txt` | Python dependencies (used by Dockerfile) |
| `.python-version` | Development Python 3.14; Docker image uses `python:3.11-slim` |
| `pyproject.toml` | uv project metadata |
| `static/` | browser panel (no build step) |

## Running

```bash
docker compose up -d --build
# GUI + API:  http://localhost:8100      (API docs: /docs)
```

The first start downloads models from Hugging Face (cache shared with the host: `~/.cache/huggingface`). Afterwards you can cut HF traffic with `HF_OFFLINE=1` in `.env`. Other `.env` variables: `RAG_PORT` (default 8100), `RAG_BIND` (default `127.0.0.1`; `0.0.0.0` exposes the panel on the LAN, with no login), `RERANKER_MODEL`, `SCHOLAR_MIN_SCORE`, `COLPALI_MIN_SCORE`, `VLM_DESCRIPTIONS`, `RAG_IDLE_UNLOAD_S`, `LOG_LEVEL`, `HF_CACHE_DIR`.

The project uses Python 3.11 in the Docker image (`requirements.txt`) and Python 3.14 for local development (`.python-version`, `pyproject.toml`). Both are compatible.

The only outbound request at runtime is the CrossRef metadata lookup for PDFs that carry a DOI.

MCP config: run `mcp_server.py` with the project's `.venv` Python; the API address comes from `RAG_API_BASE` (default `http://localhost:8100`). Set `RAG_API_TOKEN` for private library access β€” without a token the MCP agent sees public libraries only.

## Sharing the GPU with a local LLM

- The API loads search models on the first query and drops them after 15 idle minutes (`RAG_IDLE_UNLOAD_S`) β€” no VRAM is held at rest.
- The device follows free VRAM: GPU when there is room, otherwise CPU (query ~0.2 s, reranking ~1.5 s on an i5-9400F).
- `POST /debug/gpu {"mode":"cpu"}` frees the card at once and keeps RAG on CPU for 10 minutes; `{"mode":"auto"}` lifts it. `llm-start` / `llm-stop` call it themselves.
- Ingest with a busy card: up to 40 chunks run on CPU, larger documents and the full pipeline wait in the queue. ColPali is skipped in search meanwhile.

## Known limitations

- The `scholar` reranker is the multilingual `mmarco-mMiniLMv2-L12-H384-v1` with `SCHOLAR_MIN_SCORE=-2.0` (calibrated on 12 Polish/English queries β€” a small sample). To go back to the previous English-only one: `RERANKER_MODEL=cross-encoder/ms-marco-MiniLM-L-6-v2` and `SCHOLAR_MIN_SCORE=-5.0` in `.env`. `BAAI/bge-reranker-v2-m3` separates relevant from irrelevant more cleanly but needs 20–50 s per query on CPU.
- `scholar` only returns passages that have authors or a DOI β€” books without a DOI need authors filled in (at upload or in the document details).
- After a chunking or metadata change, `POST /debug/reingest-all` recomputes everything from the stored files; a document's previous version is replaced only once the new one is ready.
- One worker = one document at a time.

TDQS

A4/5.0

Scored across 2 tools

Disambiguation5/5

The two tools have completely distinct roles: one adds documents to the index, the other queries it. There is no overlap or ambiguity between ingestion and search.

Naming Consistency4/5

Both tools follow a verb_noun pattern and are recognizable at a glance. The only minor inconsistency is that one uses the plural 'papers' while the other uses singular 'paper'.

Tool Count3/5

Two tools is a thin surface, falling below the typical 3-15 well-scoped range. Each tool is essential for the core RAG workflow, but the set still feels minimal for anything beyond basic ingest-and-query usage.

Completeness3/5

The core ingest and search operations are present, giving agents the main RAG loop. However, there is no way to list, delete, or update ingested papers, which leaves obvious workflow gaps around managing the collection.

Maintenance

ActivityMaintained
ResponsivenessOutdated data