Back to .md Directory

QuantumPDF Chat App - System Architecture

Maps the full request flow for a PDF chat app: ingestion, caching, guardrails, vector search, model gateway, and monitoring.

May 2, 2026
0 downloads
1 views
ai rag guardrails
View source

What this file does

Maps the full request flow for a PDF chat app: ingestion, caching, guardrails, vector search, model gateway, and monitoring.

When to use it

  • Designing a RAG-based chat system with PDF ingestion
  • Planning caching and guardrail layers for an LLM app
  • Documenting a multi-component architecture for a team
  • Reviewing gaps in an existing RAG pipeline

Assumes this stack

PineconeWeaviateHuggingFaceOpenAINext.jsTypeScript

QuantumPDF Chat App - System Architecture

---
id: c5c1e6a6-1e69-4e2a-b471-360fc59330cf
---
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#e3f2fd', 'primaryTextColor': '#1565c0', 'primaryBorderColor': '#1976d2', 'lineColor': '#424242', 'secondaryColor': '#fff8e1', 'tertiaryColor': '#f3e5f5'}}}%%

flowchart TB
    %% ===== ORCHESTRATION LAYER =====
    subgraph ORCH["<b>Orchestration</b><br/>(RAGEngine + AppStore)"]
        direction TB
    end

    %% ===== USER ENTRY =====
    USER((("๐Ÿ‘ค User")))
    USER -->|"Query"| CACHE_IN

    %% ===== CACHE LAYER =====
    subgraph CACHE_LAYER["Cache Layer"]
        CACHE_IN{{"๐Ÿ—„๏ธ Query Cache<br/><i>Check cached responses</i>"}}
        EMB_CACHE[("๐Ÿ’พ Embedding Cache<br/><i>TTL: 30min, Max: 1000</i>")]
    end
    
    CACHE_IN -.->|"Cache Hit"| FINAL_RESP
    CACHE_IN -->|"Cache Miss"| CONTEXT

    %% ===== CONTEXT CONSTRUCTION =====
    subgraph CONTEXT_BOX["Context Construction"]
        direction TB
        CONTEXT["๐Ÿ”ง Context Construction<br/><i>RAG, query rewriting,<br/>synonym expansion</i>"]
        QUERY_ENH["๐Ÿ“ Query Enhancement<br/><i>Acronym expansion,<br/>spell check, synonyms</i>"]
        CONTEXT --> QUERY_ENH
    end

    QUERY_ENH --> INPUT_GUARD

    %% ===== INPUT GUARDRAILS =====
    subgraph INPUT_BOX["Input Guardrails"]
        INPUT_GUARD["๐Ÿ›ก๏ธ Input Guardrails<br/><i>PII redaction, injection detection,<br/>rate limiting, validation</i>"]
    end

    %% ===== DATA LAYER =====
    subgraph DATA_LAYER["Databases"]
        direction TB
        VECTORDB[("๐Ÿ”ฎ Vector Database<br/><i>Pinecone / Weaviate / Local</i>")]
        DOCS[("๐Ÿ“„ Documents<br/><i>In-memory store</i>")]
        CHAT_HIST[("๐Ÿ’ฌ Chat History")]
    end

    %% ===== READ/WRITE ACTIONS =====
    subgraph ACTIONS["Actions"]
        direction TB
        
        subgraph READ_ACT["Read-only Actions"]
            VEC_SEARCH["๐Ÿ” Vector Search<br/><i>Semantic + Hybrid</i>"]
            MULTI_QUERY["๐Ÿ”„ Multi-Query RRF<br/><i>Reciprocal Rank Fusion</i>"]
            WEB_SEARCH["๐ŸŒ Web Search<br/><i>arXiv, PubMed, etc.</i>"]
        end
        
        subgraph WRITE_ACT["Write Actions"]
            ADD_DOC["๐Ÿ“ฅ Add Documents"]
            DEL_DOC["๐Ÿ—‘๏ธ Delete Documents"]
            CLEAR_DB["๐Ÿงน Clear Database"]
        end
    end

    INPUT_GUARD --> VEC_SEARCH
    INPUT_GUARD --> MULTI_QUERY
    VEC_SEARCH <--> VECTORDB
    VEC_SEARCH <--> DOCS
    MULTI_QUERY <--> VECTORDB
    WEB_SEARCH --> VEC_SEARCH

    %% ===== MODEL GATEWAY =====
    subgraph MODEL_GW["Model Gateway<br/>(AIClient)"]
        direction TB
        ROUTING["๐Ÿ”€ Routing<br/><i>Provider selection</i>"]
        GENERATION["โšก Generation<br/><i>Text generation</i>"]
        EMBEDDING["๐Ÿงฌ Embedding<br/><i>Vector generation</i>"]
        SCORING["๐Ÿ“Š Scoring<br/><i>Similarity calculation</i>"]
        
        ROUTING --> GENERATION
        ROUTING --> EMBEDDING
        GENERATION --> SCORING
    end

    VEC_SEARCH --> EMBEDDING
    EMBEDDING <--> EMB_CACHE
    MULTI_QUERY --> GENERATION

    %% ===== OUTPUT GUARDRAILS =====
    subgraph OUTPUT_BOX["Output Guardrails"]
        OUTPUT_GUARD["๐Ÿ›ก๏ธ Output Guardrails<br/><i>Safety/verification,<br/>hallucination detection,<br/>structured outputs</i>"]
    end

    GENERATION --> OUTPUT_GUARD

    %% ===== FINAL RESPONSE =====
    FINAL_RESP["๐Ÿ“ค Final Response"]
    OUTPUT_GUARD --> FINAL_RESP
    FINAL_RESP -->|"Response"| USER

    %% ===== LOGGING & MONITORING =====
    subgraph LOGGING["Logging, Monitoring, and Analytics"]
        direction LR
        TELEMETRY["๐Ÿ“ˆ Telemetry"]
        EVAL_STORE["๐Ÿ“‹ Evaluations<br/><i>Quality metrics</i>"]
        RATE_LIMIT["โฑ๏ธ Rate Limiting"]
    end

    ORCH -.-> TELEMETRY
    MODEL_GW -.-> TELEMETRY
    VECTORDB -.-> TELEMETRY
    OUTPUT_GUARD -.-> EVAL_STORE
    INPUT_GUARD -.-> RATE_LIMIT

    %% ===== DOCUMENT INGESTION PATH =====
    USER -->|"PDF Upload"| PDF_PROC
    subgraph INGEST["Document Ingestion"]
        PDF_PROC["๐Ÿ“„ PDF Parser<br/><i>Text extraction</i>"]
        CHUNKING["โœ‚๏ธ Chunking<br/><i>Adaptive sizing</i>"]
        EMB_GEN["๐Ÿงฌ Embedding Gen"]
        PDF_PROC --> CHUNKING --> EMB_GEN
    end
    EMB_GEN --> ADD_DOC
    ADD_DOC --> VECTORDB
    ADD_DOC --> DOCS

    %% ===== STYLING =====
    classDef userNode fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px,color:#1b5e20
    classDef cacheNode fill:#fff3e0,stroke:#ef6c00,stroke-width:2px
    classDef guardNode fill:#ffebee,stroke:#c62828,stroke-width:2px
    classDef dataNode fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
    classDef actionNode fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
    classDef modelNode fill:#e0f2f1,stroke:#00695c,stroke-width:2px
    classDef logNode fill:#fafafa,stroke:#616161,stroke-width:1px,stroke-dasharray: 5 5
    classDef responseNode fill:#c8e6c9,stroke:#388e3c,stroke-width:2px

    class USER userNode
    class CACHE_IN,EMB_CACHE cacheNode
    class INPUT_GUARD,OUTPUT_GUARD guardNode
    class VECTORDB,DOCS,CHAT_HIST dataNode
    class VEC_SEARCH,MULTI_QUERY,WEB_SEARCH,ADD_DOC,DEL_DOC,CLEAR_DB actionNode
    class ROUTING,GENERATION,EMBEDDING,SCORING modelNode
    class TELEMETRY,EVAL_STORE,RATE_LIMIT logNode
    class FINAL_RESP responseNode

