Skip to content

Repository files navigation

πŸ›‘οΈ Enterprise Multi-Tenant Agentic RAG Platform

A production-oriented, containerized Retrieval-Augmented Generation (RAG) platform featuring strict multi-tenant isolation, role-based access control (RBAC), hybrid dense-sparse vector search, self-correcting agentic workflows, OWASP defensive guardrails, and real-time distributed tracing.


Platform Dashboard Overview Figure 1: Production Operator Dashboard featuring tenant-scoped streaming chat, role-based document ingestion, and live telemetry.


🌟 Executive Overview & Key Capabilities

This platform is engineered to solve the most critical enterprise challenges in Generative AI: cross-tenant data leakage, unauthorized privilege escalation, hallucination in knowledge retrieval, and adversarial prompt injection attacks.

Capability Enterprise Implementation Production Impact
Multi-Tenant Isolation Composite key (tenant_id, username) in PostgreSQL + Mandatory metadata filters in Qdrant Zero cross-tenant data leakage at database, vector, and cache layers.
Granular RBAC Role-filtered retrieval (admin, analyst, viewer) Restricted users cannot retrieve confidential chunks even within the same tenant.
Credential Lifecycle Tenant-scoped failed-login lockout/reset, active-user checks, and Redis-backed access-token revocation via /auth/logout Limits brute-force attempts without account-enumeration details; revoked tokens stop working across replicas when Redis is available.
Defensive AI & NeMo Guardrails NVIDIA NeMo Guardrails (Colang input/output rails) + OWASP injection regexes + Presidio PII Redaction Malicious prompts are blocked and PII is redacted before touching downstream LLMs or vector stores.
Hybrid Search (Dense + Sparse) FastEmbed BGE (384d) + BM25 Sparse Tokenizer + Qdrant Reciprocal Rank Fusion (RRF) Superior retrieval accuracy for both semantic intent and exact hardware SKUs / legal codes.
Cross-Encoder Reranking Cohere Rerank API (rerank-v3.5) cross-encoder re-ordering Re-scores hybrid retrieval candidates with high semantic precision before passing to LLM.
Corrective Agentic RAG (CRAG) Stateful LangGraph workflow with LLM-as-a-Judge grading and autonomous query reformulation Bounded self-correction prevents hallucinations and loops when retrieval is weak.
Universal Parser & OCR PDF, DOCX, XLSX, CSV, HTML, Code + Pytesseract OCR for scanned/image-based PDFs Seamless multi-format knowledge extraction with automatic OCR fallback.
Async Background Ingestion Dedicated POST /api/v1/ingest/async & GET /api/v1/ingest/status/{task_id} polling Non-blocking ingestion for large documents without HTTP gateway timeouts.
Stateful Persistence PostgreSQL Checkpointing via AsyncPostgresSaver Multi-turn chat state persists safely across container restarts and horizontal scale.
Version-Scoped Caching SHA-256 digested Redis keys with Tenant Version Epochs (tenant_ver:<tenant_id>) Sub-5ms cache hits; instant tenant-wide cache invalidation upon uploading new documents.
High-Throughput Inference Groq Cloud integration with asynchronous SSE token streaming Token generation at ultra-low latency.
Durable Ingestion Queue Redis-backed queue with processing retention and acknowledgement Async ingestion can be consumed across backend replicas instead of relying only on process memory.
Distributed Observability In-memory span tracker + REST API telemetry + Native Langfuse Cloud sync Real-time visibility into node-by-node latencies (retrieve_hybrid, rerank_cohere, grade, generate_llm).

πŸ—οΈ High-Level System Architecture

For the complete topology, data-isolation model, CRAG state graph, security controls, deployment design, and latency analysis, see ARCHITECTURE.md.

                                +---------------------------------------------+
                                |     Streamlit Operator Dashboard (UI)       |
                                |    (Chat Interface + Observability Tabs)    |
                                +---------------------------------------------+
                                                       β”‚  (HTTP / SSE Stream)
                                                       β–Ό
+─────────────────────────────────────────────────────────────────────────────────────────────────────────────────+
|                                           FastAPI Gateway (Port 8000)                                           |
|                                                                                                                 |
|  [Security Headers] ──► [JWT / RBAC Auth] ──► [NVIDIA NeMo Guardrails / OWASP Regex] ──► [Presidio PII Redaction]|
+───────────────────────────────────────────────────┬─────────────────────────────────────────────────────────────+
                                                    β”‚
                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                   β–Ό                                                                 β–Ό
      +──────────────────────────+                                     +──────────────────────────+
      |  Redis Response Cache    |                                     |    Distributed Tracing   |
      |  (Scoped by Tenant+Role) |                                     | (Spans & Langfuse Sync)  |
      +──────────────────────────+                                     +──────────────────────────+
                   β”‚ (Cache Miss)                                                    β”‚
                   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                    β”‚
                                                    β–Ό
                           +──────────────────────────────────────────────────+
                           |       LangGraph Corrective Agentic Engine        |
                           |                                                  |
                           |  [retrieve_hybrid] ──► [Cohere Reranker (v3.5)]  |
                           |          β–²                      β”‚                |
                           |          β”‚                      β–Ό                |
                           |          β”‚             [grade_documents (LLM)]   |
                           |          β”‚                      β”‚                |
                           |          β”‚ (Low Relevance)      β–Ό (Relevant)     |
                           |   [rewrite_query] ◄────── [decide_to_generate]   |
                           |                                 β”‚                |
                           |                                 β–Ό                |
                           |                          [generate_llm]          |
                           +────────────────────────┬─────────────────────────+
                                                    β”‚
                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                   β–Ό                                                                 β–Ό
      +──────────────────────────+                                     +──────────────────────────+
      |   Qdrant Hybrid Vector   |                                     |  PostgreSQL Checkpoints  |
      | Dense + BM25 Sparse RRF  |                                     |  & Tenant User Registry  |
      +──────────────────────────+                                     +──────────────────────────+

πŸ“Έ Platform Showcase & Screenshot Guide

To customize the documentation with your live screenshots, save your images in docs/screenshots/ matching the filenames below:

1. Granular RBAC Multi-Select Document Ingestion

RBAC Document Ingestion Figure 2: Administrator document upload with multi-select role permissions and automatic hybrid indexing.


2. Live Prompt Injection Defense & Interception

Prompt Injection Interception Figure 3: Immediate pre-flight interception of adversarial prompt injection and DAN jailbreak attempts.


3. Distributed Telemetry & Span Execution Timelines

Observability and Traces Figure 4: Real-time telemetry dashboard detailing sub-operation execution spans and latency percentiles.


⚑ Quick Start & Deployment

Prerequisites

  • Docker Engine 24.0+ and Docker Compose v2
  • A Groq API Key (https://console.groq.com)
  • Python 3.11+ (if running tests locally)

1. Clone & Configure

git clone https://github.com/your-org/multi-tenant-agentic-rag-platform.git
cd multi-tenant-agentic-rag-platform

# Copy the environment template
cp .env.example .env

2. Configure Environment Variables

Edit .env and set your secrets:

SECRET_KEY="generate-a-secure-random-32-char-secret-key"
GROQ_API_KEY="gsk_your_groq_api_key_here"
GROQ_MODEL="llama-3.3-70b-versatile"

BOOTSTRAP_ADMIN_USERNAME="admin_user"
BOOTSTRAP_ADMIN_PASSWORD="your-strong-password-under-72-characters"
BOOTSTRAP_ADMIN_TENANT_ID="tenant_alpha"

# Optional: Langfuse Cloud or Self-Hosted Telemetry Sync
LANGFUSE_PUBLIC_KEY=""
LANGFUSE_SECRET_KEY=""
LANGFUSE_HOST="https://cloud.langfuse.com"

3. Launch the Stack

docker compose up --build -d

4. Service Endpoints

Service URL Purpose
Streamlit Dashboard http://localhost:8501 Multi-tenant operator interface & tracing viewer
FastAPI Gateway http://localhost:8000/docs Interactive Swagger API documentation
Readiness Probe http://localhost:8000/ready Orchestrator health check (PostgreSQL, Qdrant, Redis)

Docker deployment

Docker Compose is the supported deployment for this repository. It runs one backend worker locally to avoid loading duplicate embedding models into memory. The root Dockerfile also runs the FastAPI service on the platform-provided PORT for container hosts such as Render.

The primary answer-generation model is Groq Cloud llama-3.3-70b-versatile. NeMo Guardrails is optional by configuration and, when enabled, uses a separate evaluator; it is not the primary generation model. The configured NeMo provider must have access to its model credentials. MFA and refresh-token flows are not exposed by the current API.

External hosting & Cloud Deployment

You can deploy the platform in either of two hosting models:

Option A: Full-Stack on Render (Recommended Blueprint)

The repository includes a multi-service render.yaml Blueprint that automatically provisions both the FastAPI Backend Gateway and the Streamlit Frontend Operator UI within the same Render environment:

  1. Connect your repository to Render as a Blueprint.
  2. Render automatically builds both services using the multi-stage Dockerfile.
  3. The frontend service automatically discovers and links to the backend via API_BASE_URL (fromService: host).

Option B: Decoupled (Streamlit Community Cloud + Render Backend)

  1. Frontend: Deploy the repository on Streamlit Community Cloud with entrypoint frontend/app.py and requirements file frontend/requirements.txt.
  2. Backend: Deploy on Render (or any container host) as a Docker web service using the root Dockerfile and readiness probe /ready.
  3. Environment & Secrets Synchronization:
    • In Streamlit Cloud settings or secrets, configure API_BASE_URL=https://<your-render-backend-domain>/api/v1 (the frontend automatically normalizes protocols and paths).
    • In Render backend environment variables, set CORS_ORIGINS=https://<your-streamlit-app>.streamlit.app.
    • Provide managed datastores (Neon/Supabase PostgreSQL POSTGRES_*, Upstash REDIS_URL, Qdrant Cloud QDRANT_URL + QDRANT_API_KEY).
    • Configure model secrets (GROQ_API_KEY, SECRET_KEY, and optional COHERE_API_KEY / LANGFUSE_*).

For production environments, set REQUIRE_REDIS=true. The frontend includes live backend reachability and latency checks in the sidebar with automatic status notices during cold starts.


πŸ§ͺ Comprehensive Verification & Test Suite

The platform includes a unit and regression test suite verifying tenant boundaries, RBAC isolation, and guardrails:

# Run unit tests
python -m pytest -q

# Output:
# 24 passed

Reproducible RAG evaluation

The built-in evaluation harness uses Ragas for context precision and context recall, with measured mean and P95 latency reported alongside the quality scores. The bundled smoke fixture is deterministic in its inputs but requires a configured Groq key because Ragas evaluates retrieval quality with an LLM:

python -m scripts.evaluate_rag

For credible hiring or production evidence, replace the fixture with labeled tenant-safe queries and record Ragas results for dense-only, sparse-only, hybrid RRF, and hybrid-plus-reranking configurations. Report the dataset size, K, hardware, provider, and whether latency includes network time. Langfuse remains the request-level observability layer for tracing retrieval, reranking, grading, and generation latency.

Latency budget and measurement

The platform intentionally accepts additional latency for stronger security, retrieval quality, tenant isolation, and observability. Each component is measured separately so the critical path can be optimized without claiming an artificially low end-to-end number.

For a warm request with external reranking disabled, the current portfolio reference is approximately 2.2 seconds average for the retrieval-to-first-response path:

Stage Local target Main variable
Request validation, JWT, and rate-limit lookup ~0.05 s Redis and database connection reuse
Dense + sparse query embedding ~0.35 s Warm CPU models and query length
Tenant-filtered Qdrant hybrid retrieval ~0.45 s Collection size and network round trip
Relevance grading ~0.01 s Heuristic grading; LLM grading is slower
Checkpoint and cache persistence ~0.20 s PostgreSQL/Redis health and connection reuse
Groq generation to first visible response ~1.14 s Provider queue, prompt size, and network
Warm-path average ~2.20 s Excludes cold starts and optional Cohere reranking

The 2.2-second figure is a warm-path reference budget, not a universal guarantee. Cold starts, hosted database poolers, Qdrant Cloud, NeMo checks, Cohere reranking, model queueing, and long completions can increase total latency. The telemetry API reports each span and should be used to replace this reference with measurements from the target deployment.

Verified local test matrix

Test Scenario Query / Action Expected Result Live Result Status
Admin Login Auth token request (tenant_alpha, admin) JWT token with tenant/role claims Token issued successfully βœ… PASS
Cross-Tenant Guard Tenant Alpha provisions user for Tenant Beta 403 Forbidden Blocked with 403 status βœ… PASS
Confidential Ingest Upload admin-only financial memo Ingested with allowed_roles=['admin'] Indexed with Dense + BM25 βœ… PASS
Prompt Injection Submit DAN / override instructions 400 Bad Request / Policy block Intercepted pre-flight βœ… PASS
PII Redaction Query with SSN and Email In-memory redaction before LLM PII masked, clean answer streamed βœ… PASS
RBAC Isolation Viewer queries confidential admin memo 0 chunks returned / safe fallback "No authorized records found" βœ… PASS
RBAC Access Admin queries confidential admin memo Relevant chunks retrieved & synthesized Accurate answer generated βœ… PASS
Cross-Tenant Isolation Tenant Beta queries Tenant Alpha data Complete data isolation (Zero leak) "No authorized records found" βœ… PASS
Hybrid Search (SKU) Exact keyword search #K8S-9921 Dense + BM25 RRF fusion match Retrieved exact SKU specifications βœ… PASS
Response Cache Repeat identical query in same thread Version-scoped Redis cache hit (cached: true) Covered by implementation and runtime smoke checks βœ… PASS

πŸ›‘οΈ Defensive AI, NeMo Guardrails & OWASP Compliance

[ Incoming Request ]
        β”‚
        β–Ό
[ NVIDIA NeMo Guardrails / OWASP Pattern Inspector ]
        β”‚ ──► Matches Jailbreak / Policy Violation? ──► YES ──► Raise HTTP 400 & Log Security Audit Event
        β”‚ (Clean)
        β–Ό
[ Presidio PII Redaction Engine ] ──► Masks Emails, Phones, SSNs, Credit Cards, JWTs, API Keys
        β”‚ (Sanitized)
        β–Ό
[ Hybrid Vector Retrieval (Qdrant) ──► Cohere Cross-Encoder Reranker ──► LLM-as-a-Judge Grading ]
        β”‚ (Answer Generated)
        β–Ό
[ NeMo Output Guardrails & PII Scrubbing ] ──► Final SSE Token Stream
  1. NVIDIA NeMo Guardrails (Input & Output Rails): Configured via Colang flows in guardrails/rails.co to enforce conversational boundaries, prevent prompt injections, stop roleplaying jailbreaks, and sanitize output.
  2. Deterministic & Presidio PII Sanitization: Redacts sensitive patterns in-memory ([REDACTED_EMAIL], [REDACTED_SSN], [REDACTED_CARD], etc.) using Microsoft Presidio and optimized regex scrubbers.
  3. Structured Audit Events: Emits immutable JSON security logs (auth.login, document.ingest) recording timestamps, IP, tenant ID, and user ID without logging raw credentials or prompts.

πŸ“Š Distributed Tracing & Observability

Every request automatically creates a distributed trace containing detailed sub-operation spans:

{
  "trace_id": "df1202c0-c7a0-4434-a9fb-f6e6cd18ba5d",
  "tenant_id": "tenant_alpha",
  "user_id": "admin_user",
  "total_duration_ms": 2233.86,
  "cache_hit": false,
  "spans": [
    { "name": "retrieve_hybrid", "duration_ms": 699.25, "status": "ok", "metadata": { "retrieved_count": 8 } },
    { "name": "rerank_cohere", "duration_ms": 182.40, "status": "ok", "metadata": { "reranked_count": 5 } },
    { "name": "grade_documents", "duration_ms": 110.15, "status": "ok", "metadata": { "grader_type": "llm_as_judge", "is_relevant": true } },
    { "name": "generate_llm", "duration_ms": 1404.70, "status": "ok", "metadata": { "response_length": 1686 } }
  ]
}
  • View live trace breakdowns and P95 latency percentiles directly inside the Streamlit UI or query /api/v1/telemetry/traces. Trace deletion is restricted to tenant administrators.
  • Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to seamlessly stream traces to Langfuse Cloud or self-hosted Langfuse.

πŸ“‚ Project Structure

β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ agents/              # LangGraph workflow, nodes, and LLM routers
β”‚   β”‚   β”œβ”€β”€ graph.py         # Corrective Agentic RAG graph with LLM grading & Cohere rerank
β”‚   β”‚   └── llm.py           # Groq Cloud chat model client
β”‚   β”œβ”€β”€ api/                 # FastAPI routes and schemas
β”‚   β”‚   └── routes.py        # Auth, Ingest (Sync & Async), Streaming Chat, Telemetry
β”‚   β”œβ”€β”€ core/                # Core security, auth, and telemetry infrastructure
β”‚   β”‚   β”œβ”€β”€ audit.py         # Structured JSON audit logging
β”‚   β”‚   β”œβ”€β”€ auth.py          # Multi-tenant JWT auth & OIDC JWKS validator
β”‚   β”‚   β”œβ”€β”€ rerank.py        # Cohere cross-encoder reranker client
β”‚   β”‚   β”œβ”€β”€ security.py      # NVIDIA NeMo Guardrails, OWASP injection & PII redaction
β”‚   β”‚   └── tracing.py       # Distributed span collector & Langfuse export
β”‚   β”œβ”€β”€ db/                  # Qdrant hybrid vector store integration
β”‚   β”‚   └── qdrant.py        # Named dense+sparse collection & RRF hybrid search
β”‚   β”œβ”€β”€ ingestion/           # Multi-format document parser
β”‚   β”‚   └── parser.py        # PDF, DOCX, XLSX, HTML, Code & Pytesseract OCR
β”‚   β”œβ”€β”€ migrations/          # Versioned PostgreSQL schema migrations
β”‚   β”œβ”€β”€ config.py            # Pydantic v2 application settings
β”‚   β”œβ”€β”€ database.py          # Async PostgreSQL connection pool & checkpointer
β”‚   β”œβ”€β”€ main.py              # FastAPI application & lifespan pre-warming
β”‚   └── redis_client.py      # Async Redis client & tenant cache versioning
β”œβ”€β”€ frontend/
β”‚   └── app.py               # Streamlit operator dashboard & telemetry viewer
β”œβ”€β”€ scripts/
β”‚   β”œβ”€β”€ evaluate_rag.py      # Ragas retrieval evaluation runner
β”‚   └── __init__.py
β”œβ”€β”€ scratch/
β”‚   └── check_documents.py   # Local document inspection utility
β”œβ”€β”€ guardrails/              # NVIDIA NeMo Guardrails configuration
β”‚   β”œβ”€β”€ config.yml           # Model & rail definitions
β”‚   β”œβ”€β”€ prompts.yml          # Self-check prompt templates
β”‚   └── rails.co             # Colang flow security definitions
β”œβ”€β”€ tests/                   # Automated unit and regression test suite
β”œβ”€β”€ .github/
β”‚   └── workflows/           # CI and container delivery workflows
β”œβ”€β”€ docs/
β”‚   └── screenshots/         # Optional documentation screenshots
β”œβ”€β”€ docker-compose.yml       # Supported local deployment stack
β”œβ”€β”€ Dockerfile               # Multi-stage non-root container build
β”œβ”€β”€ ARCHITECTURE.md          # In-depth architectural design specification
└── requirements.txt         # Version-constrained runtime dependencies

πŸ“œ License

Distributed under the Apache 2.0 License. See LICENSE for the complete terms.

About

Production-grade, multi-tenant Agentic RAG platform featuring LangGraph CRAG orchestration, hybrid dense/sparse vector retrieval via Qdrant, RBAC isolation, Redis caching, and automated CI/CD security gating.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Packages

Contributors

Languages