Grounded RAG Assistant for Automotive Documentation

Hard · System Design · Software Engineer · Technical Screen

Prompt

Architect a Retrieval-Augmented Generation (RAG) question-answering assistant over an automotive manufacturer's technical library and structured fleet datasets.

Corpus profile & workload: - Content categories: powertrain specification books, diagnostic and repair guides, regional warranty booklets, and structured vehicle reference datasets. - File formats: PDF manuals (ranging from single-page bulletins up to 1,000-page shop manuals), HTML and Markdown articles, and CSV tables that may span millions of rows. - Traffic & mutability: overwhelmingly read-dominated chat workload; once published, files are never edited in place, though revised editions are periodically added alongside older versions.

Functional expectations: - Accept conversational questions—for example, "How much ATF fluid does a 2023 AWD transmission drain-and-fill take?" or "Does corrosion coverage apply to a five-year-old Canadian hatchback?"—and synthesize answers strictly supported by the retrieved material. - Attach verifiable source citations pinpointing the exact document edition plus page region, heading anchor, or table row span. - Query both unstructured text/tables inside manuals and large structured CSV datasets seamlessly.

Scope & Expectations

  • End-to-end architecture & data model: Present both the asynchronous ingestion/indexing pipeline and the low-latency online query flow, along with schemas for versioned documents, citable chunks, metadata, and structured CSV tables.
  • Format-aware parsing, indexing & hybrid retrieval: Justify your vector/search engine strategy and explain how multi-hundred-page PDFs, HTML/Markdown pages, and massive CSVs are parsed, chunked, embedded, and queried without losing layout context or citation coordinates.
  • Service targets, access control & observability: Propose concrete latency, throughput, and quality goals; enforce entitlement filtering across vehicle trims, markets, and user roles; and detail retrieval diagnostics, failure fallbacks, and core design trade-offs.

Step-by-step walkthrough

  1. Clarify requirements, vehicle context, and quality targets

    RAG (Retrieval-Augmented Generation) is a pattern where a search system first fetches relevant passages from trusted documents and passes them into a Large Language Model (LLM) so the model answers from those passages instead of relying on memory. What makes vehicle documentation uniquely unforgiving compared to generic company wikis is that the exact same question has different right answers depending on the vehicle, and a wrong number looks completely plausible:

    • Pouring 8.3 L of transmission fluid instead of 4.8 L during a routine drain-and-fill because the retriever pulled the dry overhaul row or the FWD manual instead of the 2.5L AWD drain-and-fill specification overfills and damages the gearbox.
    • Telling an owner their rusted fender panel is covered under corrosion warranty because the retriever used the 2026 Canadian booklet (7 years) instead of the 2021 Canadian booklet (5 years / 100,000 km) active on their car's delivery date creates legal liability.

    Therefore, our entire architecture centers on explicit vehicle scoping, structure-preserving parsing, verifiable page/row citations, and refusing to guess.

    Clarifying assumptions

    • Users & entitlements: three user tiers authenticated via single sign-on: vehicle owners (public owner manuals and warranty booklets), dealer technicians (service/repair manuals and diagnostic bulletins), and internal warranty/engineering staff (all docs plus internal vehicle datasets).
    • Vehicle context: requests usually carry a VIN (Vehicle Identification Number) — a 17-character code decoded automatically into model, model_year, engine, region, and in_service_date — or explicit vehicle attributes. When a question's answer depends on missing vehicle attributes, the assistant must ask a clarifying question.
    • Document lifecycle: documents are immutable once published; updates arrive as brand-new versions (2024-03 superseding 2023-09), and historical warranty versions must stay searchable by in_service_date.

    Proposed non-functional targets

    Latency       Retrieval + reranking:  p95 < 500 ms
                  Time to first token:    p95 < 2.5 s (general prose procedures)
                  Full verified answer:   p95 < 8.0 s (numeric spec & warranty answers are verified
                                          against cited text before display so wrong numbers never flash)
    Throughput    ~250,000 questions/day (~3 req/s average, 30 req/s peak during service-bay hours)
    Quality       Retrieval Recall@8 >= 90% on expert golden set (gold passage inside top 8 sent to LLM)
                  Numeric specification accuracy >= 98%; citation support precision >= 95%
                  Correct refusal / clarification on unanswerable or ambiguous queries >= 90%
    Security      Zero unauthorized chunks ever enter an LLM prompt (enforced in search + CI tests)
    Freshness     New manual or dataset version live within 1 hour of upload
    
  2. Back-of-the-envelope numbers for corpus, memory, and GPUs

    Sizing the text corpus, structured CSVs, vector memory, and GPU compute immediately steers three big architectural choices:

    1. Corpus Size & Chunk Count (1 token ≈ 0.75 English words)
       PDF manuals       20,000 files x ~150 pages avg = 3M pages x ~500 tokens/page = 1.5B tokens
       HTML / Markdown   50,000 articles x ~1,000 tokens                             = 50M tokens
       Small CSV tables  ~5M reference rows grouped into 20-row chunks               = 250k chunks
       Large CSV files   ~1B rows (~200 GB raw: VIN build sheets, parts, recalls)    -> SQL warehouse!
    
       Text chunking (~400 tokens/chunk, 50-token overlap -> 350-token stride):
         1.55B text tokens / 350 ≈ 4.43M text chunks + 0.25M small-CSV chunks        ≈ 4.7M (~5M) chunks
         (One newly published 1,000-page service manual adds ~1,400 chunks)
    
    2. Search & Vector Index Footprint (5M chunks, 1024-dim embeddings)
       Float32 vectors   5M x 1,024 dims x 4 bytes                                   ≈ 20.5 GB
       Int8 quantized    5M x 1,024 dims x 1 byte                                    ≈ 5.1 GB
       HNSW graph links  5M x 32 neighbor IDs x 4 bytes + overhead                   ≈ 1.0 GB
       Chunk text + BM25 5M x ~2 KB text/metadata + inverted keyword index           ≈ 13 GB on NVMe
       -> Entire 5M-chunk index fits comfortably in RAM on a single 64 GB node!
          (We run 2 shards x 3 replicas = 6 nodes purely for HA and 30 req/s read headroom.)
    
    3. Ingestion & Query-Time GPU Math
       Initial corpus embed (~335M-param encoder, ~0.67 GFLOP/token -> ~270 GFLOP/chunk):
         1 A100-class GPU (~130 TFLOP/s effective) embeds ~480 chunks/s
         5M chunks take ~2.9 hours on 1 GPU (or ~22 minutes across 8 GPUs)
       Peak query reranking (30 req/s x 40 candidate pairs x ~450 tokens ≈ 12 TFLOP/question):
         ~100 ms GPU compute/question -> 30 x 0.10 s = 3.0 GPUs active -> 6 GPUs for low-queue p95
       Peak LLM token budget (30 req/s):
         Input:  ~4,000 tokens/req (system + history + 8 chunks) -> 120k input tokens/s (~1B/day)
         Output: ~250 tokens/req                                 -> 7.5k output tokens/s (~62.5M/day)
    

    Three takeaways leap out of these numbers:

    1. 5 million chunks is modest (~22 GB of float32 vectors) — we do not need exotic billion-vector sharding; metadata filtering, keyword+vector hybrid accuracy, and clean operations matter far more.
    2. Never embed 1 billion CSV rows into a vector database. Turning 1 billion VIN/recall rows into vectors would blow up index RAM 200x (> 4 TB) while still failing basic exact lookups and counts ("How many 2022 sedans have open recall 22V-410?"). Large CSVs belong in a columnar SQL engine, bridged into RAG via lightweight dataset description cards.
    3. LLM input tokens dominate cost and latency (1B tokens/day), so spending ~100 ms on a reranker to send 8 high-precision chunks instead of 20 noisy ones pays for itself in lower LLM bills and fewer hallucinations.
  3. Chat, citation, and ingestion APIs

    Every chat call authenticates the caller (deriving roles and allowed_regions from their token) and passes structured vehicle context alongside the message:

    POST /v1/chat
      Request:
      {
        "conversation_id": "conv-81f2",
        "message": "How much ATF fluid does a transmission drain-and-fill take?",
        "vehicle": {"vin": "JM3KFBCM0P0100042"}   // or {"model", "model_year", "engine", "region"}
      }
    
      Response (Server-Sent Events):
        event: token   {"text": "A drain-and-fill on the 6-speed AWD automatic transmission..."}
        event: final
        {
          "request_id": "req-9c1e",
          "status": "ANSWERED",   // or "NEEDS_CLARIFICATION" | "NOT_FOUND"
          "answer": "A drain-and-fill on the 6-speed AWD automatic transmission takes 4.8 L of ATF-FZ fluid [C1].",
          "clarifying_question": null,
          "citations": [
            {
              "marker": "C1",
              "source_type": "pdf",
              "doc_id": "doc-2023-06-trans-awd",
              "title": "2.5L AWD Transmission Service Manual",
              "version": "2023-06",
              "section": "5.2 Automatic Transmission > Fluid Specifications",
              "page_start": 184,
              "page_end": 184,
              "highlights": [{"page": 184, "bbox": [68, 340, 536, 402]}]
            }
          ]
        }
    
    GET  /v1/documents/{doc_id}/pages/{page_no}     // returns rendered page image (re-checks user ACL!)
    POST /v1/feedback                               // {"request_id", "rating": "up"|"down", "reason"}
    POST /v1/internal/ingest                        // {"source_uri", "family_id", "version", "acl", ...}
    

    When a user clicks [C1] in the UI, GET /v1/documents/{doc_id}/pages/184 re-verifies the user's entitlement and renders page 184 with the bounding box ([x1, y1, x2, y2] pixel coordinates captured during PDF parsing) highlighted in yellow so a mechanic can visually verify 4.8 L in two seconds.

  4. Data model for versioned documents, chunks, and datasets

    Relational metadata lives in PostgreSQL, raw files and rendered page PNGs live in Object Storage (S3), searchable chunks live in OpenSearch, and large structured CSVs live in a Columnar SQL Warehouse:

    1. PostgreSQL: Document & Version Registry (Source of Truth for Lifecycle & Active Versions)
       documents (
         doc_id          PK,                 -- e.g. "doc-2024-03-eng20" (immutable once ingested)
         family_id       TEXT,               -- groups versions of the same manual ("eng20-service")
         version         TEXT,               -- "2024-03"
         doc_type        ENUM,               -- engine_spec | repair | warranty | owner | dataset_card
         format          ENUM,               -- pdf | html | md | csv
         effective_from  DATE,               -- for warranty booklets (matched against in_service_date)
         effective_to    DATE,               -- '9999-12-31' sentinel while open-ended so range filters work
         applicability   JSONB,              -- {models[], model_years[], engines[], regions[]}
         acl             JSONB,              -- {audiences: [public|dealer|internal], regions[]}
         status          ENUM,               -- INGESTING | EVALUATING | LIVE | SUPERSEDED | FAILED
         is_latest       BOOLEAN,            -- flipped atomically in 1 SQL transaction on publish!
         checksum_sha256 TEXT UNIQUE
       )
    
    2. OpenSearch: Immutable Chunk Index (BM25 Keywords + 1024-d HNSW Vectors + Filter Fields)
       chunk_doc {
         chunk_id, doc_id, family_id, version, doc_type,
         chunk_type:    "prose" | "pdf_table" | "csv_group" | "dataset_card",
         section_path:  "2.5L AWD Transmission Service Manual > 5 Transmission > 5.2 Fluid Specifications",
         page_start, page_end, highlights: [{page, bbox}],   -- PDF citation coordinates
         html_anchor,                                        -- "#fluid-specifications" for HTML/MD
         csv_file, row_start, row_end,                       -- 1-based row span for small CSVs
         display_text:  "<clean markdown table or prose shown to LLM and user>",
         embed_text:    "[Model: CX-50 | Year: 2023 | Engine: 2.5L AWD | 5.2 Fluid Specs]\n<display_text>",
         -- Denormalized filter arrays for single-query pre-filtering:
         audiences[], allowed_regions[], models[], model_years[], engines[],
         effective_from, effective_to, low_ocr_confidence
       }
    
    3. SQL Warehouse Registry (for Large CSVs)
       datasets (dataset_id, version, table_name, column_schemas_json, acl, row_security_view)
    

    Notice three deliberate modeling decisions:

    • Separate embed_text from display_text. Two fluid-capacity tables from the 2.5L FWD and 2.5L AWD manuals often contain nearly identical words ("Drain and fill | 3.9 L" vs "Drain and fill | 4.8 L"). Prepending the vehicle and section breadcrumb ([Model: ... | Engine: 2.5L AWD | ...]) into embed_text and the BM25 field ensures both vector and keyword search distinguish them cleanly.
    • Zero-rewrite atomic version publishing. In Lucene-based search engines, updating a flag on 1,400 chunks rewrites their vectors and exposes half-updated manuals across 1-second index refreshes! Instead, chunks are indexed once, immutably under doc_id. Because documents has only ~20,000 rows (~320 KB in orchestrator memory, updated instantly via Postgres notification), flipping status = LIVE, is_latest = true on v2 and is_latest = false on v1 in one Postgres transaction switches the active doc_id filter atomically for all readers with zero vector rewrites!
    • Denormalize ACL and vehicle fields onto every chunk so access control and vehicle filtering execute inside the single OpenSearch retrieval pass rather than via slow, leaky post-joins.
  5. High-level ingestion and query architecture

    ======================== OFFLINE / ASYNC INGESTION PIPELINE ========================
    
      CMS / S3 Drops ---> [Ingest Queue] ---> [Format-Specific Parsers]
                                                |- PDF: layout + native text / OCR + table extractor
                                                |- HTML/MD: DOM heading tree + anchor preservation
                                                \- CSV Profiler:
                                                     <= 50k rows -> 20-row text chunks + SQL table
                                                     >  50k rows -> Columnar SQL Warehouse + Dataset Card
                                                           |
                                                           v
                          [Smoke Eval Gate] <--- [GPU Embedders] <--- [Structure-Aware Chunker]
                          (golden Qs pass?)            |
                                 | yes                 v
                                 +---> Flip doc_id LIVE in Postgres (atomic cutover!) + bump cache epoch
    
    ======================== ONLINE QUERY FLOW (p95 < 2.5s / 8s) =======================
    
      User + Token + VIN ---> [API Gateway] ---> [Stateless Chat Orchestrator]
                                                   | 1. Decode VIN + fetch user ACL + active doc_ids
                                                   | 2. Query Analyzer (intent, entities, clarify check)
                                                   +--------------------+--------------------+
                                                   | (Unstructured)     | (Structured CSV)   |
                                                   v                    v                    |
                                       [OpenSearch Hybrid Query]   [Read-Only SQL Tool]      |
                                       (BM25 + HNSW w/ pre-filter) (RLS-enforced views)      |
                                                   |                    |                    |
                                                   v                    |                    |
                                       [RRF Merge -> GPU Reranker]      |                    |
                                           (top 40 -> top 8)            |                    |
                                                   \--------------------+                    |
                                                            |                                |
                                                            v                                |
                                             [Grounded LLM Generation]                       |
                                                            |                                |
                                                            v                                |
                                        [Deterministic Citation & Number Verifier] ----------+
                                          (pass -> emit answer; fail -> retry / extractive fallback)
    

    Ingestion and live chat are completely decoupled: even if 50 new 1,000-page service manuals land in the ingest queue simultaneously, GPU embedding workers chew through the queue asynchronously without adding a millisecond to user chat latency.

  6. Processing PDFs, HTML, and CSVs into citable chunks

    Naive fixed-size chunking ("split every 400 tokens regardless of layout") wrecks vehicle manuals: it slices a fluid specification table right between the column headers on row 1 and "4.8 L" on row 19, or chops step 7 of a brake-bleeding procedure away from the safety depressurization warning in step 1!

    PDF processing rules (1 to 1,000 pages):

    1. Layout-aware extraction + OCR confidence: extract text blocks with (page_no, [x1, y1, x2, y2]) bounding boxes from the PDF text layer. Pages lacking a text layer (scanned legacy manuals) run through OCR (Optical Character Recognition) — vision models that read text and tables from images — recording ocr_confidence per page so low-confidence digits can be flagged for human review.
    2. Keep tables intact (or repeat headers on splits): extracted tables are rendered as clean Markdown tables. Tables under ~600 tokens stay as one atomic chunk; huge multi-page tables split into 20-row sub-tables where every chunk repeats the table caption and column header row so no number ever loses its row/column label.
    3. Respect section and procedure boundaries: prose chunks target ~350–400 tokens with ~50 tokens of overlap, never crossing a heading boundary and splitting numbered repair steps only between steps:
    from typing import Any, Dict, List
    
    
    def build_chunk(blocks: List[Dict[str, Any]]) -> Dict[str, Any]:
        """Combine consecutive layout blocks from the same section into one citable chunk."""
        return {
            "section": blocks[0]["section"],
            "page_start": blocks[0]["page"],
            "page_end": blocks[-1]["page"],
            "chunk_type": blocks[0]["kind"],
            # Keep every block's (page, bbox) so the UI can highlight exact regions on click
            "highlights": [{"page": b["page"], "bbox": b["bbox"]} for b in blocks],
            "display_text": "\n".join(b["text"] for b in blocks),
        }
    
    
    def chunk_pdf_blocks(blocks: List[Dict[str, Any]], max_words: int = 300) -> List[Dict[str, Any]]:
        """Group parsed blocks in reading order without cutting across sections or tables."""
        chunks: List[Dict[str, Any]] = []
        current_group: List[Dict[str, Any]] = []
        current_words = 0
    
        for block in blocks:
            block_words = len(block["text"].split())
            is_table = block["kind"] == "pdf_table"
            crossed_section = bool(current_group) and block["section"] != current_group[0]["section"]
            exceeds_budget = bool(current_group) and (current_words + block_words > max_words)
    
            # Flush accumulated prose before starting a table, new section, or full chunk
            if current_group and (is_table or crossed_section or exceeds_budget):
                chunks.append(build_chunk(current_group))
                current_group = []
                current_words = 0
    
            # Emit each extracted table (or header-augmented table slice) as its own chunk
            if is_table:
                chunks.append(build_chunk([block]))
                continue
    
            current_group.append(block)
            current_words += block_words
    
        if current_group:
            chunks.append(build_chunk(current_group))
        return chunks
    

    HTML, Markdown, and the two-tier CSV strategy:

    • HTML / Markdown: split along <h1>..<h3> DOM headings after stripping navbars, storing #heading-anchor for direct link citations.
    • Small reference CSVs (<= 50k rows, e.g., fluid capacities or fuse maps): chunk into 20-row col_name: value blocks with headers repeated, recording csv_file and row_start..row_end for row-level citations (and also load into SQL).
    • Large dataset CSVs (> 50k up to 1B rows, e.g., VIN recall tables or parts catalogs): bulk-load into columnar Parquet/SQL warehouse tables behind Row-Level Security (RLS) views (database views that automatically filter rows by the caller's role and region). Index one dataset_card chunk per table in OpenSearch describing its schema, sample values, and example questions; when retrieved, the orchestrator invokes a read-only SELECT SQL tool (with LIMIT, timeout, and AST allowlist) and cites {dataset_id, version, sql_query, row_keys}.
  7. Hybrid retrieval, access-control pre-filtering, and vector store choice

    Step 1 — Query analysis & ambiguity guard (~120 ms): a fast small model + regex extractor pulls out fault codes (P0301), part numbers, and vehicle attributes, merging them with the decoded VIN and classifying intent (spec, procedure, warranty, dataset). If a user asks "How much ATF fluid does a drain-and-fill take?" with no VIN, and retrieval finds conflicting capacities across the 2.5L FWD and 2.5L AWD drivetrains, the orchestrator immediately returns status = NEEDS_CLARIFICATION ("Which drivetrain does your vehicle have: 2.5L FWD or 2.5L AWD?") rather than guessing!

    Step 2 — Orchestrator-built mandatory pre-filters (never generated by the LLM!):

    Mandatory OpenSearch Filter Clause (Built in Deterministic Code)
      AND doc_id        IN active_doc_ids_from_snapshot   -- latest LIVE docs (or effective_date match
                                                          -- on in_service_date for warranty queries!)
      AND audiences     INTERSECTS user.roles             -- public | dealer | internal
      AND allowed_regions CONTAINS user.region            -- e.g. "US", "EU"
      AND (models CONTAINS vehicle.model OR models CONTAINS "ALL")
      AND (engines CONTAINS vehicle.engine OR engines CONTAINS "ALL")
    

    Why pre-filtering (applying filters during index search) instead of post-filtering (fetching global top-50 vectors and dropping unauthorized chunks afterwards)? If a vehicle owner is entitled to see only 2% of the corpus (public manuals for one car), global top-50 vector search might return 50 dealer-only repair chunks, leaving zero results after post-filtering! Pre-filtering guarantees full recall within the user's allowed slice and ensures unauthorized text never even enters orchestrator memory (we still re-verify chunk ACLs in code before prompt assembly as defense-in-depth).

    Step 3 — Hybrid search (BM25 + HNSW) -> Reciprocal Rank Fusion -> Cross-Encoder Rerank:

    • BM25 (classic keyword scoring based on exact term frequency and rarity) nails exact strings like fault code P0420, part 11127555212, or bolt size M10x1.5 where dense embeddings blur similar codes together.
    • Dense vector search using HNSW (Hierarchical Navigable Small World) — a multi-layer proximity graph over 1024-d embeddings — catches semantic paraphrases like "car shudders at idle" matching "rough idle misfire diagnosis".
    • Both run in parallel (top 50 each) and merge via Reciprocal Rank Fusion (RRF) — combining rank positions rather than raw incompatible scores:
    from typing import Dict, List
    
    
    def reciprocal_rank_fusion(ranked_lists: List[List[str]], k: int = 60) -> List[str]:
        """Fuse multiple ranked chunk-ID lists using 1 / (k + rank) without score calibration."""
        fused_scores: Dict[str, float] = {}
        for ranked_ids in ranked_lists:
            for rank, chunk_id in enumerate(ranked_ids, start=1):
                # k=60 smooths top ranks so a chunk strong in BOTH BM25 and vector beats a fluke #1
                fused_scores[chunk_id] = fused_scores.get(chunk_id, 0.0) + 1.0 / (k + rank)
    
        return sorted(fused_scores, key=lambda cid: fused_scores[cid], reverse=True)
    

    Finally, a cross-encoder reranker (a transformer that reads (question, chunk_text) side by side with full cross-attention across all tokens, unlike separate bi-encoder embeddings) scores the top 40 fused candidates on GPU in ~100–120 ms and hands the sharpest 8 chunks to the LLM.

    Why OpenSearch / Elasticsearch over alternatives? At 5M chunks (~22 GB), running one engine that executes strong BM25 keyword search, HNSW vector traversal, and metadata pre-filters in a single query beats stitching a dedicated vector DB (Milvus/Qdrant) to a separate keyword index, and provides stronger BM25 + horizontal read replicas than pgvector alone.

  8. Grounded generation, numeric citation checks, and safe fallbacks

    The orchestrator formats the top 8 chunks as numbered blocks [C1] .. [C8] with explicit vehicle/version headers and instructs the LLM: (1) answer strictly from [C1]..[C8], ending every factual sentence with its [Ci] tag(s); (2) copy numbers and units verbatim (if the user asks for US quarts when the manual lists 4.8 L, a deterministic Python unit converter injects 4.8 L = 5.1 US qt into the prompt context so the LLM never does mental math!); and (3) output NOT_FOUND if the passages do not answer the question.

    Before finalizing any answer (and before showing tokens at all for spec and warranty intents), a fast deterministic verifier checks every sentence in < 2 ms:

    import re
    from typing import Dict, List, Set, Tuple
    
    CITATION_RE = re.compile(r"\[(C\d+)\]")
    # Matches integers, comma-grouped thousands ("60,000"), and decimals ("40.5")
    NUMBER_RE = re.compile(r"\d(?:[\d,]*\d)?(?:\.\d+)?")
    
    
    def extract_normalized_numbers(text: str) -> Set[str]:
        """Extract numeric literals with thousands commas stripped ('60,000' -> '60000')."""
        return {match.replace(",", "") for match in NUMBER_RE.findall(text)}
    
    
    def verify_answer_sentence(
        sentence: str,
        sources_by_id: Dict[str, str],
        user_question: str,
    ) -> Tuple[List[str], List[str]]:
        """Verify citations exist and every stated number appears in a cited source or the question."""
        cited_ids = CITATION_RE.findall(sentence)
        issues: List[str] = []
        if not cited_ids:
            issues.append("missing citation marker")
    
        # Numbers already mentioned by the user (e.g. "at 70,000 miles") are allowed in the reply
        allowed_numbers = extract_normalized_numbers(user_question)
        for cid in cited_ids:
            if cid not in sources_by_id:
                issues.append(f"hallucinated source marker {cid}")
            else:
                allowed_numbers.update(extract_normalized_numbers(sources_by_id[cid]))
    
        # Strip "[C1]" markers first so the digit "1" inside "[C1]" is not checked as a claim!
        claim_text = CITATION_RE.sub("", sentence)
        for num in extract_normalized_numbers(claim_text):
            if num not in allowed_numbers:
                issues.append(f"unsupported number {num}")
    
        return cited_ids, issues
    

    If verify_answer_sentence flags an issue (or if a cited chunk's engines[] disagrees with the decoded VIN), the orchestrator retries generation once with the error feedback; if the retry still fails, it falls back to extractive mode — displaying the top retrieved specification table and highlighted PDF page directly without LLM synthesis. Showing a mechanic the exact table row beats risking a fabricated fluid volume!

  9. ML framing: labels, features, models, offline metrics, and A/B testing

    To iterate scientifically instead of tuning prompts by gut feel, we treat retrieval and grounded generation as measurable ML stages:

    • Problem framing & evaluation labels: build a stratified 1,000-question expert golden set authored by master technicians and warranty specialists (30% specs, 25% procedures, 25% warranty date/region cases, 10% CSV dataset queries, 10% unanswerable/ambiguous traps). Each item records (vehicle_context, question, gold_chunk_ids, exact_expected_numbers, expected_outcome). Supplement long-tail coverage with LLM-synthesized questions vetted by experts, plus online signals (thumbs up/down with reason tags, citation click-throughs, support escalations).
    • Ranking features & models: four cooperating models power the pipeline — (1) a lightweight intent/entity classifier, (2) a 1024-d bi-encoder embedding model (fine-tuned on domain (question, gold_chunk) pairs once collected), (3) a cross-encoder reranker, and (4) the grounded generator / text-to-SQL LLM. Once click and expert-judgment logs accumulate, a lightweight gradient-boosted second-stage ranker can combine bm25_score, cosine_sim, cross_encoder_logit, exact_engine_match, and chunk_type == pdf_table (for spec queries).
    • Offline CI gate metrics:
      • Retrieval: Recall@40 (fraction of queries where the gold chunk enters the reranker) and Recall@8 / MRR (Mean Reciprocal Rank — average of 1 / first_gold_rank) after reranking.
      • Generation & citations: exact numeric match on spec questions (>= 98%), entailment / faithfulness (whether cited text logically supports every sentence, scored by a calibrated judge model validated against 200 human-graded answers), citation precision/recall, and refusal precision/recall on unanswerable traps.
    • Online A/B testing: randomize by user_id (never per request, which gives inconsistent behavior mid-conversation) for at least 1–2 full weeks to capture weekday dealer traffic and weekend DIY owner traffic. Track task resolution rate without human support escalation and helpful rating rate (using user-clustered standard errors because power users submit multiple ratings) as primary metrics, guarded by p95 latency, cost/query, thumbs-down rate, and a mandatory human expert audit of 200 sampled spec/warranty answers per treatment arm.
  10. Latency budget, scaling, observability, failure modes, and trade-offs

    End-to-End p95 Query Latency Budget
      Auth + VIN decode + active doc_id snapshot   ~20 ms   (in-memory / session cache)
      Query analysis (intent + entity extraction)  ~120 ms  (skipped on simple same-vehicle follow-ups)
      Query embedding (GPU)                        ~25 ms
      OpenSearch BM25 + HNSW pre-filtered search   ~60 ms   (parallel across shards)
      Cross-encoder rerank (40 pairs on GPU)       ~120 ms
      Prompt assembly + ACL defense-in-depth       ~10 ms   ---> Retrieval subtotal: ~355 ms (< 500 ms!)
      LLM first token / full generation (~250 tok) ~1.2 s TTFT  /  ~4.5 s full answer (< 8.0 s target!)
    

    Scaling, caching, and zero-downtime re-embedding:

    • Exact first-turn answer cache: because published manuals are static, caching answers under (normalized_query, vehicle_tuple, entitlement_key, vehicle_corpus_epoch, prompt_ver, model_ver) safely serves repeated questions ("atf drain and fill capacity 2023 2.5l awd") in ~20 ms while preventing cross-role ACL leaks. Scoping vehicle_corpus_epoch per (model, model_year) prevents an unrelated truck manual upload from invalidating crossover cache entries.
    • 10x corpus growth (50M chunks): shard OpenSearch across 8–10 primary shards and turn on int8 scalar quantization (4x less vector RAM while re-scoring the top 200 candidates against disk float32 vectors to preserve recall). When upgrading the embedding model, build a parallel index in the background (blue/green indexing), pass the golden evaluation gate, and swap the index alias atomically — never mix vectors from two embedding models in one HNSW graph!

    Observability & critical failure modes:

    • Full-pipeline OpenTelemetry tracing & replay: every request_id logs the resolved filters, pre/post-filter hit counts, top BM25/vector/reranker chunk IDs and scores, prompt version, and verifier results so engineers can replay any bad answer deterministically. Alert on drops in top-1 reranker confidence (catches broken parsers or model drift early) and spikes in empty-filter or verifier-rejection rates.
    • Key failure defenses: flag low-OCR-confidence pages and route broken PDF tables to human QA; defend against prompt injection (malicious instructions hidden inside HTML/docs) by fencing sources as untrusted data and giving the SQL tool strictly read-only SELECT views; and if the LLM provider suffers an outage, automatically degrade to extractive search mode (returning the top reranked chunks and highlighted PDF pages directly) so technicians in service bays are never blocked.

    Summary of key trade-offs:

    • BM25 + vector hybrid search + cross-encoder reranking (~180 ms extra) vs. vector-only search: essential for exact fault/part codes and trims LLM context to 8 chunks, saving more time and money in LLM tokens than the reranker costs.
    • Dual storage (OpenSearch for prose/small tables + SQL Warehouse for billion-row CSVs) vs. embedding everything: adds a SQL tool path, but keeps vector RAM 200x smaller and makes aggregations and VIN lookups 100% exact.
    • Hold-until-verified responses on specs/warranty vs. instant token streaming: trades ~3–4 s of perceived first-token wait on numeric intents so an unverified fluid volume or false warranty promise never flashes on a user's screen.

Intuition & how it works

Think of a vehicle-documentation RAG (Retrieval-Augmented Generation) system — an architecture that searches trusted reference documents first and feeds the matching excerpts to a language model — like a master shop foreman standing beside a wall of versioned service binders and a parts computer. Before answering "How much ATF fluid does a transmission drain-and-fill take?", a good foreman never guesses from memory: they first check the car's VIN (Vehicle Identification Number) on the work order (2023 Crossover, 2.5L AWD, Canada), pull only the 2.5L AWD binder the caller is authorized to read, open the exact fluid-specification table on page 184, double-check every digit before speaking, and point their finger directly at row 3 of page 184 so the mechanic can verify it at a glance.

Why does a naive "chop every PDF and CSV into 500-character chunks, embed them in a vector database, and stream the LLM output" pipeline fail catastrophically here? First, fixed-size text splitting cuts specification tables apart — separating "4.8 L" from "6-speed AWD drain-and-fill" — and identically worded tables from the 2.5L FWD and 2.5L AWD manuals produce nearly identical embeddings (lists of floating-point numbers representing meaning), causing the retriever to feed the wrong drivetrain's fluid spec to the LLM! Second, embedding a 1-billion-row VIN recall CSV into vectors would bloat RAM 200x (> 4 TB) while still failing simple exact queries like "Does VIN JM3K... have an open recall?". Third, checking access permissions after vector search (post-filtering) returns zero results whenever a regular car owner's allowed manuals make up only 2% of a dealer-heavy corpus.

Walk through a concrete 4-step trace when a dealer technician asks "How much ATF fluid does a transmission drain-and-fill take?" with VIN -> 2023 Crossover, 2.5L AWD, CA:

1. Scope & Pre-Filter (Deterministic Code, ~20 ms):
   -> Orchestrator decodes VIN (2023 Crossover, 2.5L AWD, CA), verifies role = "dealer", and looks up
      the atomic LIVE doc_id set in memory (zero half-indexed manuals ever visible!).

2. Hybrid Search + Rerank (~300 ms):
   -> OpenSearch runs BM25 (exact keyword match on "ATF", "drain-and-fill") AND 1024-d HNSW vector
      search in parallel, pre-filtered to {audiences: dealer, engine: 2.5L AWD, is_latest: true}.
   -> Reciprocal Rank Fusion merges top-50 lists by rank; a GPU cross-encoder reranker scores
      the top 40 (question, chunk) pairs together and picks the top 8 chunks (including [C1]:
      the intact Markdown table from "2.5L AWD Transmission Manual v2023-06, Page 184").

3. Grounded Generation (~3.5 s):
   -> LLM reads [C1]..[C8] (each stamped with its vehicle/page breadcrumb) and drafts:
      "A drain-and-fill on the 6-speed AWD automatic transmission takes 4.8 L of ATF-FZ fluid [C1]."

4. Deterministic Verification & Highlight Citation (< 2 ms):
   -> Verifier strips "[C1]" and confirms "6" and "4.8" both appear verbatim inside [C1]
      (or the question) and that [C1]'s drivetrain metadata matches "2.5L AWD".
   -> Answer is released with [C1] linked to Page 184's bounding box [68, 340, 536, 402]!

Key trade-offs

  • Hybrid search (BM25 + dense vectors) vs. vector-only retrieval. Running BM25 (exact keyword frequency scoring) alongside dense vector search adds a second index structure and a Reciprocal Rank Fusion (RRF) merge step, but embeddings alone routinely confuse alphanumeric fault codes (P0301 vs P0304), thread sizes (M10 vs M12), and 12-digit part numbers where exact token matching is mandatory.
  • Cross-encoder GPU reranking vs. passing top-20 raw search hits to the LLM. A cross-encoder (a transformer scoring (query, passage) pairs jointly) adds ~100–120 ms and 6 GPUs at 30 req/s peak, but lifts top-8 precision enough to cut the LLM prompt from 20 chunks (~8,500 tokens) down to 8 chunks (~4,000 tokens) — saving more in LLM latency, token cost, and wrong-row errors than the reranker costs.
  • Structure-aware chunking vs. fixed-token sliding windows. Preserving PDF tables (repeating column headers across 20-row slices) and numbered repair procedures produces uneven chunk lengths and requires layout/OCR parsing, in exchange for never severing a numeric spec from its row label or a repair step from its safety warning.
  • Columnar SQL warehouse + dataset cards for large CSVs vs. embedding rows. Maintaining a read-only text-to-SQL tool alongside OpenSearch introduces SQL generation errors that need allowlist validation and retries, but keeps 1 billion structured rows out of vector RAM (~22 GB index instead of > 4 TB) and answers exact VIN lookups, filters, and counts with 100% precision.
  • Search-time pre-filtering vs. post-filtering. Denormalizing audiences[], regions[], models[], and engines[] onto every chunk so OpenSearch filters during traversal requires per-persona recall testing (since highly selective filters can prune HNSW graph paths), but prevents unauthorized chunks from ever entering application memory and preserves recall for restricted user roles.
  • Verify-before-display on numeric intents vs. immediate token streaming. Holding spec and warranty answers until the deterministic number/citation verifier finishes delays the first visible character from ~1.5 s to ~4–5 s, trading perceived chat snappiness for safety where flashing a hallucinated 8.3 L fluid volume on screen could cause mechanical damage.
  • Atomic metadata doc_id cutover vs. in-place chunk flag updates. Resolving active/latest doc_ids from a tiny ACID Postgres registry (~320 KB cached in memory) rather than rewriting is_latest flags on chunks inside OpenSearch avoids costly HNSW vector segment rewrites and guarantees readers never see a half-published manual across 1-second search refreshes.

Common mistakes

  • Indexing chunks without prepending vehicle and section breadcrumbs into embed_text. Raw table rows from a 2.5L FWD manual and a 2.5L AWD manual look almost identical in isolation; without [Model | Year | Engine | Section] baked into the embedded and BM25-indexed text, retrieval mixes drivetrain variants constantly.
  • Slicing PDFs at fixed 400-token boundaries and discarding (page, bounding_box) layout metadata, which destroys table headers and makes clickable page-highlight citations impossible to reconstruct at query time.
  • Embedding millions or billions of CSV rows into a vector index, wasting terabytes of memory while failing basic exact-match VIN lookups and aggregate counts.
  • Enforcing access control in the LLM prompt ("Ignore dealer chunks if user is an owner") or letting the LLM write its own security filters. Prompt instructions are easily bypassed via prompt injection; the orchestrator must construct ACL and Row-Level Security (RLS) filters deterministically from the user's verified auth token.
  • Letting the LLM perform unit conversions or mileage math in its head. If a manual states 4.8 L and the user asks for US quarts, an LLM-computed 5.1 is both error-prone and absent from the source text (breaking strict numeric verification); compute unit conversions in deterministic code and pass the converted value into the prompt context.
  • Always filtering by is_latest = true on warranty questions. Warranty coverage legally depends on the booklet whose [effective_from, effective_to) window covers the car's in_service_date, not today's newly revised booklet!
  • Tuning chunking, embeddings, or prompts by eye without a stratified expert golden set, making it impossible to notice that a change boosting prose fluency silently dropped numeric specification accuracy from 98% to 91%.

Follow-up questions

  • How should the assistant handle a multi-step question that requires joining structured VIN recall rows with a PDF repair manual? Equip the orchestrator with a bounded two-step plan (capped at <= 3 tool calls so tail latency stays predictable): Step 1 queries the RLS-protected SQL recall_campaigns view by the decoded VIN, returning any open campaign IDs and affected part codes (e.g., Campaign 24V-118, high-pressure fuel pump). Step 2 feeds those exact campaign IDs and component names into the pre-filtered OpenSearch hybrid retriever to fetch the matching dealer recall bulletin and labor-time table, producing a unified answer that cites [C1] (the exact SQL query and VIN row key) alongside [C2] (the recall bulletin PDF page and highlight box).
  • Walk through what happens when a revised edition of a service manual is uploaded to supersede an active version. The ingestion pipeline parses, chunks, and embeds 2024-09 under a brand-new immutable doc_id while its Postgres status is INGESTING (so live user queries, which filter against the cached LIVE doc_id set, never see a half-indexed manual). Once all ~1,400 chunks are indexed, an automated smoke-evaluation gate runs the family's golden test questions explicitly against the new doc_id; when it passes, one ACID Postgres transaction marks 2024-09 LIVE (is_latest = true), marks 2024-03 SUPERSEDED (is_latest = false), and increments that vehicle's cache epoch so stale cached answers expire instantly with zero vector rewrites in OpenSearch.
  • If chat traffic increases tenfold, how can you reduce GPU and LLM serving expenses without degrading factual precision? Attack token volume and model routing in three layers, validating every step against the 1,000-question golden gate: first, serve exact cache hits from the (normalized_query, vehicle, entitlement, epoch) first-turn cache and enable prompt prefix caching on the inference server so the shared system instructions are not recomputed on every call. Second, route by intent complexity — single-row spec lookups ("ATF drain-and-fill capacity", "coolant volume") can be answered by a 10x-cheaper small model (or extractive table rendering) once reranked, reserving the frontier model for multi-chunk warranty reasoning and text-to-SQL. Third, distill the GPU cross-encoder into an int8/FP8 TensorRT engine to double reranker throughput per GPU.

Follow-up questions

Similar questions

More Sonatus interview questions

All 2 Sonatus questions →