Skip to content

About

A retrieval-augmented generation app that indexes prose and pixels separately and fuses them at query time, so a question can be answered by a chart on page 7 even when no sentence on that page mentions the topic.

Topics

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

MultiRAG — multimodal RAG over text, documents and images

A retrieval-augmented generation app that indexes prose and pixels separately and fuses them at query time, so a question can be answered by a chart on page 7 even when no sentence on that page mentions the topic.

Runs entirely on free models — Google AI Studio's free tier by default, or fully offline local models with a single config flag.

MultiRAG frontend


The core idea

Most RAG pipelines extract text from a PDF and throw the page away. That loses every chart, table, diagram and layout cue. MultiRAG indexes each PDF twice:

Space What goes in What it's good at
text Extracted prose, chunked with overlap Exact terms, names, numbers, quoted wording
image Every page rendered to a PNG Charts, tables, diagrams, scanned pages, layout

Both are searched on every query and merged with reciprocal rank fusion. A page that ranks in both lists accumulates both contributions and rises to the top, arriving as a single citation carrying its text snippet and its page image — which is then handed to a vision-capable model to read directly.

Why RRF and not a weighted score

The two spaces produce similarity scores on incomparable scales, and under the local provider they come from entirely different models. Adding them is meaningless. RRF discards the magnitudes and keeps only the ranks, which are comparable by construction. No training, no tuning — one damping constant.


Architecture

flowchart TB
    UI["React + Vite<br/>:5194"] -->|/api proxy| API["FastAPI<br/>:8810"]

    API --> ING[services/ingestion]
    API --> RET[services/retrieval]
    API --> RAG[services/rag]

    ING -->|PyMuPDF: text + rendered pages| EMB
    RET -->|query vector per space| EMB
    RAG --> RET
    RAG -->|answer + page images| GEN

    subgraph providers["Pluggable providers"]
        EMB[embeddings/Embedder]
        GEN[generation/Generator]
    end

    EMB -.->|EMBEDDING_PROVIDER=gemini| GEM["Gemini free tier<br/>one shared space"]
    EMB -.->|EMBEDDING_PROVIDER=local| LOC["Qwen3-Embedding + SigLIP2<br/>two separate spaces"]
    GEN -.->|gemini| GFLASH[gemini-2.5-flash]
    GEN -.->|local| OLL[Ollama qwen3-vl]

    ING --> VS[repositories/vector_store]
    RET --> VS
    VS --> QD[("Qdrant :6335<br/>multirag_text · multirag_image")]
    ING --> CAT[repositories/catalog]
    CAT --> SQL[("SQLite<br/>document catalog")]
    ING --> DISK[/"storage/images/<br/>rendered pages"/]
Loading

The provider abstraction hides the single most important difference between the two backends: Gemini's multimodal model puts text and images in one shared space (one query vector searches both collections), while the local provider uses two different models and must encode the query twice. Callers never know — they call embed_query() and get a vector per space.

Query flow

sequenceDiagram
    participant U as Browser
    participant A as FastAPI
    participant E as Embedder
    participant Q as Qdrant
    participant G as Generator

    U->>A: POST /api/chat {query}
    A->>E: embed_query(query)
    E-->>A: {text: vec, image: vec}
    par search both spaces
        A->>Q: search(text space)
        Q-->>A: ranked chunks
    and
        A->>Q: search(image space)
        Q-->>A: ranked pages
    end
    A->>A: RRF fuse on (document_id, page)
    A->>A: load page images for top hits
    A->>G: prompt + text excerpts + page images
    G-->>A: grounded answer with [file p.N] citations
    A-->>U: {answer, citations[]}
Loading

Stack

Layer Choice
API FastAPI · Pydantic v2 · uv · structlog
Vector store Qdrant (one collection per space)
Catalog SQLite (stdlib sqlite3)
Documents PyMuPDF — text extraction + page rendering
Frontend React 19 · TypeScript (strict) · Vite · Tailwind v4
Embeddings Gemini free tier or Qwen3-Embedding + SigLIP2
Generation gemini-2.5-flash or Ollama qwen3-vl

Ports

Service Port
API 8810
Frontend 5194
Qdrant HTTP + dashboard 6335 (dashboard)
Qdrant gRPC 6336

