Skip to content
laojun509Public

About

Enterprise-grade RAG reference: RBAC-aware retrieval, citation-numbered prompts, audit log, offline eval. Runs on Ollama, swaps to OpenAI with one env var.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

ragdemo · Enterprise-grade RAG, in one repo

Python FastAPI React Qdrant License: MIT

A minimal but production-shaped Retrieval-Augmented Generation reference. Not "hello world" RAG — the same shape you would actually ship: permission-aware retrieval, citation-numbered prompts, query audit log, offline eval. Runs fully offline on Ollama, swaps to OpenAI / Azure / Qwen with a single env var.

简体中文 · English


Why another RAG demo

Most RAG examples stop at "embed → search → stuff into prompt". The hard parts in real deployments are everywhere else:

  1. Permission filtering must happen inside the ANN, not after — otherwise your top-k gets eaten by chunks the user can't read.
  2. Citations only work if source/page/chunk_id ride along in the vector payload from day one. Bolted on later means re-ingesting everything.
  3. Every answer needs an audit trail — query, retrieved chunks, latencies — or you can't debug, A/B, or comply.
  4. Eval is non-negotiable. "It feels good" is not a metric.

This repo is the smallest codebase that demonstrates all four, end-to-end.

What you get

  • RBAC-aware vector search — (department, permission_level) are Qdrant payload filters applied during ANN, not after
  • Citation-numbered prompts — model output references [1][3] linked to source files & page numbers
  • Multi-provider, OpenAI-compatible everywhere — works with OpenAI, Azure OpenAI, Ollama, vLLM, Qwen DashScope, Moonshot, by editing .env
  • Embedded Qdrant mode — zero external services for local development
  • Async ingest CLI — drop-in script for ingesting books / large PDFs without HTTP timeouts
  • Built-in offline eval — retrieval_hit + answer_hit over a JSON eval set
  • Full audit log — every query lands in SQLite with retrieved chunks, latencies, user identity

Quick start (60 seconds, fully local)

git clone https://github.com/laojun509/ragdemo.git
cd ragdemo/enterprise-rag-agent-demo

# 1. Bring up your local LLM stack (one-time)
ollama pull qwen2.5:7b
ollama pull bge-m3

# 2. Configure
cp .env.example .env

# 3. Run
docker compose up --build

Then:

No GPU? qwen2.5:3b runs on a 16GB MacBook just fine. Want OpenAI instead? Edit .env — that's the only change.

Architecture

                    ┌──────────────┐
   user identity ──▶│ FastAPI      │──▶ retriever (embed → ANN with RBAC filter)
   (X-User-* hdr)   │  pipeline    │──▶ prompt (numbered citations [1][2]…)
                    │              │──▶ LLM (OpenAI-compatible chat)
                    └──────┬───────┘
                           │
                           ▼
              ┌──────────────────────────────┐
              │  SQLite: documents,          │   ◀── metadata + audit + eval
              │           query_logs,        │
              │           eval_records       │
              ├──────────────────────────────┤
              │  Qdrant (local OR service):  │   ◀── vectors + payload-indexed RBAC
              │  payload = {doc_id, source,  │
              │             page, chunk_id,  │
              │             department,      │
              │             permission_level,│
              │             text}            │
              └──────────────────────────────┘

Pipeline call path: api/query.py → rag/pipeline.py → rag/retriever.py → rag/vectorstore.py:search (with Filter) → rag/prompt.py → rag/llm.py → write QueryLog.

Permission-aware retrieval, in code

The thing most "enterprise RAG" tutorials get wrong:

# enterprise-rag-agent-demo/backend/app/rag/vectorstore.py
def build_permission_filter(department: str, permission_level: int) -> qm.Filter:
    department_clause = qm.Filter(should=[
        qm.FieldCondition(key="department", match=qm.MatchValue(value=department)),
        qm.FieldCondition(key="department", match=qm.MatchValue(value="public")),
    ])
    level_clause = qm.FieldCondition(
        key="permission_level", range=qm.Range(lte=permission_level),
    )
    return qm.Filter(must=[department_clause, level_clause])

This is passed as query_filter into client.search(...) so Qdrant rules out chunks the user can't read before computing top-k. Filtering after the fact silently shrinks your recall — possibly to zero.

Tech stack