โœ… NEWLY IMPLEMENTED Components (Dec 2024)

ComponentLocationDescription
Query Response Cachelib/query-processor.tsFull queryโ†’response caching with 30min TTL, LRU eviction, document-aware invalidation
LLM Query Rewritinglib/query-processor.tsAI-powered query reformulation for better retrieval
HyDElib/query-processor.tsHypothetical Document Embeddings - generates ideal answer for semantic search
Step-back Promptinglib/query-processor.tsGenerates broader questions for complex queries to get foundational context
Query Classificationlib/query-processor.tsClassifies queries (factual, analytical, comparative, etc.) for optimal processing
Cache Invalidationlib/rag-engine.tsAutomatic cache invalidation when documents are added/removed

โš ๏ธ REMAINING Gaps

ComponentStatusNotes
Write Actionsโš ๏ธ LimitedOnly document add/delete, no external writes (emails, etc.)
Model Routingโš ๏ธ BasicProvider switching exists, no cost/latency-based intelligent routing
Streaming CacheโŒ MissingCached responses don't support streaming

โœ… PREVIOUSLY IMPLEMENTED Components

ComponentLocationDescription
Embedding Cachelib/ai-client.ts:59-137LRU cache with 30min TTL, max 1000 entries
Input Guardrailslib/guardrails.ts:33-86Query validation, injection detection, PII check
Output Guardrailslib/guardrails.ts:205-273Toxicity scoring, hallucination detection
Rate Limitinglib/guardrails.ts:276-346Per-session rate limiting
Query Enhancementapi/search/unified/route.ts:449-534Acronym expansion, synonyms, spell check
Multi-Query RRFlib/rag-engine.tsReciprocal Rank Fusion for retrieval
Evaluation Metricslib/guardrails.ts:348-619Retrieval & generation quality metrics
Telemetrylib/telemetry.tsDocument tracking, query logging