All non-default, chosen to coexist with the other local stacks on this machine. Note 8800 is already claimed by the Redis playground project.


Running it day to day

Already set up? This is the only command you need — it starts Qdrant, the API and the UI together, and Ctrl-C stops all three:

make dev

Then open http://localhost:5194.

If a port is still held by a previous run:

make stop
Running the pieces separately

make dev is just these three, wired together with cleanup on exit:

make up    # Qdrant (detached; keeps running until `make down`)
make api   # API on :8810
make ui    # frontend on :5194

Useful when you want the API and UI in separate terminals with separate logs.


First-time setup

Only needed once per clone.

1. Configure. Copy the example env file and add a free Google AI Studio key (no credit card required — get one here):

cp .env.example .env
GEMINI_API_KEY=your-key-here

2. Install dependencies. Backend into a uv venv, frontend into node_modules:

make setup

3. Start it with make dev above.

Prerequisites: Docker, uv, and Node 20+.

Verifying the setup

GET /api/health/providers is the first thing to check when anything misbehaves. It reports the resolved model ids and vector dimensions rather than the configured ones, which is how you discover that a preview model id quietly fell back to the stable text-only model:

curl -s http://localhost:8810/api/health/providers | python3 -m json.tool

Going fully offline

No API key, nothing leaves the machine — at the cost of a ~3–4 GB install:

cd backend && uv pip install -e ".[local]"

Set EMBEDDING_PROVIDER=local and GENERATION_PROVIDER=local in .env, then ollama pull qwen3-vl:8b. Switching providers changes the vector width, and the store detects the mismatch and rebuilds the collections automatically — you will need to re-ingest.


Tests

cd backend && uv run pytest -q

Unit tests cover chunking and RRF fusion. Integration tests run the real ingest → retrieve pipeline against a live Qdrant using a deterministic bag-of-words stub embedder, so they assert our behaviour (PDF parsing, dual-space indexing, fusion, page-image wiring) rather than a third party's model quality. They skip cleanly when Qdrant is not running.

cd backend && uv run ruff format . && uv run ruff check . && uv run mypy app

API

Method Path Purpose
POST /api/documents Ingest a PDF, image, or text file
GET /api/documents List indexed documents
DELETE /api/documents/{id} Remove vectors, catalog row, and rendered images
GET /api/documents/{id}/pages/{n}/image Serve a rendered page
POST /api/search Fused retrieval only — useful for debugging recall
POST /api/chat Retrieve, attach page images, answer with citations
GET /api/health/providers Resolved models, dimensions, collection counts

Interactive docs at http://localhost:8810/docs.


Gotchas

  • Port 8800 is taken by the Redis playground project — this project uses 8810.
  • Verified model ids (Aug 2026 free tier): gemini-embedding-2 (multimodal, 3072-d, enables cross-modal search); gemini-embedding-001 (text-only fallback); gemini-3.6-flash for generation — gemini-2.5-flash is listed but returns 404.
  • Never put an embedding model in GEMINI_GENERATION_MODEL — produces a cryptic 404. A startup validator now rejects it with an explanatory message.
  • Image-capability probe uses a 64×64 PNG. A 1×1 PNG is rejected by gemini-embedding-2 with an error indistinguishable from "modality not supported", silently demoting the model to text-only.
  • Free tier: ~5 generation RPM. Bursts return 429. The health probe checks model metadata rather than a test generation to avoid burning quota.
  • Page images must be bound to citation numbers in the prompt. Without an explicit image N = [n] (file p.N) manifest the model invents citations. Covered by tests/unit/test_prompt_building.py.
  • Gemini 3.x reasoning counts against maxOutputTokens — too tight a cap yields an empty answer (finishReason=MAX_TOKENS), not a truncated one.
  • Changing a model id in .env auto-rebuilds Qdrant collections (dimensions are discovered at startup, never hardcoded). You will need to re-ingest after a provider switch.
  • Qdrant client/server must stay within one minor version — compose.yaml and qdrant-client in pyproject.toml are kept aligned.
  • Scanned PDFs have no text layer — they index as page images only; the ingest response includes a warning.

About

A retrieval-augmented generation app that indexes prose and pixels separately and fuses them at query time, so a question can be answered by a chart on page 7 even when no sentence on that page mentions the topic.

Topics

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages