🧠

[Project 2b] Retrieval-Augmented Generation (RAG) System for Jack H. Park Studio

Designing a Knowledge Backbone on Real Portfolio Content

👉🏻
Executive Summary
This project focuses on designing a Retrieval-Augmented Generation (RAG) system that serves as the knowledge backbone for my personal AI assistant. Rather than assuming retrieval is correct by default, the system treats retrieved context as a fallible hypothesis that must be evaluated, constrained, and sometimes retried. It covers the full RAG lifecycle—from ingestion and embedding to retrieval, context assembly, and citation—prioritizing quality, traceability, and determinism over raw recall. Auto-RAG mechanisms such as weak-retrieval detection, query rewriting, and fallback strategies are used to reduce confidently incorrect answers. The project reframes RAG as a system design and safety problem, ensuring that only reliable, explainable context reaches downstream generation.
Type: 🧭 Personal Learning & Demo (Non-Commercial)
Context: A core knowledge subsystem powering my personal AI Chat Assistant on jackhpark.com
Focus: How knowledge is ingested, structured, retrieved, and validated before it reaches an LLM

🎯 Objective

As large language models become more capable, a recurring failure mode becomes more visible:
answers that sound confident, fluent, and wrong.
This project focuses on the part of the system that most directly influences that outcome—the Retrieval-Augmented Generation (RAG) layer.
Rather than optimizing prompts or chat experiences, I intentionally stepped one layer earlier in the stack to explore:
  • How real-world content can be ingested and normalized reliably
  • How chunking and embeddings affect semantic recall
  • How retrieval quality can be measured, constrained, and corrected
  • Why retrieval should be treated as fallible, not authoritative
The goal of this project is not to retrieve more information, but to retrieve better, safer context for downstream generation.

⚙️ High-Level Architecture

This system is structured around two decoupled architectural paths: a triggered-pull ingestion path that refreshes the knowledge base on a daily schedule and after a portfolio page is published, and a self-correcting retrieval path that decides what evidence is strong enough to send downstream to generation. On the ingestion side, content from Notion pages and external URLs is normalized, checked for meaningful change, and refreshed without duplicating or mixing old and new chunks. On the retrieval side, the system treats first-pass search as a hypothesis rather than a fact, using bounded recovery mechanisms when initial results look weak instead of assuming semantic search is always trustworthy. The chat runtime adds a separate reliability boundary around that retrieval flow, isolating lightweight request handling from heavier retrieval and model-execution work so the system behaves more predictably in a serverless environment. LangChain is used selectively where it provides architectural structure — especially around retrieval orchestration, provider abstraction, and vector-store integration — while guardrails, caching, and most operational logic remain outside that layer. The result is not just a search component in front of an LLM, but a context-quality pipeline designed for grounding, traceability, and controlled failure handling.

🗂️ RAG Ingestion & ETL

The ingestion pipeline follows a deliberate triggered-pull model: an admin action or CLI run can fetch Notion content, a daily scheduled run refreshes the corpus, and a targeted refresh fetches the edited page immediately after a portfolio publish. External URLs use their own fetch adapter before entering the shared change-detection and embedding path. Unchanged content is skipped, metadata-only changes avoid re-embedding, and changed content is chunked and refreshed together. This trades immediate visibility for bounded freshness, lower embedding cost, and updates that are easier to reason about.
flowchart TD
  subgraph T["Notion refresh triggers"]
    A["Admin UI / CLI"]
    D["Daily scheduled run"]
    P["Publish-coupled page refresh"]
  end
  subgraph S["Sources"]
    N["Notion pages"]
    U["External URLs"]
  end
  A --> N
  D --> N
  P --> N
  X["Explicit URL ingestion"] --> U
  subgraph E["Fetch and normalize"]
    NX["Notion to plain text"]
    UX["URL to article text"]
    Z["Normalize text"]
  end
  N --> NX --> Z
  U --> UX --> Z
  Z --> H["Compare content hash and metadata"]
  H --> Q{"What changed?"}
  Q -->|"Nothing"| R1["Record ingestion run"]
  Q -->|"Metadata only"| R2["Update document metadata"]
  Q -->|"Content"| K["Chunk with overlap"]
  K --> ES["Choose embedding space"] --> EM["Embed and replace changed chunks"]
  EM --> R3["Supabase: pgvector chunks"]
  EM --> R2
  R2 --> R1
  R3 --> R1

Key design decisions:

  • Notion-first ingestion Portfolio content authored in Notion is treated as the canonical source of truth.
  • Controlled recursive crawling Linked pages can be followed up to a bounded depth and page count, preventing uncontrolled ingestion.
  • Content-hash based change detection Each document is hashed and compared against its prior version to determine whether re-ingestion is required.
  • Atomic document refresh When content changes, existing chunks are fully replaced rather than partially updated, avoiding mixed or inconsistent states.
This reflects a conscious trade-off: slightly delayed freshness in exchange for debuggability, determinism, and data integrity.

✂️ Chunking & Tokenization Strategy

Chunking is one of the most underestimated levers in RAG quality.
This system uses a sliding-window, token-aware chunking strategy designed to preserve semantic coherence while respecting downstream token budgets.
Key characteristics:
  • 450-token target window with 75-token overlap (a 6:1 ratio) — large enough to hold a coherent thought, while preserving key terms that sit at chunk boundaries
  • Word-boundary awareness to avoid semantic fragmentation
  • Token-based measurement via a BPE tokenizer (gpt-tokenizer), aligned to LLM context windows rather than character length
The goal is not maximum recall, but context that survives compression when injected into an LLM prompt.
This balances:
  • Semantic completeness
  • Token efficiency
  • Reduced redundancy during retrieval

🧬 Embedding Strategy & Vector Persistence

The embedding layer was designed to keep the retrieval system flexible as content and model choices evolved over time. Rather than locking the project into a single provider, I structured it around isolated, versioned embedding spaces — vectors live in tables partitioned by provider and dimension (e.g. rag_chunks_openai_te3s_v1 at 1536-d and rag_chunks_gemini_te4_v1 at 768-d) — so different providers and model versions can be compared, upgraded incrementally, and managed without risky full-corpus rebuilds. I also chose Supabase with pgvector (using ivfflat indexing) so embeddings stay closely tied to document metadata and refresh workflows, making filtering simpler and reducing the risk of stale chunks surviving when source content changes. From a PM perspective, this was less about maximizing raw vector-search performance and more about building a retrieval foundation that could be iterated on safely and understood operationally.

Multi-provider, isolated embedding spaces

Instead of locking the system into a single embedding provider, I structured it so each provider and model version could live in its own isolated embedding space. That separation makes it possible to compare retrieval quality across providers, roll out upgrades incrementally, and test new embedding setups without forcing a risky full-corpus migration. It also keeps refresh and replacement workflows operationally cleaner, since one embedding strategy can evolve without destabilizing another. From a PM perspective, this was less about optionality for its own sake and more about creating a safer path for iteration as model quality, cost, and latency trade-offs changed over time.

🧠 Retrieval Engine — Auto-RAG (Self-Correcting Retrieval)

The retrieval layer is built around a simple but important assumption: the first search result is not always good enough to trust. Instead of treating vector search as a one-shot answer, this system evaluates whether the initial retrieval is actually strong enough to support generation, using concrete weakness signals — a top similarity score below the default 0.4 threshold plus a 0.05 margin, fewer than three matches, or no hits at all. When the first pass looks weak, the pipeline can automatically escalate into a managed Auto-RAG flow, using strategies like query rewriting, HyDE, or multi-query fusion to search again from a better angle. A scoring step then compares the base and fallback results before deciding which context to keep, so the system does not blindly prefer the more complex path. From a PM perspective, this makes retrieval feel less like a static backend utility and more like a quality-control layer designed to reduce confident but poorly grounded answers.

Auto-RAG: self-correcting retrieval

When base retrieval looks weak, the system does not immediately trust the first pass or fail silently. It first checks for concrete weakness signals such as low similarity, sparse match density, or insufficient coverage, then decides whether an Auto-RAG fallback should run. Depending on the situation, that fallback can rewrite the query, generate a hypothetical answer document through HyDE, or run multiple query variations and merge the results through max-score fusion (CombMAX). A comparison step then evaluates whether the fallback actually improved retrieval before selecting the final candidate set, so escalation is treated as a controlled retry rather than an automatic override. This matters because it turns retrieval from a one-shot lookup into a managed recovery mechanism designed to improve grounding when the initial search path is not strong enough.
flowchart TD
  Q["User Query"] --> V["Vector Search<br>(pgvector, top-k)"]
  V --> E{"Weak retrieval?<br>(low similarity · sparse match)"}
  E -->|"Strong"| C["Context Assembly"]
  E -->|"Weak"| AR["<b>Auto-RAG</b><br>Query rewrite · HyDE · <b>Multi-query fusion</b>"]
  AR --> RF["Max-score fusion (CombMAX)<br>(base vs. fallback comparison)"]
  RF --> C
  C --> D["<b>Dedup · Token budget · Per-doc quota</b>"]
  D --> OUT["<b>Curated Context + Citations</b>"]

📚 Context Assembly & Citations

Retrieval quality in this system is shaped not just by which chunks are found, but by how evidence is assembled before it reaches the model. After candidate chunks are retrieved, a separate context-selection step applies token-budget controls, deduplicates overlapping sliding-window chunks, and enforces per-document quotas so one source cannot dominate the final prompt. This design turns retrieval from a naive top-k dump into a curated evidence pipeline: breadth is preserved, redundancy is reduced, and the final context remains usable under real prompt constraints. The system also attaches structured citations to every retained chunk, including source URL, title, and document breadcrumbs, so responses stay traceable back to the underlying material. From a portfolio perspective, this is one of the project’s strongest ideas: it treats answer quality as a context-composition problem, not just a vector search problem.

⚖️ Design Trade-offs & Constraints

This system intentionally prioritizes retrieval quality, traceability, and operational clarity over raw speed or infrastructure specialization. I accepted some latency overhead from the Auto-RAG loop because, in this context, reducing confidently wrong answers mattered more than optimizing for the fastest possible first response. I also chose to keep vector storage in Postgres with pgvector rather than moving to a more specialized vector database, because metadata filtering, document refresh consistency, and debugging transparency were more important than maximum ANN performance at this stage. Similarly, the ingestion model favors controlled, triggered updates over real-time freshness, trading immediacy for deterministic change handling and cleaner operational reasoning. From a PM perspective, these were not accidental limitations—they were deliberate decisions about which forms of quality mattered most for this product.

🔍 Observability Bridge (Toward Project 2c: Telemetry & Governance)

Although this project focuses on retrieval quality, it was designed to produce the signals needed to evaluate that quality over time. The system separates retrieval-stage observations from final context-selection observations, making it easier to distinguish between problems like weak search results, duplicate-heavy candidates, quota pressure, or token-budget loss. It also uses a dual telemetry model: Langfuse captures detailed LLM and retrieval traces for engineering diagnosis, while PostHog supports higher-level product interpretation around reliability, latency, and user experience. That structure makes the RAG layer more than a backend component—it becomes an observable decision system whose behavior can be inspected, explained, and improved. From a PM perspective, this matters because better AI systems are not just built once; they need feedback loops that make quality visible and operationally actionable.

🧠 PM Learning Outcomes

This project reinforced for me that retrieval quality is not a prompt-writing problem; it is a systems design problem with direct product consequences. I came away with a stronger appreciation for how retrieval choices made before generation shape whether the final answer feels grounded and trustworthy. It also clarified that “more context” is often the wrong goal—what matters is selecting evidence that is relevant, bounded, and explainable. Just as importantly, I learned that AI quality cannot be improved reliably without observability: teams need signals that explain not only what the system answered, but why it answered that way. From a PM perspective, the most valuable takeaway was that good AI products are built by designing feedback loops around uncertainty, not by assuming the model is usually right.

🗺️ How This Fits Into the Larger System

  • Project 2b: RAG System ← here — knowledge and retrieval backbone
Together, these projects demonstrate an end-to-end view of building, operating, and improving AI systems through a product lens.