Key Components

  1. User Interface

    • Chat Interface: Handles user interactions and displays responses
    • Document Library: Manages uploaded PDFs and documents
    • Configuration Panel: For system settings and preferences
  2. API Layer

    • Search Handler: Processes search queries and returns results
    • Vector DB Handler: Manages vector database operations
    • PDF Processor: Extracts and processes text from uploaded PDFs
  3. Core Services

    • RAG Engine: Orchestrates the retrieval-augmented generation process
    • AI Client: Interfaces with language models for text generation
    • Vector DB Client: Handles vector storage and retrieval
    • Document Store: Manages document metadata and content
  4. External Services

    • Vector Database: Pinecone/Weaviate for similarity search
    • AI Models: HuggingFace/OpenAI for embeddings and text generation
    • Local Storage: For document persistence

Data Flow

  1. Document Ingestion

    • User uploads PDF โ†’ PDF Processor extracts text โ†’ Text is chunked โ†’ Chunks are embedded โ†’ Stored in Vector DB
  2. Query Processing

    • User submits query โ†’ Query is embedded โ†’ Similar chunks retrieved โ†’ Context sent to LLM โ†’ Response returned to user
  3. Context Management

    • System maintains conversation history and document context
    • Vector DB enables semantic search across all processed documents

What's inside

1 Mermaid flowchart, 3 status tables, 4 key component lists, 3 data flow descriptions

Change this for your project

  • Replace lib/query-processor.ts with your own query processor path
  • Replace lib/rag-engine.ts with your own RAG engine path
  • Replace lib/ai-client.ts with your own AI client path
  • Replace lib/guardrails.ts with your own guardrails path

Where it goes

Save in docs/ or the repository root. Gives agents and new contributors a map of the codebase.

Worth borrowing

  • Separate read-only and write actions to clarify system boundaries
  • Use a cache layer with TTL and LRU eviction before hitting the RAG pipeline
  • Add a table of implemented vs. missing components to track project maturity

Related Documents