<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by AMIT KASHYAP on Medium]]></title>
        <description><![CDATA[Stories by AMIT KASHYAP on Medium]]></description>
        <link>https://medium.com/@hunkcool1991?source=rss-9c75f648a393------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7YDeadLhgWQ1U77urk5WKQ.png</url>
            <title>Stories by AMIT KASHYAP on Medium</title>
            <link>https://medium.com/@hunkcool1991?source=rss-9c75f648a393------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:45:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hunkcool1991/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Advanced RAG: How Corrective RAG (CRAG) Solves Traditional RAG Problems]]></title>
            <link>https://medium.com/@hunkcool1991/advanced-rag-how-corrective-rag-crag-solves-traditional-rag-problems-b1ac355e2846?source=rss-9c75f648a393------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1ac355e2846</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[AMIT KASHYAP]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 09:51:59 GMT</pubDate>
            <atom:updated>2026-08-11T09:51:59.113Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_pZ_5SYaIWXQey_zY_gjw.png" /></figure><h3>Naive RAG assumes retrieval worked. Corrective RAG checks — and fixes it when it didn’t.</h3><p>Everything we’ve built in this series so far — document loading, splitting, vector storage, retrieval — follows the same basic script: retrieve some chunks, hand them to the LLM, generate an answer. That’s <strong>naive RAG</strong>, and it’s the right starting point. But it rests on an assumption that quietly breaks in production more often than you’d expect: <em>that retrieval actually found something useful.</em></p><p>Naive RAG has no way to know if the top-k chunks it fetched are genuinely relevant, only tangentially related, or completely off-target. It just hands whatever it retrieved to the LLM and hopes for the best. When retrieval fails silently — which happens constantly with ambiguous queries, sparse knowledge bases, or questions the underlying documents simply don’t cover — the LLM is left to either produce a vague non-answer or, worse, confidently hallucinate something plausible-sounding.</p><p><strong>Corrective RAG (CRAG)</strong> — introduced in the paper <em>“Corrective Retrieval Augmented Generation”</em> by Yan et al. (2024) — adds exactly one structural idea to fix this: <strong>grade the retrieved documents before generation, and take a different corrective action depending on the grade.</strong></p><p>In this article, we’ll cover:</p><ul><li>Where naive RAG silently breaks down</li><li>The core idea behind CRAG and how it differs from standard RAG</li><li>The three-way decision CRAG makes on every retrieval, and what happens in each branch</li><li>How the “knowledge refinement” (decompose-then-recompose) step works</li><li>A practical LangGraph implementation you can adapt</li><li>When CRAG is (and isn’t) worth the added complexity</li></ul><h3>Where Naive RAG Breaks Down</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8O4ycP-tWc91U4kPUvMbw.png" /></figure><p>A few concrete failure patterns show up constantly once a RAG system leaves the demo stage:</p><ul><li><strong>Irrelevant retrieval that looks relevant.</strong> The top-k chunks are the closest <em>vectors</em> to the query — but “closest” doesn’t guarantee “actually answers the question.” A query about a discontinued product feature might retrieve chunks that mention the product by name but say nothing about the specific behavior being asked about.</li><li><strong>No fallback when the knowledge base doesn’t have the answer.</strong> If nothing in your vector store is genuinely relevant, naive RAG still retrieves <em>something</em> (it always returns top-k, never “nothing”), and that something gets passed to the LLM regardless.</li><li><strong>Hallucination on weak context.</strong> Handed marginal or irrelevant context, LLMs don’t reliably say “I don’t know” — they often blend the weak context with their own general knowledge, producing answers that sound grounded but aren’t.</li><li><strong>Noisy, partially-relevant chunks.</strong> Even a genuinely useful chunk often contains a mix of relevant and irrelevant sentences, diluting the signal the LLM actually needs.</li></ul><p>Every one of these stems from the same root cause: naive RAG has no checkpoint. Retrieval happens, and generation happens immediately after, with nothing in between to catch a bad result.</p><h3>The Core Idea: Grade, Then Act</h3><p>CRAG’s central addition is a <strong>Retrieval Evaluator</strong> — a lightweight model (in the original paper, a fine-tuned T5-based evaluator; in practice, often just an LLM prompted to judge relevance) that scores each retrieved document against the query <em>before</em> generation happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYzXz_XesATQrhpDGrsbOA.png" /></figure><p>Based on those scores, CRAG routes to one of three corrective actions:</p><h3>Correct → Knowledge Refinement</h3><p>If retrieval found genuinely relevant documents, CRAG doesn’t just pass them through as-is. It applies a <strong>decompose-then-recompose</strong> algorithm: break each retrieved document into smaller “knowledge strips” (roughly sentence-level), score each strip individually for relevance, discard the irrelevant ones, and recompose the surviving strips into a cleaner, denser context. This directly addresses the “noisy chunk” problem — even a correctly-retrieved document usually isn’t uniformly useful sentence-by-sentence.</p><h3>Incorrect → Web Search Fallback</h3><p>If none of the retrieved documents are relevant, CRAG discards them entirely and falls back to a live web search instead. The original query is first rewritten into a cleaner search query (stripping conversational phrasing, extracting keywords), then used to fetch fresh, external information the internal knowledge base evidently doesn’t contain.</p><h3>Ambiguous → Both, Combined</h3><p>When the evaluator can’t confidently classify the retrieval as clearly correct or clearly incorrect, CRAG hedges: it applies knowledge refinement to the internal documents <em>and</em> runs a supplementary web search, then combines both sources into the final context. This handles the common middle case where internal documents are partially relevant but likely incomplete.</p><h3>Naive RAG vs CRAG, Side by Side</h3><p>The structural difference is small — one evaluation step and a branching decision — but the behavioral difference is significant. Naive RAG has exactly one path, regardless of retrieval quality. CRAG has three, and it picks the right one based on an actual quality check rather than blind trust in the vector similarity score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNbzAxH3yFJonptBibrPRw.png" /></figure><h3>Implementing CRAG With LangGraph</h3><p>CRAG’s branching, corrective structure maps naturally onto <strong>LangGraph</strong>, LangChain’s library for building stateful, graph-structured LLM workflows — much more naturally than a single linear chain.</p><h3>Step 1: Define the State</h3><pre>from typing import List, TypedDict<br><br>class CRAGState(TypedDict):<br>    question: str<br>    documents: List[str]<br>    web_search_needed: bool<br>    generation: str</pre><h3>Step 2: The Retrieval Evaluator</h3><pre>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_openai import ChatOpenAI<br>from langchain_core.pydantic_v1 import BaseModel, Field<br><br>class GradeDocument(BaseModel):<br>    relevant: str = Field(description=&quot;&#39;yes&#39; or &#39;no&#39; - is this document relevant to the question?&quot;)<br><br>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0)<br>grader = llm.with_structured_output(GradeDocument)<br><br>grade_prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>You are grading the relevance of a retrieved document to a user question.<br>Give a binary score &#39;yes&#39; or &#39;no&#39; - does this document contain information<br>relevant to answering the question?<br><br>Document: {document}<br>Question: {question}<br>&quot;&quot;&quot;)<br><br>grading_chain = grade_prompt | grader<br><br>def grade_documents(state: CRAGState) -&gt; CRAGState:<br>    filtered_docs = []<br>    web_search_needed = False<br><br>    for doc in state[&quot;documents&quot;]:<br>        result = grading_chain.invoke({&quot;document&quot;: doc, &quot;question&quot;: state[&quot;question&quot;]})<br>        if result.relevant == &quot;yes&quot;:<br>            filtered_docs.append(doc)<br>        else:<br>            web_search_needed = True<br><br>    # If too few documents survived grading, trigger web search<br>    if len(filtered_docs) &lt; 2:<br>        web_search_needed = True<br><br>    return {**state, &quot;documents&quot;: filtered_docs, &quot;web_search_needed&quot;: web_search_needed}</pre><h3>Step 3: The Web Search Fallback</h3><pre>from langchain_community.tools import DuckDuckGoSearchRun<br><br>search_tool = DuckDuckGoSearchRun()<br><br>def web_search(state: CRAGState) -&gt; CRAGState:<br>    results = search_tool.run(state[&quot;question&quot;])<br>    combined_docs = state[&quot;documents&quot;] + [results]<br>    return {**state, &quot;documents&quot;: combined_docs}</pre><h3>Step 4: Generation</h3><pre>generation_prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>Answer the question using only the provided context. If the context is<br>insufficient, say so clearly rather than guessing.<br><br>Context:<br>{context}<br><br>Question: {question}<br>Answer:<br>&quot;&quot;&quot;)<br><br>def generate(state: CRAGState) -&gt; CRAGState:<br>    context = &quot;\n\n&quot;.join(state[&quot;documents&quot;])<br>    chain = generation_prompt | llm<br>    result = chain.invoke({&quot;context&quot;: context, &quot;question&quot;: state[&quot;question&quot;]})<br>    return {**state, &quot;generation&quot;: result.content}</pre><h3>Step 5: Wire It Into a Graph</h3><pre>from langgraph.graph import StateGraph, END<br><br>def route_after_grading(state: CRAGState) -&gt; str:<br>    return &quot;web_search&quot; if state[&quot;web_search_needed&quot;] else &quot;generate&quot;<br><br>workflow = StateGraph(CRAGState)<br><br>workflow.add_node(&quot;grade_documents&quot;, grade_documents)<br>workflow.add_node(&quot;web_search&quot;, web_search)<br>workflow.add_node(&quot;generate&quot;, generate)<br><br>workflow.set_entry_point(&quot;grade_documents&quot;)<br>workflow.add_conditional_edges(<br>    &quot;grade_documents&quot;,<br>    route_after_grading,<br>    {&quot;web_search&quot;: &quot;web_search&quot;, &quot;generate&quot;: &quot;generate&quot;},<br>)<br>workflow.add_edge(&quot;web_search&quot;, &quot;generate&quot;)<br>workflow.add_edge(&quot;generate&quot;, END)<br><br>crag_app = workflow.compile()</pre><h3>Running It</h3><pre>result = crag_app.invoke({<br>    &quot;question&quot;: &quot;What is the current pricing for the Pro plan?&quot;,<br>    &quot;documents&quot;: retriever.invoke(&quot;What is the current pricing for the Pro plan?&quot;),<br>    &quot;web_search_needed&quot;: False,<br>    &quot;generation&quot;: &quot;&quot;,<br>})<br><br>print(result[&quot;generation&quot;])</pre><p>This simplified version handles the “correct” and “incorrect” branches; adding the “ambiguous” path (refine internal docs <em>and</em> search the web, then merge) is a matter of adding a third routing outcome and a corresponding node that runs both the refinement and search steps before generation.</p><h3>When Is CRAG Worth the Extra Complexity?</h3><p>CRAG adds real cost — at minimum, one extra LLM call per retrieved document for grading, plus occasional web search latency. It’s worth adopting when:</p><ul><li><strong>Your knowledge base has real coverage gaps.</strong> If users regularly ask about things your documents don’t cover, a web search fallback meaningfully improves answer quality instead of returning a confident non-answer.</li><li><strong>Retrieval precision matters more than latency.</strong> Customer-facing support bots, internal knowledge assistants, and anything where a wrong answer has real cost benefit the most from a correctness check before generation.</li><li><strong>You’re already seeing hallucination on weak context.</strong> If you’ve noticed your RAG system confidently answering questions your documents don’t actually address, CRAG’s evaluator is a direct fix for that specific failure mode.</li></ul><p>It’s probably overkill when:</p><ul><li><strong>Your knowledge base is small, well-curated, and closely matches your query patterns</strong> — the marginal benefit of grading is small if retrieval is already reliably good.</li><li><strong>Latency is the dominant constraint</strong> and occasional bad answers are an acceptable trade-off (e.g., low-stakes internal tools).</li></ul><h3>Wrapping Up</h3><p>The core insight behind CRAG is almost embarrassingly simple once you see it: naive RAG treats every retrieval as trustworthy by default, and CRAG just… checks. That one addition — evaluate before you generate, and branch based on what you find — turns a system that fails silently into one that fails gracefully, falling back to fresh information when its own knowledge base comes up short.</p><p>This is also a useful pattern to internalize beyond CRAG specifically: most of the meaningful improvements in “advanced RAG” techniques come from adding verification and correction steps around the same basic retrieve-then-generate core, rather than reinventing retrieval or generation from scratch. Once you’re comfortable with the pipeline from the rest of this series, CRAG is a natural next step — the same building blocks, with one honest quality check added in between.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1ac355e2846" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a YouTube RAG Chatbot With LangChain (Start to Finish)]]></title>
            <link>https://medium.com/@hunkcool1991/building-a-youtube-rag-chatbot-with-langchain-start-to-finish-be388d3eb6d6?source=rss-9c75f648a393------2</link>
            <guid isPermaLink="false">https://medium.com/p/be388d3eb6d6</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[AMIT KASHYAP]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 16:08:07 GMT</pubDate>
            <atom:updated>2026-08-10T16:08:07.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tABhA27_d7zCySSTYQx33Q.png" /></figure><h3>You’ve learned Document Loaders, Text Splitters, Vector Stores, and Retrievers separately. Here’s how they snap together into one real, working application.</h3><p>Over this series, we’ve walked through each piece of a RAG pipeline in isolation: loading documents, splitting them into chunks, storing embeddings in a vector store, and retrieving the right context with a retriever. Each of those pieces makes sense on its own — but the real payoff is seeing them wired together into something you can actually use.</p><p>So let’s build one: a chatbot that can answer questions about <strong>any YouTube video</strong>, using only its transcript. Paste in a video URL, and instead of scrubbing through an hour-long video looking for the one part that matters, you just ask.</p><p>This is a genuinely practical project, and it’s a great capstone because it forces every piece of the pipeline to work together for real — loading a transcript instead of a PDF, splitting spoken-language text instead of clean prose, and building a retrieval chain that actually answers grounded in the source material.</p><p>In this article, we’ll build the whole thing, step by step:</p><ol><li>Pulling a transcript from a YouTube video</li><li>Splitting the transcript into retrievable chunks</li><li>Embedding and storing those chunks in a vector store</li><li>Building a retriever and a prompt-driven answer chain</li><li>Wiring it into a simple, working chat loop</li><li>A few practical upgrades worth adding</li></ol><h3>The Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uqnu-QOSzzBHxEKl8WKmGg.png" /></figure><p>Here’s the full system, end to end — the ingestion pipeline that runs once per video, and the query-time path that runs on every question a user asks.</p><p>Notice this is exactly the pipeline from the rest of this series — Document Loader → Text Splitter → Embedding Model → Vector Store → Retriever → LLM — just applied to one specific, very useful source: a video transcript instead of a PDF or webpage.</p><h3>Step 1: Install What You Need</h3><p>You’ll also need an OpenAI API key (or swap in whichever LLM/embedding provider you prefer — the LangChain interface stays the same).</p><pre>pip install langchain langchain-openai langchain-community \<br>            youtube-transcript-api chromadb tiktoken</pre><pre>import os<br>os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;your-api-key-here&quot;</pre><p>YouTube videos with captions enabled (auto-generated or manual) can have their transcript pulled directly, with no video download required, using the youtube-transcript-api library.</p><pre>from youtube_transcript_api import YouTubeTranscriptApi<br>from youtube_transcript_api._errors import TranscriptsDisabled<br><br>def get_transcript(video_id: str) -&gt; str:<br>    try:<br>        transcript_list = YouTubeTranscriptApi.get_transcript(video_id, languages=[&quot;en&quot;])<br>    except TranscriptsDisabled:<br>        raise ValueError(&quot;No captions available for this video.&quot;)<br><br>    full_text = &quot; &quot;.join(chunk[&quot;text&quot;] for chunk in transcript_list)<br>    return full_text<br><br>video_id = &quot;dQw4w9WgXcQ&quot;  # the part after &#39;v=&#39; in the YouTube URL<br>transcript = get_transcript(video_id)</pre><p>A couple of practical notes here:</p><ul><li>video_id is just the part after v= in a standard YouTube URL — you&#39;ll want a small helper to extract this from whatever URL format the user pastes in.</li><li>Not every video has captions — TranscriptsDisabled (or a NoTranscriptFound error) is common enough that you should handle it explicitly rather than letting your app crash.</li><li>If you need timestamps later (for “jump to this part of the video” links), keep the original list of {text, start, duration} dictionaries instead of immediately joining everything into one string — we&#39;ll use this in the enhancements section.</li></ul><p>This is effectively your <strong>document loader</strong> — instead of a PyPDFLoader, this is a custom loader for a source type LangChain doesn&#39;t ship out of the box.</p><h3>Step 3: Split the Transcript Into Chunks</h3><p>Video transcripts are a great real-world case for the <strong>Recursive Character Text Splitter</strong> covered earlier in this series — they’re long, spoken-language text with no reliable paragraph structure (captions rarely include punctuation-perfect sentence breaks), so a structure-aware splitter with sensible overlap does a lot of the work for you.</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_core.documents import Document<br><br>splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)<br><br>doc = Document(page_content=transcript, metadata={&quot;source&quot;: video_id})<br>chunks = splitter.split_documents([doc])</pre><p>A chunk_overlap of around 15–20% (as recommended in the Text Splitters article) matters more here than usual — spoken explanations often build on the previous sentence without a clean break, so a bit of overlap helps avoid losing context mid-thought.</p><h3>Step 4: Embed and Store in a Vector Store</h3><p>Now we turn those chunks into vectors and store them, exactly as covered in the Vector Stores article.</p><pre>from langchain_openai import OpenAIEmbeddings<br>from langchain_community.vectorstores import Chroma<br><br>embeddings = OpenAIEmbeddings()<br><br>vector_store = Chroma.from_documents(<br>    documents=chunks,<br>    embedding=embeddings,<br>    persist_directory=f&quot;./chroma_db_{video_id}&quot;,<br>)</pre><p>Using a video-specific persist_directory means you can cache the vector store per video — if a user asks about the same video again later, you skip re-fetching the transcript and re-embedding everything from scratch.</p><h3>Step 5: Build the Retriever and the Answer Chain</h3><p>This is where the Retrievers article pays off. We’ll start with MMR for a good balance of relevance and diversity across the transcript, since spoken content often repeats the same point in slightly different words.</p><pre>retriever = vector_store.as_retriever(<br>    search_type=&quot;mmr&quot;,<br>    search_kwargs={&quot;k&quot;: 4, &quot;fetch_k&quot;: 15},<br>)</pre><pre>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_openai import ChatOpenAI<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnablePassthrough<br><br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>You are answering questions about a YouTube video using only its transcript.<br>Answer based ONLY on the context below. If the answer isn&#39;t in the context,<br>say you don&#39;t have enough information from the video to answer.<br><br>Context:<br>{context}<br><br>Question: {question}<br><br>Answer:<br>&quot;&quot;&quot;)<br><br>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;, temperature=0)<br><br>def format_docs(docs):<br>    return &quot;\n\n&quot;.join(doc.page_content for doc in docs)<br><br>chain = (<br>    {&quot;context&quot;: retriever | format_docs, &quot;question&quot;: RunnablePassthrough()}<br>    | prompt<br>    | llm<br>    | StrOutputParser()<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bi5YRTZK5l8lNDbmMPDQWg.png" /></figure><p>That explicit instruction in the prompt — <em>“answer based only on the context… if the answer isn’t in the context, say you don’t have enough information”</em> — matters a lot in practice. Without it, the LLM will happily fall back on its general knowledge about the topic instead of staying grounded in what the video actually says, which defeats the entire purpose of building a RAG system in the first place.</p><h3>Step 6: A Simple Chat Loop</h3><p>Putting it all together into something you can actually run:</p><pre>def ask(question: str) -&gt; str:<br>    return chain.invoke(question)<br><br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;Ask anything about the video. Type &#39;quit&#39; to exit.\n&quot;)<br>    while True:<br>        question = input(&quot;You: &quot;)<br>        if question.lower() in (&quot;quit&quot;, &quot;exit&quot;):<br>            break<br>        answer = ask(question)<br>        print(f&quot;\nBot: {answer}\n&quot;)</pre><p>At this point, you have a fully working, end-to-end RAG chatbot: paste a YouTube video ID, and ask it anything covered in the video.</p><h3>Enhancements Worth Adding</h3><p>The version above works, but a few upgrades make it noticeably more usable in practice.</p><h3>1. Return Timestamps, Not Just Text</h3><p>If you kept the original caption fragments (with start times) instead of collapsing everything into one string, you can attach approximate timestamps to each chunk&#39;s metadata during splitting, then surface them in the answer — turning &quot;the video mentions X&quot; into a clickable &quot;jump to 14:32.&quot;</p><pre>def build_documents_with_timestamps(transcript_list, video_id):<br>    docs = []<br>    for entry in transcript_list:<br>        docs.append(Document(<br>            page_content=entry[&quot;text&quot;],<br>            metadata={&quot;source&quot;: video_id, &quot;start&quot;: entry[&quot;start&quot;]},<br>        ))<br>    return docs</pre><p>You’d then adjust your splitter step to preserve one representative timestamp per resulting chunk (e.g., the start of its first source fragment) rather than concatenating everything into a single undifferentiated string first.</p><h3>2. Add Conversation Memory</h3><p>Right now, every question is treated independently — the chatbot has no memory of what was asked before. For natural back-and-forth (“what about the second point he made?”), you’ll want to fold prior turns into the retrieval step:</p><pre>from langchain.chains import create_history_aware_retriever<br>from langchain_core.prompts import MessagesPlaceholder<br><br>contextualize_prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;Rewrite the user&#39;s question as a standalone question, &quot;<br>               &quot;using the chat history for context if needed.&quot;),<br>    MessagesPlaceholder(&quot;chat_history&quot;),<br>    (&quot;human&quot;, &quot;{input}&quot;),<br>])<br><br>history_aware_retriever = create_history_aware_retriever(llm, retriever, contextualize_prompt)</pre><p>This rewrites follow-up questions into standalone ones before retrieval runs, so “what about the second point?” correctly resolves to something the retriever can actually search for.</p><h3>3. Handle Long Videos Gracefully</h3><p>For a 3-hour podcast transcript, you’re looking at hundreds of chunks and a non-trivial embedding cost every time a new video is submitted. Cache aggressively (the persist_directory pattern above), and consider showing ingestion progress to the user rather than making them wait on a blank screen.</p><h3>4. Wrap It in a Simple UI</h3><p>The chat loop above works from the terminal, but wrapping the same chain.invoke() call in a small Streamlit or Gradio app takes only a few extra lines and turns this into something you can actually share:</p><pre>import streamlit as st<br><br>st.title(&quot;YouTube Video Chatbot&quot;)<br>video_url = st.text_input(&quot;Paste a YouTube URL&quot;)<br>question = st.text_input(&quot;Ask a question about the video&quot;)<br><br>if st.button(&quot;Ask&quot;) and video_url and question:<br>    with st.spinner(&quot;Thinking...&quot;):<br>        answer = ask(question)<br>    st.write(answer)</pre><h3>Wrapping Up</h3><p>This is the payoff of the whole series: Document Loaders got the raw transcript in, Text Splitters broke it into retrievable chunks, the Vector Store made it searchable, and the Retriever decided exactly what the LLM gets to see before answering. None of these pieces are complicated on their own — the skill is in how they fit together, and in the small decisions (chunk overlap for spoken text, MMR for repetitive content, an explicit “don’t make things up” instruction in the prompt) that separate a demo that mostly works from one you’d actually want to use.</p><p>From here, the same pattern — load, split, embed, store, retrieve, generate — applies to almost any source you want to build a chatbot over: internal documentation, customer support tickets, research papers, or your own note-taking system. The YouTube transcript was just today’s example.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be388d3eb6d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrievers in RAG: The Strategy Layer That Decides What Your LLM Actually Sees]]></title>
            <link>https://medium.com/@hunkcool1991/retrievers-in-rag-the-strategy-layer-that-decides-what-your-llm-actually-sees-02eaca2bea54?source=rss-9c75f648a393------2</link>
            <guid isPermaLink="false">https://medium.com/p/02eaca2bea54</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[AMIT KASHYAP]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 16:15:58 GMT</pubDate>
            <atom:updated>2026-08-09T16:15:58.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20JubwafOztrEn_mj4XDsQ.png" /></figure><h3>Your vector store can find similar chunks. A retriever decides which similar chunks are actually worth sending to the LLM — and that distinction matters more than most tutorials let on.</h3><p>It’s easy to conflate “vector store” and “retriever” — plenty of getting-started tutorials use the two terms almost interchangeably, since the simplest retriever really is just “run a similarity search against the vector store.” But once you’ve built a couple of real RAG applications, you start hitting the limits of that simple approach: redundant chunks that all say the same thing, queries that need context the embedding alone doesn’t capture, knowledge bases where keyword matching would clearly help but pure vector similarity misses it.</p><p>That’s where <strong>retrievers</strong> as a distinct concept come in. A retriever is the strategy layer sitting on top of your vector store, and there’s a lot more nuance to it than “fetch the top-k nearest vectors.”</p><p>In this article, we’ll cover:</p><ul><li>What a retriever actually is, and how it differs from the vector store underneath it</li><li>Where retrievers fit in a RAG pipeline</li><li>The most useful retrieval strategies — MMR, Multi-Query, Contextual Compression, Self-Query, Parent Document, Ensemble/Hybrid, and Reranking — with LangChain code for each</li><li>How to think about choosing (and combining) strategies for your own application</li></ul><h3>What Is a Retriever?</h3><p>A <strong>retriever</strong> is a component with one job: given a query, return the most relevant pieces of content to help answer it. In LangChain, this is formalized as a simple interface — any retriever exposes an invoke(query) method (or the older get_relevant_documents) that takes a string and returns a list of Document objects.</p><p>The simplest possible retriever just wraps a vector store’s similarity search. But because it’s a defined interface rather than a single fixed algorithm, a retriever can do arbitrarily more: rewrite the query first, fetch from multiple sources, filter by metadata, re-rank results with a second model, or combine several of these together. From the outside, your RAG chain doesn’t need to know or care — it just calls .invoke(query) and gets documents back.</p><p>This separation is the whole point. Your vector store answers “which vectors are numerically closest to this one?” Your retriever answers the actually useful question: <strong>“what should the LLM see to answer this question well?”</strong> Those aren’t always the same thing.</p><h3>Where Retrievers Fit in a RAG Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rn2SlQS3784ckP85oYrK7A.png" /></figure><p>The retriever sits right after the user’s query comes in, and right before the LLM generates its answer. It’s the component responsible for turning a raw question into the actual context window the LLM will reason over.</p><p>This makes the retriever a high-leverage place to fix RAG quality problems. If your answers are vague, missing details, repeating the same point, or ignoring an obvious filter the user implied (“in the 2024 report,” “from the engineering team”), the fix is very often in the retrieval strategy — not in the embedding model, and not in prompt engineering on the LLM side.</p><h3>Strategy 1: Plain Similarity Search (the Baseline)</h3><p>This is the retriever everyone starts with, and it’s what you get by default when you wrap a vector store:</p><pre>retriever = vector_store.as_retriever(search_kwargs={&quot;k&quot;: 4})<br>docs = retriever.invoke(&quot;What changed in the version 2 release?&quot;)</pre><p>It works well for straightforward queries against a reasonably clean knowledge base. Its main weakness shows up as your knowledge base grows: the top-k nearest vectors are often clustered tightly together — near-duplicate chunks from the same section of the same document — which wastes context space without actually broadening what the LLM can see.</p><h3>Strategy 2: MMR (Maximal Marginal Relevance)</h3><p>MMR fixes the redundancy problem directly. Instead of just picking the k closest vectors, it iteratively selects results that are relevant to the query <strong>and</strong> dissimilar from what’s already been picked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8e484VYPkl6Z8G9UKz0gw.png" /></figure><pre>retriever = vector_store.as_retriever(<br>    search_type=&quot;mmr&quot;,<br>    search_kwargs={&quot;k&quot;: 4, &quot;fetch_k&quot;: 20, &quot;lambda_mult&quot;: 0.5},<br>)<br>docs = retriever.invoke(&quot;What changed in the version 2 release?&quot;)</pre><ul><li>fetch_k controls how large the initial candidate pool is before diversification kicks in.</li><li>lambda_mult controls the relevance/diversity trade-off — 1.0 behaves like pure similarity search, 0.0 maximizes diversity, and 0.5 is a reasonable middle ground.</li></ul><p>MMR is a strong default upgrade over plain similarity search for almost any knowledge base with more than a handful of documents — it costs almost nothing and meaningfully reduces redundant context.</p><h3>Strategy 3: Multi-Query Retriever</h3><p>Sometimes the problem isn’t redundancy — it’s that the user’s exact phrasing doesn’t closely match how the relevant content was written. A <strong>Multi-Query Retriever</strong> uses an LLM to generate several different phrasings of the same question, runs similarity search for each, and merges the results.</p><pre>from langchain.retrievers.multi_query import MultiQueryRetriever<br>from langchain_openai import ChatOpenAI<br><br>llm = ChatOpenAI(temperature=0)<br><br>retriever = MultiQueryRetriever.from_llm(<br>    retriever=vector_store.as_retriever(),<br>    llm=llm,<br>)<br><br>docs = retriever.invoke(&quot;How do I fix a slow database?&quot;)<br># Internally might also search:<br># &quot;What causes database performance issues?&quot;<br># &quot;How to optimize database query speed?&quot;<br># &quot;Steps to troubleshoot database latency&quot;</pre><p>This trades extra LLM calls (and latency) for meaningfully better recall — it’s especially useful when your users’ vocabulary doesn’t match your documents’ vocabulary, which happens constantly in technical or internal-knowledge-base settings.</p><h3>Strategy 4: Contextual Compression</h3><p>Even a well-chosen chunk often contains irrelevant sentences mixed in with the useful part. <strong>Contextual Compression</strong> runs a second pass over retrieved documents to strip out anything that isn’t actually relevant to the query, before handing the result to the LLM.</p><pre>from langchain.retrievers import ContextualCompressionRetriever<br>from langchain.retrievers.document_compressors import LLMChainExtractor<br><br>compressor = LLMChainExtractor.from_llm(llm)<br><br>compression_retriever = ContextualCompressionRetriever(<br>    base_compressor=compressor,<br>    base_retriever=vector_store.as_retriever(),<br>)<br><br>docs = compression_retriever.invoke(&quot;What changed in the version 2 release?&quot;)<br># &quot;Steps to troubleshoot database latency&quot;</pre><p>This is particularly useful when your chunks are on the larger side and tend to mix multiple topics — compression keeps the signal-to-noise ratio in your final context high, which tends to reduce hallucination and improve answer focus.</p><h3>Strategy 5: Self-Query Retriever</h3><p>Some queries have a semantic part and a structured filter part mixed together — “customer complaints about shipping <strong>from last month</strong>” combines a meaning-based search (“complaints about shipping”) with a metadata filter (date within the last month). A <strong>Self-Query Retriever</strong> uses an LLM to automatically split a natural-language query into both parts.</p><pre>from langchain.retrievers.self_query.base import SelfQueryRetriever<br>from langchain.chains.query_constructor.schema import AttributeInfo<br><br>metadata_field_info = [<br>    AttributeInfo(name=&quot;source&quot;, description=&quot;the file the chunk came from&quot;, type=&quot;string&quot;),<br>    AttributeInfo(name=&quot;date&quot;, description=&quot;the date the document was published&quot;, type=&quot;string&quot;),<br>    AttributeInfo(name=&quot;category&quot;, description=&quot;the document&#39;s category&quot;, type=&quot;string&quot;),<br>]<br><br>retriever = SelfQueryRetriever.from_llm(<br>    llm=llm,<br>    vectorstore=vector_store,<br>    document_contents=&quot;Customer support tickets&quot;,<br>    metadata_field_info=metadata_field_info,<br>)<br><br>docs = retriever.invoke(&quot;shipping complaints from last month&quot;)</pre><p>This saves you from having to manually parse filters out of user queries yourself — the LLM figures out which part of the question is a semantic search and which part should become a structured metadata filter.</p><h3>Strategy 6: Parent Document Retriever</h3><p>There’s a tension in chunk sizing: small chunks produce more precise embeddings (as covered in the Text Splitters article in this series), but small chunks alone often lack enough surrounding context for the LLM to give a complete answer. The <strong>Parent Document Retriever</strong> resolves this by searching over small child chunks, but returning the larger parent chunk (or the full original document) they came from.</p><pre>from langchain.retrievers import ParentDocumentRetriever<br>from langchain.storage import InMemoryStore<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br><br>parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000)<br>child_splitter = RecursiveCharacterTextSplitter(chunk_size=400)<br><br>store = InMemoryStore()<br><br>retriever = ParentDocumentRetriever(<br>    vectorstore=vector_store,<br>    docstore=store,<br>    child_splitter=child_splitter,<br>    parent_splitter=parent_splitter,<br>)<br><br>retriever.add_documents(raw_documents)<br><br>docs = retriever.invoke(&quot;What changed in the version 2 release?&quot;)<br># search matches small, precise child chunks --<br># but returns the larger parent chunk for full context</pre><p>This gives you the best of both worlds: precise matching at search time, and enough surrounding context at answer time.</p><h3>Strategy 7: Ensemble (Hybrid) Retriever</h3><p>Vector similarity search is excellent at capturing meaning, but it can miss exact keyword matches — product codes, error messages, acronyms, names — that a traditional keyword search (like BM25) would catch instantly. An <strong>Ensemble Retriever</strong> combines both approaches and merges their ranked results.</p><pre>from langchain.retrievers import EnsembleRetriever<br>from langchain_community.retrievers import BM25Retriever<br><br>bm25_retriever = BM25Retriever.from_documents(chunks)<br>bm25_retriever.k = 4<br><br>vector_retriever = vector_store.as_retriever(search_kwargs={&quot;k&quot;: 4})<br><br>ensemble_retriever = EnsembleRetriever(<br>    retrievers=[bm25_retriever, vector_retriever],<br>    weights=[0.4, 0.6],<br>)<br><br>docs = ensemble_retriever.invoke(&quot;error code E4021 timeout&quot;)</pre><p>This <strong>hybrid search</strong> pattern — vector search plus keyword search — is one of the highest-value upgrades you can make to a production RAG system, because the two methods fail in different, complementary ways.</p><h3>Strategy 8: Reranking</h3><p>All of the strategies above retrieve a candidate set using relatively cheap methods. <strong>Reranking</strong> adds one more step: pass the top candidates through a more expensive but more accurate cross-encoder model that directly scores query-document relevance, then keep only the best few.</p><pre>from langchain.retrievers import ContextualCompressionRetriever<br>from langchain.retrievers.document_compressors import CohereRerank<br><br>reranker = CohereRerank(top_n=3)<br><br>reranking_retriever = ContextualCompressionRetriever(<br>    base_compressor=reranker,<br>    base_retriever=ensemble_retriever,<br>)<br><br>docs = reranking_retriever.invoke(&quot;What changed in the version 2 release?&quot;)</pre><p>Rerankers are slower and often cost more per query than embedding-based search alone, so they’re typically used as a final polishing step on top of a cheaper first-pass retriever — fetch 20 candidates cheaply, rerank down to the best 3–5.</p><h3>Choosing (and Combining) Strategies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eesvwWII1t7hwUnDwxZoiA.png" /></figure><p>You don’t have to pick exactly one of these. In practice, production RAG systems often stack several together — for example: an <strong>Ensemble Retriever</strong> (vector + BM25) as the first pass, followed by a <strong>Reranker</strong> to polish the final selection. Or a <strong>Self-Query Retriever</strong> to handle structured filters, feeding into <strong>MMR</strong> for diversity within the filtered results.</p><p>A practical way to decide where to start:</p><ul><li><strong>Redundant, near-duplicate results?</strong> → Add MMR.</li><li><strong>Users phrase questions differently than your documents are written?</strong> → Add Multi-Query.</li><li><strong>Chunks contain a lot of irrelevant filler?</strong> → Add Contextual Compression.</li><li><strong>Queries often reference dates, categories, or specific sources?</strong> → Add Self-Query.</li><li><strong>Chunks feel too small to answer fully, but you need small chunks for good embeddings?</strong> → Add Parent Document Retriever.</li><li><strong>Users search for exact terms, codes, or names that pure semantic search seems to miss?</strong> → Add an Ensemble/Hybrid retriever.</li><li><strong>You have budget for one more model call and need the highest possible precision?</strong> → Add Reranking on top of whatever you’re already using.</li></ul><h3>Wrapping Up</h3><p>The vector store answers “what’s numerically close?” The retriever answers the question that actually matters: “what should the LLM see?” That distinction is where most of the real engineering work in a mature RAG system lives — not in swapping embedding models or fiddling with chunk sizes, but in choosing (and combining) the retrieval strategies that match how your users actually ask questions and how your knowledge base is actually structured.</p><p>Start with plain similarity search or MMR to get something working. Then, as you notice specific failure patterns — redundant chunks, missed keyword matches, queries with implicit filters — reach for the specific strategy that addresses that failure, rather than reaching for a bigger, more expensive model to paper over a retrieval problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02eaca2bea54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector Stores in RAG: Where Your Embeddings Actually Live]]></title>
            <link>https://medium.com/@hunkcool1991/vector-stores-in-rag-where-your-embeddings-actually-live-a247c63154ec?source=rss-9c75f648a393------2</link>
            <guid isPermaLink="false">https://medium.com/p/a247c63154ec</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[AMIT KASHYAP]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 15:59:10 GMT</pubDate>
            <atom:updated>2026-08-09T15:59:10.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EntiwQwBYzpiM5yr6KjBIg.png" /></figure><h3>You’ve chunked your documents and embedded them into vectors. Now where do those vectors go — and how does your app find the right ones in milliseconds?</h3><p>By the time you reach the vector store stage of a RAG pipeline, you’ve already done a lot of work: you loaded your documents, split them into clean chunks, and ran each chunk through an embedding model to get a vector. But a pile of vectors sitting in a Python list isn’t useful on its own. You need somewhere to <strong>store</strong> those vectors permanently, and — more importantly — a way to <strong>search</strong> through potentially millions of them and find the handful that are actually relevant to a user’s question, in a fraction of a second.</p><p>That’s the entire job of a <strong>vector store</strong>.</p><p>In this article, we’ll cover:</p><ul><li>What a vector store actually is, and why a normal database can’t do this job</li><li>Where vector stores fit in a RAG pipeline</li><li>How similarity search really works under the hood (distance metrics + approximate nearest neighbor search)</li><li>The most popular vector store options and how they differ</li><li>LangChain code for building, querying, and persisting a vector store</li><li>Practical advice on choosing the right one and getting good retrieval results</li></ul><h3>What Is a Vector Store?</h3><p>A <strong>vector store</strong> is a specialized database designed to store high-dimensional vectors (embeddings) and answer one very specific kind of question extremely fast: <em>“Given this query vector, which stored vectors are most similar to it?”</em></p><p>Every chunk of your document, once embedded, becomes a vector — typically somewhere between 384 and 3072 numbers, depending on the embedding model. The vector store’s job is to:</p><ol><li><strong>Store</strong> each vector alongside its original text and metadata.</li><li><strong>Index</strong> those vectors in a way that makes searching fast, even across millions of entries.</li><li><strong>Retrieve</strong> the closest matching vectors to any new query vector, almost instantly.</li></ol><p>This is fundamentally different from what a traditional database is built for. A normal SQL database is excellent at exact lookups (WHERE id = 42) and range queries (WHERE price &lt; 100). But &quot;find me the 5 vectors that are most <em>similar</em> to this one&quot; isn&#39;t a query type traditional indexes (B-trees, hash indexes) can answer efficiently — you&#39;d have to compare your query against every single row, one by one, which becomes painfully slow once you have more than a few thousand vectors. Vector stores exist specifically to solve this problem.</p><h3>Where Vector Stores Fit in a RAG Pipeline</h3><p>The vector store sits right at the boundary between the two halves of a RAG system: it’s the last step of <strong>ingestion</strong>, and the first thing touched during <strong>retrieval</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kezrlXViZiFy2EA30MtuXQ.png" /></figure><p>During ingestion, you build the vector store once (or update it incrementally as new documents arrive): documents get loaded, split into chunks, embedded, and those embeddings get written into the vector store’s index.</p><p>During retrieval — which happens on <em>every single user query</em> — the flow reverses: the user’s question gets embedded using the same embedding model, and that query vector is handed to the vector store, which returns the top-k most similar chunks. Those chunks become the context the LLM uses to generate its answer.</p><p>This dual role is worth remembering: the vector store isn’t just “storage” — it’s an active participant in retrieval quality. A poorly configured vector store (wrong distance metric, bad indexing parameters, no metadata filtering) can quietly degrade your RAG system’s answers even if your chunking and embedding steps were done perfectly.</p><h3>How Similarity Search Actually Works</h3><p>At its core, similarity search is about measuring the “distance” between two vectors and assuming that vectors close together in that high-dimensional space represent semantically similar content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pM4TZkgPE3Y8d0XpuQh4w.png" /></figure><h3>Distance Metrics</h3><p>There are three distance metrics you’ll run into constantly:</p><ul><li><strong>Cosine similarity</strong> — measures the angle between two vectors, ignoring their magnitude. This is the most common choice for text embeddings, since it captures directional similarity in meaning regardless of vector length.</li><li><strong>Dot product</strong> — similar to cosine similarity but also factors in magnitude. Some embedding models are specifically trained to work best with dot product, so it’s worth checking your model’s documentation.</li><li><strong>Euclidean (L2) distance</strong> — straight-line distance between two points. More common in classic ML contexts than in text embedding search, but still supported by most vector stores.</li></ul><p>Most embedding models will tell you which metric they were optimized for — using the wrong one won’t necessarily break your pipeline, but it can quietly hurt retrieval quality.</p><h3>Why You Need Approximate Nearest Neighbor (ANN) Search</h3><p>The naive way to find the closest vectors is <strong>brute-force search</strong>: compare your query vector against every single stored vector, compute the distance for each, and sort. This is exact, but it’s an O(n) operation — and it gets painfully slow once you’re indexing hundreds of thousands or millions of chunks.</p><p>This is where <strong>Approximate Nearest Neighbor (ANN)</strong> algorithms come in. Instead of comparing against every vector, ANN algorithms build a smarter index structure that lets you find <em>almost certainly</em> the closest vectors while only examining a small fraction of the total data. The two most common ANN approaches you’ll encounter:</p><ul><li><strong>HNSW (Hierarchical Navigable Small World graphs)</strong> — builds a multi-layered graph where search starts at a coarse layer and progressively narrows down to precise neighbors. Used by FAISS, Chroma, Qdrant, Weaviate, and most modern vector stores. Generally the best balance of speed and accuracy for most RAG use cases.</li><li><strong>IVF (Inverted File Index)</strong> — clusters vectors into buckets ahead of time, then only searches within the buckets closest to the query. Faster to build than HNSW at very large scale, with a small accuracy trade-off.</li></ul><p>You rarely need to implement these yourself — every major vector store handles ANN indexing internally. But understanding that retrieval is <em>approximate</em>, not exhaustive, explains why tuning index parameters (like ef_search in HNSW) can meaningfully affect both speed and recall in production systems.</p><h3>Popular Vector Store Options</h3><p>There’s no single “correct” vector store — the right choice depends on your scale, whether you want to self-host, and how tightly integrated you need filtering and hybrid search to be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nbb8CMxvOJND44Epz-cG2w.png" /></figure><p>A quick breakdown:</p><ul><li><strong>FAISS</strong> — Meta’s open-source ANN library. Extremely fast, runs entirely in-memory or on disk, no server required. Great for prototyping or smaller, self-contained applications, but you handle persistence and scaling yourself.</li><li><strong>Chroma</strong> — a lightweight, embeddable vector store built specifically with LLM applications in mind. Very easy to get running locally, which makes it a popular first choice for RAG tutorials and small-to-medium projects.</li><li><strong>Pinecone</strong> — a fully managed, serverless vector database. You don’t manage any infrastructure; it scales to billions of vectors and handles indexing, sharding, and availability for you — at the cost of being a paid, hosted service.</li><li><strong>Weaviate</strong> — open-source, with built-in support for hybrid search (combining vector similarity with traditional keyword/BM25 search) and rich metadata filtering out of the box.</li><li><strong>Qdrant</strong> — written in Rust, known for fast, precise filtering on metadata alongside vector search, which matters a lot when you need to combine “similar to X” with “and published after 2024.”</li><li><strong>Milvus</strong> — built for very large-scale, distributed vector search, commonly used when you’re indexing hundreds of millions of vectors across a cluster.</li><li><strong>pgvector</strong> — a PostgreSQL extension that adds vector similarity search directly into Postgres. Ideal if you already run Postgres and want to avoid standing up a separate vector database service.</li><li><strong>Elasticsearch</strong> — adds vector search capabilities onto an existing Elasticsearch deployment, useful if you already rely on it for logging or full-text search and want to add semantic search without a new system.</li></ul><p>For most people getting started, <strong>Chroma</strong> or <strong>FAISS</strong> are the easiest on-ramps. For production systems with real scale and uptime requirements, <strong>Pinecone</strong>, <strong>Qdrant</strong>, or <strong>Weaviate</strong> are common choices.</p><h3>Using a Vector Store in LangChain</h3><p>LangChain provides a consistent interface across almost all of these vector stores, so switching between them later is mostly a matter of changing a few lines, not rewriting your pipeline.</p><h3>Building a Vector Store from Documents</h3><pre>from langchain_community.vectorstores import Chroma<br>from langchain_openai import OpenAIEmbeddings<br><br># &#39;chunks&#39; is the list of Document objects from your text splitter<br>embeddings = OpenAIEmbeddings()<br><br>vector_store = Chroma.from_documents(<br>    documents=chunks,<br>    embedding=embeddings,<br>    persist_directory=&quot;./chroma_db&quot;,<br>)</pre><p>That single call embeds every chunk and writes both the vectors and their metadata into a local, persistent Chroma index.</p><h3>Querying the Vector Store</h3><pre>query = &quot;What changed in the version 2 release?&quot;<br><br>results = vector_store.similarity_search(query, k=4)<br><br>for doc in results:<br>    print(doc.page_content[:200])<br>    print(doc.metadata)<br>    print(&quot;---&quot;)</pre><p>similarity_search handles embedding the query internally and returns the top-k most similar Document objects, ready to feed into your LLM as context.</p><p>If you want the actual similarity scores alongside the results (useful for debugging or setting a relevance threshold):</p><pre>results_with_scores = vector_store.similarity_search_with_score(query, k=4)<br><br>for doc, score in results_with_scores:<br>    print(f&quot;{score:.4f}  {doc.page_content[:100]}&quot;)</pre><h3>Filtering by Metadata</h3><p>Since every chunk carries metadata from the document loading step, you can narrow a search to a subset of your data — for example, only chunks from a specific file or after a certain date:</p><pre>results = vector_store.similarity_search(<br>    query,<br>    k=4,<br>    filter={&quot;source&quot;: &quot;release_notes_v2.pdf&quot;},<br>)</pre><p>This is one of the most underused features of vector stores — combining semantic similarity with structured metadata filters usually produces noticeably better retrieval than similarity search alone, especially in knowledge bases with many overlapping topics.</p><h3>Using FAISS Instead</h3><p>Swapping to a different vector store is largely mechanical:</p><pre>from langchain_community.vectorstores import FAISS<br><br>vector_store = FAISS.from_documents(chunks, embeddings)<br><br># Save to disk<br>vector_store.save_local(&quot;faiss_index&quot;)<br><br># Reload later<br>vector_store = FAISS.load_local(<br>    &quot;faiss_index&quot;, embeddings, allow_dangerous_deserialization=True<br>)</pre><h3>Turning a Vector Store Into a Retriever</h3><p>For use inside a RAG chain, you’ll usually wrap the vector store as a retriever:</p><pre>retriever = vector_store.as_retriever(search_kwargs={&quot;k&quot;: 4})<br><br>relevant_docs = retriever.invoke(&quot;What changed in the version 2 release?&quot;)</pre><p>This is the object that typically gets passed directly into a RAG chain, so the retrieval step is a single, clean call.</p><h3>Practical Tips</h3><ul><li><strong>Match your distance metric to your embedding model.</strong> Most embedding models document which metric they were trained for — using cosine similarity with a model trained for dot product (or vice versa) can silently hurt retrieval quality.</li><li><strong>Don’t over-fetch.</strong> Retrieving k=20 chunks &quot;just in case&quot; usually hurts more than it helps — it dilutes the LLM&#39;s context with less relevant material. Start with k=3 to k=5 and adjust based on actual answer quality.</li><li><strong>Use metadata filters aggressively.</strong> If you know a query is about a specific document, date range, or category, filtering before (or alongside) similarity search almost always beats pure semantic search alone.</li><li><strong>Re-index when you change embedding models.</strong> Vectors from different embedding models aren’t compatible with each other — if you switch models, you need to re-embed and rebuild your entire vector store, not just append new vectors.</li><li><strong>Persist your index.</strong> Don’t rebuild your vector store from scratch on every application restart — use persist_directory, save_local, or your store&#39;s equivalent so ingestion only has to happen once (and again when your source documents change).</li></ul><h3>Wrapping Up</h3><p>The vector store is where all the earlier work in your RAG pipeline — loading, splitting, embedding — actually pays off. It’s the component that turns a pile of numeric vectors into something genuinely useful: the ability to ask a natural-language question and get back exactly the right pieces of your knowledge base, in milliseconds, no matter how large that knowledge base grows.</p><p>Start simple — Chroma or FAISS running locally is more than enough for prototyping and most small-to-medium applications. As your data and traffic grow, the same LangChain interface makes it straightforward to move to a managed option like Pinecone or a self-hosted, filter-heavy option like Qdrant, without rethinking the rest of your pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a247c63154ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Document Loaders in RAG: The First (and Most Overlooked) Step of Your Pipeline]]></title>
            <link>https://medium.com/@hunkcool1991/document-loaders-in-rag-the-first-and-most-overlooked-step-of-your-pipeline-af3106c5a186?source=rss-9c75f648a393------2</link>
            <guid isPermaLink="false">https://medium.com/p/af3106c5a186</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[AMIT KASHYAP]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 05:56:46 GMT</pubDate>
            <atom:updated>2026-08-06T05:56:46.186Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pxKn8hnRKtfldTjoVPwX5w.png" /></figure><h3>Before you can split, embed, or retrieve anything — you have to get your data in. Here’s how that actually works.</h3><p>Every RAG (Retrieval-Augmented Generation) tutorial spends most of its time on the glamorous parts: embeddings, vector databases, retrieval strategies, prompt design. Almost nobody spends real time on the component that runs <em>before</em> any of that — the one responsible for actually getting your raw data into your pipeline in the first place.</p><p>That component is the <strong>Document Loader</strong>, and it’s the true starting point of every RAG application. Get it wrong, and everything downstream — your chunks, your embeddings, your retrieved context — inherits the damage. Get it right, and the rest of your pipeline barely has to think about <em>where</em> the data came from.</p><p>In this article, we’ll cover:</p><ul><li>What a document loader actually is, and the common Document object every loader produces</li><li>Where document loaders fit in a RAG pipeline</li><li>Why a dedicated loading step matters instead of just reading files yourself</li><li>The most common loader types — PDFs, web pages, CSVs, JSON, plain text, whole directories — with LangChain code for each</li><li>Practical tips for choosing and combining loaders</li></ul><h3>What Is a Document Loader?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZI-JFdm54xLSeZXM_6v0A.png" /></figure><p>A <strong>document loader</strong> is a small, focused piece of code whose only job is to pull content from some external source — a PDF on disk, a live webpage, a CSV file, a Notion workspace, a database — and convert it into a <strong>standard, predictable format</strong> that the rest of your RAG pipeline can work with.</p><p>That standard format, at least in LangChain, is a Document object. No matter which loader you use, you get back a list of Document objects, and every one of them has exactly two things:</p><ul><li><strong>page_content</strong> — the actual text extracted from the source (a page of a PDF, a paragraph from a webpage, a row from a spreadsheet)</li><li><strong>metadata</strong> — a dictionary of contextual information about where that content came from (file name, page number, URL, row index, timestamps, and so on)</li></ul><p>This uniformity is the entire point. Your text splitter doesn’t need to know or care whether the underlying source was a PDF or a Notion page — it just sees a Document with a page_content string and splits it. Your embedding model doesn&#39;t care either — it just embeds page_content. The metadata tags along for the ride so you can later filter search results, cite sources, or trace an answer back to exactly which file and page it came from.</p><h3>Where Document Loaders Fit in a RAG Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ru-WcgQLcOPapj0sTGczWQ.png" /></figure><p>Document loaders sit at the very front of the ingestion pipeline — before text splitting, before embedding, before anything else happens.</p><p>The flow looks like this:</p><ol><li><strong>Raw Sources</strong> — your actual data, wherever it lives: PDFs, HTML pages, CSVs, APIs, internal databases.</li><li><strong>Document Loaders</strong> — pull that raw content and normalize it into Document objects.</li><li><strong>Text Splitters</strong> — break each Document into smaller, manageable chunks.</li><li><strong>Embedding Model</strong> — converts each chunk into a vector.</li><li><strong>Vector Store</strong> — stores and indexes those vectors for retrieval.</li></ol><p>Everything from step 3 onward assumes it’s working with clean Document objects. If your loading step is sloppy — say, it drops page numbers, or garbles PDF text extraction, or fails silently on half your files — that damage propagates through every later stage, and you often won&#39;t notice until your retrieval results start looking oddly incomplete or your citations point to the wrong source.</p><h3>Why Not Just Read the Files Yourself?</h3><p>It’s a fair question — reading a text file is one line of Python. So why bother with a dedicated loader abstraction at all?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mruAGLTqaGPWM3iRnHZOUQ.png" /></figure><p>A few concrete reasons:</p><h3>1. A Consistent Interface Across Wildly Different Sources</h3><p>Reading a .txt file, parsing a PDF, scraping a live webpage, and querying a Notion database are all completely different problems under the hood. A document loader hides that complexity behind one consistent method — .load() — so the rest of your code never has to branch on &quot;if this is a PDF do X, if it&#39;s a webpage do Y.&quot;</p><h3>2. Correct Handling of Format-Specific Quirks</h3><p>PDFs are notoriously messy — text can be embedded in unpredictable reading order, tables can turn into scrambled text, images and scanned pages need OCR. A good loader handles these quirks for you (or at least gives you consistent, predictable failure modes) instead of leaving you to reinvent PDF parsing from scratch.</p><h3>3. Automatic Metadata Capture</h3><p>A loader typically captures useful metadata automatically — file path, page number, URL, last-modified date — that you’d otherwise have to track manually. This metadata becomes essential later for filtering searches or showing users exactly where an answer came from.</p><h3>4. Batch and Directory-Level Loading</h3><p>Real-world RAG systems rarely ingest a single file — they ingest folders full of files, or entire websites, or a whole Notion workspace. Loaders built for this (like a DirectoryLoader) handle iteration, error handling, and aggregation for you.</p><p>Now let’s get into the loaders themselves.</p><h3>1. Loading PDFs</h3><p>PDFs are probably the single most common source in real RAG applications — reports, research papers, manuals, contracts. LangChain’s PyPDFLoader extracts text page by page, and each page becomes its own Document, with the page number automatically stored in metadata.</p><pre>from langchain_community.document_loaders import PyPDFLoader<br><br>loader = PyPDFLoader(&quot;quarterly_report.pdf&quot;)<br>docs = loader.load()<br><br>print(f&quot;Loaded {len(docs)} pages&quot;)<br>print(docs[0].page_content[:300])<br>print(docs[0].metadata)<br># {&#39;source&#39;: &#39;quarterly_report.pdf&#39;, &#39;page&#39;: 0}</pre><p>Since each page becomes a separate Document, you get accurate page-level metadata for free — which is exactly what you want when you later need to point a user to &quot;page 4 of the Q3 report&quot; instead of just &quot;somewhere in this PDF.&quot;</p><p>For PDFs with tricky layouts (multi-column text, embedded tables, scanned images), you may need a more advanced loader like UnstructuredPDFLoader or an OCR-aware pipeline — but PyPDFLoader is the right default starting point for standard, text-based PDFs.</p><h3>2. Loading Web Pages</h3><p>If your knowledge base includes live web content — documentation sites, blog posts, product pages — WebBaseLoader fetches and parses HTML directly from a URL.</p><pre>from langchain_community.document_loaders import WebBaseLoader<br><br>loader = WebBaseLoader(&quot;https://example.com/blog/rag-best-practices&quot;)<br>docs = loader.load()<br><br>print(docs[0].page_content[:500])<br>print(docs[0].metadata)<br># {&#39;source&#39;: &#39;https://example.com/blog/rag-best-practices&#39;, &#39;title&#39;: &#39;...&#39;}</pre><p>You can also pass a list of URLs to load multiple pages in one call:</p><pre>loader = WebBaseLoader([<br>    &quot;https://example.com/docs/getting-started&quot;,<br>    &quot;https://example.com/docs/api-reference&quot;,<br>])<br>docs = loader.load()</pre><p>Keep in mind that raw HTML often carries a lot of noise — navigation menus, footers, ads — mixed in with the actual content. Depending on the site, you may want to pair this with additional cleanup, or use a more targeted extraction loader for particularly messy pages.</p><h3>3. Loading CSV Files</h3><p>Tabular data — customer records, product catalogs, survey responses — needs a different treatment than free-flowing prose. CSVLoader loads a CSV row by row, turning each row into its own Document.</p><pre>from langchain_community.document_loaders import CSVLoader<br><br>loader = CSVLoader(file_path=&quot;products.csv&quot;)<br>docs = loader.load()<br><br>print(docs[0].page_content)<br># &quot;name: Wireless Mouse\nprice: 799\ncategory: Electronics&quot;<br>print(docs[0].metadata)<br># {&#39;source&#39;: &#39;products.csv&#39;, &#39;row&#39;: 0}</pre><p>Each row’s columns are rendered as key: value pairs inside page_content by default, which keeps the row&#39;s structure readable and embeddable. You can also tell the loader which column to treat as the primary content field if your CSV has one obvious &quot;main text&quot; column (like a product description) and treat the rest as supporting metadata.</p><h3>4. Loading Plain Text Files</h3><p>The simplest case — a .txt file — is handled by TextLoader.</p><pre>from langchain_community.document_loaders import TextLoader<br><br>loader = TextLoader(&quot;notes.txt&quot;, encoding=&quot;utf-8&quot;)<br>docs = loader.load()<br><br>print(docs[0].page_content)<br>print(docs[0].metadata)<br># {&#39;source&#39;: &#39;notes.txt&#39;}</pre><p>There’s no page or row structure here — the whole file becomes a single Document. This is usually fine, since your text splitter will handle breaking it down further in the next pipeline stage.</p><h3>5. Loading Structured JSON</h3><p>JSON files are common for API exports, structured logs, or configuration-driven content. JSONLoader uses a jq-style query to pull out exactly the fields you want as page_content.</p><pre>from langchain_community.document_loaders import JSONLoader<br><br>loader = JSONLoader(<br>    file_path=&quot;support_tickets.json&quot;,<br>    jq_schema=&quot;.tickets[].description&quot;,<br>    text_content=True,<br>)<br>docs = loader.load()<br><br>print(docs[0].page_content)<br>print(len(docs))</pre><p>The jq_schema parameter is powerful once you get comfortable with it — it lets you navigate nested JSON structures precisely, rather than dumping the entire raw JSON blob as text (which usually produces poor embeddings, since JSON syntax itself carries no semantic meaning).</p><h3>6. Loading an Entire Directory</h3><p>In practice, you’re rarely loading a single file — you’re loading an entire folder of mixed documents. DirectoryLoader handles this by recursively walking a directory and applying a specified loader class to every matching file.</p><pre>from langchain_community.document_loaders import DirectoryLoader, PyPDFLoader<br><br>loader = DirectoryLoader(<br>    &quot;./knowledge_base/&quot;,<br>    glob=&quot;**/*.pdf&quot;,<br>    loader_cls=PyPDFLoader,<br>    show_progress=True,<br>)<br>docs = loader.load()<br><br>print(f&quot;Loaded {len(docs)} pages across all PDFs&quot;)</pre><p>You can run this once per file type (one pass for PDFs, another for .txt files, another for .csv files) and simply concatenate the resulting Document lists before passing everything into your text splitter. This pattern — one DirectoryLoader per format, merged into a single list — is how most real-world ingestion pipelines are actually built.</p><h3>7. Loading From Other Sources (Notion, Databases, and Beyond)</h3><p>Beyond files, LangChain ships loaders for a long list of third-party sources — Notion workspaces, Confluence spaces, Slack exports, SQL databases, Google Drive, S3 buckets, and many more. The interface stays exactly the same: instantiate the loader with your source-specific credentials or query, call .load(), and get back a list of Document objects.</p><pre>from langchain_community.document_loaders import NotionDBLoader<br><br>loader = NotionDBLoader(<br>    integration_token=&quot;secret_...&quot;,<br>    database_id=&quot;your-database-id&quot;,<br>)<br>docs = loader.load()</pre><p>This is the real payoff of the loader abstraction: once you’ve learned the pattern once, adding a brand-new data source to your RAG pipeline is rarely more than a few lines of setup code, not a new parsing system to build from scratch.</p><h3>Practical Tips for Working With Loaders</h3><p>A few things worth keeping in mind as you build out a real ingestion pipeline:</p><ul><li><strong>Always inspect </strong><strong>metadata after loading a new source.</strong> Different loaders populate different fields, and you&#39;ll want to know exactly what&#39;s available before you rely on it for filtering or citations later.</li><li><strong>Handle loading failures gracefully</strong>, especially with DirectoryLoader over large, messy folders — a single corrupted PDF shouldn&#39;t take down your entire ingestion run.</li><li><strong>Normalize metadata keys</strong> across loaders if you’re combining multiple source types, so your retrieval and citation logic doesn’t have to special-case every loader.</li><li><strong>Don’t skip the loading step even for “simple” sources.</strong> It’s tempting to just open(file).read() a text file directly, but going through a loader keeps your metadata and downstream pipeline consistent, and makes it trivial to swap in a different source later.</li></ul><h3>Wrapping Up</h3><p>Document loaders don’t get much attention in most RAG tutorials, but they’re doing quietly essential work: turning a chaotic mix of PDFs, webpages, spreadsheets, and databases into one consistent shape that the rest of your pipeline can rely on. The Document object — page_content plus metadata — is the contract that makes everything downstream (splitting, embedding, retrieval, citation) work generically, regardless of where the data actually came from.</p><p>Get comfortable with the common loaders — PDF, web, CSV, text, JSON, and directory-level batch loading — and you’ll be able to plug almost any data source into a RAG pipeline in a few lines of code.</p><p>Next up in this series: once your documents are loaded, it’s time to break them into the right-sized chunks — which is exactly what <a href="https://medium.com/">Text Splitters</a> handle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af3106c5a186" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Splitters in RAG: The Most Underrated Component of Your LLM Pipeline]]></title>
            <link>https://medium.com/@hunkcool1991/text-splitters-in-rag-the-most-underrated-component-of-your-llm-pipeline-a3b7fc4422c2?source=rss-9c75f648a393------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3b7fc4422c2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[AMIT KASHYAP]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 05:34:18 GMT</pubDate>
            <atom:updated>2026-08-06T05:35:31.337Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why breaking your documents into the right chunks matters more than you think — and four practical strategies to do it well</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqwwH781bNUowGtlJgvgNg.png" /></figure><p>If you’re building a Retrieval-Augmented Generation (RAG) application, it’s tempting to focus all your energy on picking the “best” LLM or the fanciest vector database. But there’s a quieter component sitting right in the middle of your pipeline that quietly decides whether your whole system works well or falls apart: <strong>the text splitter</strong>.</p><p>In this article, we’ll cover:</p><ul><li>What text splitting actually is, and why it matters so much for LLM-powered applications</li><li>Exactly where text splitters fit inside a RAG pipeline</li><li>Four practical text-splitting strategies — Length Based, Text Structure Based, Document Structure Based, and Semantic Meaning Based — with code examples using LangChain</li><li>The trade-offs of each approach, so you know which one to reach for</li></ul><h3>What Is Text Splitting?</h3><p>Imagine you have a massive PDF — thousands of pages long — and you need an LLM to process it somehow: summarize it, answer questions about it, or search through it semantically. Feeding the entire document to the model in one shot is usually a bad idea, and often not even possible.</p><p><strong>Text splitting</strong> is the process of breaking a large piece of text (an article, a PDF, an HTML page, a book) into smaller, manageable pieces — called <strong>chunks</strong> — that an LLM (or an embedding model) can handle effectively. The tool that performs this operation is called a <strong>text splitter</strong>.</p><p>The simplest mental picture: take one large document and break it into several smaller ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwHnVSenLozarrqc4uROOA.png" /></figure><p>Once you understand what text splitting is, the natural next question is: where does this actually happen in a real application? Let’s zoom out and look at the bigger picture first.</p><h3>Where Text Splitters Fit in a RAG Pipeline</h3><p>A typical RAG pipeline has two halves: an <strong>ingestion pipeline</strong> (where you prepare your knowledge base) and a <strong>retrieval + generation pipeline</strong> (where you actually answer user queries).</p><p>Text splitters sit right in the middle of the ingestion half — immediately after your documents are loaded, and immediately before they’re turned into embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXeFOpyun44cIt_XPzHrVQ.png" /></figure><p>Here’s the flow in words:</p><ol><li><strong>Document Loaders</strong> pull raw content from PDFs, websites, APIs, or files, and turn each source into a Document object.</li><li><strong>Text Splitters</strong> break each document into smaller chunks.</li><li>An <strong>Embedding Model</strong> converts each chunk into a vector.</li><li>A <strong>Vector Store</strong> stores and indexes those vectors for fast similarity search.</li><li>When a user asks a question, a <strong>Retriever</strong> searches the vector store for the most relevant chunks.</li><li>Those chunks are passed to the <strong>LLM</strong>, which uses them as context to generate a grounded answer.</li></ol><p>If your text splitter does a poor job, every downstream step inherits that damage: noisy embeddings, irrelevant retrieval results, and vague or hallucinated answers. Good chunking is what makes the rest of the pipeline trustworthy.</p><h3>Why Text Splitting Is So Important</h3><p>There are a few concrete, well-documented reasons why text splitting matters so much when building LLM-powered applications.</p><h4>1. It Overcomes Context Length Limits</h4><p>Every LLM (and every embedding model) has a maximum input size — a <strong>context length</strong>. Suppose a model can only accept 50,000 words in a single input, and your PDF has over 100,000 words. You simply cannot send the whole document in one go. Splitting the text into chunks that individually fit within the model’s context window is the most basic reason text splitters exist.</p><h4>2. It Improves Embedding Quality</h4><p>When you generate an embedding for a very large piece of text, the resulting vector struggles to capture the semantic meaning of everything inside it. A giant blob of text covering multiple topics gets compressed into a single vector that represents none of those topics particularly well.</p><p>For example, imagine one long paragraph that talks about three different IPL cricket teams, one after another. If you embed that entire paragraph as a single vector, the embedding will be a blurry average of three different topics. But if you split it so each team gets its own chunk — and generate a separate embedding for each — every vector captures its topic’s meaning far more precisely.</p><h4>3. It Improves Semantic Search</h4><p>This follows directly from better embeddings. If you’ve split your documents into focused, topic-coherent chunks and generated separate embeddings for each, a similarity search against a user’s query will surface far more relevant matches than searching over embeddings of huge, mixed-topic documents.</p><h4>4. It Improves Summarization and Reduces Hallucination</h4><p>LLMs tend to struggle with very large inputs — they can drift off-topic or even hallucinate details that aren’t actually in the source document. Feeding smaller, focused chunks (and summarizing or processing them individually, then combining results) empirically produces more reliable output.</p><h4>5. It Optimizes Computational Resources</h4><p>Smaller chunks require less memory to process and store, and they can be processed in parallel — which matters a lot once you’re dealing with production-scale document collections.</p><p>Now that we understand <em>why</em> text splitting matters, let’s get into <em>how</em> it’s actually done. There are four major strategies, and we’ll go through each one in order of increasing sophistication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzXmbbF5Ve2gSHSiscj0TQ.png" /></figure><h3>1. Length-Based Text Splitting</h3><p>This is, honestly, the simplest and fastest way to split text.</p><p><strong>How it works:</strong> You decide upfront how big each chunk should be — in characters or tokens. Then you simply walk through the text from the beginning, and every time you hit your chunk size limit, you cut and start a new chunk.</p><p>For example, if your chunk size is 100 characters, you traverse the text, and the moment you’ve collected 100 characters, that becomes Chunk 1. You resume right where you left off, count another 100 characters, and that becomes Chunk 2 — and so on until the text is exhausted.</p><h4>LangChain Implementation</h4><pre>from langchain_text_splitters import CharacterTextSplitter<br><br>text = &quot;your large piece of text goes here...&quot;<br><br>splitter = CharacterTextSplitter(<br>    chunk_size=100,<br>    chunk_overlap=0,<br>    separator=&quot;&quot;<br>)<br><br>chunks = splitter.split_text(text)<br>print(chunks)</pre><p>You can also connect this directly to a document loader:</p><pre>from langchain_community.document_loaders import PyPDFLoader<br>from langchain_text_splitters import CharacterTextSplitter<br><br>loader = PyPDFLoader(&quot;your_file.pdf&quot;)<br>docs = loader.load()<br><br>splitter = CharacterTextSplitter(chunk_size=200, chunk_overlap=0, separator=&quot;&quot;)<br>chunks = splitter.split_documents(docs)<br><br>print(chunks[0].page_content)</pre><h4>Pros and Cons</h4><p><strong>Advantage:</strong> It’s conceptually simple, trivial to implement, and extremely fast.</p><p><strong>Disadvantage:</strong> It has zero awareness of linguistic structure, grammar, or semantic meaning. If the 100-character mark lands in the middle of a word, a sentence, or a paragraph — it doesn’t care. It just cuts. This means important context can get split awkwardly across two chunks, hurting embedding quality and downstream retrieval.</p><h4>A Quick Note on Chunk Overlap</h4><p>Alongside chunk_size, LangChain&#39;s splitters expose a chunk_overlap parameter. This defines how many characters are repeated between two consecutive chunks.</p><p>The idea: since abrupt cuts can break context mid-sentence or mid-word, overlapping a small window of text between chunks lets some of that “lost” context carry over into the next chunk.</p><p>There’s a trade-off, though. Too much overlap means more redundant content across chunks (and more chunks overall, meaning more computation). Too little, and you lose the benefit entirely. A commonly recommended range for RAG applications is <strong>10–20% of your chunk size</strong> as overlap. So for a chunk size of 100, an overlap somewhere between 10 and 20 characters is a reasonable starting point.</p><h3>2. Text-Structure-Based Text Splitting</h3><p>Length-based splitting ignores structure completely — but real text is never just a flat stream of characters. It’s organized hierarchically: documents are made of <strong>paragraphs</strong>, paragraphs are made of <strong>sentences</strong>, and sentences are made of <strong>words</strong>.</p><p>This is exactly the insight the next technique exploits. It’s called the <strong>Recursive Character Text Splitter</strong>, and it’s one of the most widely used text splitters in practice.</p><h4>How It Works</h4><p>You define a prioritized list of separators, roughly in this order:</p><ol><li>&quot;\n\n&quot; — paragraph breaks</li><li>&quot;\n&quot; — line/sentence breaks</li><li>&quot; &quot; — word boundaries (spaces)</li><li>&quot;&quot; — individual characters (last resort)</li></ol><p>The algorithm tries the largest, most “natural” separator first. If splitting on paragraphs produces chunks that are still too big, it falls back to splitting on sentences. If that’s still too big, it falls back to words. And only if nothing else works does it fall back to raw character-level splitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZlL6Op2McmFT2Kn5pR6Jw.png" /></figure><p>After splitting, the algorithm also tries to be efficient: if two adjacent small chunks can be merged back together without exceeding the chunk size limit, it merges them — so you don’t end up with a pile of unnecessarily tiny chunks.</p><h4>Walking Through an Example</h4><p>Say your text is:</p><pre>My name is Amit. I am 35 years old.<br>I live in Gurgaon.<br>How are you?</pre><p>With a chunk size of 10:</p><ul><li>It first tries to split on paragraphs. Since the whole thing is one paragraph in this case (no blank line), it falls to the next separator.</li><li>It splits on sentences (\n), then on words, since individual sentences still exceed 10 characters.</li><li>At the word level, it greedily merges adjacent short words back together as long as the merged chunk stays under the limit — e.g., “My” and “name” might merge into “My name”, but adding “is” would push it over 10, so it stops there.</li><li>The final result ends up being chunks like &quot;My name is&quot;, &quot;Amit.&quot;, &quot;I am 35&quot;, &quot;years old.&quot;, &quot;I live in&quot;, &quot;Gurgaon.&quot;, &quot;How are&quot;, &quot;you?&quot; — never breaking in the middle of a word.</li></ul><p>If you increase the chunk size to 25, you’ll notice the splitter increasingly favors sentence-level chunks. Push it to 50, and it may keep entire paragraphs intact. The bigger your chunk size, the more “natural” (paragraph- or sentence-level) your splits become — which is exactly why this method significantly outperforms plain length-based splitting.</p><h4>LangChain Implementation</h4><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br><br>text = &quot;your large piece of text goes here...&quot;<br><br>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=300,<br>    chunk_overlap=0<br>)<br><br>chunks = splitter.split_text(text)<br>print(len(chunks))<br>print(chunks[0])</pre><p>Because it respects natural language boundaries far better than a pure length-based approach, the Recursive Character Text Splitter is the technique you’ll reach for most often in real-world RAG applications.</p><h3>3. Document-Structure-Based Text Splitting</h3><p>Text-structure-based splitting assumes your content is organized like natural language — paragraphs, sentences, words. But what if your document isn’t plain prose at all? What if it’s source code, or Markdown?</p><p>Code and Markdown have their own structural conventions — class and def keywords in Python, headings and lists in Markdown — instead of paragraphs and sentences. This is where <strong>Document-Structure-Based splitting</strong> comes in.</p><p>It’s really just an extension of the Recursive Character Text Splitter, with a different set of separators tailored to the document type. For Python code, for example, the separator hierarchy includes constructs like class, def, and standard newline/space separators as fallbacks. For Markdown, the separators are things like headers, list markers, and code blocks.</p><h4>LangChain Implementation — Python Code</h4><p>python</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter, Language<br><br>python_code = &quot;&quot;&quot;<br>class Calculator:<br>    def __init__(self):<br>        self.result = 0<br><br>    def add(self, x):<br>        self.result += x<br>        return self.result<br><br>calc = Calculator()<br>if calc.add(5) &gt; 0:<br>    print(&quot;positive&quot;)<br>&quot;&quot;&quot;<br><br>splitter = RecursiveCharacterTextSplitter.from_language(<br>    language=Language.PYTHON,<br>    chunk_size=150,<br>    chunk_overlap=0<br>)<br><br>chunks = splitter.split_text(python_code)<br>print(chunks[0])  # class definition and constructor<br>print(chunks[1])  # usage code</pre><h4>LangChain Implementation — Markdown</h4><p>python</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter, Language<br><br>markdown_text = &quot;&quot;&quot;<br># Getting Started<br>Install the package and set up your environment.<br><br>## Features<br>- Fast<br>- Lightweight<br><br>## Text Tags<br>Use tags to organize your content.<br>&quot;&quot;&quot;<br><br>splitter = RecursiveCharacterTextSplitter.from_language(<br>    language=Language.MARKDOWN,<br>    chunk_size=200,<br>    chunk_overlap=0<br>)<br><br>chunks = splitter.split_text(markdown_text)<br>for c in chunks:<br>    print(c)<br>    print(&quot;---&quot;)</pre><p>LangChain supports this from_language pattern for many languages beyond Python and Markdown — including JavaScript, Java, PHP, and HTML — so the same core idea (recursive splitting with language-aware separators) extends naturally to almost any structured document type you&#39;re likely to encounter.</p><h3>4. Semantic-Meaning-Based Text Splitting</h3><p>Length-based and structure-based splitting both work well in most cases — but there’s a category of scenario where both fail.</p><p>Consider a paragraph that starts off talking about farmers and agriculture, then — without any paragraph break — shifts into talking about an IPL cricket match, and finally, in a separate paragraph, discusses terrorism. Structurally, this looks like two paragraphs. But semantically, there are really <strong>three</strong> distinct topics, and the topic shift happens <em>mid-paragraph</em>, where no structural separator exists to catch it.</p><p>If you run a Recursive Character Text Splitter on this text, it’ll likely produce two chunks — split on the paragraph break — but the first chunk will still contain two unrelated topics jammed together, hurting the quality of its embedding.</p><p>This is exactly the gap that <strong>Semantic Meaning Based</strong> splitting is designed to fill.</p><h4>How It Works</h4><p>Instead of deciding where to split based on length or structural separators, this approach decides based on the <em>meaning</em> of the text itself:</p><ol><li>Break the text into individual sentences.</li><li>Generate an embedding vector for each sentence using an embedding model (e.g., an OpenAI embedding model).</li><li>Compute the similarity (typically cosine similarity) between each pair of consecutive sentence embeddings, sliding through the text one sentence at a time.</li><li>Wherever the similarity between two consecutive sentences drops sharply, that’s flagged as a likely topic change — and a split point.</li></ol><p>One common way to define “sharply” is using <strong>standard deviation</strong>: calculate the standard deviation across all the consecutive-sentence similarity scores, then treat any point where the distance between two sentences exceeds a chosen number of standard deviations (e.g., one) as a breakpoint.</p><h4>LangChain Implementation</h4><p>python</p><pre>from langchain_experimental.text_splitter import SemanticChunker<br>from langchain_openai.embeddings import OpenAIEmbeddings<br><br>text = &quot;your large piece of text with mixed topics...&quot;<br><br>splitter = SemanticChunker(<br>    OpenAIEmbeddings(),<br>    breakpoint_threshold_type=&quot;standard_deviation&quot;,<br>    breakpoint_threshold_amount=1<br>)<br><br>chunks = splitter.create_documents([text])<br>print(len(chunks))<br>for c in chunks:<br>    print(c.page_content)<br>    print(&quot;---&quot;)</pre><p>Other supported threshold types include percentile, interquartile range, and gradient-based methods — each offering a different way to decide how large a similarity drop needs to be before it counts as a topic boundary.</p><h4>The Catch</h4><p>This is a genuinely promising idea, and as embedding models continue to improve, it’s likely to become more reliable over time. But as of today, it’s still fairly experimental — it lives in langchain_experimental rather than the core library, and in practice its results can be inconsistent. Sentences sometimes end up grouped with the wrong topic, and boundaries don&#39;t always land where you&#39;d expect. It&#39;s worth experimenting with, but not yet something to rely on for production-grade chunking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*HAJfsQbmUrN3Srxs59ih2Q.png" /></figure><h3>Wrapping Up</h3><p>Text splitting is one of those components that’s easy to treat as an afterthought — a quick chunk_size=500 and move on. But as we&#39;ve seen, the way you split your documents has a direct, measurable impact on embedding quality, retrieval accuracy, and the final quality of your LLM&#39;s answers.</p><p>If you’re building a RAG application, it’s worth treating your text splitter with the same care you’d give to choosing your embedding model or vector database. Start with a Recursive Character Text Splitter, tune your chunk_size and chunk_overlap based on your specific documents, and reach for document-structure-aware or semantic splitting only when your content genuinely calls for it.</p><p>Get the chunking right, and everything downstream — embeddings, retrieval, generation — gets noticeably better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3b7fc4422c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Four Building Blocks of RAG: Document Loaders, Text Splitters, Vector Databases & Retrievers]]></title>
            <link>https://medium.com/@hunkcool1991/the-four-building-blocks-of-rag-document-loaders-text-splitters-vector-databases-retrievers-e07728c78442?source=rss-9c75f648a393------2</link>
            <guid isPermaLink="false">https://medium.com/p/e07728c78442</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[AMIT KASHYAP]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 17:43:35 GMT</pubDate>
            <atom:updated>2026-07-18T17:43:35.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*UFgpYoliYlyQujGaXwNcyQ.png" /></figure><p>Before you can build a Retrieval-Augmented Generation system, you need to understand the four components that make up its <em>indexing</em> and <em>retrieval</em> stages. Skip this step, and RAG feels like magic. Understand it, and every RAG pipeline you look at afterward — no matter which framework it’s built in — becomes obvious.</p><p>This article walks through each component individually: what problem it solves, how it works internally, the main design decisions you’ll face, and how they fit together into the retriever that eventually feeds context to your LLM.</p><h3>Where These Four Components Fit</h3><p>Recall the four-stage RAG pipeline: <strong>Indexing → Retrieval → Augmentation → Generation</strong>. The four components in this article map directly onto the first two stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*MRGS-DwOpOfM8JV2qMvbUw.png" /></figure><p>Get these four right, and the quality of your RAG system’s answers improves dramatically — most RAG failures in production trace back to a weak link in one of these four stages, not to the LLM itself.</p><h3>1. Document Loaders</h3><h3>The Problem</h3><p>Your source data doesn’t live in a format an LLM (or a vector database) can use directly. It might be a PDF sitting in S3, a set of Notion pages, a folder of .docx files, a YouTube transcript, or rows in a SQL database. Before anything else can happen, this data has to be <strong>ingested</strong> — pulled from wherever it lives and converted into a common, usable text representation.</p><h3>What a Document Loader Actually Does</h3><p>A document loader is a thin abstraction that:</p><ol><li>Connects to a data source (filesystem, API, database, cloud storage).</li><li>Extracts the raw content.</li><li>Wraps it in a standard object — typically something like:</li></ol><pre>Document(<br>    page_content=&quot;The actual extracted text...&quot;,<br>    metadata={&quot;source&quot;: &quot;handbook.pdf&quot;, &quot;page&quot;: 4}<br>)</pre><p>That metadata field matters more than people initially expect — it&#39;s what lets you later filter search results by source, date, author, or page number, and it&#39;s what lets you show users <em>where</em> an answer came from.</p><h3>Common Loader Types</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*CjpcLLep2ZdcvWCVaBKuuQ.png" /></figure><h3>Example (LangChain)</h3><pre>from langchain_community.document_loaders import PyPDFLoader<br><br>loader = PyPDFLoader(&quot;company_handbook.pdf&quot;)<br>documents = loader.load()<br><br>print(documents[0].page_content[:200])<br>print(documents[0].metadata)  # {&#39;source&#39;: &#39;company_handbook.pdf&#39;, &#39;page&#39;: 0}</pre><h3>Design Considerations</h3><ul><li><strong>Structure preservation</strong>: A naive PDF loader might scramble multi-column layouts or tables. If your source documents are structurally complex, invest in a loader that preserves layout (or post-process to fix it) — garbage extraction here poisons every downstream stage.</li><li><strong>Metadata richness</strong>: Capture as much metadata as you can at load time (source, page, timestamp, author). It’s far cheaper to discard metadata later than to reconstruct it after chunking.</li><li><strong>Incremental loading</strong>: For frequently updated sources, design your ingestion so you can re-load only what changed, rather than reprocessing everything.</li></ul><h3>2. Text Splitters</h3><h3>The Problem</h3><p>Once your document is loaded, it’s typically one long string — potentially thousands or millions of characters. You can’t hand this whole thing to an LLM for two concrete reasons:</p><ol><li><strong>Context window limits</strong> — LLMs can only process a bounded number of tokens per prompt.</li><li><strong>Semantic search quality</strong> — embedding a huge block of text blurs its meaning into a vague average; embedding <em>focused</em> chunks produces much sharper, more relevant search results.</li></ol><p>So the large document needs to be broken into smaller, semantically coherent pieces — this is <strong>chunking</strong>.</p><h3>What Good Chunking Looks Like</h3><p>The goal isn’t just “cut every N characters.” A good chunk is a self-contained, meaningful unit — ideally one that stays on a single topic rather than abruptly cutting a sentence or idea in half.</p><h3>Common Text Splitters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*pbfkcVPeBnwCFlHerReYEQ.png" /></figure><h3>Example (LangChain)</h3><pre>from langchain.text_splitter import RecursiveCharacterTextSplitter<br><br>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=1000,<br>    chunk_overlap=150,<br>)<br><br>chunks = splitter.split_documents(documents)<br>print(f&quot;Split into {len(chunks)} chunks&quot;)</pre><h3>Key Parameters</h3><ul><li><strong>chunk_size</strong>: How large each chunk is (measured in characters or tokens, depending on the splitter). Too small, and chunks lose context; too large, and you dilute semantic focus (and waste context window space at retrieval time).</li><li><strong>chunk_overlap</strong>: How much adjacent chunks overlap. A small overlap (10–20% of chunk size) helps preserve continuity across a chunk boundary — so a sentence split awkwardly across two chunks still has enough surrounding context in each.</li></ul><h3>Design Considerations</h3><ul><li><strong>Match the splitter to the document type.</strong> A splitter that respects Markdown headers will produce far better chunks for documentation than a generic character splitter.</li><li><strong>Chunk size is a tuning parameter, not a constant.</strong> Dense technical text often benefits from smaller chunks; narrative or conversational text can tolerate larger ones. This is worth A/B testing against your actual retrieval quality, not guessing once and moving on.</li><li><strong>Don’t split code carelessly.</strong> If you’re chunking source code, use a code-aware splitter that respects function/class boundaries — a chunk split mid-function is nearly useless as context.</li></ul><h3>3. Vector Databases</h3><h3>The Problem</h3><p>You now have hundreds or thousands of small text chunks. To find the <em>right</em> ones for a given query later, you need a way to search by <strong>meaning</strong>, not just keyword matching. That requires converting text into <strong>embeddings</strong> — dense numerical vectors that capture semantic meaning — and a specialized store that can search across those vectors efficiently.</p><h3>How It Works</h3><ol><li>Each chunk is passed through an <strong>embedding model</strong> (e.g., OpenAI embeddings, sentence-transformers), producing a fixed-length dense vector.</li><li>That vector, along with the original chunk text and its metadata, is stored in a <strong>vector database</strong>.</li><li>At query time, the same embedding model converts the user’s query into a vector, and the database finds the stored vectors closest to it — typically via cosine similarity or approximate nearest-neighbor (ANN) search.</li></ol><pre>from langchain_community.vectorstores import Chroma<br>from langchain_openai import OpenAIEmbeddings<br><br>embeddings = OpenAIEmbeddings()<br>vectorstore = Chroma.from_documents(<br>    documents=chunks,<br>    embedding=embeddings,<br>    persist_directory=&quot;./chroma_db&quot;<br>)</pre><h3>Comparing Options</h3><p>Vector DB Type Notes <strong>FAISS</strong> Local library Extremely fast, no server needed, great for prototyping — no built-in persistence/metadata filtering out of the box <strong>Chroma</strong> Local/embedded Simple API, good metadata filtering, easy to persist to disk <strong>Pinecone</strong> Managed cloud Fully managed, scales well, good for production without ops overhead <strong>Weaviate</strong> Self-hosted or cloud Rich filtering, hybrid search (keyword + vector) built in <strong>Milvus</strong> Self-hosted or cloud Built for very large-scale vector search <strong>Qdrant</strong> Self-hosted or cloud Strong filtering support, good performance, open source</p><h3>Design Considerations</h3><ul><li><strong>Local vs. managed</strong>: FAISS/Chroma are great for development and smaller-scale use; managed services (Pinecone, Weaviate Cloud) remove operational burden as you scale.</li><li><strong>Metadata filtering matters more than people expect</strong>: being able to query “top 5 most similar chunks, but only from documents tagged department: legal&quot; is often the difference between a usable and unusable system.</li><li><strong>Embedding model consistency</strong>: You must use the <em>exact same</em> embedding model for indexing and querying. Swapping embedding models means you have to re-embed and re-index everything — the vectors from two different models are not comparable.</li><li><strong>Hybrid search</strong>: Pure semantic search sometimes misses exact keyword matches (product codes, names, acronyms). Many vector DBs now support combining keyword (BM25) and vector search — worth considering if your queries include a lot of exact terms.</li></ul><h3>4. Retrievers</h3><h3>The Problem</h3><p>Having a vector database is not the same as having a good retrieval strategy. The retriever is the component that takes a query, decides <em>how</em> to search the vector store, and returns the chunks that will actually be used as context.</p><h3>The Basic Retrieval Flow</h3><ol><li>Embed the incoming query using the same embedding model used for indexing.</li><li>Search the vector store for the top-k closest vectors.</li><li>(Optionally) re-rank or filter the results.</li><li>Return the corresponding chunk text as context.</li></ol><pre>retriever = vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 4})<br>relevant_chunks = retriever.invoke(&quot;How does gradient descent work?&quot;)</pre><h3>Beyond Basic Similarity Search</h3><p>A plain top-k similarity search is the starting point, but several refinements often produce meaningfully better results:</p><p>Technique What It Does When to Use <strong>Top-k similarity search</strong> Returns the k nearest vectors by distance Default baseline <strong>MMR (Maximal Marginal Relevance)</strong> Balances relevance with diversity, avoiding near-duplicate chunks When top results tend to be redundant <strong>Contextual compression</strong> Uses an LLM to strip irrelevant parts out of retrieved chunks before passing them on When chunks are long but only partially relevant <strong>Reranking (cross-encoder)</strong> Re-scores the initial candidates with a more expensive, more accurate model When retrieval precision matters more than latency <strong>Hybrid search</strong> Combines keyword and vector search When queries mix exact terms and natural language <strong>Multi-query retrieval</strong> Generates several reworded versions of the query to widen the search When user queries are short or ambiguous</p><h3>Example: MMR Retrieval</h3><pre>retriever = vectorstore.as_retriever(<br>    search_type=&quot;mmr&quot;,<br>    search_kwargs={&quot;k&quot;: 4, &quot;fetch_k&quot;: 20, &quot;lambda_mult&quot;: 0.5}<br>)</pre><p>Here, fetch_k candidates are retrieved first, and MMR then selects k of them that balance relevance against diversity — reducing the odds of your context window being filled with four near-identical chunks.</p><h3>Design Considerations</h3><ul><li><strong>Tune </strong><strong>k deliberately.</strong> Too few chunks and you risk missing the answer; too many and you dilute the context with irrelevant text (and burn tokens).</li><li><strong>Retrieval quality is usually the bottleneck</strong>, not the LLM. If your RAG system gives wrong answers, check retrieved chunks <em>before</em> blaming the model — most of the time, the right context simply wasn’t retrieved.</li><li><strong>Log what gets retrieved.</strong> In production, retaining a log of (query → retrieved chunks → final answer) is invaluable for debugging and for building an evaluation set later.</li></ul><h3>Practical Checklist</h3><p>Before considering your indexing/retrieval pipeline production-ready:</p><ul><li>Document loader preserves structure and captures rich metadata (source, page, date)</li><li>Chunking strategy matches document type (Markdown, code, plain text, etc.)</li><li>Chunk size and overlap have been tuned against real queries, not left at defaults</li><li>The same embedding model is used consistently across indexing and querying</li><li>Vector database supports the metadata filtering your use case needs</li><li>Retriever’s k value has been tuned, not just left at a default like 4</li><li>MMR, reranking, or hybrid search has been evaluated if basic similarity search underperforms</li><li>A process exists for re-indexing when source documents are added, updated, or removed</li><li>Retrieved chunks are logged for debugging and future evaluation</li></ul><h3>Summary</h3><p>Component Solves Key Decision Document Loader Getting raw data into a usable form Which loader matches your source format, and how much metadata to capture Text Splitter Breaking large text into meaningful, model-sized pieces Chunk size, overlap, and splitter type Vector Database Storing and searching embeddings efficiently Local vs. managed, and metadata filtering support Retriever Finding the most relevant chunks for a query Similarity search vs. MMR, reranking, or hybrid search</p><p>These four components are the scaffolding every RAG system is built on — regardless of framework. Get them right, and the rest of the pipeline (prompt construction and generation) becomes almost mechanical.</p><p><strong>Next up</strong>: we’ll take these four components and wire them together into a complete, working RAG system from scratch using LangChain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e07728c78442" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[std::vector vs std::array: Choosing the Right Container]]></title>
            <link>https://medium.com/@hunkcool1991/std-vector-vs-std-array-choosing-the-right-container-90988b4df7e9?source=rss-9c75f648a393------2</link>
            <guid isPermaLink="false">https://medium.com/p/90988b4df7e9</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[AMIT KASHYAP]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 17:26:19 GMT</pubDate>
            <atom:updated>2026-07-18T17:26:19.255Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Phase 2 — Standard Library Mastery, Article 1</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCWtA6YPCNuAXnHmHTbi4w.png" /></figure><p>If Phase 1 was about writing cleaner, safer code with auto, smart pointers, and move semantics, Phase 2 is about knowing which tool from the standard library to reach for — and why. There&#39;s no better place to start than the two containers you&#39;ll use more than anything else: std::vector and std::array.</p><p>They look similar on the surface. Both give you contiguous storage, random access, and clean RAII semantics. But they solve different problems, and picking the wrong one costs you either performance or flexibility. Let’s break down exactly where each one shines.</p><h3>The Core Difference: Compile-Time vs Runtime Size</h3><p>The single most important distinction:</p><ul><li>std::array&lt;T, N&gt; — size N is a <strong>compile-time constant</strong>, baked into the type itself.</li><li>std::vector&lt;T&gt; — size is determined <strong>at runtime</strong>, and can grow or shrink.</li></ul><pre>#include &lt;array&gt;<br>#include &lt;vector&gt;<br><br>std::array&lt;int, 5&gt; fixed = {1, 2, 3, 4, 5}; // size fixed forever, part of the type<br>std::vector&lt;int&gt; dynamic = {1, 2, 3};        // size can change<br><br>dynamic.push_back(4); // fine<br>dynamic.push_back(5); // fine<br><br>// fixed.push_back(6); // doesn&#39;t even compile — array has no push_back</pre><p>Because N is a template parameter, std::array&lt;int, 5&gt; and std::array&lt;int, 10&gt; are literally different types. This has real implications for function signatures and generic code, which we&#39;ll get to below.</p><h3>Memory Layout</h3><p>Both containers store their elements contiguously — this is what makes them cache-friendly and compatible with raw pointers and C-style APIs. But <em>where</em> that memory lives differs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*2WhfYmqf7cGCDujvsak17w.png" /></figure><h3>Performance Characteristics</h3><p>std::array has an edge in a few specific ways:</p><ol><li><strong>No heap allocation.</strong> For small, fixed-size data, this avoids allocator overhead entirely — meaningful in hot loops, embedded contexts, or real-time systems where allocation is unpredictable or disallowed.</li><li><strong>Better cache locality guarantees.</strong> Because it lives inline (often on the stack), there’s no pointer chase to reach the data — you’re already there.</li><li><strong>No hidden reallocation cost.</strong> A std::vector that grows past its capacity reallocates and copies/moves every existing element. This is amortized O(1) per push_back, but it&#39;s not <em>free</em>, and it can be a real source of stutter in latency-sensitive code if you didn&#39;t reserve() up front.</li></ol><p>std::vector wins when:</p><ul><li>You don’t know the size ahead of time.</li><li>The size needs to change during the program’s life.</li><li>The data is large enough that stack allocation is risky (large std::array objects can blow the stack — there&#39;s no bounds-checking on that).</li></ul><pre>// Risky: several MB on the stack, depending on platform limits<br>std::array&lt;double, 1&#39;000&#39;000&gt; big_stack_array; // likely to crash<br><br>// Safe: heap-allocated, stack just holds a small handle<br>std::vector&lt;double&gt; big_heap_vector(1&#39;000&#39;000);</pre><h3>API Differences That Trip People Up</h3><p>std::array supports almost the entire container interface — size(), begin()/end(), operator[], at(), range-based for — everything except operations that would change its size:</p><pre>std::array&lt;int, 4&gt; arr = {10, 20, 30, 40};<br><br>for (int x : arr) { /* works */ }<br>arr.at(2);        // works, bounds-checked<br>arr.size();       // works, always returns N<br>// arr.resize(6); // does not exist<br>// arr.push_back(50); // does not exist</pre><p>One subtlety: std::array&lt;T, N&gt; aggregates need an extra brace in some initialization styles because the array itself is wrapped in a struct-like object:</p><pre>std::array&lt;int, 3&gt; a1 = {1, 2, 3};   // fine, brace elision applies<br>std::array&lt;int, 3&gt; a2{{1, 2, 3}};    // also fine, fully explicit</pre><p>std::vector additionally gives you push_back, pop_back, insert, erase, resize, reserve, and capacity — all the tools for a container whose contents change shape over time.</p><h3>Passing Them to Functions</h3><p>This is where the compile-time-size aspect of std::array becomes a real design consideration. A function taking std::array&lt;int, 5&gt; cannot accept std::array&lt;int, 10&gt; — they&#39;re unrelated types:</p><pre>void process(std::array&lt;int, 5&gt; arr);   // only accepts size-5 arrays<br><br>// process(std::array&lt;int, 10&gt;{});      // compile error — wrong type</pre><p>To write size-agnostic code over std::array, you reach for a template:</p><pre>template &lt;std::size_t N&gt;<br>void process(const std::array&lt;int, N&gt;&amp; arr) {<br>    for (auto x : arr) { /* ... */ }<br>}</pre><p>std::vector, by contrast, has one type regardless of how many elements it holds, so ordinary functions work without templates:</p><pre>void process(const std::vector&lt;int&gt;&amp; vec); // accepts any size vector</pre><p>If you want a uniform view over <em>both</em> contiguous containers (and C arrays) without templating everything, that’s exactly what std::span (C++20) was built for — but that&#39;s a topic for its own article later in this phase.</p><h3>Decision Checklist</h3><p>Use this as a quick gut-check when reaching for a container:</p><ul><li>[ ] <strong>Is the size known at compile time and truly fixed for the object’s lifetime?</strong> → std::array</li><li>[ ] <strong>Does the size depend on runtime input (file contents, user input, network data)?</strong> → std::vector</li><li>[ ] <strong>Is the element count small (a handful to a few hundred) and safe to put on the stack?</strong> → std::array is worth considering</li><li>[ ] <strong>Could the element count be large or unpredictable?</strong> → std::vector, to avoid stack overflow</li><li>[ ] <strong>Do you need to grow/shrink, insert, or erase elements?</strong> → std::vector (arrays can&#39;t resize)</li><li>[ ] <strong>Are you optimizing a hot path and want to eliminate heap allocation?</strong> → std::array (or a std::vector with reserve() called once upfront)</li><li>[ ] <strong>Do you need the container to be cheap to move (e.g., returned from a function)?</strong> → std::vector</li><li>[ ] <strong>Do you want the size to be part of the type for compile-time safety (e.g., a fixed-size matrix row)?</strong> → std::array</li></ul><h3>Summary Table</h3><p>Use Case Recommended Container Fixed-size buffer known at compile time (e.g., a 3x3 matrix row, RGB triple) std::array Reading an unknown number of lines from a file std::vector Small lookup table baked into the binary std::array Building up a collection element-by-element std::vector Function return value that should be cheap to move std::vector Stack-allocated scratch buffer in a tight loop std::array Data structure needing to grow unpredictably std::vector</p><h3>The Takeaway</h3><p>std::array is a zero-overhead wrapper around a C-style array — same performance, same stack allocation, but with the safety and interface of a standard container. Reach for it when the size is fixed and known at compile time.</p><p>std::vector is your general-purpose, dynamically-sized workhorse. It&#39;s what you use by default unless you have a specific reason not to — and &quot;I want to avoid one heap allocation&quot; is a specific reason, but only when profiling actually says it matters.</p><p>The rule of thumb: <strong>default to </strong><strong>std::vector. Switch to </strong><strong>std::array when the size is fixed and you can prove the stack allocation is safe and worth it.</strong></p><p><em>Next up in Phase 2 — Standard Library Mastery: we’ll look at how associative containers like </em><em>std::map and </em><em>std::unordered_map compare, and when the O(log n) guarantee of a red-black tree actually beats a hash table in practice.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90988b4df7e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval-Augmented Generation (RAG): Why It Exists and How It Actually Works]]></title>
            <link>https://medium.com/@hunkcool1991/retrieval-augmented-generation-rag-why-it-exists-and-how-it-actually-works-51a29c0010b3?source=rss-9c75f648a393------2</link>
            <guid isPermaLink="false">https://medium.com/p/51a29c0010b3</guid>
            <dc:creator><![CDATA[AMIT KASHYAP]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 07:05:58 GMT</pubDate>
            <atom:updated>2026-07-16T07:05:58.729Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUHwXC13rL_FO6dZlxeedA.png" /></figure><p>If you’ve spent any time around generative AI in the last couple of years, you’ve almost certainly heard the term <strong>RAG</strong>. It’s one of the most common — and arguably the most <em>useful</em> — patterns built on top of large language models today. But most explanations jump straight into “vector databases” and “embeddings” without answering the more basic question: <strong>why do we need RAG in the first place?</strong></p><p>This article takes the long way around. We’ll start with how LLMs actually store knowledge, walk through the three real problems that show up when you rely on that knowledge alone, look at why the obvious fix (fine-tuning) isn’t always practical, and only then arrive at RAG — followed by a detailed, step-by-step breakdown of how a RAG pipeline works under the hood.</p><h3>How LLMs Store Knowledge</h3><p>At a technical level, an LLM is a transformer-based neural network with an enormous number of parameters — weights and biases. During <strong>pre-training</strong>, the model is exposed to a massive amount of text, roughly at internet scale. The result is that the model ends up with a broad, general understanding of the world — but that understanding is stored entirely inside its parameters, as numbers. This is why we call it <strong>parametric knowledge</strong>: the bigger the parameter count, the more of this knowledge a model can hold, which is roughly why a 70B-parameter model tends to outperform a 13B one, which outperforms a 7B one.</p><p>To access this knowledge, you send the model a <strong>prompt</strong>. The model reads the prompt, reaches into its parametric knowledge, and generates a response word by word. Most of the time, this simple flow — prompt in, answer out — works just fine.</p><p>But there are three situations where it reliably breaks down.</p><h3>Problem 1: Private Data</h3><p>If you ask a general-purpose model a question about your own company’s internal documents, or about a lecture video on your own course platform, it simply can’t answer. The model never saw that data during pre-training. No amount of clever prompting will conjure knowledge the model was never exposed to.</p><h3>Problem 2: Recent Data</h3><p>Every LLM has a <strong>knowledge cutoff date</strong> — the point up to which its training data extends. Ask it about today’s news, and it typically can’t answer, because that information didn’t exist when it was trained. (Tools like ChatGPT get around this by using live web search — but a base open-source model downloaded from a hub like Hugging Face will not know anything past its cutoff.)</p><h3>Problem 3: Hallucination</h3><p>LLMs are fundamentally probabilistic text generators. Sometimes, instead of admitting uncertainty, they confidently produce information that is simply false — for example, inventing a fictional detail about a historical figure and stating it as fact. This is called <strong>hallucination</strong>, and it’s a direct consequence of how these models generate text.</p><p>So: private data, stale knowledge, and hallucination. Is there a way to address all three?</p><h3>The First Attempt: Fine-Tuning</h3><p>The traditional answer is <strong>fine-tuning</strong> — taking a pre-trained model and continuing its training on a smaller, domain-specific dataset.</p><p>Think of it like a fresh engineering graduate. Their degree (pre-training) gave them broad knowledge — physics, computer science, communication. But when they join a company, they still go through a few months of on-the-job training so they learn how <em>this specific company</em> operates. That on-the-job training is fine-tuning.</p><p>There are several flavors of this:</p><ul><li><strong>Supervised fine-tuning</strong> — training on labeled (prompt, desired-output) pairs, often somewhere between a few thousand and a million examples.</li><li><strong>Continued pre-training</strong> — an unsupervised approach where you simply keep training the model on new raw domain text (e.g., feeding it your lecture transcripts).</li><li>Other techniques like <strong>RLHF</strong> (reinforcement learning from human feedback), <strong>LoRA</strong>, and <strong>QLoRA</strong> for more parameter-efficient tuning.</li></ul><p>A typical supervised fine-tuning workflow looks like: (1) collect a labeled dataset, (2) choose a method — full fine-tuning vs. a parameter-efficient method like LoRA, (3) train for a small number of epochs, and (4) evaluate using exact-match accuracy, factuality checks, or hallucination rate.</p><p>Fine-tuning genuinely helps with all three problems: train on your private data, and the model can now answer questions about it. Retrain periodically, and it can incorporate newer information. Add tricky examples where the “correct” answer is “I don’t know,” and you can reduce hallucination.</p><p><strong>But fine-tuning has serious drawbacks:</strong></p><ol><li>It’s <strong>computationally expensive</strong> — you’re retraining a huge model, even on a small dataset.</li><li>It requires <strong>serious technical expertise</strong> — proper ML engineers and data scientists.</li><li>It doesn’t scale well with <strong>frequent updates</strong>. If your course catalog changes every week, you’d need to fine-tune every week — expensive, and impractical for fast-moving domains.</li></ol><p>So we’re back to the same question: is there another way to solve these three problems?</p><h3>The Bridge: In-Context Learning</h3><p>This is where <strong>in-context learning (ICL)</strong> enters the picture. ICL is a core capability of large language models like GPT-3, Claude, and LLaMA, where the model learns to perform a task purely by seeing examples <em>inside the prompt</em> — without any weight updates at all.</p><p>For example, you can show a model a few labeled sentiment examples (“I love this phone → positive,” “This app crashes a lot → negative”) and then ask it to classify a new sentence. The model picks up the pattern from the examples and applies it. This example-driven prompting is often called <strong>few-shot prompting</strong>.</p><p>Interestingly, ICL is an <strong>emergent property</strong> — a capability that wasn’t explicitly engineered but simply appeared once models crossed a certain scale. Smaller models like GPT-1 and GPT-2 didn’t reliably show this behavior. It was GPT-3, with around 175 billion parameters, that clearly demonstrated the ability to learn from examples embedded in the prompt — a finding formalized in the landmark paper <em>“Language Models are Few-Shot Learners.”</em> Later alignment techniques (supervised fine-tuning, RLHF) further strengthened this ability in subsequent model generations.</p><h3>From Examples to Context: This Is RAG</h3><p>Here’s the key insight: instead of giving the model <em>examples of how to solve a task</em>, what if we gave it the <em>actual context</em> needed to answer a specific question?</p><p>Imagine a two-hour lecture on linear regression, and a student has a doubt specifically about gradient descent. Rather than feeding the entire two-hour transcript to the model, you locate just the relevant segment — say, minutes 5 to 25 — and send <em>that</em> along with the student’s question as context.</p><p>That’s <strong>Retrieval-Augmented Generation (RAG)</strong>: a way to make a language model smarter by supplying it with extra, relevant information at the exact moment you ask your question. The model combines this injected context with its own parametric knowledge to produce a grounded, accurate answer.</p><h3>The Four Stages of a RAG Pipeline</h3><p>Structurally, RAG sits at the intersection of two much older ideas: <strong>information retrieval</strong> (a classic computer science problem) and <strong>text generation</strong> (popularized by LLMs). A working RAG system can be broken into four stages:</p><h3>1. Indexing</h3><p>This is where you build your <strong>external knowledge base</strong> — the source from which context will eventually be pulled. Indexing itself has sub-steps:</p><ul><li><strong>Document ingestion</strong>: loading raw source data into memory (a transcript from a server, files from Google Drive or S3, etc.).</li><li><strong>Text chunking</strong>: breaking large documents into smaller, semantically meaningful chunks — necessary both because LLMs have limited context windows and because semantic search performs poorly on very large blocks of text.</li><li><strong>Embedding generation</strong>: converting each chunk into a dense vector that captures its meaning, using an embedding model.</li><li><strong>Vector storage</strong>: storing these vectors, along with the original text and metadata, in a vector database (FAISS, Chroma, Pinecone, Weaviate, Milvus, Qdrant, etc.).</li></ul><p>At the end of indexing, you have a searchable external knowledge base.</p><h3>2. Retrieval</h3><p>When a user sends a query, the retriever:</p><ol><li>Converts the query into an embedding using the <em>same</em> embedding model used during indexing.</li><li>Searches the vector store for the closest matching vectors (via cosine similarity, MMR, contextual compression, or more advanced reranking).</li><li>Ranks the results and pulls back the text of the top-matching chunks.</li></ol><p>Those top chunks become your <strong>context</strong> — for instance, retrieving only the gradient-descent segments of a lecture rather than the entire transcript.</p><h3>3. Augmentation</h3><p>This is simply <strong>prompt construction</strong>: combining the user’s original query with the retrieved context into a single, structured prompt — something like:</p><blockquote><em>“You are a helpful assistant. Answer the question only from the provided context. If the context is insufficient, just say you don’t know. [Context] [Question]”</em></blockquote><h3>4. Generation</h3><p>Finally, the assembled prompt goes to the LLM, which uses its text-generation ability <em>and</em> in-context learning to produce a grounded answer based on both the retrieved context and its own parametric knowledge.</p><h3>Why RAG Solves All Three Problems</h3><ul><li><strong>Private data</strong>: Since the external knowledge base is built from your own documents, the retrieved context — and therefore the answer — naturally reflects your data.</li><li><strong>Recent data</strong>: To incorporate new information, you just embed and add new documents to the vector store. No retraining required — a much cheaper update cycle than fine-tuning.</li><li><strong>Hallucination</strong>: By explicitly instructing the model to answer only from the provided context (and to say “I don’t know” when the context is insufficient), you ground its responses and significantly reduce the chance of invented facts.</li></ul><p>And as a bonus: RAG is generally <strong>cheaper and simpler</strong> than fine-tuning. There’s no model training involved, no need for labeled datasets — just documents converted into embeddings and stored in a vector database.</p><h3>What’s Next</h3><p>This is the conceptual foundation. The natural next step is implementation: building an actual RAG pipeline — document loaders, text splitters, embedding models, a vector store, and a retriever — wired together with a framework like LangChain. That’s a hands-on exercise for another day, but with the mental model above, the “why” behind every line of that code should make a lot more sense.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51a29c0010b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Versioning for ML: Treating Datasets Like Code]]></title>
            <link>https://medium.com/@hunkcool1991/data-versioning-for-ml-treating-datasets-like-code-75f13d40cb5a?source=rss-9c75f648a393------2</link>
            <guid isPermaLink="false">https://medium.com/p/75f13d40cb5a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[AMIT KASHYAP]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 18:57:00 GMT</pubDate>
            <atom:updated>2026-07-09T18:57:00.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6dfWvbu9zOz30bBQGQA9Q.png" /></figure><h3>Your model is only as reproducible as the data behind it</h3><p><em>Part 3 of the MLOps series — read Part 1: [MLOps: A Practical Introduction] and Part 2: [Experiment Tracking 101]</em></p><p>In the last article, we solved “which config was that again?” with experiment tracking. But there’s a second, quieter version of the same problem that experiment tracking alone doesn’t fix: <strong>which dataset was that again?</strong></p><p>You can log every hyperparameter perfectly and still be unable to reproduce a model, because the CSV file it was trained on got overwritten, updated, or “cleaned up” three weeks later — and nobody kept a copy of what it looked like at training time. This article is about why that happens, and how <strong>data versioning</strong> closes the gap.</p><h3>1. The Problem: Data Changes, and Nobody Notices</h3><p>In most teams, a dataset lives at a path — s3://company-data/transactions.csv, or a table in a warehouse — and that path is treated like a fixed reference. But the file behind that path rarely stays fixed:</p><ul><li>A pipeline appends new rows every night.</li><li>Someone fixes a labeling error and overwrites the file in place.</li><li>A column gets renamed or dropped in an upstream ETL job.</li><li>Outliers get filtered out as part of routine “data cleaning.”</li></ul><p>None of these changes touch a single line of your training code. Your train.py script looks identical to the one from three months ago. But if you re-run it today, it loads a different dataset than the one that actually produced your production model — and the result can be a meaningfully different model, with no code diff to explain why.</p><p>This is the ML-specific version of a problem software engineers solved decades ago for code: without a system that snapshots and labels every version, you’re stuck hoping nothing important changed since last time.</p><h3>2. Why Git Alone Doesn’t Solve This</h3><p>Git is excellent at versioning code, and the instinct to just git add your dataset and commit it is understandable — but it breaks down quickly for a few reasons:</p><p><strong>Size.</strong> Git is built for text diffs. A 10 GB dataset committed to a repository makes every clone, pull, and checkout dramatically slower, and most Git hosting platforms enforce hard file size limits well below that.</p><p><strong>Diffing doesn’t make sense.</strong> Git shows you line-by-line changes, which is meaningless for a binary file or a million-row table. You don’t want to know “row 45,392 changed from 3.2 to 3.4” — you want to know “does this dataset still look statistically like the one I trained on?”</p><p><strong>Storage cost.</strong> Every version of a large file lives forever in Git’s history, multiplying storage needs fast — Git wasn’t designed to be a data warehouse.</p><p>Because of this, teams need something that gives Git-style versioning — commits, branches, meaningful history — without actually stuffing large files into Git itself.</p><h3>3. How Data Versioning Tools Solve This</h3><p>The most common approach, used by tools like <strong>DVC (Data Version Control)</strong>, separates the <em>pointer</em> from the <em>data</em>:</p><ul><li>Git tracks a small metadata file (a hash, essentially a fingerprint of the dataset).</li><li>The actual data lives in cheap storage — S3, GCS, Azure Blob, or even a local drive.</li><li>Checking out a Git commit pulls down the small metadata file instantly, and a separate command fetches the matching large file from storage.</li></ul><p>In practice, this looks like:</p><pre>dvc add data/transactions.csv<br>git add data/transactions.csv.dvc<br>git commit -m &quot;Add transactions dataset v1&quot;</pre><p>That .dvc file is tiny — just a hash and a path — while the actual multi-gigabyte CSV sits in your configured storage backend. Git now has a permanent, lightweight record of exactly which dataset version went with which code commit, without ever storing the heavy file itself.</p><p>Later, reproducing an old experiment is a two-step process:</p><pre>git checkout &lt;old-commit&gt;<br>dvc pull</pre><p>The first command restores the code and the .dvc pointer files. The second fetches the exact matching data from storage. Together, they reconstruct the full picture — not just what the code looked like, but what it was trained on.</p><h3>4. What “Versioning a Dataset” Actually Captures</h3><p>A good data versioning setup tracks more than just “this file changed.” It typically records:</p><ul><li><strong>A content hash</strong> — a fingerprint that changes if even one value in the dataset changes, so you can prove two datasets are (or aren’t) identical.</li><li><strong>Where the data lives</strong> — the storage location the actual bytes can be pulled from.</li><li><strong>Lineage</strong> — which pipeline or transformation produced this version from a previous one.</li><li><strong>A human-readable tag or message</strong> — “v3: removed pre-2020 rows with missing labels,” so future-you doesn’t have to reverse-engineer what changed from the hash alone.</li></ul><p>That last point matters more than it sounds. A hash tells you <em>that</em> something changed; a commit message tells you <em>why</em> — and six months later, “why” is almost always the more useful answer.</p><h3>5. A Concrete Example</h3><p>Imagine a churn-prediction model trained on customer data. Three months in, accuracy in production has quietly dropped, and you want to compare today’s model against the one that shipped originally.</p><p><strong>Without data versioning:</strong> You retrain using the current customers.csv, get a different result, and have no way to tell whether the difference is due to a code change, a hyperparameter change, or the fact that the underlying customer data has simply changed — maybe there are three months of new customers in it now that didn&#39;t exist before.</p><p><strong>With data versioning:</strong></p><pre>git log --oneline -- customers.csv.dvc</pre><p>This shows every version of the dataset ever used, each tied to a specific commit. You check out the exact version from the original training run:</p><pre>git checkout &lt;original-commit&gt; -- customers.csv.dvc<br>dvc pull</pre><p>Now you have the <em>exact</em> data the original model saw. Retraining on it and comparing against retraining on current data isolates the data drift from everything else — you’re finally comparing like with like.</p><h3>6. Pairing Data Versioning with Experiment Tracking</h3><p>Data versioning and experiment tracking (from the last article) are designed to work together, not compete. A well-tracked run logs the dataset version alongside its parameters and metrics:</p><pre>import mlflow</pre><pre>with mlflow.start_run():<br>    mlflow.log_param(&quot;dataset_version&quot;, &quot;customers_v3&quot;)<br>    mlflow.log_param(&quot;dataset_hash&quot;, &quot;a1b2c3d4...&quot;)<br>    # ... train and log metrics as usual</pre><p>Now every logged experiment answers both questions at once: which code and hyperparameters produced this result, <em>and</em> which exact snapshot of the data it saw. That combination is what makes a model result fully reproducible — not just “we can find the code,” but “we can rebuild the exact conditions that produced this number.”</p><h3>7. Common Tools</h3><p>Tool Notable for <strong>DVC</strong> Git-native workflow, works with any storage backend (S3, GCS, local) <strong>LakeFS</strong> Git-like branching and merging for entire data lakes <strong>Delta Lake</strong> Built-in versioning (“time travel”) for tables in a data lake <strong>Pachyderm</strong> Data versioning combined with pipeline orchestration</p><p>The right choice depends heavily on scale and existing infrastructure — a small team with CSVs on S3 has very different needs from one running petabyte-scale pipelines on a data lake.</p><h3>8. Getting Started: A Minimal Setup</h3><p>You don’t need to version every dataset in your organization on day one. A practical starting point:</p><ol><li><strong>Version the datasets that feed production models first.</strong> Not every exploratory CSV needs tracking — the ones that actually train what’s running in production do.</li><li><strong>Snapshot before every training run that matters</strong>, not just when data “officially” changes. Silent, incremental changes are exactly the ones that cause the most confusion later.</li><li><strong>Log the dataset version inside your experiment tracker</strong>, so the two systems stay linked rather than living in separate silos.</li><li><strong>Write a short message with every new version.</strong> A hash proves something changed; a sentence explains what and why — and that’s what saves time months later.</li></ol><h3>Closing Thoughts</h3><p>Code review culture spent years teaching engineers to never trust an untracked change. Machine learning is still catching up to the same lesson, applied to data instead of code. A model is a function of both, and treating only one of them as version-controlled leaves half the reproducibility problem unsolved.</p><p>Data versioning isn’t about ceremony — it’s about being able to answer, with certainty rather than memory, the question that experiment tracking alone can’t: not just what configuration produced this model, but what world it was trained to understand.</p><p>Next in the series, we’ll move one layer up the stack: feature stores, and how they solve a subtler problem — making sure the features a model sees in production match the ones it was trained on.</p><p><em>If this helped, follow along for the rest of the MLOps series — next up: Feature Stores Explained.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75f13d40cb5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>