Layer Choice Why
API FastAPI + Uvicorn Async, lifespan startup hooks, Swagger out of the box
Validation Pydantic v2 + pydantic-settings .env → Settings singleton
Metadata DB SQLite + SQLAlchemy 2.0 async + aiosqlite Documents / QueryLog / EvalRecord
Vector DB Qdrant 1.11 (embedded or service mode) Payload-indexed RBAC filters
Parsing pypdf + custom normalize_pdf_text Joins Calibre-style visual line breaks for Chinese books
Chunking LangChain RecursiveCharacterTextSplitter Chinese-friendly separators
Embeddings OpenAI-compatible (Ollama bge-m3 by default) Switch provider via .env
LLM OpenAI-compatible chat (Ollama qwen2.5:7b) Same
Frontend React 18 + Vite 5 No state-mgmt library, no UI kit, intentionally lean
Deploy Docker Compose One-command local; production-ready Dockerfiles

Layout

enterprise-rag-agent-demo/
├─ backend/
│  └─ app/
│     ├─ main.py                FastAPI lifespan + table/collection bootstrap
│     ├─ config.py              .env → Settings
│     ├─ deps/auth.py           X-User-* headers → UserContext
│     ├─ db/                    models + async engine
│     ├─ core/
│     │  ├─ loader.py           txt/md/pdf + Calibre-PDF normalizer
│     │  ├─ chunker.py          recursive / paragraph / fixed
│     │  └─ embedder.py         batched OpenAI-compatible embedding
│     ├─ rag/
│     │  ├─ vectorstore.py      Qdrant wrapper + RBAC filter
│     │  ├─ retriever.py        query → embed → search
│     │  ├─ prompt.py           numbered-citation prompt
│     │  ├─ llm.py              OpenAI-compatible chat
│     │  └─ pipeline.py         end-to-end RAG, instrumented
│     ├─ services/ingest.py     upload → ingest service layer
│     ├─ scripts/ingest_book.py CLI ingest for large books
│     ├─ eval/runner.py         retrieval_hit + answer_hit
│     └─ api/                   /documents /query /logs /eval
├─ frontend/                    React + Vite UI
├─ data/                        sample docs + eval set
├─ docs/                        architecture.md + api.md
└─ docker-compose.yml

Ingesting a whole book

For long PDFs, HTTP upload will timeout. Use the offline CLI:

# Stop the backend first — embedded Qdrant is single-process
docker compose stop backend

backend/.venv/Scripts/python.exe \
  backend/app/scripts/ingest_book.py \
  "/path/to/your-book.pdf" \
  --department public --permission-level 1 \
  --chunk-size 700 --chunk-overlap 100 --batch-size 16

docker compose start backend

The script prints a per-batch progress bar with ETA. A 290-page Chinese trading book (~140k chars) takes about 25 seconds end-to-end on local Ollama with bge-m3.

Switching providers

Want OpenAI? Edit .env:

- LLM_BASE_URL=http://localhost:11434/v1
- LLM_API_KEY=ollama
- LLM_MODEL=qwen2.5:7b
+ LLM_BASE_URL=https://api.openai.com/v1
+ LLM_API_KEY=sk-...
+ LLM_MODEL=gpt-4o-mini

Same pattern for Azure OpenAI, Qwen DashScope, Moonshot, vLLM, LocalAI — anything that speaks the OpenAI HTTP shape.

API at a glance

Method Path Purpose
POST /api/documents Upload + ingest a file
GET /api/documents List visible to current user
DELETE /api/documents/{id} Delete (also clears Qdrant)
POST /api/query RAG question answering
GET /api/logs Audit log
GET /api/eval/sample Built-in eval set
POST /api/eval/run Run offline eval, write summary

User identity is injected via headers: X-User-Id, X-User-Department, X-User-Permission-Level. In production you'd swap this dependency for OIDC / JWT.

Roadmap

  • Streaming responses (SSE) — most-requested next
  • Hybrid retrieval (BM25 + vector + RRF)
  • Cross-encoder reranking
  • Async ingest queue (Celery / RQ) + progress polling
  • OpenTelemetry traces
  • Ragas evaluation integration
  • PII redaction & prompt-injection defenses

PRs welcome on any of the above. Each is a self-contained module — see docs/architecture.md for where the seams are.

Contributing

Issues and PRs are welcome. The codebase is intentionally tiny so the diff to add a feature stays small. Please:

  1. Open an issue first for anything beyond a typo / micro-fix.
  2. Keep new modules under core/ or rag/ — don't bloat pipeline.py.
  3. If you change retrieval behavior, run POST /api/eval/run and include the summary.

Star history

If this saved you time, a star helps others find it.

Star History Chart

License

MIT — use it commercially, fork it, ship it. A backlink is appreciated but not required.

About

Enterprise-grade RAG reference: RBAC-aware retrieval, citation-numbered prompts, audit log, offline eval. Runs on Ollama, swaps to OpenAI with one env var.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages