<?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 md wasim on Medium]]></title>
        <description><![CDATA[Stories by md wasim on Medium]]></description>
        <link>https://medium.com/@md.wasim3?source=rss-4362f970560b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VcdaaWp6oJ1yJfw_P2FqpA.jpeg</url>
            <title>Stories by md wasim on Medium</title>
            <link>https://medium.com/@md.wasim3?source=rss-4362f970560b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:28:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@md.wasim3/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[Generative AI vs AI Agents vs Agentic AI Explained]]></title>
            <link>https://medium.com/@md.wasim3/generative-ai-vs-ai-agents-vs-agentic-ai-explained-595bcebca361?source=rss-4362f970560b------2</link>
            <guid isPermaLink="false">https://medium.com/p/595bcebca361</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[genrative-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[md wasim]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 11:53:53 GMT</pubDate>
            <atom:updated>2026-10-09T11:53:53.001Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Executive Summary &amp; Progression Model</h3><ul><li><strong>The Core Problem</strong>: In 2026, terms like “AI Agents” and “Agentic AI” are frequently misused to market basic chatbots or simple API wrappers.</li><li><strong>The Progression Model</strong>: Generative AI, AI Agents, and Agentic AI are not separate competing technologies; they form a <strong>3-level progression ladder</strong> where each higher level builds directly on top of the lower levels:</li></ul><ol><li><strong>Level 1</strong>: Generative AI (The Brain).</li><li><strong>Level 2</strong>: AI Agent (The Worker = Brain + Hands + Memory + Loop).</li><li><strong>Level 3</strong>: Agentic AI (The Entire Company = Planning + Multi-Agent Teams + Orchestration + Autonomy).</li></ol><h3>2. Level 1: Generative AI (Gen AI)</h3><ul><li><strong>Core Definition</strong>: Generative AI operates primarily as a <strong>prediction engine</strong> trained on vast internet text, code, images, and media to predict the next word or token.</li><li><strong>Real-World Analogy</strong>: An exceptionally smart, well-read friend who can write 10 creative decorator ideas or design a caterer menu for a wedding, but cannot make a phone call to book the caterer.</li><li><strong>Key Tools</strong>: ChatGPT, Claude, Gemini, Midjourney, Sora, Suno.</li></ul><p><strong>Three Major Limitations</strong>:</p><ol><li><strong>No “Hands”</strong>: It can generate text or code, but cannot send emails, execute code, run tests, or book services directly.</li><li><strong>Goldfish Memory (Stateless Core)</strong>: Core models operate statelessly and start fresh without intrinsic context across independent sessions.</li><li><strong>100% Confidence, 0% Guarantee (Hallucination)</strong>: It generates plausible-sounding answers with high confidence even when incorrect.</li></ol><h3>3. Level 2: AI Agents</h3><ul><li><strong>Core Definition</strong>: An AI Agent combines a <strong>Generative AI model (Brain)</strong> with <strong>Tools (Hands)</strong>, <strong>Memory</strong>, and an <strong>Execution Loop</strong>.</li><li><strong>Real-World Analogy</strong>: Hiring a professional wedding planner given a budget (e.g., ₹2 Lakhs) who evaluates options, calls caterers, compares pricing, rejects out-of-budget quotes, and completes the booking.</li></ul><p><strong>Four Essential Components</strong>:</p><ul><li><strong>Brain (LLM)</strong>: Uses underlying LLMs (GPT, Claude, Gemini) as its reasoning engine.</li><li><strong>Tools (Hands)</strong>: Accesses external capabilities like web search, code interpreters, email APIs, and calculators.</li><li><strong>Memory</strong>: Stores task states, intermediate outputs, and results to proceed logically to the next step.</li><li><strong>Loop</strong>: Operates in an iterative <em>Think → Act → Observe → Re-think</em> cycle until the goal is achieved.</li></ul><p><strong><em>AI Agents vs. Traditional Automation (e.g., Zapier)</em></strong><em>:</em></p><ul><li><strong>Zapier Automation</strong>: Follows a <strong>fixed, hardcoded path</strong> with predefined triggers and actions; if an edge case occurs, the script breaks.</li><li><strong>AI Agent</strong>: Dynamically reasons about changing situations and <strong>determines its own next step</strong> autonomously.</li></ul><h3>4. Level 3: Agentic AI</h3><ul><li><strong>Core Definition</strong>: Agentic AI is an <strong>architectural framework</strong> where multiple specialized AI agents collaborate within an orchestrated system to solve complex, multi-step goals.</li><li><strong>Real-World Analogy</strong>: Hiring an entire event management firm where a Head Planner breaks a single prompt (<em>“Manage my 500-guest wedding on Feb 19”</em>) into sub-tasks and delegates them across specialized departments (Catering, Decor, DJ, Logistics).</li><li><strong>Four Pillars of Agentic AI</strong>:</li></ul><ol><li><strong>Automated Planning</strong>: Decomposes high-level goals into ordered sub-plans without human micro-management.</li><li><strong>Specialized Agents</strong>: Assigns distinct sub-tasks to dedicated worker agents (e.g., researcher, coder, tester, reviewer).</li><li><strong>Orchestration</strong>: A manager agent coordinates execution timing, data flow, and dependency resolution between agents.</li><li><strong>High Autonomy</strong>: Executes end-to-end multi-stage workflows with minimal human input.</li></ol><ul><li><strong>Real-World Examples</strong>: Devyn (AI Software Engineer) and Emergent.</li><li><strong>Current Bottlenecks</strong>: High token/API costs per iteration step, error accumulation across agents, and agent coordination confusion.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cTthc48eTIXvOs9afbbCdQ.png" /></figure><h3>5. The 3-Second Identification Test</h3><p>When evaluating any AI tool or feature, ask these three questions:</p><ol><li><strong>Generative AI</strong>: Does it only output text, images, or code recommendations?</li><li><strong>AI Agent</strong>: Does it use tools in an iterative loop to execute a single task?</li><li><strong>Agentic AI</strong>: Do multiple specialized agents collaborate using automated planning to complete a broad goal?</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=595bcebca361" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Context Protocol (MCP) Architecture & Concepts]]></title>
            <link>https://medium.com/@md.wasim3/model-context-protocol-mcp-architecture-concepts-ec9c3aaada72?source=rss-4362f970560b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec9c3aaada72</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[agnoai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[crew-ai]]></category>
            <dc:creator><![CDATA[md wasim]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 17:04:13 GMT</pubDate>
            <atom:updated>2026-10-06T17:04:13.981Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Background: The Problem with Traditional API Integration</h3><ul><li><strong>Manual API Coding</strong>: When building Generative or Agentic AI applications (such as a Travel Planning AI app), developers traditionally had to write custom integration code for every single external service, including Weather APIs, Google Drive, GitHub, databases, and Flight APIs.</li><li><strong>Document &amp; Format Overhead</strong>: Each external API uses different authentication mechanisms, documentation rules, request structures, and response formats. Developers had to study and handle each API individually.</li><li><strong>Framework Fragmentation</strong>: If an agent was built in one framework (e.g., <strong>LangGraph</strong>) and needed to be ported to another (e.g., <strong>OpenAI Agent SDK</strong>, <strong>CrewAI</strong>, or <strong>Agno</strong>), the developer had to rewrite all API integration code from scratch to match each framework’s specific format.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QFI80jQBN58RnP2QmXDkcw.jpeg" /></figure><h3>2. What is Model Context Protocol (MCP)?</h3><ul><li><strong>Standardized Connection Layer</strong>: MCP is an open standard protocol designed to unify how AI applications connect with and execute external tools and data sources.</li><li><strong>Beyond REST APIs</strong>: An MCP Server is not limited to web APIs — it can expose databases, local file systems, Google Drive, GitHub repositories, operating system tools, or internal company documentation.</li><li><strong>Framework Independence</strong>: App logic is decoupled from tool logic. A single MCP server can connect to AI applications built across different frameworks (LangGraph, CrewAI, OpenAI SDK, Agno) using identical connection logic.</li></ul><h3>3. Key Components of MCP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RbsdhD5QPywYmxMRMxnQpg.png" /></figure><h3>4. Step-by-Step Execution Flow</h3><ol><li><strong>Server Discovery</strong>: When the AI application starts up, the <strong>MCP Client</strong> automatically connects to all configured MCP Servers and requests their list of available tools (<em>“What tools do you have?”</em>).</li><li><strong>Tool Registration</strong>: MCP Servers return their exposed tool list (e.g., get_current_weather, get_weather_forecast) to the MCP Client, which stores them and provides them to the LLM.</li><li><strong>User Request &amp; LLM Reasoning</strong>: The user submits a prompt (e.g., <em>“What is the weather in Delhi today?”</em>). The <strong>LLM</strong> evaluates if it can answer from its pre-training data; if real-time data is needed, it scans the available tools and selects get_current_weather.</li><li><strong>JSON-RPC Request Conversion</strong>: The LLM issues a tool call request. The <strong>MCP Client</strong> formats this request into a standardized <strong>JSON-RPC</strong> message format.</li><li><strong>Tool Execution</strong>: The request is routed to the designated <strong>Weather MCP Server</strong>, which executes the call against the underlying Weather API.</li><li><strong>JSON-RPC Response Handling</strong>: The Weather API returns raw data to the MCP Server, which converts the response back into <strong>JSON-RPC</strong> format and sends it to the MCP Client.</li><li><strong>Final Output</strong>: The MCP Client passes the result to the LLM, which formats a human-readable response for the user.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MEftZ_NKNz_ZjAaRdjMe4Q.jpeg" /></figure><h3>Full workflow of MCP server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1IgfI0jwfzisCjdMf87YWQ.jpeg" /></figure><h3>5. MCP Server Types &amp; Transport Protocols</h3><h4>Server Deployment Types</h4><ul><li><strong>Local MCP Servers</strong>: Run on the same local physical machine as the AI application.</li><li><strong>Remote MCP Servers</strong>: Hosted on a remote server/cloud/VPS and accessed over a network or the internet.</li><li><strong>Custom MCP Servers</strong>: Developer-built servers created to securely interface with private company databases or internal systems without exposing raw data directly to the internet.</li></ul><h4>Transport Protocols</h4><ul><li><strong>Standard Input/Output (</strong><strong>STDIO)</strong>: Used for communication between a local MCP Client and a local MCP Server running on the same machine.</li><li><strong>Streamable HTTP</strong>: Used for remote MCP Servers over the network. It supports continuous streaming updates for long-running AI operations (e.g., progress status like 25%, 50%, complete) rather than timing out on long single requests.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec9c3aaada72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Context Protocol (MCP) vs. APIs]]></title>
            <link>https://medium.com/@md.wasim3/model-context-protocol-mcp-vs-apis-061f66eb4f1b?source=rss-4362f970560b------2</link>
            <guid isPermaLink="false">https://medium.com/p/061f66eb4f1b</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[mcp-client]]></category>
            <category><![CDATA[mcp-vs-api]]></category>
            <dc:creator><![CDATA[md wasim]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 23:01:02 GMT</pubDate>
            <atom:updated>2026-09-30T23:01:02.851Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. How Traditional APIs Work in AI Applications</h3><ul><li><strong>Definition of API</strong>: An <strong>Application Programming Interface (API)</strong> is a mechanism that allows an application to communicate directly with a specific external service (e.g., a weather service or database).</li><li><strong>The Traditional Approach (Before MCP)</strong>:</li><li>To equip an AI agent with capabilities — such as web search, database querying, flight lookups, weather forecasts, or sending emails — developers directly integrated individual APIs into the application codebase.</li><li><strong>Example</strong>: Requesting weather for Delhi requires writing code to hit a Weather API endpoint (e.g., OpenWeather API) with specific query parameters, which processes the request and returns data like <em>32°C, Sunny, 60% humidity</em>.</li></ul><h3><strong>Limitations of API-Only Integration for Multi-Tool Agents</strong></h3><ul><li><strong>Fragmentation</strong>: When an AI agent needs to use dozens of tools (flights, hotels, databases, web search, bookings), every API brings its own <strong>unique authentication mechanism</strong>, <strong>parameter requirements</strong>, and <strong>request/response formats</strong>.</li><li><strong>Code Fragility</strong>: If an API provider changes a parameter name (for instance, updating lat to latitude), the hardcoded API calls inside the AI application fail, causing the application code to break.</li><li><strong>Maintenance Overhead</strong>: Developers must continuously update their client application code whenever any third-party API changes.</li></ul><p>Below is a glance at the overhead we have when using API alone in our code. Each API has different parameters, formats and authentication methods.</p><figure><img alt="API usese" src="https://cdn-images-1.medium.com/max/1024/1*nalBtJ6t1T3iq2buwm_WZQ.jpeg" /></figure><h3>3. What is Model Context Protocol (MCP)?</h3><blockquote><strong>Definition</strong>: MCP is a <strong>standardized protocol</strong> designed to unify how AI applications connect with and execute external tools and services.</blockquote><blockquote><strong>Core Architecture</strong>:</blockquote><ul><li><strong>MCP Client</strong>: Resides within the main AI application being developed.</li><li><strong>MCP Servers</strong>: Independent server modules that expose specific tools and capabilities (e.g., Weather MCP Server, Aviation MCP Server, Web Search MCP Server, Database MCP Server).</li></ul><blockquote><strong>Key Capabilities</strong>:</blockquote><ul><li><strong>One Client to Many Servers</strong>: A <strong>single MCP client</strong> inside an AI app can connect to <strong>multiple MCP servers</strong> using the exact same standard protocol.</li><li><strong>Full Abstraction of API Details</strong>: The AI application <strong>does not need to know internal API specifics</strong> — such as endpoints, exact parameter names, authentication logic, or custom response payloads.</li><li><strong>Resilience to Changes</strong>: The MCP Server handles API calls behind the scenes. If an underlying API changes its parameters or endpoints, the maintainer updates the MCP Server, leaving the AI application codebase completely unaffected and error-free.</li></ul><figure><img alt="MCP flow" src="https://cdn-images-1.medium.com/max/1024/1*7zt9h5A2sX-RBmJc7q83XA.jpeg" /></figure><h3>4. Key Differences: Does MCP Replace APIs?</h3><ul><li><strong>Direct Answer</strong>: <strong>No, MCP does not replace APIs</strong>.</li><li><strong>Complementary Roles</strong>:</li><li><strong>APIs</strong> provide the underlying connection to communicate directly with a backend service.</li><li><strong>MCP</strong> provides a standardized interaction layer that lets AI agents dynamically discover and use tools across diverse services.</li><li><strong>Behind the Scenes</strong>: MCP Servers still utilize APIs under the hood to fetch data and perform operations.</li><li><strong>Direct Comparison Table</strong>:</li></ul><figure><img alt="APIvsMCp" src="https://cdn-images-1.medium.com/max/1024/0*0UJ81PrShcmRAYnl" /></figure><h3>5. Summary Takeaways</h3><ol><li><strong>APIs are still required</strong> to connect to services and fetch data.</li><li><strong>MCP standardizes agent integration</strong>, acting as universal glue so AI applications don&#39;t have to handle fragmented API specifications.</li><li>Comparing MCP vs. APIs as direct competitors is a misconception — they operate at different levels of the AI integration stack.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=061f66eb4f1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson 15 — Conversation History + RAG]]></title>
            <link>https://medium.com/@md.wasim3/lesson-15-conversation-history-rag-3daa75d545b6?source=rss-4362f970560b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3daa75d545b6</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[md wasim]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 21:56:01 GMT</pubDate>
            <atom:updated>2026-09-29T21:56:01.928Z</atom:updated>
            <content:encoded><![CDATA[<p>This is one of the most important steps in becoming comfortable with real-world LangChain applications.</p><p>You’ve already learned these two concepts separately:</p><pre>Conversation History<br>→ helps the model understand previous turns<br><br>RAG<br>→ retrieves information from your documents</pre><p>Now we’re going to combine them:</p><pre>Conversation History<br>        +<br>     Retrieval<br>        +<br>       LLM<br>        ↓<br>Conversational RAG</pre><p>The core problem is simple:</p><blockquote><strong><em>A follow-up question often does not contain enough information to search your documents by itself.</em></strong></blockquote><h3>1. The problem</h3><p>Imagine your company policy PDF contains:</p><pre>Annual Leave Policy<br><br>Employees receive 24 annual leave days per year.<br><br>Unused annual leave can be carried forward for<br>up to 5 days into the following year.</pre><p>The conversation:</p><pre>User:<br>How many annual leave days do employees receive?<br><br>AI:<br>Employees receive 24 annual leave days per year.<br><br>User:<br>Can I carry those days into next year?</pre><p>Look carefully at the second question:</p><pre>Can I carry those days into next year?</pre><p>What are <strong>“those days”</strong>?</p><p>A human understands:</p><pre>those days = annual leave days</pre><p>But if we send only this to the retriever:</p><pre>&quot;Can I carry those days into next year?&quot;</pre><p>the retrieval system has less useful information to work with.</p><p>This is the problem conversational RAG solves.</p><h3>2. The key idea</h3><p>We need to turn:</p><pre>Follow-up question<br>+<br>Conversation history</pre><p>into:</p><pre>Standalone search question</pre><p>For example:</p><pre>Conversation:<br><br>User:<br>How many annual leave days do employees receive?<br><br>AI:<br>Employees receive 24 annual leave days.<br><br>Current question:<br>Can I carry those days into next year?</pre><p>We transform that into:</p><pre>Standalone question:<br><br>Can employees carry annual leave days into the following year?</pre><p>Then we search the document with that clearer question.</p><p>This pattern is commonly called <strong>question contextualization</strong>, <strong>query rewriting</strong>, or <strong>history-aware retrieval</strong>. LangChain’s current reference describes create_history_aware_retriever as doing exactly this: when chat history exists, an LLM uses it to generate a search query, which is then passed to the retriever.</p><h3>3. The new architecture</h3><p>Previously:</p><pre>Question<br>   ↓<br>Retriever<br>   ↓<br>Documents<br>   ↓<br>LLM<br>   ↓<br>Answer</pre><p>Now:</p><pre>Conversation History + Question<br>              ↓<br>       Query Rewriter<br>              ↓<br>       Standalone Question<br>              ↓<br>          Retriever<br>              ↓<br>       Relevant Documents<br>              ↓<br>            Prompt<br>              ↓<br>             LLM<br>              ↓<br>            Answer</pre><p>This is the architecture I want you to understand.</p><h3>4. There are actually two different uses of history</h3><p>This is a subtle but very important point. Conversation history can be used for:</p><h3>Purpose 1 — Rewrite the question</h3><pre>History + current question<br>        ↓<br>Better search query</pre><h3>Purpose 2 — Help generate the final answer</h3><pre>History + retrieved context + question<br>        ↓<br>Final answer</pre><p>So history can appear in <strong>two different places</strong>.</p><pre>History<br>                  ↙       ↘<br>         Query Rewriter   Final Answer<br>                ↓              ↑<br>         Search Question       │<br>                ↓              │<br>            Retriever          │<br>                ↓              │<br>             Context ──────────┘</pre><p>This is one of the most important diagrams in conversational RAG.</p><h3>5. Why not just send the entire history to the retriever?</h3><p>You might think:</p><pre>&quot;Here is the entire conversation.<br>Now search my documents.&quot;</pre><p>You could do that, but a retriever normally expects a <strong>query</strong>.</p><p>A cleaner approach is:</p><pre>History<br>+<br>Latest question<br>        ↓<br>Rewrite<br>        ↓<br>One clear search query</pre><p>For example:</p><pre>History:<br>User: What is ERP?<br>AI: ERP integrates business processes.<br><br>Question:<br>What departments use it?</pre><p>Rewrite to:</p><pre>What departments can an ERP system support?</pre><p>That is much easier to search.</p><h3>6. Let’s build this step by step</h3><p>We’ll use the same ERP-style knowledge base.</p><p>Our documents:</p><pre>from langchain_core.documents import Document<br><br>documents = [<br>    Document(<br>        page_content=(<br>            &quot;ERP stands for Enterprise Resource Planning. &quot;<br>            &quot;ERP systems integrate multiple business processes.&quot;<br>        ),<br>        metadata={&quot;source&quot;: &quot;erp_guide.pdf&quot;, &quot;page&quot;: 1}<br>    ),<br>    Document(<br>        page_content=(<br>            &quot;ERP systems commonly support finance, inventory, &quot;<br>            &quot;human resources, sales, procurement, and manufacturing.&quot;<br>        ),<br>        metadata={&quot;source&quot;: &quot;erp_guide.pdf&quot;, &quot;page&quot;: 3}<br>    ),<br>    Document(<br>        page_content=(<br>            &quot;ERP provides a centralized view of business data &quot;<br>            &quot;and can help standardize business processes.&quot;<br>        ),<br>        metadata={&quot;source&quot;: &quot;erp_guide.pdf&quot;, &quot;page&quot;: 5}<br>    ),<br>]</pre><h3>7. Create embeddings and vector store</h3><p>Same as before:</p><pre>from langchain_openai import OpenAIEmbeddings<br>from langchain_core.vectorstores import InMemoryVectorStore<br><br>embeddings = OpenAIEmbeddings(<br>    model=&quot;text-embedding-3-small&quot;<br>)<br><br>vector_store = InMemoryVectorStore(<br>    embedding=embeddings<br>)<br><br>vector_store.add_documents(documents)</pre><p>Then:</p><pre>retriever = vector_store.as_retriever(<br>    search_kwargs={&quot;k&quot;: 2}<br>)</pre><p>Nothing new here.</p><h3>8. Create the query-rewriting prompt</h3><p>Now we create a special prompt whose job is <strong>not to answer the user</strong>.</p><p>Its only job is:</p><blockquote><em>Turn the conversation + latest question into a standalone search query.</em></blockquote><pre>from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder<br><br>rewrite_prompt = ChatPromptTemplate.from_messages([<br>    (<br>        &quot;system&quot;,<br>        &quot;&quot;&quot;Given the conversation history and the latest user question,<br>rewrite the question as a standalone search query.<br><br>Use the conversation history to resolve references such as:<br>&#39;it&#39;, &#39;they&#39;, &#39;those&#39;, &#39;that&#39;, or &#39;the above&#39;.<br><br>Do not answer the question.<br>Return only the rewritten search query.&quot;&quot;&quot;<br>    ),<br>    MessagesPlaceholder(variable_name=&quot;chat_history&quot;),<br>    (&quot;human&quot;, &quot;{input}&quot;)<br>])</pre><p>The important instruction is:</p><pre>Do not answer the question.<br>Return only the rewritten search query.</pre><p>We’re separating two jobs:</p><pre>Query Rewriter<br>→ search query<br><br>Answer Model<br>→ final answer</pre><h3>9. Example of the query rewriter</h3><p>Suppose:</p><pre>history = [<br>    HumanMessage(<br>        content=&quot;What is ERP?&quot;<br>    ),<br>    AIMessage(<br>        content=&quot;ERP stands for Enterprise Resource Planning.&quot;<br>    )<br>]</pre><p>and the current question is:</p><pre>What departments use it?</pre><p>The rewriter should produce something like:</p><pre>What departments commonly use or are supported by ERP systems?</pre><p>Notice:</p><pre>&quot;What departments use it?&quot;</pre><p>became:</p><pre>&quot;What departments commonly use or are supported by ERP systems?&quot;</pre><p>The missing reference was resolved.</p><h3>10. Create the query-rewriting chain</h3><pre>model = ChatOllama(model=&quot;llama3.2&quot;)<br><br>rewrite_chain = rewrite_prompt | model</pre><p>Then:</p><pre>response = rewrite_chain.invoke({<br>    &quot;chat_history&quot;: history,<br>    &quot;input&quot;: &quot;What departments use it?&quot;<br>})<br><br>print(response.content)</pre><p>Conceptually:</p><pre>History + Question<br>       ↓<br> Query Rewriter<br>       ↓<br>Standalone query</pre><h3>11. Now send the rewritten query to the retriever</h3><p>Suppose:</p><pre>standalone_question = response.content</pre><p>Then:</p><pre>docs = retriever.invoke(<br>    standalone_question<br>)</pre><p>Now:</p><pre>&quot;What departments use it?&quot;</pre><p>has become:</p><pre>&quot;What departments commonly use ERP systems?&quot;</pre><p>and <strong>that</strong> gets embedded and searched.</p><h3>12. This gives us a two-stage process</h3><pre>STAGE 1<br>=======<br>Conversation<br>+<br>Question<br> ↓<br>Query Rewriter<br> ↓<br>Standalone Question<br><br><br>STAGE 2<br>=======<br>Standalone Question<br> ↓<br>Retriever<br> ↓<br>Documents</pre><p>Then:</p><pre>STAGE 3<br>=======<br>Documents<br>+<br>Conversation<br>+<br>Question<br> ↓<br>LLM<br> ↓<br>Answer</pre><h3>13. Why does the final answer still need history?</h3><p>Suppose the conversation is:</p><pre>User:<br>What is ERP?<br><br>AI:<br>ERP is Enterprise Resource Planning software.<br><br>User:<br>Which departments use it?<br><br>AI:<br>ERP is commonly used by finance, HR, sales, procurement, etc.<br><br>User:<br>Why is it useful for them?</pre><p>The last question:</p><pre>Why is it useful for them?</pre><p>still contains references:</p><pre>it = ERP<br><br>them = those departments</pre><p>The rewritten search query might become:</p><pre>Why is ERP useful for departments such as finance,<br>HR, sales, and procurement?</pre><p>But for the final answer, conversation history can still help the model understand the conversational context.</p><p>So the final generation stage can receive:</p><pre>History<br>+<br>Retrieved Context<br>+<br>Current Question</pre><h3>14. Final-answer prompt</h3><p>Create:</p><pre>answer_prompt = ChatPromptTemplate.from_messages([<br>    (<br>        &quot;system&quot;,<br>        &quot;&quot;&quot;You are an ERP knowledge assistant.<br><br>Use the retrieved context to answer the user&#39;s question.<br><br>If the answer is not supported by the context,<br>say that you do not have enough information.<br><br>Do not invent facts.&quot;&quot;&quot;<br>    ),<br>    MessagesPlaceholder(variable_name=&quot;chat_history&quot;),<br>    (<br>        &quot;human&quot;,<br>        &quot;&quot;&quot;Context:<br>{context}<br><br>Question:<br>{input}&quot;&quot;&quot;<br>    )<br>])</pre><p>Now history is included.</p><h3>15. Format retrieved documents</h3><pre>def format_docs(docs):<br>    return &quot;\n\n&quot;.join(<br>        doc.page_content<br>        for doc in docs<br>    )</pre><p>Then:</p><pre>context = format_docs(docs)</pre><h3>16. Generate the final answer</h3><pre>answer_chain = answer_prompt | model<br><br>answer = answer_chain.invoke({<br>    &quot;chat_history&quot;: history,<br>    &quot;context&quot;: context,<br>    &quot;input&quot;: &quot;What departments use it?&quot;<br>})<br><br>print(answer.content)</pre><p>Conceptually:</p><pre>History<br>   +<br>Context<br>   +<br>Question<br>   ↓<br>Answer Model<br>   ↓<br>Answer</pre><h3>17. Put the pieces together</h3><p>We can now create a simple conversational RAG function.</p><pre>from langchain_core.documents import Document<br>from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder<br>from langchain_core.messages import HumanMessage, AIMessage<br>from langchain_core.vectorstores import InMemoryVectorStore<br><br># Import Ollama specific modules<br>from langchain_ollama import ChatOllama<br>from langchain_ollama import OllamaEmbeddings<br><br># ==========================================<br># 1. Setup the Ollama Model and Embeddings<br># ==========================================<br># Ensure you have run: ollama pull llama3 and ollama pull nomic-embed-text<br>model = ChatOllama(model=&quot;llama3.2&quot;, temperature=0)<br>embeddings = OllamaEmbeddings(model=&quot;nomic-embed-text&quot;)<br><br># ==========================================<br># 2. Prepare the Knowledge Base<br># ==========================================<br>documents = [<br>    Document(<br>        page_content=(&quot;ERP stands for Enterprise Resource Planning. &quot;<br>                      &quot;ERP systems integrate multiple business processes.&quot;),<br>        metadata={&quot;source&quot;: &quot;erp_guide.pdf&quot;, &quot;page&quot;: 1}<br>    ),<br>    Document(<br>        page_content=(&quot;ERP systems commonly support finance, inventory, &quot;<br>                      &quot;human resources, sales, procurement, and manufacturing.&quot;),<br>        metadata={&quot;source&quot;: &quot;erp_guide.pdf&quot;, &quot;page&quot;: 3}<br>    ),<br>    Document(<br>        page_content=(&quot;ERP provides a centralized view of business data &quot;<br>                      &quot;and can help standardize business processes.&quot;),<br>        metadata={&quot;source&quot;: &quot;erp_guide.pdf&quot;, &quot;page&quot;: 5}<br>    ),<br>]<br><br>vector_store = InMemoryVectorStore(embedding=embeddings)<br>vector_store.add_documents(documents)<br>retriever = vector_store.as_retriever(search_kwargs={&quot;k&quot;: 2})<br><br># ==========================================<br># 3. Create the Query-Rewriting Prompt &amp; Chain<br># ==========================================<br>rewrite_prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;&quot;&quot;Given the conversation history and the latest user question,<br>    rewrite the question as a standalone search query. Use the conversation history<br>    to resolve references such as: &#39;it&#39;, &#39;they&#39;, &#39;those&#39;, &#39;that&#39;, or &#39;the above&#39;.<br>    Do not answer the question. Return only the rewritten search query.&quot;&quot;&quot;),<br>    MessagesPlaceholder(variable_name=&quot;chat_history&quot;),<br>    (&quot;human&quot;, &quot;{input}&quot;)<br>])<br><br>rewrite_chain = rewrite_prompt | model<br><br># ==========================================<br># 4. Create the Final Answer Prompt &amp; Chain<br># ==========================================<br>answer_prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;&quot;&quot;You are an ERP knowledge assistant. Use the retrieved context<br>    to answer the user&#39;s question. If the answer is not supported by the context,<br>    say that you do not have enough information. Do not invent facts.&quot;&quot;&quot;),<br>    MessagesPlaceholder(variable_name=&quot;chat_history&quot;),<br>    (&quot;human&quot;, &quot;Context: {context}\n\nQuestion: {input}&quot;)<br>])<br><br>answer_chain = answer_prompt | model<br><br>def format_docs(docs):<br>    return &quot;\n\n&quot;.join(doc.page_content for doc in docs)<br><br># ==========================================<br># 5. Build the Conversational RAG function<br># ==========================================<br>history = []<br><br>def chat(question):<br>    print(f&quot;\n{&#39;=&#39;*50}\nUSER QUESTION: {question}\n{&#39;=&#39;*50}&quot;)<br><br>    # Step 1: Rewrite question if history exists<br>    if history:<br>        rewritten = rewrite_chain.invoke({<br>            &quot;chat_history&quot;: history,<br>            &quot;input&quot;: question<br>        })<br>        standalone_question = rewritten.content<br>    else:<br>        # No need to rewrite if it&#39;s the very first question<br>        standalone_question = question<br><br>    print(f&quot;🔍 Rewritten search query: {standalone_question}&quot;)<br><br>    # Step 2: Retrieve documents<br>    docs = retriever.invoke(standalone_question)<br>    context = format_docs(docs)<br>    print(f&quot;📄 Retrieved context:\n{context}&quot;)<br><br>    # Step 3: Generate answer<br>    answer = answer_chain.invoke({<br>        &quot;chat_history&quot;: history,<br>        &quot;context&quot;: context,<br>        &quot;input&quot;: question<br>    })<br><br>    print(f&quot;\n🤖 Final answer: {answer.content}&quot;)<br><br>    # Step 4: Save conversation to history<br>    history.append(HumanMessage(content=question))<br>    history.append(AIMessage(content=answer.content))<br><br>    return answer.content<br><br># ==========================================<br># 6. Test the Conversational Agent<br># ==========================================<br>if __name__ == &quot;__main__&quot;:<br>    chat(&quot;What is ERP?&quot;)<br>    chat(&quot;Which departments use it?&quot;)<br>    chat(&quot;Why is it useful for them?&quot;)<br>    chat(&quot;What about inventory specifically?&quot;)</pre><p>Now:</p><pre>print(chat(&quot;What is ERP?&quot;))</pre><p>Then:</p><pre>print(chat(&quot;Which departments use it?&quot;))</pre><p>Then:</p><pre>print(chat(&quot;Why is it useful for them?&quot;))</pre><p>The application now combines:</p><pre>Conversation<br>+<br>Retrieval<br>+<br>Generation</pre><h3>18. Let’s trace the first question</h3><p>User:</p><pre>What is ERP?</pre><p>There’s no previous history.</p><p>So:</p><pre>History = empty</pre><p>The search query can simply be:</p><pre>What is ERP?</pre><p>Retriever:</p><pre>What is ERP?<br> ↓<br>ERP definition chunk</pre><p>LLM:</p><pre>Context + question<br> ↓<br>ERP answer</pre><p>Then history becomes:</p><pre>Human:<br>What is ERP?<br><br>AI:<br>ERP stands for Enterprise Resource Planning...</pre><h3>19. Trace the second question</h3><p>User:</p><pre>Which departments use it?</pre><p>History:</p><pre>Human:<br>What is ERP?<br><br>AI:<br>ERP stands for Enterprise Resource Planning...</pre><p>Now:</p><pre>History + current question<br>        ↓<br>Query Rewriter<br>        ↓<br>&quot;What departments use ERP systems?&quot;</pre><p>Then:</p><pre>&quot;What departments use ERP systems?&quot;<br>        ↓<br>Retriever<br>        ↓<br>ERP department chunk</pre><p>Then:</p><pre>History<br>+<br>Retrieved context<br>+<br>Current question<br>        ↓<br>LLM<br>        ↓<br>Answer</pre><h3>20. Trace the third question</h3><p>User:</p><pre>Why is it useful for them?</pre><p>History contains the previous discussion about:</p><pre>ERP<br>departments</pre><p>The query rewriter might produce:</p><pre>Why is ERP useful for departments such as finance,<br>HR, sales, procurement, and manufacturing?</pre><p>Then the retriever searches for:</p><pre>ERP benefits</pre><p>rather than searching literally for:</p><pre>&quot;Why is it useful for them?&quot;</pre><p>That’s the key benefit.</p><h3>21. Why query rewriting is so powerful</h3><p>Compare:</p><h3>Original question</h3><pre>Why is it useful for them?</pre><h3>Rewritten question</h3><pre>Why is ERP useful for departments such as finance,<br>HR, sales, procurement, and manufacturing?</pre><p>The second query gives the retrieval system much more semantic information.</p><p>So:</p><pre>Conversation-aware retrieval</pre><p>can be significantly more useful for multi-turn document conversations.</p><h3>22. A useful distinction: search question vs user question</h3><p>You should now understand that these can be different.</p><pre>User question:<br>Why is it useful for them?</pre><p>Search question:</p><pre>Why is ERP useful for finance, HR, sales,<br>procurement, and manufacturing departments?</pre><p>The search query is an <strong>internal intermediate representation</strong>.</p><p>The user doesn’t necessarily need to see it.</p><p>Think:</p><pre>User language<br>     ↓<br>Query transformation<br>     ↓<br>Search language<br>     ↓<br>Retriever</pre><h3>23. This is not the same as conversation memory</h3><p>This distinction is important.</p><h3>Conversation history</h3><p>Contains:</p><pre>what happened in the conversation</pre><p>Example:</p><pre>User: What is ERP?<br>AI: ERP is...</pre><h3>RAG knowledge base</h3><p>Contains:</p><pre>external knowledge/documents</pre><p>Example:</p><pre>ERP Guide.pdf</pre><p>They’re different sources of context:</p><pre>Conversation Context<br>+<br>Knowledge Context</pre><p>Then:</p><pre>LLM</pre><p>uses both.</p><h3>24. Conversation history doesn’t replace RAG</h3><p>Suppose the conversation says:</p><pre>AI:<br>ERP provides 24 annual leave days.</pre><p>but that information wasn’t actually in your source documents.</p><p>History alone doesn’t prove it’s correct.</p><p>RAG provides access to your external knowledge source.</p><p>So:</p><pre>History<br>→ conversational context<br><br>RAG<br>→ external knowledge</pre><h3>25. RAG doesn’t replace conversation history either</h3><p>Suppose your document says:</p><pre>ERP supports finance, HR, sales and procurement.</pre><p>User says:</p><pre>Which departments use it?</pre><p>The document alone doesn’t clarify:</p><pre>it = ERP</pre><p>Conversation history helps resolve the reference.</p><p>So:</p><pre>History → understand the user&#39;s reference<br><br>Retriever → find the actual information</pre><p>That’s why they work so well together.</p><h3>26. A common architecture</h3><p>You can think of conversational RAG as:</p><pre>Conversation<br>                         │<br>                         ▼<br>                  Query Rewriter<br>                         │<br>                         ▼<br>                   Search Query<br>                         │<br>                         ▼<br>                    Retriever<br>                         │<br>                         ▼<br>                  Retrieved Docs<br>                         │<br>                         ▼<br>                 ┌───────────────┐<br>                 │ Final Prompt  │<br>                 │               │<br>                 │ History       │<br>                 │ Context       │<br>                 │ Question      │<br>                 └───────┬───────┘<br>                         ↓<br>                        LLM<br>                         ↓<br>                      Answer</pre><p>That’s the architecture I want you to be able to draw from memory.</p><h3>27. What happens when history is empty?</h3><p>This is another subtle detail. You don’t need to rewrite:</p><pre>What is ERP?</pre><p>into something else if there is no history.</p><p>You can simply search:</p><pre>What is ERP?</pre><p>The history-aware retriever pattern in LangChain’s current reference behaves this way: without chat_history, it passes the input directly to the retriever; with history, it uses the LLM to generate a search query first.</p><p>So:</p><pre>No history<br>   ↓<br>Question → Retriever<br><br>History exists<br>   ↓<br>History + Question<br>   ↓<br>Rewrite<br>   ↓<br>Retriever</pre><p>This avoids unnecessary rewriting.</p><h3>28. LangChain’s create_history_aware_retriever</h3><p>You may come across code like:</p><pre>from langchain_classic.chains import (<br>    create_history_aware_retriever<br>)</pre><p>and:</p><pre>history_aware_retriever = create_history_aware_retriever(<br>    model,<br>    retriever,<br>    rewrite_prompt<br>)</pre><p>This is a convenience abstraction for the exact pattern we just built manually.</p><p>The current LangChain reference documents create_history_aware_retriever under <strong>langchain_classic</strong>, and says it creates a chain that takes conversation history and returns documents; with history, it uses the prompt + LLM to generate the search query.</p><h3>29. Why I’m emphasizing this</h3><p>A beginner might write:</p><pre>history_aware_retriever = create_history_aware_retriever(...)</pre><p>and move on.</p><p>But then they may not understand:</p><pre>What did it actually do?</pre><p>Now you do.</p><p>Internally, conceptually:</p><pre>chat_history<br>      +<br>current question<br>      ↓<br>LLM<br>      ↓<br>standalone search query<br>      ↓<br>retriever</pre><p>That’s much more valuable knowledge than memorizing one API call.</p><h3>30. Another important LangChain concept: MessagesPlaceholder</h3><p>You’ve used:</p><pre>MessagesPlaceholder(<br>    variable_name=&quot;chat_history&quot;<br>)</pre><p>It means:</p><blockquote><em>Insert a sequence of actual chat messages at this location.</em></blockquote><p>For example:</p><pre>System:<br>You are helpful.<br><br>MessagesPlaceholder(&quot;chat_history&quot;)<br><br>Human:<br>What departments use it?</pre><p>If history is:</p><pre>Human: What is ERP?<br>AI: ERP is Enterprise Resource Planning.</pre><p>the final prompt becomes conceptually:</p><pre>System:<br>You are helpful.<br><br>Human:<br>What is ERP?<br><br>AI:<br>ERP is Enterprise Resource Planning.<br><br>Human:<br>What departments use it?</pre><p>This is why MessagesPlaceholder is useful for conversations.</p><h3>31. History should have actual message objects</h3><p>For example:</p><pre>history = [<br>    HumanMessage(<br>        content=&quot;What is ERP?&quot;<br>    ),<br>    AIMessage(<br>        content=&quot;ERP stands for Enterprise Resource Planning.&quot;<br>    )<br>]</pre><p>Not:</p><pre>history = [<br>    &quot;User asked what ERP is&quot;,<br>    &quot;AI explained ERP&quot;<br>]</pre><p>The message representation preserves the conversational roles.</p><h3>32. What about long conversations?</h3><p>Now we encounter a practical problem.</p><p>Imagine:</p><pre>500 messages</pre><p>You don’t necessarily want to send the entire conversation every time.</p><p>Why? Because:</p><pre>More history<br>   ↓<br>More context<br>   ↓<br>More tokens<br>   ↓<br>More latency/cost</pre><p>and eventually too much irrelevant information can make the prompt less effective.</p><p>LangChain’s current memory documentation distinguishes <strong>short-term memory</strong> for a single conversation/thread from <strong>long-term memory</strong> across conversations. It describes short-term memory as conversation history/state within a thread, while long-term memory persists across conversations.</p><h3>33. History vs long-term memory</h3><p>Don’t confuse:</p><pre>Conversation History</pre><p>with:</p><pre>Long-term Memory</pre><h3>Conversation history</h3><p>Example:</p><pre>User:<br>My favorite programming language is Python.<br><br>AI:<br>Got it.<br><br>User:<br>Why do I like it?</pre><p>That’s current conversational context.</p><h3>Long-term memory</h3><p>Suppose the user returns next month:</p><pre>User:<br>What programming language do I usually prefer?</pre><p>The application might retrieve a stored preference from persistent memory.</p><p>Current LangChain documentation describes long-term memory as information that persists across conversations, while short-term memory is associated with a single session/thread.</p><p>We’ll get into the persistent-memory architecture later.</p><h3>34. Conversational RAG vs Agentic RAG</h3><p>These are also different.</p><h3>Conversational RAG</h3><pre>History<br> +<br>Question<br> ↓<br>Retrieve<br> ↓<br>Answer</pre><h3>Agentic RAG</h3><pre>History<br> +<br>Question<br> ↓<br>Agent<br> ↓<br>Should I search?<br> ↓<br>Search tool<br> ↓<br>Should I search again?<br> ↓<br>Maybe calculator<br> ↓<br>Maybe another tool<br> ↓<br>Answer</pre><p>LangChain’s current retrieval documentation describes 2-step RAG as always retrieving before generation, while agentic RAG allows an LLM-powered agent to decide when and how retrieval occurs.</p><h3>35. What happens if the user changes topic?</h3><p>Consider:</p><pre>User:<br>What is ERP?<br><br>AI:<br>...<br><br>User:<br>Which departments use it?<br><br>AI:<br>...<br><br>User:<br>Now explain Python decorators.</pre><p>The retriever should not blindly let the old ERP context dominate the new question.</p><p>A query rewriter should recognize that:</p><pre>&quot;Now explain Python decorators.&quot;</pre><p>is a new topic.</p><p>The resulting search query can remain:</p><pre>Explain Python decorators.</pre><p>This is one reason contextualization should be designed carefully.</p><h3>36. The biggest lesson</h3><p>In normal RAG:</p><pre>Question → Retriever</pre><p>In conversational RAG:</p><pre>History + Question<br>        ↓<br>    Rewrite<br>        ↓<br>    Retriever</pre><p>That’s the difference.</p><p>And then:</p><pre>History + Retrieved Context + Question<br>                ↓<br>                LLM</pre><p>for the final response.</p><h3>37. Complete architecture</h3><p>Here’s the final diagram:</p><pre>USER<br>                       │<br>                       ▼<br>                Current Question<br>                       │<br>                       │<br>              Conversation History<br>                       │<br>                       ▼<br>               ┌────────────────┐<br>               │ Query Rewriter │<br>               └───────┬────────┘<br>                       │<br>                       ▼<br>                Standalone Query<br>                       │<br>                       ▼<br>                 ┌────────────┐<br>                 │ Retriever │<br>                 └─────┬──────┘<br>                       │<br>                       ▼<br>               Relevant Documents<br>                       │<br>                       ▼<br>          ┌───────────────────────────┐<br>          │        Final Prompt       │<br>          │                           │<br>          │ Conversation History      │<br>          │ Retrieved Context         │<br>          │ Current Question          │<br>          └─────────────┬─────────────┘<br>                        │<br>                        ▼<br>                       LLM<br>                        │<br>                        ▼<br>                      Answer<br>                        │<br>                        ▼<br>               Update Conversation</pre><p>This is the core architecture of conversational RAG.</p><h3>Next Lesson — Lesson 16: RAG Quality — Why Retrieval Fails</h3><p>We’ll tackle one of the most important real-world problems:</p><blockquote><strong><em>“My RAG application has the right PDF, but it’s still giving wrong answers.”</em></strong></blockquote><p>We’ll learn about <strong>bad chunking, wrong </strong><strong>k, similarity thresholds, metadata filtering, query rewriting, reranking, hybrid search, and context quality</strong>, and you&#39;ll learn how to systematically find <em>which part</em> of the RAG pipeline is failing. LangChain&#39;s current retrieval guidance explicitly treats retrieval quality as a separate evaluation problem from answer correctness and groundedness.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3daa75d545b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson 14 — Building a Real “Chat with PDF” RAG Application]]></title>
            <link>https://medium.com/@md.wasim3/lesson-14-building-a-real-chat-with-pdf-rag-application-986ee7d66569?source=rss-4362f970560b------2</link>
            <guid isPermaLink="false">https://medium.com/p/986ee7d66569</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[md wasim]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 07:10:44 GMT</pubDate>
            <atom:updated>2026-09-29T07:10:44.203Z</atom:updated>
            <content:encoded><![CDATA[<p>Now we’re going to take everything you’ve learned and apply it to an actual <strong>PDF file</strong>.</p><p>The goal is to build:</p><pre>company_policy.pdf<br>                         ↓<br>                    PDF Loader<br>                         ↓<br>                     Documents<br>                         ↓<br>                   Text Chunks<br>                         ↓<br>                    Embeddings<br>                         ↓<br>                    Vector Store<br>                         ↓<br>                     Retriever<br>                         ↓<br>                   Relevant Chunks<br>                         ↓<br>                       Prompt<br>                         ↓<br>                        LLM<br>                         ↓<br>                  Answer + Source</pre><p>LangChain’s current retrieval documentation describes this as a modular pipeline: document loaders create standardized Document objects, text splitters create retrievable chunks, embeddings map text to vectors, vector stores search those vectors, and retrievers return relevant documents.</p><h3>1. The problem we’re solving</h3><p>Imagine this PDF:</p><pre>company_policy.pdf<br>Page 1<br>Company Leave Policy<br>Employees receive 24 annual leave days per year.<br>Page 2<br>Sick Leave Policy<br>Employees receive 10 sick leave days per year.<br>Page 3<br>Remote Work Policy<br>Employees may work remotely up to 3 days per week.</pre><p>The user asks:</p><pre>How many annual leave days do employees receive?</pre><p>Our application should answer:</p><pre>Employees receive 24 annual leave days per year.</pre><pre>Source: company_policy.pdf<br>Page: 1</pre><p>This is much more useful than simply:</p><pre>24 days.</pre><h3>2. First: what is a PDF loader?</h3><p>A <strong>document loader</strong> is responsible for taking data from an external source and turning it into LangChain Document objects.</p><p>The current LangChain retrieval docs describe document loaders as the component that ingests external sources and returns standardized Document objects. For a basic text PDF, a commonly used integration is PyPDFLoader.</p><p>Conceptually:</p><pre>PDF<br> ↓<br>PyPDFLoader<br> ↓<br>Document objects</pre><h3>3. Install the required packages</h3><p>For this example:</p><pre>pip install -U langchain langchain-openai langchain-community langchain-text-splitters pypdf</pre><p>You also need:</p><pre>OPENAI_API_KEY or local running Ollama</pre><p>set in your environment.</p><h3>4. Load the PDF</h3><p>Suppose your file is:</p><pre>company_policy.pdf</pre><p>Code:</p><pre>from langchain_community.document_loaders import PyPDFLoader<br>loader = PyPDFLoader(&quot;company_policy.pdf&quot;)<br>documents = loader.load()</pre><p>Now:</p><pre>documents</pre><p>contains Document objects representing the PDF content.</p><h3>5. What does one Document look like?</h3><p>Try:</p><pre>print(documents[0])</pre><p>Conceptually, you’ll see something like:</p><pre>Document(<br>    page_content=&quot;Company Leave Policy ...&quot;,<br>    metadata={<br>        &quot;source&quot;: &quot;company_policy.pdf&quot;,<br>        &quot;page&quot;: 0<br>    }<br>)</pre><p>The exact metadata depends on the loader and configuration.</p><p>The important parts are:</p><pre>document.page_content</pre><p>and:</p><pre>document.metadata</pre><h3>6. page_content</h3><p>This contains the actual text.</p><pre>print(documents[0].page_content)</pre><p>For example:</p><pre>Company Leave Policy<br>Employees receive 24 annual leave days per year.</pre><p>So:</p><pre>Document<br>   ├── page_content<br>   └── metadata</pre><h3>7. metadata</h3><p>Metadata tells us additional information about the document.</p><p>For example:</p><pre>print(documents[0].metadata)</pre><p>You may see information similar to:</p><pre>{<br>    &quot;source&quot;: &quot;company_policy.pdf&quot;,<br>    &quot;page&quot;: 0,<br>    ...<br>}</pre><p>Depending on the loader, metadata can include things such as source file, page number, total pages, or page label. This becomes extremely useful for citations.</p><h3>8. Why metadata matters</h3><p>Suppose the retriever finds:</p><pre>Employees receive 24 annual leave days per year.</pre><p>The LLM can answer:</p><pre>Employees receive 24 annual leave days.</pre><p>But your application can also inspect:</p><pre>doc.metadata</pre><p>and discover:</p><pre>source = company_policy.pdf<br>page = 0</pre><p>Then your UI could show:</p><pre>Employees receive 24 annual leave days.<br>Source: company_policy.pdf, Page 1</pre><p>So metadata travels alongside the text.</p><p>Think:</p><pre>Text<br>+<br>Metadata<br>=<br>Document</pre><h3>9. Important: page numbering can be confusing</h3><p>Suppose metadata says:</p><pre>&quot;page&quot;: 0</pre><p>A user doesn’t normally think:</p><pre>Page 0</pre><p>They think:</p><pre>Page 1</pre><p>Many PDF-processing APIs use <strong>zero-based indexing</strong> internally.</p><p>So when displaying sources to users, you may need:</p><pre>display_page = doc.metadata[&quot;page&quot;] + 1</pre><p>But don’t blindly assume every loader uses the same metadata fields; inspect your actual Document.metadata.</p><p>This is a good general rule:</p><pre>Internal metadata<br>        ↓<br>Inspect it<br>        ↓<br>Convert it to user-friendly source information</pre><h3>10. Load all pages</h3><p>Let’s inspect the document:</p><pre>for i, doc in enumerate(documents):<br>print(f&quot;\n--- Document {i} ---&quot;)<br>    print(doc.page_content)<br>    print(&quot;Metadata:&quot;)<br>    print(doc.metadata)</pre><p>You might get:</p><pre>--- Document 0 ---<br>Company Leave Policy<br>Employees receive 24 annual leave days per year.<br>Metadata:<br>{&#39;source&#39;: &#39;company_policy.pdf&#39;, &#39;page&#39;: 0}<br><br>--- Document 1 ---<br>Sick Leave Policy<br>Employees receive 10 sick leave days per year.<br>Metadata:<br>{&#39;source&#39;: &#39;company_policy.pdf&#39;, &#39;page&#39;: 1}</pre><p>Now you can clearly see:</p><pre>PDF page<br>   ↓<br>Document</pre><h3>11. What if the PDF has 100 pages?</h3><p>Then:</p><pre>documents = loader.load()</pre><p>might produce roughly:</p><pre>Document 0 → page 1<br>Document 1 → page 2<br>Document 2 → page 3<br>...<br>Document 99 → page 100</pre><p>So the PDF has already been broken into page-level documents.</p><p>But that’s <strong>not necessarily the final chunking we want</strong>.</p><p>A page can contain a lot of text.</p><p>That’s where our text splitter comes in.</p><h3>12. Split the PDF documents</h3><p>Use:</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter</pre><p>Then:</p><pre>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=500,<br>    chunk_overlap=100<br>)<br>chunks = splitter.split_documents(documents)</pre><p>The current LangChain documentation recommends RecursiveCharacterTextSplitter as a general-purpose splitter. It tries separators in order so that paragraphs, then sentences/words, stay together when possible; its default size measurement is characters.</p><h3>13. Does splitting destroy the page information?</h3><p>This is an important question. Normally, when you split Document objects using:</p><pre>chunks = splitter.split_documents(documents)</pre><p>the resulting chunks remain Document objects and can retain the original metadata.</p><p>So you can get something like:</p><pre>Chunk 1<br>content = &quot;Employees receive 24 annual leave days...&quot;<br>metadata = page 0<br>Chunk 2<br>content = &quot;Annual leave should normally be requested...&quot;<br>metadata = page 0<br>Chunk 3<br>content = &quot;Employees receive 10 sick leave days...&quot;<br>metadata = page 1</pre><p>That’s exactly what we want.</p><p>We now have:</p><pre>PDF<br> ↓<br>Pages<br> ↓<br>Chunks</pre><p>while still keeping source information.</p><p>The splitter documentation specifically notes that Document objects are the intended output for downstream tasks.</p><h3>14. Why split pages into chunks?</h3><p>Imagine page 8 contains:</p><pre>Leave Policy<br>...<br>lots of unrelated information...<br>...<br>Annual leave carry-forward policy<br>...<br>...<br>Remote work...<br>...</pre><p>The user asks:</p><pre>How many days can I carry forward?</pre><p>We don’t necessarily want to retrieve the entire page.</p><p>We want a smaller relevant piece:</p><pre>Annual leave carry-forward policy...</pre><p>So:</p><pre>Page<br> ↓<br>Smaller chunks<br> ↓<br>More precise retrieval</pre><p>This is why text splitting is a key RAG step. LangChain describes splitters as breaking large documents into smaller chunks that can be retrieved individually and fit into model context.</p><h3>15. Inspect your chunks</h3><p>Always do this while learning.</p><pre>for i, chunk in enumerate(chunks[:5]):</pre><pre>    print(f&quot;\n--- Chunk {i} ---&quot;)</pre><pre>    print(chunk.page_content)</pre><pre>    print(&quot;Metadata:&quot;)<br>    print(chunk.metadata)</pre><p>You’ll start developing an important RAG debugging habit:</p><blockquote><strong><em>Never blindly trust the chunking step. Inspect what it produced.</em></strong></blockquote><h3>16. Create embeddings</h3><p>Now:</p><pre>from langchain_openai import OpenAIEmbeddings<br>embeddings = OpenAIEmbeddings(<br>    model=&quot;text-embedding-3-small&quot;<br>)</pre><p>Conceptually:</p><pre>Chunk<br> ↓<br>Embedding Model<br> ↓<br>Vector</pre><p>Each chunk becomes a vector representation.</p><h3>17. Create the vector store</h3><p>For learning:</p><pre>from langchain_core.vectorstores import InMemoryVectorStore<br>vector_store = InMemoryVectorStore(<br>    embedding=embeddings<br>)</pre><p>Then:</p><pre>vector_store.add_documents(chunks)</pre><p>Now:</p><pre>Chunks<br> ↓<br>Embeddings<br> ↓<br>Vectors<br> ↓<br>Vector Store</pre><h3>18. Create the retriever</h3><pre>retriever = vector_store.as_retriever(<br>    search_kwargs={&quot;k&quot;: 3}<br>)</pre><p>This means:</p><pre>Question<br> ↓<br>Retriever<br> ↓<br>Try to find 3 relevant chunks</pre><h3>19. Test retrieval before using the LLM</h3><p>This is extremely important.</p><p>Ask:</p><pre>question = &quot;How many annual leave days do employees receive?&quot;</pre><p>Then:</p><pre>results = retriever.invoke(question)</pre><p>Inspect them:</p><pre>for i, doc in enumerate(results):<br>print(f&quot;\n--- Result {i + 1} ---&quot;)<br>    print(doc.page_content)<br>    print(&quot;Source:&quot;, doc.metadata)</pre><p>You might see:</p><pre>--- Result 1 ---<br>Employees receive 24 annual leave days per year.<br>Source:<br>{&#39;source&#39;: &#39;company_policy.pdf&#39;, &#39;page&#39;: 0}</pre><p><em>Excellent</em>. Now the retrieval stage is working.</p><h3>20. If retrieval returns the wrong page</h3><p>Suppose you ask:</p><pre>How many annual leave days do employees receive?</pre><p>but get:</p><pre>Remote Work Policy<br>Employees may work remotely...</pre><p>Don’t immediately change the LLM prompt.</p><p>The problem is here:</p><pre>Question<br> ↓<br>Retriever<br> ↓<br>❌ Wrong chunks</pre><p>This is a <strong>retrieval problem</strong>.</p><p>Remember the debugging rule from the previous lessons:</p><pre>Wrong answer?<br>       ↓<br>Inspect retrieved documents first.</pre><h3>21. Create the RAG prompt</h3><p>Now:</p><pre>from langchain_core.prompts import ChatPromptTemplate<br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>You are a company policy assistant.<br>Answer the question using only the provided context.<br>If the answer is not contained in the context,<br>say that you do not have enough information.<br>Context:<br>{context}<br>Question:<br>{question}<br>&quot;&quot;&quot;)</pre><h3>22. Create the model</h3><pre>from langchain_openai import ChatOpenAI<br>model = ChatOpenAI(<br>    model=&quot;gpt-5.4-mini&quot;<br>)</pre><h3>23. Format the retrieved documents</h3><p>We’ll create:</p><pre>def format_docs(docs):<br>    return &quot;\n\n&quot;.join(<br>        doc.page_content<br>        for doc in docs<br>    )</pre><p>The retriever gives us:</p><pre>Document<br>Document<br>Document</pre><p>We convert them to:</p><pre>string</pre><p>for the prompt.</p><h3>24. Build the RAG chain</h3><p>Now combine what you learned in Lesson 13:</p><pre>from langchain_core.runnables import RunnablePassthrough<br>rag_chain = (<br>    {<br>        &quot;context&quot;: retriever | format_docs,<br>        &quot;question&quot;: RunnablePassthrough()<br>    }<br>    | prompt<br>    | model<br>)</pre><p>The data flow is:</p><pre>Question<br>                    │<br>          ┌─────────┴─────────┐<br>          ↓                   ↓<br>      Retriever          Passthrough<br>          ↓                   ↓<br>       Documents           Question<br>          ↓<br>    format_docs()<br>          ↓<br>        Context<br>          └─────────┬─────────┘<br>                    ↓<br>                  Prompt<br>                    ↓<br>                   LLM<br>                    ↓<br>                 Answer</pre><h3>25. Ask a question</h3><pre>response = rag_chain.invoke(<br>    &quot;How many annual leave days do employees receive?&quot;<br>)<br>print(response.content)</pre><p>The answer should be something like:</p><pre>Employees receive 24 annual leave days per year.</pre><p>We now have a complete <strong>PDF → RAG → answer</strong> application.</p><h3>26. But we still have one problem</h3><p>The answer doesn’t tell us:</p><pre>Where did this information come from?</pre><p>We want:</p><pre>Employees receive 24 annual leave days per year.<br>Source: company_policy.pdf<br>Page: 1</pre><p>So we need to preserve the retrieved documents, rather than converting them only into a string and throwing the metadata away.</p><p>This leads to a very useful pattern.</p><h3>27. Return both answer and source documents</h3><p>One simple approach while learning is to retrieve first:</p><pre>question = &quot;How many annual leave days do employees receive?&quot;<br>docs = retriever.invoke(question)</pre><p>Then create context:</p><pre>context = format_docs(docs)</pre><p>Then:</p><pre>response = (prompt | model).invoke({<br>    &quot;context&quot;: context,<br>    &quot;question&quot;: question<br>})</pre><p>Now we have two things:</p><pre>response → answer<br>docs     → source information</pre><p>That’s useful.</p><h3>28. Print the answer and sources</h3><pre>print(&quot;ANSWER:&quot;)<br>print(response.content)<br>print(&quot;\nSOURCES:&quot;)<br>for doc in docs:<br>    source = doc.metadata.get(&quot;source&quot;)<br>    page = doc.metadata.get(&quot;page&quot;)<br>    if page is not None:<br>        page = page + 1<br>    print(f&quot;{source} - Page {page}&quot;)</pre><p>You might get:</p><pre>ANSWER:<br>Employees receive 24 annual leave days per year.<br>SOURCES:<br>company_policy.pdf - Page 1</pre><p>Now you’ve created a primitive <strong>source citation system</strong>.</p><h3>29. Why shouldn’t we rely entirely on the LLM for citations?</h3><p>Suppose we ask:</p><pre>Tell me the source and page number.</pre><p>The model could potentially produce:</p><pre>Page 4</pre><p>even if the actual document was page 2. That’s because the LLM is generating text.</p><p>A safer architecture is:</p><pre>Retriever<br> ↓<br>Real metadata<br> ↓<br>Application formats source</pre><p>rather than asking the model to invent source metadata.</p><p>So:</p><pre>LLM → answer<br>Application → source metadata</pre><p>This separation is useful.</p><h3>30. Better source formatting</h3><p>Let’s modify our formatter:</p><pre>def format_docs(docs):<br>    formatted = []<br>for doc in docs:<br>        source = doc.metadata.get(&quot;source&quot;, &quot;Unknown&quot;)<br>        page = doc.metadata.get(&quot;page&quot;)<br>        if page is not None:<br>            page = page + 1<br>        formatted.append(<br>            f&quot;Source: {source}, Page: {page}\n&quot;<br>            f&quot;{doc.page_content}&quot;<br>        )<br>    return &quot;\n\n&quot;.join(formatted)</pre><p>Now the model receives:</p><pre>Source: company_policy.pdf, Page: 1<br>Employees receive 24 annual leave days per year.<br>Source: company_policy.pdf, Page: 2<br>Employees receive 10 sick leave days per year.</pre><p>This gives the model more context about where the information came from.</p><h3>31. But don’t confuse source metadata with truth</h3><p>Even if the prompt says:</p><pre>Source: company_policy.pdf, Page: 1</pre><p>the model could still generate an incorrect answer.</p><p>So we still need:</p><pre>Good retrieval<br>+<br>Good context<br>+<br>Good prompt<br>+<br>Good model behavior</pre><p>RAG improves access to external information, but doesn’t mathematically guarantee correctness. LangChain’s retrieval documentation treats retrieval quality and answer correctness/groundedness as separate evaluation concerns.</p><h3>32. What about scanned PDFs?</h3><p>This is a very important real-world issue.</p><p>Imagine your PDF looks like:</p><pre>📄 scanned image</pre><p>rather than:</p><pre>📄 text layer</pre><p>A normal text-based PDF loader may not be able to extract useful text.</p><p>For example:</p><pre>Scanned PDF<br>     ↓<br>PDF loader<br>     ↓<br>Little/no text<br>     ↓<br>Chunks = useless<br>     ↓<br>RAG = useless</pre><p>In that situation you need an OCR/document-understanding approach appropriate to the PDF.</p><p>So before debugging embeddings, always ask:</p><pre>Can I actually extract the text from this PDF?</pre><h3>33. Another real-world problem: tables</h3><p>Suppose a PDF contains:</p><pre>| Employee Level | Leave Days |<br>|---------------|------------|<br>| Junior        | 20         |<br>| Senior        | 24         |<br>| Manager       | 28         |</pre><p>PDF extraction can sometimes turn this into poorly ordered text.</p><p>You might get something like:</p><pre>Employee Level Leave Days Junior 20 Senior 24 Manager 28</pre><p>or worse.</p><p>Now retrieval may work poorly.</p><p>This is why:</p><pre>PDF parsing</pre><p>is itself an important part of production RAG.</p><p>Not every PDF is simply:</p><pre>paragraph<br>paragraph<br>paragraph</pre><h3>34. Another problem: headers and footers</h3><p>Imagine every page contains:</p><pre>CONFIDENTIAL — ACME CORPORATION</pre><p>Then your chunks could repeatedly contain:</p><pre>CONFIDENTIAL — ACME CORPORATION</pre><p>This adds noise. A production pipeline may clean or normalize extracted text before embedding.</p><h3>35. Another problem: chunk boundaries</h3><p>Imagine the PDF says:</p><pre>Employees are eligible for annual leave after<br>completing six months of continuous service.</pre><p>and your splitter creates:</p><pre>Chunk 1:<br>Employees are eligible for annual leave after<br>Chunk 2:<br>completing six months of continuous service.</pre><p>Retrieval may return only one.</p><p>Now you have incomplete context.</p><p>That’s one reason overlapping chunks can help. LangChain’s splitter documentation explicitly notes that overlap helps mitigate information loss when context is divided between chunks.</p><h3>36. Source citation architecture</h3><p>A useful production mental model is:</p><pre>PDF<br> ↓<br>Document<br> ↓<br>Chunk<br> ├── page_content<br> └── metadata<br>        ├── source<br>        ├── page<br>        └── other metadata<br> ↓<br>Embedding<br> ↓<br>Vector Store<br> ↓<br>Retriever<br> ↓<br>Relevant chunks<br> ├── content<br> └── metadata<br> ↓<br>LLM</pre><p>The metadata never needs to disappear.</p><p>That’s why we keep Document objects around during retrieval.</p><h3>37. Complete simple PDF RAG example</h3><p>Here is the complete learning version:</p><pre>from langchain_ollama import ChatOllama, OllamaEmbeddings<br>from langchain_core.vectorstores import InMemoryVectorStore<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_community.document_loaders import PyPDFLoader<br><br><br># -------------------------<br># 1. Load documents from PDF<br># -------------------------<br><br>PDF_PATH = &quot;/root/india_leave.pdf&quot;  # update to your PDF&#39;s path<br><br>loader = PyPDFLoader(PDF_PATH)<br>documents = loader.load()<br><br><br># -------------------------<br># 2. Split documents<br># -------------------------<br><br>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=300,<br>    chunk_overlap=50<br>)<br><br>chunks = splitter.split_documents(documents)<br><br><br># -------------------------<br># Inspect chunks<br># -------------------------<br><br>for doc in chunks:<br>    print(doc.metadata)<br>    print(doc.page_content)<br>    print(&quot;---&quot;)<br><br><br># -------------------------<br># 3. Embeddings<br># -------------------------<br><br>embeddings = OllamaEmbeddings(<br>    model=&quot;nomic-embed-text&quot;<br>)<br><br><br># -------------------------<br># 4. Vector store<br># -------------------------<br><br>vector_store = InMemoryVectorStore(<br>    embedding=embeddings<br>)<br><br>vector_store.add_documents(chunks)<br><br><br># -------------------------<br># 5. Retriever<br># -------------------------<br><br>retriever = vector_store.as_retriever(<br>    search_kwargs={&quot;k&quot;: 2}<br>)<br><br><br># -------------------------<br># 6. Model<br># -------------------------<br><br>model = ChatOllama(<br>    model=&quot;llama3.2&quot;<br>)<br><br><br># -------------------------<br># 7. Prompt<br># -------------------------<br><br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>You are a company policy assistant.<br><br>Use only the context below.<br><br>If the answer is not in the context,<br>say that you do not have enough information.<br><br>Context:<br>{context}<br><br>Question:<br>{question}<br>&quot;&quot;&quot;)<br><br><br># -------------------------<br># 8. Chain<br># -------------------------<br><br>chain = prompt | model<br><br><br># -------------------------<br># 9. Ask question<br># -------------------------<br># Sample question<br>question = &quot;what is total annual leave?&quot;<br><br>results = retriever.invoke(question)<br><br>context = &quot;\n\n&quot;.join(<br>    doc.page_content<br>    for doc in results<br>)<br><br>response = chain.invoke({<br>    &quot;context&quot;: context,<br>    &quot;question&quot;: question<br>})<br><br><br>print(response.content)</pre><h3>38. Understand the code as four phases</h3><p>Don’t memorize 40 lines of code.</p><p>Instead remember:</p><h3>Phase 1 — Ingestion</h3><pre>PDF<br> ↓<br>Loader<br> ↓<br>Documents</pre><h3>Phase 2 — Indexing</h3><pre>Documents<br> ↓<br>Chunks<br> ↓<br>Embeddings<br> ↓<br>Vector Store</pre><h3>Phase 3 — Retrieval</h3><pre>Question<br> ↓<br>Retriever<br> ↓<br>Relevant chunks</pre><h3>Phase 4 — Generation</h3><pre>Chunks + Question<br> ↓<br>Prompt<br> ↓<br>LLM<br> ↓<br>Answer</pre><p>That’s the real architecture.</p><h3>39. What happens when you ask your second question?</h3><p>Suppose:</p><pre>Question 1:<br>How many annual leave days do employees receive?</pre><p>The retriever searches the vector store.</p><p>Then:</p><pre>Question 2:<br>How much sick leave do employees receive?</pre><p>We <strong>do not need to re-embed the PDF</strong>.</p><p>The indexing phase already happened.</p><p>We simply:</p><pre>Question<br> ↓<br>Retriever<br> ↓<br>Existing Vector Store<br> ↓<br>Relevant chunks</pre><p>This is why indexing and querying are separate phases.</p><h3>40. What happens if the PDF changes?</h3><p>Suppose HR changes:</p><pre>24 annual leave days</pre><p>to:</p><pre>25 annual leave days</pre><p>Then your existing vector store contains outdated information.</p><p>You need to update/rebuild the relevant indexed data.</p><p>Conceptually:</p><pre>Old PDF<br> ↓<br>Old chunks<br> ↓<br>Old vectors</pre><pre>New PDF<br> ↓<br>New chunks<br> ↓<br>New vectors</pre><p>This is an important practical concern:</p><blockquote><em>Your RAG system is only as current as the indexed knowledge base.</em></blockquote><h3>41. RAG is not “training” the model</h3><p>This is worth reinforcing.</p><p>When you put a PDF into a vector store:</p><pre>PDF<br> ↓<br>Embeddings<br> ↓<br>Vector Store</pre><p>you are <strong>not retraining the LLM</strong>. You’re creating an external searchable knowledge base.</p><p>At question time:</p><pre>Question<br> ↓<br>Retrieve<br> ↓<br>Context<br> ↓<br>LLM</pre><p>The model uses that information for the current response.</p><p>That’s very different from fine-tuning.</p><h3>42. Your complete “Chat with PDF” mental model</h3><p>Memorize this:</p><pre>             INDEXING<br>             ========<br>               PDF<br>                ↓<br>             Loader<br>                ↓<br>            Documents<br>                ↓<br>              Chunks<br>                ↓<br>            Embeddings<br>                ↓<br>           Vector Store<br>                │<br>                │<br>                │<br>                ▼<br>                 QUERY<br>           User Question<br>                ↓<br>            Retriever<br>                ↓<br>        Relevant Documents<br>                ↓<br>              Context<br>                ↓<br>              Prompt<br>                ↓<br>                LLM<br>                ↓<br>              Answer<br>                +<br>             Metadata<br>                ↓<br>         Source / Page</pre><p>This is the foundation of a practical <strong>document Q&amp;A system</strong>.</p><h3>Next Lesson — Lesson 15: RAG + Conversation History</h3><p>We’ll combine the two concepts you’ve already learned separately:</p><pre>Conversation History<br>        +<br>RAG</pre><p>So the chatbot can understand:</p><pre>User: What is the leave policy?</pre><pre>AI: Employees receive 24 annual leave days.</pre><pre>User: Can I carry those days into next year?</pre><p>The second question needs both <strong>conversation context</strong> and <strong>document retrieval</strong>. That’s the next important step toward building a proper document chatbot.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=986ee7d66569" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson 13 — Build a Real RAG Chain]]></title>
            <link>https://medium.com/@md.wasim3/lesson-13-build-a-real-rag-chain-59a83fcfbe4b?source=rss-4362f970560b------2</link>
            <guid isPermaLink="false">https://medium.com/p/59a83fcfbe4b</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[md wasim]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 20:41:02 GMT</pubDate>
            <atom:updated>2026-09-26T20:41:02.154Z</atom:updated>
            <content:encoded><![CDATA[<p>Now we are going to combine the pieces you’ve learned into one clean pipeline.</p><p>The goal is to understand <strong>exactly how the question, retrieved documents, prompt, and LLM are connected</strong>.</p><p>LangChain’s current retrieval documentation describes 2-step RAG as a straightforward retrieve-then-generate flow: retrieval happens first, and the retrieved context is then supplied to the model.</p><h3>1. The RAG chain we want</h3><p>We’re going to build this:</p><pre>User Question<br>      ↓<br>   Retriever<br>      ↓<br>Relevant Documents<br>      ↓<br> Format Documents<br>      ↓<br>    Prompt<br>      ↓<br>     Model<br>      ↓<br>    Answer</pre><p>For example:</p><pre>Question:<br>&quot;What is the leave policy?&quot;<br>        ↓<br>Retriever<br>        ↓<br>Documents:<br>&quot;Employees receive 24 annual leave days...&quot;<br>&quot;Leave must be requested 3 days in advance...&quot;<br>        ↓<br>Prompt<br>        ↓<br>LLM<br>        ↓<br>Answer:<br>&quot;Employees receive 24 annual leave days...&quot;</pre><p>The important thing today is learning how to <strong>connect these steps cleanly</strong>.</p><h3>2. First, let’s create some knowledge</h3><p>We’ll use a small in-memory knowledge base.</p><pre>from langchain_core.documents import Document<br>documents = [<br>    Document(<br>        page_content=(<br>            &quot;Employees receive 24 annual leave days per year. &quot;<br>            &quot;Annual leave should normally be requested at least &quot;<br>            &quot;3 days in advance.&quot;<br>        ),<br>        metadata={&quot;source&quot;: &quot;leave_policy.txt&quot;}<br>    ),<br>    Document(<br>        page_content=(<br>            &quot;Employees receive 10 sick leave days per year. &quot;<br>            &quot;A medical certificate may be required for extended absence.&quot;<br>        ),<br>        metadata={&quot;source&quot;: &quot;sick_leave_policy.txt&quot;}<br>    ),<br>    Document(<br>        page_content=(<br>            &quot;Employees may work remotely up to 3 days per week &quot;<br>            &quot;subject to manager approval.&quot;<br>        ),<br>        metadata={&quot;source&quot;: &quot;remote_work_policy.txt&quot;}<br>    ),<br>]</pre><p>These are our source documents.</p><h3>3. Create the embedding model</h3><pre>from langchain_openai import OpenAIEmbeddings<br>embeddings = OpenAIEmbeddings(<br>    model=&quot;text-embedding-3-small&quot;<br>)</pre><p>The job here is:</p><pre>Document<br>   ↓<br>Embedding<br>   ↓<br>Vector</pre><p>As we learned in Lesson 11.</p><h3>4. Create the vector store</h3><pre>from langchain_core.vectorstores import InMemoryVectorStore<br>vector_store = InMemoryVectorStore(<br>    embedding=embeddings<br>)<br>vector_store.add_documents(documents)</pre><p>Now:</p><pre>Documents<br>   ↓<br>Embeddings<br>   ↓<br>Vector Store</pre><p>Our knowledge base is ready.</p><h3>5. Create the retriever</h3><pre>retriever = vector_store.as_retriever(<br>    search_kwargs={&quot;k&quot;: 2}<br>)</pre><p>Now the retriever knows:</p><blockquote><em>For each question, return the two most relevant documents.</em></blockquote><p>Remember:</p><pre>Vector Store<br>    ↓<br>as_retriever()<br>    ↓<br>Retriever</pre><p>A retriever is an abstraction that takes a query and returns documents; it doesn’t necessarily have to be backed by a vector store.</p><h3>6. Test the retriever before building the RAG chain</h3><p>This is a <strong>very important habit</strong>.</p><p>Run:</p><pre>question = &quot;How many annual leave days do employees receive?&quot;<br>docs = retriever.invoke(question)<br>for doc in docs:<br>    print(doc.page_content)<br>    print(&quot;SOURCE:&quot;, doc.metadata)<br>    print(&quot;-&quot; * 50)</pre><p>You should first verify:</p><pre>Did the retriever find the right documents?</pre><p>Before worrying about the LLM.</p><p>This is one of the best ways to debug RAG.</p><h3>7. Create the prompt</h3><p>Now we’ll tell the model what to do with the retrieved information.</p><pre>from langchain_core.prompts import ChatPromptTemplate<br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>You are a helpful company policy assistant.<br>Answer the question using only the provided context.<br>If the answer is not available in the context,<br>say that you do not have enough information.<br>Context:<br>{context}<br>Question:<br>{question}<br>&quot;&quot;&quot;)</pre><p>There are two variables:</p><pre>{context}<br>{question}</pre><p>They need to be populated before the model receives the prompt.</p><h3>8. Create the LLM</h3><pre>from langchain_ollama import ChatOllama, OllamaEmbeddings<br>model = ChatOllama(<br>    model=&quot;llama3.2&quot;<br>)</pre><p>Now we have:</p><pre>Retriever<br>Prompt<br>Model</pre><p>We need to connect them.</p><h3>9. The first problem: Retriever returns Documents</h3><p>Suppose:</p><pre>docs = retriever.invoke(question)</pre><p>returns:</p><pre>[<br>    Document(...),<br>    Document(...)<br>]</pre><p>But our prompt needs something like:</p><pre>Context:<br>Employees receive 24 annual leave days...<br>Employees must request leave...</pre><p>So we need to convert:</p><pre>list[Document]</pre><p>into:</p><pre>string</pre><p>That’s our next step.</p><h3>10. Create a document formatting function</h3><pre>def format_docs(docs):<br>    return &quot;\n\n&quot;.join(<br>        doc.page_content<br>        for doc in docs<br>    )</pre><p>Suppose we have:</p><pre>Document 1:<br>Employees receive 24 annual leave days.<br>Document 2:<br>Annual leave should normally be requested 3 days in advance.</pre><p>format_docs() turns them into:</p><pre>Employees receive 24 annual leave days.<br>Annual leave should normally be requested 3 days in advance.</pre><p>This becomes our context.</p><h3>11. The manual RAG pipeline</h3><p>Before introducing more advanced composition, let’s write it normally.</p><pre>question = &quot;How many annual leave days do employees receive?&quot;<br>docs = retriever.invoke(question)<br>context = format_docs(docs)<br>response = model.invoke(<br>    prompt.invoke({<br>        &quot;context&quot;: context,<br>        &quot;question&quot;: question<br>    })<br>)<br>print(response.content)</pre><p>This works.</p><p>And the workflow is perfectly clear:</p><pre>Question<br>   ↓<br>Retriever<br>   ↓<br>Documents<br>   ↓<br>format_docs()<br>   ↓<br>Context string<br>   ↓<br>Prompt<br>   ↓<br>Model<br>   ↓<br>Answer</pre><p>This is actually a very good way to learn. Here is the complete code for manual retrieval</p><pre>from langchain_core.documents import Document<br>from langchain_ollama import ChatOllama, OllamaEmbeddings<br>from langchain_core.vectorstores import InMemoryVectorStore<br>from langchain_core.prompts import ChatPromptTemplate<br><br>documents = [<br>    Document(<br>        page_content=(<br>            &quot;Employees receive 24 annual leave days per year. &quot;<br>            &quot;Annual leave should normally be requested at least &quot;<br>            &quot;3 days in advance.&quot;<br>        ),<br>        metadata={&quot;source&quot;: &quot;leave_policy.txt&quot;}<br>    ),<br><br>    Document(<br>        page_content=(<br>            &quot;Employees receive 10 sick leave days per year. &quot;<br>            &quot;A medical certificate may be required for extended absence.&quot;<br>        ),<br>        metadata={&quot;source&quot;: &quot;sick_leave_policy.txt&quot;}<br>    ),<br><br>    Document(<br>        page_content=(<br>            &quot;Employees may work remotely up to 3 days per week &quot;<br>            &quot;subject to manager approval.&quot;<br>        ),<br>        metadata={&quot;source&quot;: &quot;remote_work_policy.txt&quot;}<br>    ),<br>]<br><br>embeddings = OllamaEmbeddings(<br>    model=&quot;nomic-embed-text&quot;<br>)<br><br>vector_store = InMemoryVectorStore(<br>    embedding=embeddings<br>)<br><br>vector_store.add_documents(documents)<br><br>retriever = vector_store.as_retriever(<br>    search_kwargs={&quot;k&quot;: 2}<br>)<br><br># Test the retriever before building the RAG chain<br>question = &quot;How many annual leave days do employees receive?&quot;<br><br>docs = retriever.invoke(question)<br><br>for doc in docs:<br>    print(doc.page_content)<br>    print(&quot;SOURCE:&quot;, doc.metadata)<br>    print(&quot;-&quot; * 50)<br><br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>You are a helpful company policy assistant.<br><br>Answer the question using only the provided context.<br><br>If the answer is not available in the context,<br>say that you do not have enough information.<br><br>Context:<br>{context}<br><br>Question:<br>{question}<br>&quot;&quot;&quot;)<br><br>model = ChatOllama(<br>    model=&quot;llama3.2&quot;<br>)<br><br><br>def format_docs(docs):<br>    return &quot;\n\n&quot;.join(<br>        doc.page_content<br>        for doc in docs<br>    )<br><br><br>docs = retriever.invoke(question)<br><br>context = format_docs(docs)<br><br>response = model.invoke(<br>    prompt.invoke({<br>        &quot;context&quot;: context,<br>        &quot;question&quot;: question<br>    })<br>)<br><br>print(response.content)</pre><h3>12. But now we want a chain</h3><p>Instead of manually calling each component:</p><pre>docs = retriever.invoke(...)<br>context = format_docs(docs)<br>prompt.invoke(...)<br>model.invoke(...)</pre><p>we can compose them.</p><p>This is where LangChain’s runnable composition becomes useful.</p><p>Think of each component as a function:</p><pre>Retriever<br>    ↓<br>takes question<br>    ↓<br>returns Documents</pre><p>Then:</p><pre>format_docs<br>    ↓<br>takes Documents<br>    ↓<br>returns string</pre><p>Then:</p><pre>Prompt<br>    ↓<br>takes dictionary<br>    ↓<br>returns messages</pre><p>Then:</p><pre>Model<br>    ↓<br>takes messages<br>    ↓<br>returns AIMessage</pre><p>So we can connect them.</p><h3>13. The pipe operator again</h3><p>You’ve already seen:</p><pre>chain = prompt | model</pre><p>This means:</p><pre>prompt output → model input</pre><p>For RAG:</p><pre>retriever → formatting → prompt → model</pre><p>But there’s a small complication.</p><p>Our prompt needs <strong>two values</strong>:</p><pre>context<br>question</pre><p>The retriever needs the question, while the question itself also needs to be passed into the prompt.</p><p>So we need to create a small mapping.</p><h3>14. RunnablePassthrough</h3><p>LangChain provides:</p><pre>from langchain_core.runnables import RunnablePassthrough</pre><p>The name looks complicated, but the idea is simple.</p><p>It means:</p><blockquote><em>Pass the input through unchanged.</em></blockquote><p>For example:</p><pre>Question<br>  ↓<br>RunnablePassthrough<br>  ↓<br>Same Question</pre><p>Suppose our input is:</p><pre>&quot;How many annual leave days?&quot;</pre><p>Then:</p><pre>RunnablePassthrough</pre><p>outputs the same question.</p><p>This becomes useful when one input must go to multiple places.</p><h3>15. Creating the RAG chain</h3><p>Now we can write:</p><pre>rag_chain = (<br>    {<br>        &quot;context&quot;: retriever | format_docs,<br>        &quot;question&quot;: RunnablePassthrough()<br>    }<br>    | prompt<br>    | model<br>)</pre><p>This is one of the most important pieces of code in your LangChain learning journey. Let’s not memorize it yet. Let’s understand it.</p><h3>16. First part</h3><p>Look at:</p><pre>{<br>    &quot;context&quot;: retriever | format_docs,<br>    &quot;question&quot;: RunnablePassthrough()<br>}</pre><p>This means:</p><blockquote><em>Create two outputs: </em><em>context and </em><em>question.</em></blockquote><p>Conceptually:</p><pre>Input Question<br>                          │<br>                ┌─────────┴─────────┐<br>                ↓                   ↓<br>           Retriever          Passthrough<br>                ↓                   ↓<br>          Documents            Question<br>                ↓<br>          format_docs()<br>                ↓<br>             Context</pre><p>So the same original question goes down <strong>two paths</strong>.</p><h3>17. The context path</h3><p>This:</p><pre>&quot;context&quot;: retriever | format_docs</pre><p>means:</p><pre>Question<br>   ↓<br>Retriever<br>   ↓<br>Documents<br>   ↓<br>format_docs<br>   ↓<br>Context string</pre><p>Example:</p><pre>     Question:<br>How many annual leave days?<br>        ↓<br>    Retriever<br>        ↓<br>    Documents<br>        ↓<br>    format_docs()<br>        ↓<br>&quot;Employees receive 24 annual leave days...&quot;</pre><p>So:</p><pre>context = &quot;Employees receive 24 annual leave days...&quot;</pre><h3>18. The question path</h3><p>This:</p><pre>&quot;question&quot;: RunnablePassthrough()</pre><p>means:</p><pre>Question<br>   ↓<br>Pass through unchanged<br>   ↓<br>question</pre><p>So:</p><pre>question = &quot;How many annual leave days?&quot;</pre><h3>19. Now we have a dictionary</h3><p>After this part:</p><pre>{<br>    &quot;context&quot;: retriever | format_docs,<br>    &quot;question&quot;: RunnablePassthrough()<br>}</pre><p>the result conceptually looks like:</p><pre>{<br>    &quot;context&quot;: &quot;&quot;&quot;<br>        Employees receive 24 annual leave days.<br>    &quot;&quot;&quot;,<br>&quot;question&quot;: &quot;&quot;&quot;<br>        How many annual leave days do employees receive?<br>    &quot;&quot;&quot;<br>}</pre><p>And that’s exactly what our prompt needs.</p><h3>20. Then the prompt receives that dictionary</h3><p>We then have:</p><pre>| prompt</pre><p>So:</p><pre>Dictionary<br>   ↓<br>Prompt<br>   ↓<br>Messages</pre><p>The prompt fills:</p><pre>{context}</pre><p>with the retrieved content.</p><p>And:</p><pre>{question}</pre><p>with the original question.</p><h3>21. Then the model receives the prompt</h3><p>Finally:</p><pre>| model</pre><p>So:</p><pre>Prompt<br>   ↓<br>Chat Model<br>   ↓<br>AIMessage</pre><p>The complete chain becomes:</p><pre>Question<br>                   │<br>          ┌────────┴────────┐<br>          ↓                 ↓<br>      Retriever        Passthrough<br>          ↓                 ↓<br>      Documents          Question<br>          ↓<br>     format_docs()<br>          ↓<br>       Context<br>          └────────┬────────┘<br>                   ↓<br>                 Prompt<br>                   ↓<br>                  LLM<br>                   ↓<br>                AIMessage</pre><p>That’s a <strong>real RAG chain</strong>.</p><h3>22. Complete code</h3><p>Here’s the whole example:</p><pre>from langchain_ollama import (<br>    ChatOllama,<br>    OllamaEmbeddings<br>)<br><br>from langchain_core.documents import Document<br>from langchain_core.vectorstores import InMemoryVectorStore<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.runnables import RunnablePassthrough<br><br><br># --------------------------------<br># 1. Documents<br># --------------------------------<br><br>documents = [<br>    Document(<br>        page_content=(<br>            &quot;Employees receive 24 annual leave days per year. &quot;<br>            &quot;Annual leave should normally be requested at least &quot;<br>            &quot;3 days in advance.&quot;<br>        ),<br>        metadata={&quot;source&quot;: &quot;leave_policy.txt&quot;}<br>    ),<br><br>    Document(<br>        page_content=(<br>            &quot;Employees receive 10 sick leave days per year.&quot;<br>        ),<br>        metadata={&quot;source&quot;: &quot;sick_leave_policy.txt&quot;}<br>    ),<br><br>    Document(<br>        page_content=(<br>            &quot;Employees may work remotely up to 3 days per week &quot;<br>            &quot;subject to manager approval.&quot;<br>        ),<br>        metadata={&quot;source&quot;: &quot;remote_work_policy.txt&quot;}<br>    )<br>]<br><br><br># --------------------------------<br># 2. Embeddings<br># --------------------------------<br><br>embeddings = OllamaEmbeddings(<br>    model=&quot;nomic-embed-text&quot;<br>)<br><br><br># --------------------------------<br># 3. Vector store<br># --------------------------------<br><br>vector_store = InMemoryVectorStore(<br>    embedding=embeddings<br>)<br><br>vector_store.add_documents(documents)<br><br><br># --------------------------------<br># 4. Retriever<br># --------------------------------<br><br>retriever = vector_store.as_retriever(<br>    search_kwargs={&quot;k&quot;: 2}<br>)<br><br><br># --------------------------------<br># 5. Document formatter<br># --------------------------------<br><br>def format_docs(docs):<br>    return &quot;\n\n&quot;.join(<br>        doc.page_content<br>        for doc in docs<br>    )<br><br><br># --------------------------------<br># 6. Model<br># --------------------------------<br><br>model = ChatOllama(<br>    model=&quot;llama3.2&quot;<br>)<br><br><br># --------------------------------<br># 7. Prompt<br># --------------------------------<br><br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>You are a helpful company policy assistant.<br><br>Answer the question using only the provided context.<br><br>If the answer is not available in the context,<br>say that you do not have enough information.<br><br>Context:<br>{context}<br><br>Question:<br>{question}<br>&quot;&quot;&quot;)<br><br><br># --------------------------------<br># 8. RAG chain<br># --------------------------------<br><br>rag_chain = (<br>    {<br>        &quot;context&quot;: retriever | format_docs,<br>        &quot;question&quot;: RunnablePassthrough()<br>    }<br>    | prompt<br>    | model<br>)<br><br><br># --------------------------------<br># 9. Ask question<br># --------------------------------<br><br>response = rag_chain.invoke(<br>    &quot;How many annual leave days do employees receive?&quot;<br>)<br><br>print(response.content)</pre><h3>23. Let’s trace one question</h3><p>Suppose:</p><pre>rag_chain.invoke(<br>    &quot;How many annual leave days do employees receive?&quot;<br>)</pre><p>Start here:</p><pre>Input<br>=<br>&quot;How many annual leave days do employees receive?&quot;</pre><h3>Branch 1</h3><pre>Question<br>   ↓<br>Retriever<br>   ↓<br>Relevant Documents<br>   ↓<br>format_docs()<br>   ↓<br>Context</pre><p>Maybe:</p><pre>Employees receive 24 annual leave days per year.<br>Annual leave should normally be requested at least 3 days in advance.</pre><h3>Branch 2</h3><pre>Question<br>   ↓<br>RunnablePassthrough<br>   ↓<br>Same Question</pre><p>Then:</p><pre>{<br>    &quot;context&quot;: &quot;Employees receive 24 annual leave days...&quot;,<br>    &quot;question&quot;: &quot;How many annual leave days...&quot;<br>}</pre><p>Then:</p><pre>Dictionary<br>   ↓<br>Prompt<br>   ↓<br>Messages<br>   ↓<br>Model<br>   ↓<br>AIMessage</pre><p>Finally:</p><pre>Employees receive 24 annual leave days per year.</pre><h3>24. This pattern is very important</h3><p>You will see this pattern often:</p><pre>{<br>    &quot;context&quot;: retriever | format_docs,<br>    &quot;question&quot;: RunnablePassthrough()<br>}</pre><p>Don’t treat it as magic syntax.</p><p>Read it as:</p><blockquote><em>“For </em><em>context, run the question through the retriever and formatter. For </em><em>question, keep the original input.&quot;</em></blockquote><p>This is essentially <strong>fan-out and combine</strong>.</p><pre>Input<br>               │<br>        ┌──────┴──────┐<br>        ↓             ↓<br>      Path A         Path B<br>        ↓             ↓<br>     Context       Question<br>        └──────┬──────┘<br>               ↓<br>             Prompt</pre><h3>25. Why format_docs is separate</h3><p>You might wonder:</p><blockquote><em>Why not make the retriever return a string?</em></blockquote><p>Because retrievers return Document objects.</p><p>That’s useful because you retain:</p><pre>page_content<br>metadata<br>source<br>page number<br>etc.</pre><p>Then you decide how to format them for the LLM.</p><p>For example:</p><pre>def format_docs(docs):<br>    return &quot;\n\n&quot;.join(<br>        f&quot;Source: {doc.metadata.get(&#39;source&#39;)}\n&quot;<br>        f&quot;{doc.page_content}&quot;<br>        for doc in docs<br>    )</pre><p>Now the LLM receives:</p><pre>Source: leave_policy.txt<br>Employees receive 24 annual leave days...</pre><pre>Source: leave_policy.txt<br>Annual leave should be requested...</pre><p>That can be useful later when you want source citations.</p><h3>26. The chain is not the vector store</h3><p>This is another distinction worth remembering.</p><p>Your:</p><pre>vector_store</pre><p>does:</p><pre>Store + search knowledge</pre><p>Your:</p><pre>retriever</pre><p>does:</p><pre>Retrieve relevant documents</pre><p>Your:</p><pre>rag_chain</pre><p>does:</p><pre>Retrieve<br>+<br>Format<br>+<br>Prompt<br>+<br>Generate</pre><p>So:</p><pre>Vector Store<br>    ↓<br>Retriever<br>    ↓<br>RAG Chain</pre><p>Each level adds more functionality.</p><h3>27. RAG chain vs Agent</h3><p>Now you can see the difference much more clearly.</p><h3>RAG chain</h3><pre>Question<br> ↓<br>Retriever<br> ↓<br>Context<br> ↓<br>Prompt<br> ↓<br>LLM<br> ↓<br>Answer</pre><h3>Agent</h3><pre>Question<br> ↓<br>Agent<br> ↓<br>Model decides what to do<br> ↓<br>Tool?<br> ↓<br>Maybe Retriever<br> ↓<br>Maybe Calculator<br> ↓<br>Maybe another tool<br> ↓<br>Final answer</pre><p>Current LangChain documentation describes 2-step RAG as retrieval always happening before generation, while agentic RAG lets an LLM-powered agent decide when and how retrieval happens.</p><h3>28. Why this chain is better than a huge prompt</h3><p>Imagine doing this manually:</p><pre>Here are all the documents...<br>Here is the question...<br>Please figure out which information matters...<br>Please answer...</pre><p>The RAG chain separates responsibilities:</p><pre>Retriever<br>→ Find<br>Formatter<br>→ Prepare<br>Prompt<br>→ Instruct<br>Model<br>→ Generate</pre><p>This modularity is one of the central ideas behind LangChain’s retrieval abstractions. The current documentation emphasizes that loaders, splitters, embeddings, vector stores, and retrievers can be swapped independently.</p><h3>29. What happens if retrieval is bad?</h3><p>Suppose:</p><pre>Question:<br>&quot;How many annual leave days?&quot;</pre><p>but retriever returns:</p><pre>Remote work policy<br>Sick leave policy</pre><p>Your RAG chain will still pass them to the LLM.</p><p>So:</p><pre>Bad retrieval<br>    ↓<br>Bad context<br>    ↓<br>Potentially bad answer</pre><p>That’s why retrieval evaluation is so important.</p><p>The current LangChain retrieval docs specifically distinguish <strong>retrieval quality</strong> from <strong>answer correctness, relevance, and groundedness</strong> when evaluating RAG systems.</p><h3>30. What happens when the answer isn’t in the documents?</h3><p>Suppose:</p><pre>Question:<br>&quot;What is the office dress code?&quot;</pre><p>but your database contains only leave policies.</p><p>The retriever might still return some semantically related documents.</p><p>Then your prompt says:</p><pre>If the answer is not available in the context,<br>say that you do not have enough information.</pre><p>This gives the model guidance not to fabricate an answer from unrelated context.</p><p>But remember:</p><pre>Prompt instruction ≠ guarantee</pre><p>A robust application may need explicit retrieval thresholds, validation, or other controls.</p><h3>31. RunnablePassthrough mental model</h3><p>This one deserves a separate memory trick.</p><p>Imagine you have:</p><pre>Input = &quot;What is ERP?&quot;</pre><p>Then:</p><pre>RunnablePassthrough()</pre><p>basically says:</p><pre>&quot;What is ERP?&quot;<br>      ↓<br>&quot;What is ERP?&quot;</pre><p>It simply forwards the value.</p><p>So:</p><pre>&quot;question&quot;: RunnablePassthrough()</pre><p>means:</p><blockquote><em>Put the original input into the </em><em>question field.</em></blockquote><h3>32. Why not call retriever twice?</h3><p>You might wonder whether we could do:</p><pre>&quot;context&quot;: retriever | format_docs,<br>&quot;question&quot;: retriever</pre><p>No.</p><p>We don’t want the question to become retrieved documents.</p><p>We need:</p><pre>context = retrieved information<br>question = original question</pre><p>Therefore:</p><pre>&quot;context&quot;: retriever | format_docs</pre><p>and:</p><pre>&quot;question&quot;: RunnablePassthrough()</pre><h3>Next chapter — Lesson 14: RAG with a Real PDF</h3><p>We’ll move from manually-created Document objects to a <strong>real PDF</strong> and learn:</p><pre>PDF<br> ↓<br>PDF Loader<br> ↓<br>Documents<br> ↓<br>Chunking<br> ↓<br>Metadata<br> ↓<br>Embeddings<br> ↓<br>Vector Store<br> ↓<br>Retriever<br> ↓<br>RAG Chain<br> ↓<br>Answer</pre><p>We’ll also learn <strong>source/page citations</strong>, so the application can answer something like:</p><pre>Employees receive 24 annual leave days.</pre><pre>Source: company_policy.pdf<br>Page: 3</pre><p>That is where your RAG knowledge starts becoming a practical <strong>“Chat with PDF” application</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59a83fcfbe4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson 12 — Vector Stores and Retrievers in Depth]]></title>
            <link>https://medium.com/@md.wasim3/lesson-12-vector-stores-and-retrievers-in-depth-078005e3d1a2?source=rss-4362f970560b------2</link>
            <guid isPermaLink="false">https://medium.com/p/078005e3d1a2</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[threshold]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[md wasim]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 03:21:01 GMT</pubDate>
            <atom:updated>2026-09-26T03:21:01.773Z</atom:updated>
            <content:encoded><![CDATA[<p>This lesson is very important because people often use these two words as if they are the same:</p><pre>Vector Store<br>Retriever</pre><p>They are <strong>not the same thing</strong>.</p><p>The easiest way to understand them is:</p><pre>Vector Store = where/how documents are stored and searched<br>Retriever = the interface that asks for relevant documents</pre><p>LangChain’s current documentation describes a vector store as a component that stores embedded data and performs similarity search, while a retriever is a more general interface that takes a query and returns Document objects.</p><h3>1. First understand the difference</h3><p>Imagine a library.</p><h4>Vector Store</h4><p>Think of it as:</p><pre>📚 Library database</pre><p>It contains:</p><pre>Documents<br>Embeddings<br>Metadata</pre><p>and knows how to search them.</p><h4>Retriever</h4><p>Think of it as:</p><pre>🔎 Librarian</pre><p>You say:</p><blockquote><em>Find me information about ERP inventory management.</em></blockquote><p>The librarian searches the library and gives you relevant documents.</p><p>So:</p><pre>Vector Store<br>    ↓<br>stores/searches information<br><br><br>Retriever<br>    ↓<br>retrieves information for a query</pre><h3>2. Why does LangChain have both?</h3><p>Because a retriever doesn’t have to use a vector database. The current LangChain documentation explicitly says that retrievers are more general than vector stores. A retriever only needs to accept a query and return documents; it can be backed by a vector store, search engine, database, or another retrieval mechanism.</p><p>For example:</p><pre>Retriever<br>├── Vector Store<br>├── Search Engine<br>├── Database<br>├── Web Search<br>└── Custom Retrieval Logic</pre><p>This abstraction is powerful.</p><h3>3. Vector Store example</h3><p>Let’s create a simple vector store:</p><pre>from langchain_openai import OpenAIEmbeddings<br>from langchain_core.vectorstores import InMemoryVectorStore<br>embeddings = OpenAIEmbeddings(<br>    model=&quot;text-embedding-3-small&quot;<br>)<br>vector_store = InMemoryVectorStore(<br>    embedding=embeddings<br>)</pre><p>Now add documents:</p><pre>vector_store.add_texts([<br>    &quot;Python is a programming language.&quot;,<br>    &quot;Python is widely used for artificial intelligence.&quot;,<br>    &quot;ERP systems manage business processes.&quot;,<br>])</pre><p>The vector store internally handles the embedding/storage/search workflow.</p><p>LangChain’s current vector-store interface includes operations such as add_documents, deletion, and similarity_search.</p><h3>4. Search directly with the vector store</h3><p>You can directly do:</p><pre>results = vector_store.similarity_search(<br>    &quot;What is Python used for?&quot;,<br>    k=2<br>)</pre><p>Then:</p><pre>for doc in results:<br>    print(doc.page_content)</pre><p>Conceptually:</p><pre>Question<br>   ↓<br>Vector Store<br>   ↓<br>Similarity Search<br>   ↓<br>Top 2 Documents</pre><p>This is perfectly valid.</p><p>So why do we need a retriever?</p><h3>5. Convert the vector store into a retriever</h3><p>This is the important line:</p><pre>retriever = vector_store.as_retriever()</pre><p>Now:</p><pre>results = retriever.invoke(<br>    &quot;What is Python used for?&quot;<br>)</pre><p>The flow is:</p><pre>User Question<br>      ↓<br>Retriever<br>      ↓<br>Vector Store<br>      ↓<br>Search<br>      ↓<br>Documents</pre><p>The current LangChain API provides VectorStore.as_retriever() specifically to create a VectorStoreRetriever.</p><h3>6. So what’s the actual difference?</h3><p>Compare:</p><h3>Direct vector-store search</h3><pre>results = vector_store.similarity_search(<br>    question,<br>    k=3<br>)</pre><p>Here you’re directly telling the vector store:</p><blockquote><em>Perform a similarity search.</em></blockquote><h3>Retriever</h3><pre>retriever = vector_store.as_retriever(<br>    search_kwargs={&quot;k&quot;: 3}<br>)<br>results = retriever.invoke(question)</pre><p>Here you’re saying:</p><blockquote><em>Create a retriever from this vector store, then ask the retriever for relevant documents.</em></blockquote><p>The second approach is especially useful because other parts of your application can work with the <strong>retriever interface</strong> without needing to know exactly which underlying search system is being used.</p><h3>7. Think of it as an adapter</h3><p>This is a very useful programming concept.</p><pre>Specific implementation<br>        ↓<br>    Vector Store<br>        ↓<br>    as_retriever()<br>        ↓<br>Generic interface<br>        ↓<br>     Retriever</pre><p>Your RAG chain can simply say:</p><pre>&quot;Give me relevant documents.&quot;</pre><p>It doesn’t need to know whether they came from:</p><pre>Chroma<br>Pinecone<br>Elasticsearch<br>Postgres<br>MongoDB<br>Web Search</pre><p>LangChain’s vector-store abstraction is designed to let applications switch implementations without changing their overall retrieval logic.</p><h3>8. Now let’s understand k</h3><p>You’ve already seen:</p><pre>search_kwargs={&quot;k&quot;: 3}</pre><p>This means:</p><blockquote><em>Return up to 3 documents.</em></blockquote><p>For example:</p><pre>Similarity scores<br>Document A → 0.94<br>Document B → 0.91<br>Document C → 0.88<br>Document D → 0.72<br>Document E → 0.40</pre><p>With:</p><pre>k=3</pre><p>you get:</p><pre>A<br>B<br>C</pre><p>The current vector-store docs identify k as the number of results to return.</p><h3>9. Why k is important in RAG</h3><p>Suppose your context window receives:</p><pre>k = 2</pre><p>You might get:</p><pre>Relevant chunk A<br>Relevant chunk B</pre><p>With:</p><pre>k = 20</pre><p>you might get:</p><pre>Relevant chunk A<br>Relevant chunk B<br>...<br>Mostly irrelevant chunks</pre><p>More isn’t automatically better.</p><p>Think:</p><pre>k too low  → missing context<br>k too high → noisy context</pre><p>This becomes especially important when your RAG prompt sends all retrieved content to the LLM.</p><h3>10. similarity_search()</h3><p>The basic search is:</p><pre>docs = vector_store.similarity_search(<br>    &quot;What is ERP?&quot;,<br>    k=3<br>)</pre><p>Conceptually:</p><pre>Question<br>   ↓<br>Embedding<br>   ↓<br>Compare with stored vectors<br>   ↓<br>Rank by similarity<br>   ↓<br>Return top k</pre><p>LangChain documents similarity_search as returning the closest semantically similar documents.</p><h3>11. What about scores?</h3><p>Sometimes you want not only the document, but also a relevance value.</p><p>Some vector-store implementations support methods such as:</p><pre>similarity_search_with_score(...)</pre><p>Conceptually, the result becomes:</p><pre>[<br>    (Document A, score),<br>    (Document B, score),<br>    (Document C, score)<br>]</pre><p>This can be useful for debugging retrieval.</p><p>For example:</p><pre>Question:<br>&quot;What is the leave policy?&quot;</pre><pre>Results:</pre><pre>Document A → 0.91<br>Document B → 0.84<br>Document C → 0.31</pre><p>Now you have evidence about how strongly the retrieved items matched.</p><h3>Important</h3><p>Do <strong>not</strong> assume that a high number always means “more relevant.”</p><p>Different vector stores and search methods can expose scores or distances differently.</p><p>Recall from Lesson 11:</p><pre>Similarity:<br>higher may mean better<br>Distance:<br>lower may mean better</pre><p>The meaning depends on the API.</p><h3>12. similarity_score_threshold</h3><p>This is another useful retrieval mode.</p><p>Instead of saying:</p><blockquote><em>Give me exactly 5 documents.</em></blockquote><p>you can say:</p><blockquote><em>Give me documents only if they’re relevant enough.</em></blockquote><p>LangChain’s current as_retriever() supports:</p><pre>retriever = vector_store.as_retriever(<br>    search_type=&quot;similarity_score_threshold&quot;,<br>    search_kwargs={<br>        &quot;score_threshold&quot;: 0.8<br>    }<br>)</pre><p><strong><em>The current API lists three general retriever search types:</em></strong></p><pre>similarity<br>mmr<br>similarity_score_threshold</pre><p>and defines score_threshold as the minimum relevance threshold for the threshold-based mode.</p><p>This is conceptually:</p><pre>Question<br>   ↓<br>Search<br>   ↓<br>Is result relevant enough?<br>   ├── Yes → return<br>   └── No  → don&#39;t return</pre><h3>13. Why is threshold useful?</h3><p>Suppose your knowledge base contains:</p><pre>Python documentation<br>ERP documentation<br>HR policies<br>Finance policies</pre><p>User asks:</p><pre>What is the capital of France?</pre><p>You don’t want:</p><pre>ERP policy<br>HR policy<br>Python documentation</pre><p>just because something had to be returned.</p><p>A relevance threshold can help prevent weak matches from entering the context.</p><p>But there is a catch:</p><blockquote><em>A bad threshold can also remove useful documents.</em></blockquote><p>So threshold values need evaluation.</p><h3>14. Metadata filtering</h3><p>Suppose you have:</p><pre>from langchain_core.documents import Document<br>docs = [<br>    Document(<br>        page_content=&quot;Employees receive 24 annual leave days.&quot;,<br>        metadata={<br>            &quot;department&quot;: &quot;HR&quot;,<br>            &quot;year&quot;: 2026<br>        }<br>    ),<br>    Document(<br>        page_content=&quot;Employees must use VPN for remote access.&quot;,<br>        metadata={<br>            &quot;department&quot;: &quot;IT&quot;,<br>            &quot;year&quot;: 2026<br>        }<br>    )<br>]</pre><p>Now suppose the user asks:</p><pre>What is the leave policy?</pre><p>You could search only HR content using metadata filtering where the vector-store implementation supports it:</p><pre>vector_store.similarity_search(<br>    &quot;What is the leave policy?&quot;,<br>    k=3,<br>    filter={&quot;department&quot;: &quot;HR&quot;}<br>)</pre><p>LangChain’s vector-store documentation shows metadata-based filtering as a supported capability for many vector stores.</p><p>The idea is:</p><pre>Semantic Search<br>       +<br>Metadata Filter<br>       ↓<br>More focused results</pre><h3>15. Why metadata filtering can be better than embeddings alone</h3><p>Imagine you have:</p><pre>10,000 documents</pre><p>and these belong to:</p><pre>HR<br>Finance<br>IT<br>Legal<br>Sales</pre><p>Question:</p><pre>What is the employee leave policy?</pre><p>Instead of searching all 10,000 documents:</p><pre>All documents<br>     ↓<br>Semantic search</pre><p>you might first constrain the search:</p><pre>HR documents<br>     ↓<br>Semantic search</pre><p>This can make retrieval much more targeted.</p><h3>16. Now let’s understand MMR</h3><p>This is the more advanced concept for today.</p><p><strong>MMR = Maximal Marginal Relevance</strong></p><p>The purpose is:</p><blockquote><em>Find results that are relevant to the question while avoiding results that are too similar to each other.</em></blockquote><p>LangChain’s current as_retriever() supports search_type=&quot;mmr&quot;. Its documentation describes lambda_mult as controlling diversity: 1 gives minimum diversity, while 0 gives maximum diversity.</p><h3>17. Why ordinary similarity search can have duplicates</h3><p>Imagine your documents contain:</p><pre>Chunk 1:<br>Python is widely used in AI.<br>Chunk 2:<br>Python is commonly used for AI applications.<br>Chunk 3:<br>Python is popular in artificial intelligence.<br>Chunk 4:<br>Python is used for data science.<br>Chunk 5:<br>Python can automate tasks.</pre><p>Question:</p><pre>How is Python used?</pre><p>Normal similarity search might produce:</p><pre>Chunk 1<br>Chunk 2<br>Chunk 3<br>Chunk 4</pre><p>The first three are almost saying the same thing.</p><p>That wastes context.</p><h3>18. What MMR tries to do</h3><p>MMR says:</p><blockquote><em>I want documents that are relevant, but I also want them to provide different information.</em></blockquote><p>So instead of:</p><pre>Chunk 1<br>Chunk 2<br>Chunk 3<br>Chunk 4</pre><p>it might prefer:</p><pre>Chunk 1 → AI<br>Chunk 4 → Data Science<br>Chunk 5 → Automation</pre><p>Now your context covers more ground.</p><p>Conceptually:</p><pre>Similarity Search</pre><pre>Question<br>  ↓<br>A ██████████<br>B █████████<br>C ████████<br>D ███████<br>E ██████<br></pre><pre>MMR</pre><pre>Question<br>  ↓<br>A ██████████<br>D ███████<br>E ██████</pre><p>It sacrifices some raw similarity in exchange for <strong>diversity</strong>.</p><h3>19. lambda_mult</h3><p>MMR uses:</p><pre>lambda_mult</pre><p>This controls the balance between:</p><pre>Relevance<br>vs<br>Diversity</pre><p>Current LangChain’s reference describes the range as:</p><pre>1 → minimum diversity<br>0 → maximum diversity</pre><p>with a default of 0.5.</p><p>Think of it like:</p><pre>lambda = 1.0<br>&quot;I mostly care about relevance.&quot;<br>lambda = 0.5<br>&quot;Give me a balance.&quot;<br>lambda = 0.0<br>&quot;I strongly care about diversity.&quot;</pre><p>The exact best value depends on your data.</p><h3>20. fetch_k</h3><p>MMR introduces another parameter:</p><pre>fetch_k</pre><p>Suppose:</p><pre>k = 5</pre><p>means:</p><blockquote><em>Ultimately return 5 documents.</em></blockquote><p>But MMR might first fetch:</p><pre>fetch_k = 20</pre><p>candidate documents:</p><pre>20 candidates<br>     ↓<br>MMR selection<br>     ↓<br>5 diverse results</pre><p>That’s why the documentation describes fetch_k as the number of documents passed to the MMR algorithm, while k is the number ultimately returned.</p><p>Example:</p><pre>retriever = vector_store.as_retriever(<br>    search_type=&quot;mmr&quot;,<br>    search_kwargs={<br>        &quot;k&quot;: 5,<br>        &quot;fetch_k&quot;: 20,<br>        &quot;lambda_mult&quot;: 0.5<br>    }<br>)</pre><h3>21. Compare the three retrieval modes</h3><p>Now this should make sense:</p><blockquote><strong>Similarity</strong></blockquote><pre>search_type=&quot;similarity&quot;</pre><p>Means:</p><blockquote><em>Give me the most similar results.</em></blockquote><blockquote><strong>Similarity threshold</strong></blockquote><pre>search_type=&quot;similarity_score_threshold&quot;</pre><p>Means:</p><blockquote><em>Give me results only when their relevance clears a threshold.</em></blockquote><blockquote><strong>MMR</strong></blockquote><pre>search_type=&quot;mmr&quot;</pre><p>Means:</p><blockquote><em>Give me relevant results while reducing redundancy.</em></blockquote><p>LangChain’s current reference supports all three through VectorStore.as_retriever().</p><h3>22. A practical comparison</h3><p>Suppose these are your chunks:</p><pre>A = Python + AI<br>B = Python + AI<br>C = Python + AI<br>D = Python + Data Science<br>E = Python + Automation</pre><p>Question:</p><pre>How is Python used?</pre><blockquote><strong>Similarity</strong></blockquote><p>Possible result:</p><pre>A<br>B<br>C<br>D</pre><p>Very relevant, but repetitive.</p><blockquote><strong>MMR</strong></blockquote><p>Possible result:</p><pre>A<br>D<br>E</pre><p>More diverse.</p><blockquote><strong>Threshold</strong></blockquote><p>Potential result:</p><pre>A<br>B<br>C<br>D<br>E</pre><p>only if each passes the configured threshold.</p><p>Or fewer results if some don’t.</p><h3>23. Build each one in code</h3><h3>Similarity</h3><pre>retriever = vector_store.as_retriever(<br>    search_type=&quot;similarity&quot;,<br>    search_kwargs={&quot;k&quot;: 4}<br>)</pre><h3>MMR</h3><pre>retriever = vector_store.as_retriever(<br>    search_type=&quot;mmr&quot;,<br>    search_kwargs={<br>        &quot;k&quot;: 4,<br>        &quot;fetch_k&quot;: 20,<br>        &quot;lambda_mult&quot;: 0.5<br>    }<br>)</pre><h3>Threshold</h3><pre>retriever = vector_store.as_retriever(<br>    search_type=&quot;similarity_score_threshold&quot;,<br>    search_kwargs={<br>        &quot;score_threshold&quot;: 0.8<br>    }<br>)</pre><p>These options and parameters are part of the current LangChain VectorStore.as_retriever() interface.</p><h3>24. What happens inside retriever.invoke()?</h3><p>When you write:</p><pre>docs = retriever.invoke(<br>    &quot;How does ERP help companies?&quot;<br>)</pre><p>think of the process as:</p><pre>User Question<br>                      ↓<br>             Retriever receives it<br>                      ↓<br>             Create query embedding<br>                      ↓<br>            Search vector store<br>                      ↓<br>             Apply search strategy<br>                      ↓<br>              Rank/select results<br>                      ↓<br>               Return Documents</pre><p>The result is typically:</p><pre>list[Document]</pre><p>That’s exactly why we can do:</p><pre>for doc in docs:<br>    print(doc.page_content)</pre><p>The current retriever interface is defined as taking an unstructured query and returning a list of Document objects.</p><h3>25. This is the point where RAG becomes modular</h3><p>You can build:</p><pre>chain = retriever | prompt | model</pre><p>Conceptually:</p><pre>Question<br>   ↓<br>Retriever<br>   ↓<br>Documents<br>   ↓<br>Prompt<br>   ↓<br>LLM<br>   ↓<br>Answer</pre><p><em>The retriever doesn’t need to know anything about the LLM.</em></p><p><em>The LLM doesn’t need to know how the documents were found.</em></p><p><em>Each component has one job.</em></p><p><em>That’s one of the major strengths of LangChain’s abstractions.</em></p><h3>26. An important limitation</h3><p>This code:</p><pre>retriever = vector_store.as_retriever()</pre><p>does <strong>not</strong> automatically mean your retrieval is good.</p><p>You still need to evaluate:</p><pre>Are the right chunks being retrieved?</pre><p>Your retriever could return:</p><pre>3 semantically similar but irrelevant chunks</pre><p>and the LLM would then have bad context.</p><p>So don’t think:</p><pre>Vector DB = correct search</pre><p>Instead:</p><pre>Vector DB<br>   ↓<br>search mechanism<br>   ↓<br>retrieval quality must be evaluated</pre><h3>27. Debugging technique</h3><p>Whenever you’re building RAG, do this first:</p><pre>docs = retriever.invoke(question)<br>for i, doc in enumerate(docs):<br>    print(f&quot;\n--- Document {i + 1} ---&quot;)<br>    print(doc.page_content)<br>    print(&quot;Metadata:&quot;, doc.metadata)</pre><p>Only after confirming the results are correct should you pass them to the LLM.</p><p>This gives you a clean debugging boundary:</p><pre>Question<br> ↓<br>Retriever<br> ↓<br>Are these documents correct?<br>       ↓<br>      YES<br>       ↓<br>      LLM</pre><h3>28. Vector Store vs Retriever — final comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7OfNe_EKm0iH0gwUu4mD0A.png" /></figure><p>The important relationship is:</p><pre>Vector Store<br>     ↓<br>as_retriever()<br>     ↓<br>Retriever</pre><p>And:</p><pre>Retriever ≠ Vector Store</pre><p>But:</p><pre>Vector Store → can become Retriever</pre><p>as the current LangChain API demonstrates.</p><h3>29. The complete picture</h3><p>You’ve now learned:</p><pre>                 DOCUMENTS<br>                     ↓<br>                  Chunks<br>                     ↓<br>                Embeddings<br>                     ↓<br>                Vector Store<br>                     │<br>                     │<br>              as_retriever()<br>                     ↓<br>                 Retriever<br>                     ↓<br>              Search strategy<br>              /      |       \<br>        similarity   MMR    threshold<br>              \      |       /<br>                     ↓<br>             Relevant Documents<br>                     ↓<br>                   Prompt<br>                     ↓<br>                    LLM<br>                     ↓<br>                  Answer</pre><p>That’s a very solid understanding of retrieval.</p><h3>30. One mental model to memorize</h3><p>Imagine Amazon-style shopping.</p><pre>Vector Store      = entire product catalog<br><br>Retriever         = search service<br><br>Similarity Search = &quot;show me products most similar to this&quot;<br><br>MMR               = &quot;show me relevant products, but don&#39;t give me <br>                     five nearly identical products&quot;<br><br>Threshold         = &quot;don&#39;t show me anything below this relevance level&quot;<br><br>k                 = &quot;show me the top 5&quot;</pre><p>That analogy is surprisingly useful.</p><blockquote><strong>Below is the complete example of the above-mentioned 3 types of retriever</strong></blockquote><pre>from langchain_ollama import OllamaEmbeddings<br>from langchain_core.vectorstores import InMemoryVectorStore<br><br># -------------------------<br># 1. Embedding model<br># -------------------------<br><br>embeddings = OllamaEmbeddings(<br>    model=&quot;nomic-embed-text&quot;<br>)<br><br><br># InMemoryVectorStore&#39;s scores are already cosine similarity (0-1),<br># so similarity_score_threshold search needs a relevance score fn defined.<br>class ScoredInMemoryVectorStore(InMemoryVectorStore):<br>    def _select_relevance_score_fn(self):<br>        return lambda score: score<br><br><br># -------------------------<br># 2. Vector store<br># -------------------------<br><br>vector_store = ScoredInMemoryVectorStore(<br>    embedding=embeddings<br>)<br><br><br># -------------------------<br># 3. Knowledge base<br># -------------------------<br><br>documents = [<br>    &quot;Python is widely used in artificial intelligence.&quot;,<br>    &quot;Python is commonly used for machine learning.&quot;,<br>    &quot;Python is popular for data science.&quot;,<br>    &quot;Python can automate repetitive business tasks.&quot;,<br>    &quot;Python is used to build web applications.&quot;<br>]<br><br>vector_store.add_texts(documents)<br><br><br># -------------------------<br># 4. Retrievers<br># -------------------------<br><br>similarity_retriever = vector_store.as_retriever(<br>    search_type=&quot;similarity&quot;,<br>    search_kwargs={&quot;k&quot;: 4}<br>)<br><br>mmr_retriever = vector_store.as_retriever(<br>    search_type=&quot;mmr&quot;,<br>    search_kwargs={<br>        &quot;k&quot;: 4,<br>        &quot;fetch_k&quot;: 20,<br>        &quot;lambda_mult&quot;: 0.5<br>    }<br>)<br><br>threshold_retriever = vector_store.as_retriever(<br>    search_type=&quot;similarity_score_threshold&quot;,<br>    search_kwargs={<br>        &quot;score_threshold&quot;: 0.8<br>    }<br>)<br><br><br># -------------------------<br># 5. Question<br># -------------------------<br><br>question = &quot;How is Python used?&quot;<br><br><br># -------------------------<br># 6. Helper to print results<br># -------------------------<br><br>def print_results(title, docs):<br>    print(f&quot;\n=== {title} ===&quot;)<br>    for i, doc in enumerate(docs):<br>        print(f&quot;\n--- Document {i + 1} ---&quot;)<br>        print(doc.page_content)<br>        print(&quot;Metadata:&quot;, doc.metadata)<br><br><br># -------------------------<br># 7. Run each retriever<br># -------------------------<br><br>print_results(&quot;Similarity&quot;, similarity_retriever.invoke(question))<br>print_results(&quot;MMR&quot;, mmr_retriever.invoke(question))<br>print_results(&quot;Similarity Score Threshold&quot;, threshold_retriever.invoke(question))</pre><h3>Next Lesson — Lesson 13: Building a Real RAG Chain</h3><p>We’ll combine everything you’ve learned into a cleaner application:</p><pre>Question<br>   ↓<br>Retriever<br>   ↓<br>Documents<br>   ↓<br>Context formatting<br>   ↓<br>Prompt<br>   ↓<br>LLM<br>   ↓<br>Answer</pre><p>Then we’ll introduce an important concept called <strong>RAG chain composition</strong>, including how to pass the retrieved documents and original question through a LangChain pipeline cleanly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=078005e3d1a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson 11 — Embeddings and Vector Similarity]]></title>
            <link>https://medium.com/@md.wasim3/lesson-11-embeddings-and-vector-similarity-1ad8b11d1249?source=rss-4362f970560b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ad8b11d1249</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[md wasim]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 01:41:01 GMT</pubDate>
            <atom:updated>2026-09-25T01:41:01.545Z</atom:updated>
            <content:encoded><![CDATA[<p>This lesson is extremely important because <strong>embeddings are the reason RAG can find information based on meaning rather than just matching exact words</strong>.</p><p>In Lesson 10, you used:</p><pre>Document<br>   ↓<br>Chunk<br>   ↓<br>Embedding<br>   ↓<br>Vector Store<br>   ↓<br>Retriever</pre><p>Today we’ll focus on the middle:</p><pre>Text<br> ↓<br>Embedding<br> ↓<br>Vector<br> ↓<br>Similarity<br> ↓<br>Relevant text</pre><p>LangChain’s current embedding interface exposes methods such as embed_query() for a query and embed_documents() for multiple documents. Vector stores then use those embeddings for semantic similarity search.</p><h3>1. What exactly is an embedding?</h3><p>Take this sentence:</p><pre>Python is a programming language.</pre><p>An embedding model converts it into a list of numbers:</p><pre>[0.021, -0.184, 0.731, 0.112, ...]</pre><p>Don’t think:</p><blockquote><em>“Each number represents one word.”</em></blockquote><p>That’s not how you should think about it.</p><p>Think:</p><blockquote><strong><em>The entire piece of text is represented by a point in a high-dimensional mathematical space.</em></strong></blockquote><p>So:</p><pre>&quot;Python is a programming language.&quot;<br>             ↓<br>       Embedding Model<br>             ↓<br>        [0.021, ...]</pre><p>LangChain’s OpenAI integration exposes this directly through embed_query() and embed_documents().</p><h3>2. Why convert text into numbers?</h3><p>Computers are very good at comparing numbers. They’re not directly good at asking:</p><pre>&quot;Is this sentence semantically similar to that sentence?&quot;</pre><p>But they can compare vectors mathematically.</p><p>For example:</p><pre>Text A:<br>&quot;Python is a programming language.&quot;<br>Text B:<br>&quot;Python is used to write computer programs.&quot;</pre><p>Their embeddings may be relatively close.</p><p>While:</p><pre>Text C:<br>&quot;Delhi is the capital of India.&quot;</pre><p>may be farther away in embedding space.</p><p>Conceptually:</p><pre>Python A ●<br>                \<br>                 \<br>         Python B ●<br><br>                                          Delhi ●</pre><p>This is a simplified 2D picture. Real embeddings normally have <strong>many dimensions</strong>, not just two.</p><h3>3. Semantic similarity</h3><p>This is the key idea.</p><p>Suppose your document says:</p><pre>Employees receive 24 annual leave days.</pre><p>But the user asks:</p><pre>How many vacation days do employees get?</pre><p>There is a vocabulary difference:</p><pre>annual leave<br>vs<br>vacation days</pre><p>A traditional exact keyword search may struggle.</p><p>An embedding-based search can recognise that the meanings are related.</p><p>So:</p><pre>Document:<br>&quot;annual leave&quot;</pre><pre>Question:<br>&quot;vacation days&quot;</pre><pre>         ↓</pre><pre>Semantic similarity</pre><pre>         ↓</pre><pre>Relevant document</pre><p>That’s why embeddings are so valuable in RAG.</p><h3>4. Embedding a document</h3><p>With LangChain:</p><pre>from langchain_openai import OpenAIEmbeddings<br>embeddings = OpenAIEmbeddings(<br>    model=&quot;text-embedding-3-small&quot;<br>)</pre><p>Then:</p><pre>text = &quot;Python is a programming language.&quot;<br>vector = embeddings.embed_query(text)<br>print(vector)</pre><p>You’ll get a list of floating-point numbers.</p><p>The current LangChain OpenAI integration documents OpenAIEmbeddings and shows embed_query() for creating a vector from a single piece of text.</p><h3>5. embed_query() vs embed_documents()</h3><p>This is a small detail, but you should understand it.</p><h3>One query</h3><pre>vector = embeddings.embed_query(<br>    &quot;What is Python?&quot;<br>)</pre><p>Use this when you have one search query.</p><h3>Multiple documents</h3><pre>vectors = embeddings.embed_documents([<br>    &quot;Python is a programming language.&quot;,<br>    &quot;Python is used in AI.&quot;,<br>    &quot;Python can automate tasks.&quot;<br>])</pre><p>Use this when you’re embedding multiple pieces of source content.</p><p>Conceptually:</p><pre>embed_query()<br>    ↓<br>Question → Vector<br></pre><pre>embed_documents()<br>    ↓<br>Documents → Vectors</pre><p>LangChain’s current documentation explicitly describes these two methods and notes that vector stores/retrievers use them under the hood.</p><h3>6. What is a vector?</h3><p>A vector is simply a list of numbers:</p><pre>[<br>    0.021,<br>    -0.184,<br>    0.731,<br>    0.112,<br>    ...<br>]</pre><p>Imagine a much simpler world where vectors had only two numbers.</p><pre>Python = [2, 8]<br>AI     = [3, 7]<br>Car    = [20, 1]</pre><p>You can plot them:</p><pre>Y<br>↑<br>8       ● Python<br>7          ● AI<br>1                         ● Car<br>  ─────────────────────────────→ X</pre><p>Python and AI are close.</p><p>Car is far away.</p><p>That’s the basic intuition behind vector similarity.</p><h3>7. Real embeddings are much larger</h3><p>The real vectors used by embedding models can have many dimensions.</p><p>You don’t need to memorize the dimension count for a particular model.</p><p>What matters is:</p><pre>Text<br> ↓<br>High-dimensional vector</pre><p>The embedding model decides how the text is represented.</p><p>And different embedding models can produce different vector spaces.</p><h3>8. How does similarity get calculated?</h3><p>Now we get to the mathematical part.</p><p>Suppose:</p><pre>Vector A = [1, 2]<br>Vector B = [1, 3]</pre><p>They point in almost the same direction.</p><p>Compare:</p><pre>Vector A = [1, 2]<br>Vector C = [-1, 2]</pre><p>These point in different directions.</p><p>One commonly used similarity measure is <strong>cosine similarity</strong>.</p><p>LangChain’s vector-store documentation notes that vector stores may use cosine similarity, Euclidean distance, or dot product depending on the implementation.</p><h3>9. Cosine similarity — intuition</h3><p>You don’t need the formula yet.</p><p>Just remember:</p><pre>Cosine similarity<br>≈<br>How much two vectors point in the same direction</pre><p>For intuition:</p><pre>Very similar<br>→ high similarity<br>Very different<br>→ low similarity</pre><p>So:</p><pre>Question Vector<br>       ↓<br>Compare with document vectors<br>       ↓<br>Find closest/similar ones</pre><h3>10. A simple example</h3><p>Imagine we have:</p><pre>Document 1:<br>Python is a programming language.<br>Document 2:<br>Python is commonly used for AI.<br>Document 3:<br>The company office is open from 9 AM to 6 PM.</pre><p>User asks:</p><pre>What is Python used for?</pre><p>The embedding model creates:</p><pre>Question Vector</pre><p>The vector store compares it with:</p><pre>Document 1 Vector<br>Document 2 Vector<br>Document 3 Vector</pre><p>Conceptually:</p><pre>Question<br>   │<br>   ├── similarity → Doc 1 = 0.78<br>   ├── similarity → Doc 2 = 0.91<br>   └── similarity → Doc 3 = 0.12</pre><p>The retriever returns the most relevant ones.</p><p>So:</p><pre>Doc 2<br>Doc 1</pre><p>might be returned.</p><h3>11. This is what the vector store does</h3><p>A vector store essentially gives you a way to:</p><pre>Store vectors<br>+<br>Search vectors</pre><p>LangChain provides a common interface across vector stores, including methods such as add_documents() and similarity search. Conceptually:</p><pre>VECTOR STORE<br>        ┌─────────────────────────────┐<br>        │ Doc A → Vector A            │<br>        │ Doc B → Vector B            │<br>        │ Doc C → Vector C            │<br>        │ Doc D → Vector D            │<br>        └─────────────────────────────┘<br>                    ↑<br>                    │<br>              User Question<br>                    ↓<br>               Query Vector<br>                    ↓<br>             Similarity Search<br>                    ↓<br>             Top-k documents</pre><h3>12. Let’s write a tiny example</h3><pre>from langchain_openai import OpenAIEmbeddings<br>from langchain_core.vectorstores import InMemoryVectorStore<br>embeddings = OpenAIEmbeddings(<br>    model=&quot;text-embedding-3-small&quot;<br>)<br>vector_store = InMemoryVectorStore(<br>    embedding=embeddings<br>)<br>documents = [<br>    &quot;Python is a programming language.&quot;,<br>    &quot;Python is widely used in artificial intelligence.&quot;,<br>    &quot;The office is open from 9 AM to 6 PM.&quot;<br>]<br>vector_store.add_texts(documents)</pre><p>Now search:</p><pre>results = vector_store.similarity_search(<br>    &quot;What is Python used for?&quot;<br>)</pre><p>Then:</p><pre>for doc in results:<br>    print(doc.page_content)</pre><p>The vector store searches semantically similar content. LangChain’s vector-store abstraction exposes similarity_search() for this purpose.</p><h3>13. k — how many results?</h3><p>You can ask for a certain number of results:</p><pre>results = vector_store.similarity_search(<br>    &quot;What is Python used for?&quot;,<br>    k=2<br>)</pre><p>Now you’re saying:</p><blockquote><em>Give me the two most similar documents.</em></blockquote><p>Conceptually:</p><pre>Similarity scores<br>Doc A → 0.91<br>Doc B → 0.82<br>Doc C → 0.15<br>k = 2<br>Return:<br>Doc A<br>Doc B</pre><p>Vector-store implementations commonly expose k for the number of results.</p><h3>14. Similarity score vs distance</h3><p>One confusing thing you’ll encounter:</p><p>Some systems talk about:</p><pre>similarity</pre><p>while others talk about:</p><pre>distance</pre><p>Usually:</p><h3>Similarity</h3><pre>Higher = more similar</pre><h3>Distance</h3><pre>Lower = more similar</pre><p>For example:</p><pre>Similarity:<br>0.95 → very similar<br>0.20 → not very similar</pre><p>Whereas:</p><pre>Distance:<br>0.10 → very close<br>0.90 → far away</pre><p>So don’t automatically assume that a larger number always means “better.”</p><p>Check whether the system is reporting <strong>similarity or distance</strong>.</p><h3>15. Why the retriever sometimes returns the wrong result</h3><p>This is where things get interesting.</p><p>Suppose your document contains:</p><pre>&quot;Employees receive 24 annual leave days.&quot;<br>&quot;Employees receive 10 sick leave days.&quot;<br>&quot;Employees may work remotely 3 days per week.&quot;</pre><p>Question:</p><pre>How many leave days do I get?</pre><p>The retriever might return:</p><pre>Annual leave<br>Sick leave</pre><p>That’s reasonable because both relate to leave.</p><p>But maybe the user specifically meant:</p><pre>annual leave</pre><p>Now we have an ambiguity problem.</p><p>The embedding system isn’t “thinking”:</p><blockquote><em>“I clearly means annual leave.”</em></blockquote><p>It’s finding semantically related content.</p><p>That’s an important distinction.</p><h3>16. Embeddings don’t understand the world like humans</h3><p>This is a very useful mental model.</p><p>Don’t imagine:</p><pre>Embedding<br>= tiny human brain</pre><p>Instead:</p><pre>Embedding<br>= mathematical representation useful for comparing text</pre><p>The model learned patterns from training data, and the resulting vector space allows useful similarity comparisons.</p><p>It can be powerful without being perfect.</p><h3>17. Query wording matters</h3><p>Consider:</p><pre>Question A:<br>How many days of annual leave are provided?</pre><p>and:</p><pre>Question B:<br>Tell me about time off.</pre><p>Both could relate to leave, but Question B is much broader.</p><p>That changes what gets retrieved.</p><p>So:</p><pre>Question<br>   ↓<br>Embedding<br>   ↓<br>Similarity search</pre><p>means the wording of the question can affect the retrieved results.</p><p>This becomes important later when we study <strong>query transformation and multi-query retrieval</strong>.</p><h3>18. Why chunking and embeddings are connected</h3><p>Remember Lesson 10?</p><p>We split documents into chunks.</p><p>Now we can see why.</p><p>Suppose we have:</p><pre>100-page document</pre><p>and create one giant embedding:</p><pre>Entire PDF → One vector</pre><p>What happens when the user asks:</p><pre>What is the refund policy?</pre><p>The embedding represents the entire document.</p><p>It may not give us precise retrieval.</p><p>Instead:</p><pre>100-page PDF<br>     ↓<br>Chunks<br>     ↓<br>Each chunk gets its own vector</pre><p>Now we can find the specific chunk related to refunds.</p><p>So:</p><pre>Chunking<br>+<br>Embeddings<br>+<br>Vector search</pre><p>work together.</p><h3>19. Metadata is separate from the embedding</h3><p>Suppose:</p><pre>Document(<br>    page_content=&quot;Employees receive 24 annual leave days.&quot;,<br>    metadata={<br>        &quot;department&quot;: &quot;HR&quot;,<br>        &quot;year&quot;: 2026<br>    }<br>)</pre><p>The embedding represents:</p><pre>&quot;Employees receive 24 annual leave days.&quot;</pre><p>Metadata is additional information:</p><pre>department = HR<br>year = 2026</pre><p>The vector store can use metadata filters in addition to semantic similarity; LangChain’s vector-store interface documents filtering by metadata as a supported capability in many implementations.</p><p>For example:</p><pre>Search:<br>&quot;What is the leave policy?&quot;<br>Filter:<br>department = HR</pre><p>That can dramatically improve retrieval in larger systems.</p><h3>20. Similarity search vs keyword search</h3><p>This is worth understanding clearly.</p><h4>Keyword search</h4><p>Looks for matching words.</p><p>Question:</p><pre>&quot;vacation days&quot;</pre><p>Document:</p><pre>&quot;annual leave days&quot;</pre><p>There may be little or no exact word overlap.</p><h4>Semantic/vector search</h4><p>Looks for related meaning.</p><pre>vacation days<br>      ↕<br>annual leave days</pre><p>So:</p><pre>Keyword search<br>→ word matching<br>Vector search<br>→ semantic similarity</pre><p>Neither is universally better.</p><p>For some workloads, combining them into <strong>hybrid search</strong> can be useful.</p><h3>21. Why exact names can be tricky</h3><p>Suppose your document says:</p><pre>Employee ID: SAM-10284</pre><p>and the user asks:</p><pre>Find SAM-10284.</pre><p>Exact keyword matching may be excellent for this.</p><p>Semantic similarity isn’t always the ideal mechanism for exact identifiers.</p><p>This leads to a very useful production idea:</p><pre>Semantic search<br>+<br>Keyword/exact search</pre><p>can sometimes work better together.</p><p>We’ll study this later.</p><h3>22. The role of the embedding model</h3><p>You might wonder:</p><blockquote><em>Why does changing the embedding model matter?</em></blockquote><p><em>Because each embedding model creates its own representation space.</em></p><p>For example:</p><pre>Embedding Model A<br>→ Vector Space A<br>Embedding Model B<br>→ Vector Space B</pre><p><em>You generally shouldn’t take vectors produced by one embedding model and compare them directly with vectors from another model as though they lived in the same space.</em></p><p>More importantly, different models can perform differently on different domains and languages.</p><p>LangChain lets you plug in many different embedding providers behind its embedding interface. The current integration docs list OpenAI, Google, AWS, Hugging Face, Cohere, Mistral, Nomic, Voyage, NVIDIA, and others.</p><h3>23. A crucial rule for RAG</h3><p>Suppose you indexed your documents using:</p><pre>EmbeddingModelA</pre><p>Later you change the query embedding to:</p><pre>EmbeddingModelB</pre><p>That’s generally not something you should casually do.</p><p>Your indexed vectors and query vectors need to be compatible with the same embedding space.</p><p>So practically:</p><pre>Index documents<br>      ↓<br>Embedding Model A<br>      ↓<br>Vector Store<br><br>User query<br>      ↓<br>Embedding Model A<br>      ↓<br>Search Vector Store</pre><p>Use a consistent embedding setup.</p><h3>24. Embeddings are not generated answers</h3><p>This distinction is critical.</p><p>Embedding:</p><pre>Text<br> ↓<br>Vector</pre><p>doesn’t produce:</p><pre>&quot;Python is a programming language...&quot;</pre><p>That’s the job of your chat/generation model.</p><p>So:</p><pre>Embedding Model<br>→ FIND / REPRESENT<br>Chat Model<br>→ GENERATE / ANSWER</pre><p>Remember:</p><pre>Embedding ≠ LLM response</pre><h3>25. The entire RAG flow again</h3><p>Now that embeddings make sense:</p><pre>               DOCUMENT SIDE<br>Document<br>   ↓<br>Chunks<br>   ↓<br>Embedding Model<br>   ↓<br>Vectors<br>   ↓<br>Vector Store<br><br>               QUESTION SIDE<br>User Question<br>   ↓<br>Embedding Model<br>   ↓<br>Query Vector<br>   ↓<br>Similarity Search<br>   ↓<br>Top-k Chunks<br>   ↓<br>Prompt<br>   ↓<br>Chat Model<br>   ↓<br>Answer</pre><p>The beautiful part is that <strong>both sides enter the same vector space</strong>:</p><pre>Document chunk ──→ Vector<br>Question ────────→ Vector<br>              ↓<br>         Compare similarity<br>              ↓<br>         Find relevant chunk</pre><h3>26. One complete example</h3><p>Let’s make the architecture visible:</p><pre>from langchain_ollama import OllamaEmbeddings<br>from langchain_core.vectorstores import InMemoryVectorStore<br># 1. Embedding model<br>embeddings = OllamaEmbeddings(<br>    model=&quot;nomic-embed-text&quot;<br>)<br># 2. Vector store<br>store = InMemoryVectorStore(<br>    embedding=embeddings<br>)<br># 3. Add knowledge<br>store.add_texts([<br>    &quot;Python is a programming language.&quot;,<br>    &quot;Python is widely used for AI and data science.&quot;,<br>    &quot;ERP systems help companies manage business processes.&quot;<br>])<br># 4. User&#39;s question<br>question = &quot;what is python ?&quot;<br># 5. Semantic search<br>results = store.similarity_search(<br>    question,<br>    k=2<br>)<br># 6. Inspect results<br>for result in results:<br>    print(result.page_content)</pre><p>The important chain is:</p><pre>add_texts()<br>    ↓<br>Create embeddings<br>    ↓<br>Store vectors<br>similarity_search()<br>    ↓<br>Embed question<br>    ↓<br>Compare vectors<br>    ↓<br>Return relevant documents</pre><p>The current LangChain documentation describes this same underlying flow: vector stores use embedding methods when indexing and retrieving, and similarity search returns the closest embedded documents.</p><h3>27. The 5 things I want you to remember</h3><h3>1. Embedding</h3><pre>Text → Vector</pre><h3>2. Vector</h3><pre>A list of numbers representing the text</pre><h3>3. Similarity</h3><pre>How mathematically close/related two vectors are</pre><h3>4. Vector Store</h3><pre>Store vectors + search them</pre><h3>5. Retriever</h3><pre>Use a search mechanism to return relevant documents</pre><p>So:</p><pre>Embedding<br>   ↓<br>Vector<br>   ↓<br>Similarity<br>   ↓<br>Retriever<br>   ↓<br>Relevant context</pre><h4>Next Lesson — Lesson 12: Vector Stores and Retrievers in Depth</h4><p>We’ll go deeper into the difference between:</p><pre>Vector Store<br>      vs<br>Retriever</pre><p>and learn:</p><pre>similarity_search()<br>similarity_search_with_score()<br>as_retriever()<br>k<br>metadata filters<br>MMR</pre><p>Most importantly, you’ll understand <strong>exactly what happens between a user’s question and the chunks that reach the LLM</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ad8b11d1249" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson 10 — Building a Practical RAG Application]]></title>
            <link>https://medium.com/@md.wasim3/lesson-10-building-a-practical-rag-application-65c7fdcb7ecf?source=rss-4362f970560b------2</link>
            <guid isPermaLink="false">https://medium.com/p/65c7fdcb7ecf</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[md wasim]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 17:41:01 GMT</pubDate>
            <atom:updated>2026-09-24T17:41:01.836Z</atom:updated>
            <content:encoded><![CDATA[<p>Now let’s go one level deeper.</p><p>In Lesson 9, you learned the <strong>RAG architecture</strong>. Today, we’ll understand how the pieces actually fit together and why each piece matters.</p><p>The current LangChain documentation describes retrieval as a modular pipeline built from document loaders, text splitters, embedding models, vector stores, and retrievers. It also distinguishes <strong>2-step RAG</strong> from <strong>agentic RAG</strong>; we’ll focus on 2-step RAG first because it is simpler and more predictable.</p><h4>1. First, understand the complete problem</h4><p>Imagine you have:</p><pre>company_policy.pdf</pre><p>Inside it:</p><pre>Leave Policy<br>Employees receive 24 annual leave days.<br>Sick Leave<br>Employees receive 10 sick leave days.<br>Remote Work<br>Employees may work remotely up to 3 days per week.</pre><p>A user asks:</p><pre>How many annual leave days do employees receive?</pre><p>Our application needs to do this:</p><pre>PDF<br> ↓<br>Read PDF<br> ↓<br>Extract text<br> ↓<br>Split text<br> ↓<br>Create embeddings<br> ↓<br>Store embeddings</pre><p>Then, when the user asks:</p><pre>Question<br> ↓<br>Search vector store<br> ↓<br>Find relevant text<br> ↓<br>Put text into prompt<br> ↓<br>LLM<br> ↓<br>Answer</pre><p>Notice something important:</p><h4>Document processing happens before the question.</h4><p>That’s the <strong>indexing phase</strong>.</p><p>Then:</p><h4>Retrieval happens when the user asks something.</h4><p>That’s the <strong>query phase</strong>.</p><h4>2. Indexing vs Querying</h4><p>This distinction is fundamental.</p><h4>Indexing phase</h4><p>You do this once, or whenever your documents change:</p><pre>Documents<br>   ↓<br>Load<br>   ↓<br>Split<br>   ↓<br>Embed<br>   ↓<br>Store</pre><h4>Query phase</h4><p>You do this for every question:</p><pre>Question<br>   ↓<br>Retrieve<br>   ↓<br>Context<br>   ↓<br>LLM<br>   ↓<br>Answer</pre><p>So:</p><pre>INDEXING<br>=========<br>PDF → Chunks → Embeddings → Vector DB<br>QUERY<br>=====<br>Question → Retriever → Chunks → LLM → Answer</pre><p>This separation makes RAG much more efficient.</p><h4>3. Step 1 — Loading a real document</h4><p>For a real PDF, we need a document loader.</p><p>LangChain currently offers multiple PDF-loader integrations, and you choose the loader based on how you want to parse PDFs. The ecosystem includes loaders such as Unstructured, Docling, Upstage, MinerU, and others.</p><p>For learning, let’s use a simple loader conceptually:</p><pre>from langchain_community.document_loaders import PyPDFLoader</pre><p>Then:</p><pre>loader = PyPDFLoader(&quot;company_policy.pdf&quot;)<br>documents = loader.load()</pre><p>Now, the variable document contains LangChain Document objects.</p><p>For example:</p><pre>Document 1 → page 1<br>Document 2 → page 2<br>Document 3 → page 3<br>...</pre><p>A Document usually gives you:</p><pre>document.page_content</pre><p>for the actual text, and:</p><pre>document.metadata</pre><p>for information about where the text came from.</p><h4>4. Understanding Document</h4><p>Suppose:</p><pre>doc = documents[0]</pre><p>You could inspect:</p><pre>print(doc.page_content)</pre><p>and:</p><pre>print(doc.metadata)</pre><p>The content might look like:</p><pre>Employees receive 24 annual leave days.</pre><p>Metadata might contain information such as:</p><pre>{<br>    &quot;source&quot;: &quot;company_policy.pdf&quot;,<br>    &quot;page&quot;: 0<br>}</pre><p>The exact metadata depends on the loader. This is extremely useful.</p><p>Suppose your answer is:</p><pre>Employees receive 24 annual leave days.</pre><p>You may also want to know:</p><pre>Source: company_policy.pdf<br>Page: 1</pre><p>That’s one reason metadata should not be ignored.</p><h4>5. Step 2 — Split the document</h4><p>Now imagine our PDF contains 100 pages.</p><p>We don’t want:</p><pre>100-page PDF → 1 giant vector</pre><p>Instead:</p><pre>100-page PDF<br>      ↓<br>hundreds/thousands of chunks</pre><p>LangChain’s RecursiveCharacterTextSplitter is a common general-purpose splitter. The current package is langchain-text-splitters, rather than the older import path many tutorials use.</p><p>Install:</p><pre>pip install -U langchain-text-splitters</pre><p>Then:</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=500,<br>    chunk_overlap=100<br>)<br>chunks = splitter.split_documents(documents)</pre><h3>6. What does chunk_size=500 mean?</h3><p>Think of it as:</p><blockquote><em>Try to keep each chunk around 500 characters.</em></blockquote><p>For example:</p><pre>Original:<br>ABCDEF...very long document...<br>       ↓<br>Chunk 1<br>AAAA BBBB CCCC...<br>Chunk 2<br>EEEE FFFF GGGG...<br>Chunk 3<br>HHHH IIII JJJJ...</pre><p>The exact splitting behavior is more nuanced than simply slicing every 500 characters because the recursive splitter tries progressively smaller separators to preserve structure. The goal is to break large documents into retrievable pieces while preserving useful context.</p><h3>7. What does chunk_overlap=100 mean?</h3><p>Suppose we have:</p><pre>Chunk 1<br>A B C D E F G</pre><pre>Chunk 2<br>              F G H I J K</pre><p>The overlapping part is:</p><pre>F G</pre><p>Why?</p><p>Because important meaning might cross the boundary.</p><p>Imagine:</p><pre>Chunk 1:<br>The employee is eligible for leave after completing<br>Chunk 2:<br>completing six months of employment.</pre><p>Without overlap, retrieval might produce incomplete context.</p><p>Overlap helps preserve continuity.</p><h4>8. How should you choose chunk size?</h4><p>There is no universal perfect value.</p><p>A simple starting point might be:</p><pre>300–800 characters</pre><p>for a small learning project.</p><p>For production systems, the right value depends on the document type, structure, query patterns, embedding model, and context limits.</p><p>Think:</p><pre>Too small<br>→ not enough context<br>Too large<br>→ less precise retrieval</pre><h4>9. Step 3 — Create embeddings</h4><p>Now we convert chunks into vectors.</p><pre>from langchain_openai import OpenAIEmbeddings<br>embeddings = OpenAIEmbeddings(<br>    model=&quot;text-embedding-3-small&quot;<br>)</pre><p>LangChain’s current OpenAI embedding integration uses OpenAIEmbeddings from langchain-openai.</p><p>Conceptually:</p><pre>Chunk<br> ↓<br>Embedding Model<br> ↓<br>[0.12, -0.44, 0.91, ...]</pre><p>Do this for every chunk.</p><p>For example:</p><pre>Chunk 1 → Vector 1<br>Chunk 2 → Vector 2<br>Chunk 3 → Vector 3<br>...</pre><h4>10. Why embeddings are necessary</h4><p>Suppose the document says:</p><pre>Employees receive 24 annual leave days.</pre><p>The user asks:</p><pre>How much vacation do employees get?</pre><p>There isn’t necessarily an exact keyword match:</p><pre>annual leave ≠ vacation</pre><p>But semantically they are related.</p><p>Embeddings allow the system to compare the <strong>meaning</strong> of text rather than relying only on exact words. LangChain describes embedding models as mapping text into vector space where semantically similar texts tend to be closer.</p><h4>11. Step 4 — Store the vectors</h4><p>For learning, we can use:</p><pre>from langchain_core.vectorstores import InMemoryVectorStore<br>vector_store = InMemoryVectorStore(<br>    embedding=embeddings<br>)</pre><p>Then:</p><pre>vector_store.add_documents(chunks)</pre><p>Now we’ve created our searchable knowledge base.</p><p>Conceptually:</p><pre>Chunk 1 ──→ Vector 1<br>Chunk 2 ──→ Vector 2<br>Chunk 3 ──→ Vector 3<br>Chunk 4 ──→ Vector 4</pre><p>A production application might use a persistent vector database instead. LangChain treats vector stores as a modular component, so you can change the storage technology without changing the overall retrieval concept.</p><h4>12. Step 5 — Create the retriever</h4><p>Now:</p><pre>retriever = vector_store.as_retriever(<br>    search_kwargs={&quot;k&quot;: 3}<br>)</pre><p>k=3 means:</p><blockquote><em>Return the top 3 retrieved documents/chunks.</em></blockquote><p>Then:</p><pre>results = retriever.invoke(<br>    &quot;How many annual leave days do employees receive?&quot;<br>)</pre><p>Now results contains the most relevant chunks.</p><h3>13. Why k matters</h3><p>Suppose we have:</p><pre>k=1</pre><p>We retrieve:</p><pre>Chunk A</pre><p>Maybe that’s exactly what we need.</p><p>But perhaps Chunk A doesn’t contain the full answer.</p><p>With:</p><pre>k=5</pre><p>we get:</p><pre>Chunk A<br>Chunk B<br>Chunk C<br>Chunk D<br>Chunk E</pre><p>More context can help — but too much irrelevant context can also make the prompt noisier.</p><p>So:</p><pre>k too small<br>→ missing information<br>k too large<br>→ unnecessary/irrelevant information</pre><p>Again, this is something you tune based on your data and evaluation.</p><h4>14. Inspect the retrieved results</h4><p>This is one of the best debugging habits you can develop.</p><p>Don’t immediately send everything to the LLM.</p><p>First:</p><pre>for doc in results:<br>    print(&quot;CONTENT:&quot;)<br>    print(doc.page_content)</pre><pre>    print(&quot;METADATA:&quot;)<br>    print(doc.metadata)</pre><pre>    print(&quot;=&quot; * 50)</pre><p>Suppose the output is:</p><pre>CONTENT:<br>Employees receive 24 annual leave days.</pre><pre>METADATA:<br>{&#39;source&#39;: &#39;company_policy.pdf&#39;, &#39;page&#39;: 2}</pre><p>Great.</p><p>But imagine you see:</p><pre>CONTENT:<br>Employees may work remotely up to 3 days per week.</pre><p>when you asked about leave.</p><p>That tells you:</p><blockquote><em>The problem is in retrieval, not generation.</em></blockquote><p>This distinction is extremely important.</p><h4>15. Retrieval problem vs LLM problem</h4><p>Suppose the user asks:</p><pre>How many annual leave days do employees get?</pre><h4>Case A — Retriever finds the correct chunk</h4><pre>Employees receive 24 annual leave days.</pre><p>But the LLM answers:</p><pre>Employees receive 10 annual leave days.</pre><p>That’s primarily a <strong>generation/grounding problem</strong>.</p><h4>Case B — Retriever finds:</h4><pre>Remote work policy...<br>Sick leave...<br>Work hours...</pre><p>and never finds the annual-leave text.</p><p>Then the problem is primarily <strong>retrieval</strong>.</p><p>This gives you a powerful debugging rule:</p><pre>Wrong answer?<br>       ↓<br>Check retrieved chunks first.</pre><p>Don’t immediately blame the LLM.</p><h4>16. Step 6 — Build the prompt</h4><p>Now create:</p><pre>from langchain_core.prompts import ChatPromptTemplate<br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>You are a helpful company policy assistant.<br>Answer the question using only the supplied context.<br>If the answer is not present in the context,<br>say that you do not have enough information.<br>Context:<br>{context}<br>Question:<br>{question}<br>&quot;&quot;&quot;)</pre><p>Notice this instruction:</p><pre>If the answer is not present in the context,<br>say that you do not have enough information.</pre><p>This is useful because we don’t want the model confidently inventing an answer from unrelated knowledge.</p><h4>17. Step 7 — Combine the retrieved chunks</h4><pre>context = &quot;\n\n&quot;.join(<br>    doc.page_content<br>    for doc in results<br>)</pre><p>Now context might contain:</p><pre>Employees receive 24 annual leave days.</pre><pre>Employees must request leave at least 3 days in advance.</pre><p>Then:</p><pre>model = ChatOpenAI(model=&quot;gpt-5.4-mini&quot;)<br>chain = prompt | model</pre><p>Finally:</p><pre>response = chain.invoke({<br>    &quot;context&quot;: context,<br>    &quot;question&quot;: &quot;How many annual leave days do employees receive?&quot;<br>})<br>print(response.content)</pre><h4>18. The complete practical flow</h4><p>Now put everything together mentally:</p><pre>INDEXING<br>=========<br>PDF<br> ↓<br>Document Loader<br> ↓<br>Documents<br> ↓<br>Text Splitter<br> ↓<br>Chunks<br> ↓<br>Embedding Model<br> ↓<br>Vectors<br> ↓<br>Vector Store<br><br>QUERY<br>=====<br>User Question<br> ↓<br>Retriever<br> ↓<br>Top-k Chunks<br> ↓<br>Context<br> ↓<br>Prompt<br> ↓<br>LLM<br> ↓<br>Answer</pre><p>This is the architecture you should be able to draw from memory.</p><h4>19. A complete beginner example</h4><p>Here is a compact version:</p><pre>from langchain_ollama import ChatOllama, OllamaEmbeddings<br>from langchain_core.vectorstores import InMemoryVectorStore<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_community.document_loaders import PyPDFLoader<br><br><br># -------------------------<br># 1. Load documents from PDF<br># -------------------------<br><br>PDF_PATH = &quot;/root/india_leave.pdf&quot;  # update to your PDF&#39;s path<br><br>loader = PyPDFLoader(PDF_PATH)<br>documents = loader.load()<br><br><br># -------------------------<br># 2. Split documents<br># -------------------------<br><br>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=300,<br>    chunk_overlap=50<br>)<br><br>chunks = splitter.split_documents(documents)<br><br><br># -------------------------<br># Inspect chunks<br># -------------------------<br><br>for doc in chunks:<br>    print(doc.metadata)<br>    print(doc.page_content)<br>    print(&quot;---&quot;)<br><br><br># -------------------------<br># 3. Embeddings<br># -------------------------<br><br>embeddings = OllamaEmbeddings(<br>    model=&quot;nomic-embed-text&quot;<br>)<br><br><br># -------------------------<br># 4. Vector store<br># -------------------------<br><br>vector_store = InMemoryVectorStore(<br>    embedding=embeddings<br>)<br><br>vector_store.add_documents(chunks)<br><br><br># -------------------------<br># 5. Retriever<br># -------------------------<br><br>retriever = vector_store.as_retriever(<br>    search_kwargs={&quot;k&quot;: 2}<br>)<br><br><br># -------------------------<br># 6. Model<br># -------------------------<br><br>model = ChatOllama(<br>    model=&quot;llama3.2&quot;<br>)<br><br><br># -------------------------<br># 7. Prompt<br># -------------------------<br><br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>You are a company policy assistant.<br><br>Use only the context below.<br><br>If the answer is not in the context,<br>say that you do not have enough information.<br><br>Context:<br>{context}<br><br>Question:<br>{question}<br>&quot;&quot;&quot;)<br><br><br># -------------------------<br># 8. Chain<br># -------------------------<br><br>chain = prompt | model<br><br><br># -------------------------<br># 9. Ask question<br># -------------------------<br># Sample question<br>question = &quot;what is total annual leave?&quot;<br><br>results = retriever.invoke(question)<br><br>context = &quot;\n\n&quot;.join(<br>    doc.page_content<br>    for doc in results<br>)<br><br>response = chain.invoke({<br>    &quot;context&quot;: context,<br>    &quot;question&quot;: question<br>})<br><br><br>print(response.content)<br></pre><h4>20. But there’s something missing</h4><p>This example is good for understanding the architecture, but a real RAG system should usually do more than:</p><pre>retrieve → concatenate → ask LLM</pre><p>There are several areas you eventually need to improve:</p><pre>Document parsing<br>Chunking<br>Metadata<br>Retrieval quality<br>Query rewriting<br>Filtering<br>Reranking<br>Prompt design<br>Citations<br>Evaluation</pre><p>The current LangChain documentation explicitly treats retrieval as modular, and also describes more advanced architectures such as hybrid RAG, which can add query enhancement, retrieval validation, and answer validation.</p><p>We’ll get to these gradually.</p><h4>21. Metadata becomes very powerful</h4><p>Suppose you have:</p><pre>company_policy.pdf<br>HR_handbook.pdf<br>IT_security_policy.pdf<br>finance_policy.pdf</pre><p>Each chunk can carry:</p><pre>metadata={<br>    &quot;source&quot;: &quot;HR_handbook.pdf&quot;,<br>    &quot;department&quot;: &quot;HR&quot;,<br>    &quot;year&quot;: 2026<br>}</pre><p>Then your application can eventually filter retrieval.</p><p>For example:</p><pre>Question<br>   ↓<br>Only search HR documents<br>   ↓<br>Retrieve relevant chunks</pre><p>This is called <strong>metadata filtering</strong>.</p><h4>22. Retrieval is not just “search”</h4><p>There are different retrieval strategies.</p><p>The simplest:</p><pre>Question<br> ↓<br>Similarity search<br> ↓<br>Top-k chunks</pre><p>Later, you will encounter:</p><pre>Similarity search<br>Keyword search<br>Hybrid search<br>Metadata filtering<br>Reranking<br>Multi-query retrieval<br>Parent-document retrieval<br>Contextual compression</pre><p>Don’t worry about these yet.</p><p>Master basic similarity retrieval first.</p><h3>23. A very important RAG failure</h3><p>Consider:</p><pre>Document:<br>&quot;The employee receives 24 annual leave days.<br>Unused days expire at the end of the year.&quot;</pre><p>We split badly:</p><pre>Chunk 1:<br>The employee receives 24 annual leave days.<br>Chunk 2:<br>Unused days expire at the end of the year.</pre><p>Question:</p><pre>Do unused annual leave days expire?</pre><p>The retriever might find only Chunk 2.</p><p>That’s okay here.</p><p>But another question might depend on both pieces:</p><pre>How many days can an employee carry forward?</pre><p>If the relevant policy spans several chunks and retrieval returns only one, the answer may be incomplete.</p><p>That’s why <strong>chunking and retrieval quality are foundational</strong>.</p><h4>24. RAG does not mean “the LLM searches the database”</h4><p>This distinction is important.</p><p>Usually:</p><pre>Retriever<br>    ↓<br>Find relevant documents</pre><p>and:</p><pre>LLM<br>    ↓<br>Read retrieved context and generate answer</pre><p>are different components.</p><p>So:</p><pre>Retriever = finding information<br>LLM = using information</pre><h4>25. 2-Step RAG vs Agentic RAG</h4><p>The current LangChain documentation describes:</p><h3>2-Step RAG</h3><pre>Question<br> ↓<br>Retrieve<br> ↓<br>Generate</pre><p>This is simple and predictable.</p><h3>Agentic RAG</h3><pre>Question<br> ↓<br>Agent<br> ↓<br>&quot;Should I retrieve?&quot;<br> ↓<br>Tool<br> ↓<br>Model<br> ↓<br>Maybe another tool<br> ↓<br>Answer</pre><p>Agentic RAG gives the model more control but also makes execution more variable.</p><p>For learning, we’re using <strong><em>2-Step RAG</em></strong><em>.</em></p><h3>26. What should happen when the answer isn’t present?</h3><p>Remember your Lesson 9 exercise:</p><pre>Question:<br>What is the capital of France?</pre><p>But our documents only contain company policies.</p><p>A robust RAG application should not blindly invent:</p><pre>Paris</pre><p>Instead, your application should recognize:</p><pre>Retrieved context does not support this answer.</pre><p>and respond appropriately.</p><p>This gives us another important principle:</p><pre>RAG ≠ guaranteed factuality</pre><p>Retrieval improves grounding, but you still need good retrieval, prompts, and evaluation.</p><p>LangChain’s current retrieval material also points to evaluating correctness, relevance, groundedness, and retrieval quality as separate concerns.</p><h4>27. The most important debugging technique</h4><p>Whenever you build RAG, ask these questions in order:</p><pre>1. Did the document load correctly?<br>        ↓<br>2. Did the text split correctly?<br>        ↓<br>3. Did embeddings get created?<br>        ↓<br>4. Did the vector store contain the chunks?<br>        ↓<br>5. Did the retriever find the correct chunks?<br>        ↓<br>6. Did the prompt contain those chunks?<br>        ↓<br>7. Did the LLM use the context correctly?</pre><p>This prevents the classic mistake of saying:</p><blockquote><em>“The LLM gave a wrong answer, so the LLM is bad.”</em></blockquote><p><em>Maybe the LLM never received the relevant information.</em></p><h3>28. Your RAG mental model</h3><p>At this point, I want you to remember this picture:</p><pre>YOUR KNOWLEDGE<br>                │<br>                ▼<br>          Document Loader<br>                │<br>                ▼<br>             Chunks<br>                │<br>                ▼<br>          Embedding Model<br>                │<br>                ▼<br>           Vector Store<br>                │<br>                │<br>                │<br>USER ──► Question<br>                │<br>                ▼<br>            Retriever<br>                │<br>                ▼<br>        Relevant Chunks<br>                │<br>                ▼<br>             Prompt<br>                │<br>                ▼<br>               LLM<br>                │<br>                ▼<br>             Answer</pre><p>And the single most important relationship is:</p><pre>Retriever = FIND<br>LLM       = ANSWER</pre><h3>Next chapter — Lesson 11: Embeddings and Vector Similarity</h3><p>We’ll slow down and focus specifically on <strong>what embeddings really are</strong>, how a vector represents text, what <strong>similarity</strong> means, and why a retriever can find:</p><blockquote><em>“How many vacation days do I get?”</em></blockquote><p>when the document says:</p><blockquote><em>“Employees receive 24 annual leave days.”</em></blockquote><p>Once you understand embeddings properly, the entire RAG architecture becomes much easier to reason about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65c7fdcb7ecf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson 9 — RAG (Retrieval-Augmented Generation)]]></title>
            <link>https://medium.com/@md.wasim3/lesson-9-rag-retrieval-augmented-generation-b0c63a41b7a7?source=rss-4362f970560b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0c63a41b7a7</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[md wasim]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 02:46:01 GMT</pubDate>
            <atom:updated>2026-09-23T02:46:01.437Z</atom:updated>
            <content:encoded><![CDATA[<p>This is one of the most useful concepts in modern AI applications.</p><p>Until now, we have been asking the LLM questions using information it already knows.</p><p>With <strong>RAG</strong>, we give the application access to <strong>our own data</strong> and retrieve relevant information before asking the model to answer.</p><p>LangChain provides components for the major retrieval stages: transforming documents, creating embeddings, storing/searching them, and retrieving relevant content for generation. (<a href="https://aws.amazon.com/what-is/langchain/?utm_source=chatgpt.com">Amazon Web Services, Inc.</a>)</p><h4>1. The problem RAG solves</h4><p>Imagine you have this company document:</p><pre>Company Leave Policy<br>Employees receive 24 annual leave days.<br>Employees must request leave at least 3 days in advance.<br>Managers can approve emergency leave.</pre><p>Now ask:</p><pre>How many annual leave days do employees get?</pre><p>A normal LLM doesn’t automatically know your private company document.</p><p>You could put the entire document into the prompt:</p><pre>Here is the document:<br>...<br>Now answer:<br>How many annual leave days?</pre><p>But imagine you have:</p><pre>10,000 documents<br>100,000 documents<br>1,000,000 documents</pre><p>You cannot keep stuffing all of them into every prompt.</p><p>That’s where RAG comes in.</p><h4>2. What does RAG mean?</h4><p><strong>RAG = Retrieval-Augmented Generation</strong></p><p>Break the name apart:</p><h4>Retrieval</h4><p>Find the relevant information.</p><h4>Augmented</h4><p>Add that information to the model’s context.</p><h4>Generation</h4><p>Ask the LLM to generate the answer using that context.</p><p>So:</p><pre>User Question<br>      ↓<br>Retrieve relevant information<br>      ↓<br>Add information to prompt<br>      ↓<br>LLM<br>      ↓<br>Answer</pre><p>That’s RAG.</p><h4>3. The full RAG architecture</h4><p>The easiest architecture to remember is:</p><pre>YOUR DOCUMENTS<br>                      ↓<br>                 Load documents<br>                      ↓<br>                 Split into chunks<br>                      ↓<br>                   Embeddings<br>                      ↓<br>                 Vector Store<br>                      ↓<br>                ─────────────────<br>                     RUNTIME<br>                ─────────────────<br>                      ↑<br>                User Question<br>                      ↓<br>              Question embedding<br>                      ↓<br>                  Retriever<br>                      ↓<br>             Relevant chunks<br>                      ↓<br>                  Prompt<br>                      ↓<br>                    LLM<br>                      ↓<br>                   Answer</pre><p>There are really <strong>two phases</strong>:</p><pre>1. Prepare the data<br>2. Ask questions about the data</pre><p>This distinction is extremely important.</p><h4>4. Phase 1 — Prepare the documents</h4><p>Suppose our document is:</p><pre>ERP System Guide<br>ERP stands for Enterprise Resource Planning.<br>ERP systems integrate different business processes.<br>Common ERP modules include finance, inventory,<br>human resources, procurement, and sales.<br>ERP provides a centralized view of business data.</pre><p>We first need to load it.</p><h4>5. Step 1 — Document Loading</h4><p>LangChain represents loaded information using Document objects.</p><p>For learning, let’s create them ourselves:</p><pre>from langchain_core.documents import Document<br>documents = [<br>    Document(<br>        page_content=&quot;&quot;&quot;<br>        ERP stands for Enterprise Resource Planning.<br>        ERP systems integrate different business processes.<br>        &quot;&quot;&quot;<br>    ),<br>    Document(<br>        page_content=&quot;&quot;&quot;<br>        Common ERP modules include finance, inventory,<br>        human resources, procurement, and sales.<br>        &quot;&quot;&quot;<br>    ),<br>    Document(<br>        page_content=&quot;&quot;&quot;<br>        ERP provides a centralized view of business data.<br>        &quot;&quot;&quot;<br>    )<br>]</pre><p>Each Document contains text.</p><p>Conceptually:</p><pre>Document<br>├── page_content<br>└── metadata</pre><p>You can also attach metadata:</p><pre>Document(<br>    page_content=&quot;ERP integrates business processes.&quot;,<br>    metadata={<br>        &quot;source&quot;: &quot;erp_guide.txt&quot;,<br>        &quot;page&quot;: 1<br>    }<br>)</pre><p>Metadata becomes very useful later when you have hundreds or thousands of documents.</p><h4>6. Step 2 — Split documents into chunks</h4><p>This is one of the most important RAG concepts.</p><p>Suppose a document is 100 pages long.</p><p>We don’t usually create one giant embedding for the entire document.</p><p>Instead, we divide it into smaller pieces:</p><pre>Large Document<br>      ↓<br>Chunk 1<br>Chunk 2<br>Chunk 3<br>Chunk 4<br>...<br>Chunk 100</pre><p>Why?</p><p>Because when the user asks:</p><pre>What are common ERP modules?</pre><p>we want to retrieve the section:</p><pre>Finance<br>Inventory<br>HR<br>Procurement<br>Sales</pre><p>rather than retrieving an entire 100-page document.</p><h4>7. Chunking example</h4><p>We can use:</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter</pre><p>Then:</p><pre>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=200,<br>    chunk_overlap=50<br>)<br>chunks = splitter.split_documents(documents)</pre><p>roughly as:</p><blockquote><em>Keep each chunk around 200 characters.</em></blockquote><p>And:</p><pre>chunk_overlap = 50</pre><p>means neighboring chunks share some text.</p><p>For example:</p><pre>Chunk 1:<br>AAAA BBBB CCCC DDDD<br>Chunk 2:<br>CCCC DDDD EEEE FFFF</pre><p>The overlap helps avoid cutting useful information too sharply between chunks.</p><h4>8. Why not make chunks extremely small?</h4><p>Suppose we split this:</p><pre>ERP systems integrate finance, HR, inventory, and sales.</pre><p>into:</p><pre>ERP systems<br>integrate finance<br>HR<br>inventory<br>sales</pre><p>We lose relationships between the words.</p><p>A chunk should generally contain enough surrounding information to preserve meaning.</p><p>So chunking is a balance:</p><pre>Too small<br>→ missing context</pre><pre>Too large<br>→ retrieval becomes less precise</pre><p>There is no single chunk size that is correct for every dataset.</p><h4>9. Step 3 — Embeddings</h4><p>Now we reach a very important concept.</p><p>An <strong>embedding</strong> converts text into a numerical representation.</p><p>For example:</p><pre>&quot;ERP manages business processes&quot;</pre><p>might become conceptually:</p><pre>[0.12, -0.83, 0.44, 0.91, ...]</pre><p>Don’t focus on the exact numbers.</p><p>Think:</p><pre>Text<br> ↓<br>Embedding model<br> ↓<br>Vector</pre><p>The vector captures semantic relationships so that similar meanings can be compared mathematically.</p><p>For example:</p><pre>&quot;ERP manages inventory&quot;</pre><p>and:</p><pre>&quot;ERP helps companies control stock&quot;</pre><p>are semantically related even though the exact words are different.</p><h4>10. Create embeddings</h4><p>With OpenAI’s embedding integration:</p><pre>from langchain_openai import OpenAIEmbeddings<br>embeddings = OpenAIEmbeddings(<br>    model=&quot;text-embedding-3-small&quot;<br>)</pre><p>Now:</p><pre>Text<br> ↓<br>OpenAI Embeddings<br> ↓<br>Vector</pre><p>You normally don’t need to manually calculate the vector yourself. LangChain’s integration handles the model call.</p><h4>11. Step 4 — Store the vectors</h4><p>Now we need somewhere to store the chunks and their vectors.</p><p>That is the job of a <strong>vector store</strong>.</p><p>Conceptually:</p><pre>Chunk 1 → Vector 1<br>Chunk 2 → Vector 2<br>Chunk 3 → Vector 3<br>Chunk 4 → Vector 4</pre><p>You can use vector databases/stores such as:</p><pre>Chroma<br>FAISS<br>Pinecone<br>Qdrant<br>Weaviate<br>and others</pre><p>For learning, we’ll use an <em>in-memory vector</em> store so you don’t have to configure a database.</p><pre>from langchain_core.vectorstores import InMemoryVectorStore<br>vector_store = InMemoryVectorStore(embedding=embeddings)</pre><p>Then add the documents:</p><pre>vector_store.add_documents(chunks)</pre><p>Now our data is indexed.</p><h4>12. At this point, our preparation is finished</h4><p>We’ve done:</p><pre>Documents<br>   ↓<br>Chunks<br>   ↓<br>Embeddings<br>   ↓<br>Vector Store</pre><p>You can think of the vector store like a <strong>semantic search engine</strong>.</p><h4>13. Phase 2 — Ask a question</h4><p>Now the user asks:</p><pre>What modules are commonly included in ERP?</pre><p>We need to find the relevant chunks.</p><p>This is the <strong>retrieval</strong> part.</p><h4>14. Step 5 — Create a retriever</h4><p>We can turn the vector store into a retriever:</p><pre>retriever = vector_store.as_retriever(<br>    search_kwargs={&quot;k&quot;: 2}<br>)</pre><p>k=2 means:</p><blockquote><em>Retrieve approximately the top 2 relevant documents/chunks.</em></blockquote><p>Then:</p><pre>results = retriever.invoke(<br>    &quot;What modules are commonly included in ERP?&quot;<br>)</pre><p>Now results contains the relevant document chunks.</p><p>You could inspect them:</p><pre>for doc in results:<br>    print(doc.page_content)<br>    print(&quot;----&quot;)</pre><p>You might get:</p><pre>Common ERP modules include finance, inventory,<br>human resources, procurement, and sales.</pre><pre>----</pre><pre>ERP systems integrate different business processes.</pre><p>Notice what happened.</p><p>The retriever searched based on <strong>meaning</strong>, not merely exact keyword matching.</p><h4>15. This is the “R” in RAG</h4><p>We have:</p><pre>Question<br>   ↓<br>Retriever<br>   ↓<br>Relevant documents</pre><p>That’s:</p><p><strong>Retrieval</strong></p><h4>16. Step 6 — Augment the prompt</h4><p>Now we give those retrieved chunks to the LLM.</p><p>Create a prompt:</p><pre>from langchain_core.prompts import ChatPromptTemplate<br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>Answer the question using only the context below.<br>Context:<br>{context}<br>Question:<br>{question}<br>&quot;&quot;&quot;)</pre><p>Notice our two variables:</p><pre>{context}<br>{question}</pre><p>The context will contain the retrieved documents.</p><h4>17. Step 7 — Generate the answer</h4><p>Now we connect:</p><pre>Retriever<br> ↓<br>Prompt<br> ↓<br>Model</pre><p>For example:</p><pre>from langchain_ollama import ChatOllama, OllamaEmbeddings<br>model = ChatOllama(model=&quot;llama3.2&quot;)</pre><p>Then create a simple pipeline:</p><pre>chain = prompt | model</pre><p>For the retrieved documents, combine their text:</p><pre>context = &quot;\n\n&quot;.join(<br>    doc.page_content<br>    for doc in results<br>)</pre><p>Then:</p><pre>response = chain.invoke({<br>    &quot;context&quot;: context,<br>    &quot;question&quot;: &quot;What modules are commonly included in ERP?&quot;<br>})<br>print(response.content)</pre><p>The LLM sees something approximately like:</p><pre>System:<br>Answer using only the supplied context.</pre><pre>Context:<br>Common ERP modules include finance, inventory,<br>human resources, procurement, and sales.</pre><pre>ERP systems integrate different business processes.</pre><pre>Question:<br>What modules are commonly included in ERP?</pre><p>And produces:</p><pre>Common ERP modules include finance, inventory,<br>human resources, procurement, and sales.</pre><h4>18. Congratulations — that’s RAG</h4><p>We just created:</p><pre>DOCUMENTS<br>   ↓<br>CHUNKING<br>   ↓<br>EMBEDDINGS<br>   ↓<br>VECTOR STORE<br>   ↓<br>RETRIEVER<br>   ↓<br>RELEVANT CONTEXT<br>   ↓<br>PROMPT<br>   ↓<br>LLM<br>   ↓<br>ANSWER</pre><p>That is the fundamental RAG pipeline.</p><h3>19. Let’s combine everything</h3><p>Here’s a small complete example:</p><pre>from langchain_core.documents import Document<br>from langchain_core.vectorstores import InMemoryVectorStore<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_ollama import ChatOllama, OllamaEmbeddings<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br><br><br># --------------------------------<br># 1. Documents<br># --------------------------------<br><br>documents = [<br>    Document(<br>        page_content=&quot;&quot;&quot;<br>        ERP stands for Enterprise Resource Planning.<br>        ERP systems integrate different business processes.<br>        &quot;&quot;&quot;<br>    ),<br>    Document(<br>        page_content=&quot;&quot;&quot;<br>        Common ERP modules include finance, inventory,<br>        human resources, procurement, and sales.<br>        &quot;&quot;&quot;<br>    ),<br>    Document(<br>        page_content=&quot;&quot;&quot;<br>        ERP provides a centralized view of business data.<br>        &quot;&quot;&quot;<br>    )<br>]<br><br><br># --------------------------------<br># 2. Split documents<br># --------------------------------<br><br>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=200,<br>    chunk_overlap=50<br>)<br><br>chunks = splitter.split_documents(documents)<br><br><br># --------------------------------<br># 3. Create embeddings<br># --------------------------------<br><br>embeddings = OllamaEmbeddings(<br>    model=&quot;nomic-embed-text&quot;<br>)<br><br><br># --------------------------------<br># 4. Create vector store<br># --------------------------------<br><br>vector_store = InMemoryVectorStore(<br>    embedding=embeddings<br>)<br><br>vector_store.add_documents(chunks)<br><br><br># --------------------------------<br># 5. Create retriever<br># --------------------------------<br><br>retriever = vector_store.as_retriever(<br>    search_kwargs={&quot;k&quot;: 2}<br>)<br><br><br># --------------------------------<br># 6. Create LLM<br># --------------------------------<br><br>model = ChatOllama(<br>    model=&quot;llama3.2&quot;<br>)<br><br><br># --------------------------------<br># 7. Create prompt<br># --------------------------------<br><br>prompt = ChatPromptTemplate.from_template(&quot;&quot;&quot;<br>Answer the question using only the context below.<br><br>Context:<br>{context}<br><br>Question:<br>{question}<br>&quot;&quot;&quot;)<br><br><br># --------------------------------<br># 8. Create chain<br># --------------------------------<br><br>chain = prompt | model<br><br><br># --------------------------------<br># 9. Ask question<br># --------------------------------<br><br>question = &quot;What is ERP?&quot;<br><br>results = retriever.invoke(question)<br><br>context = &quot;\n\n&quot;.join(<br>    doc.page_content<br>    for doc in results<br>)<br><br>response = chain.invoke({<br>    &quot;context&quot;: context,<br>    &quot;question&quot;: question<br>})<br><br><br>print(response.content)<br></pre><h4>20. Understand what each component does</h4><p>This is probably the most important part of today’s lesson.</p><p>DocumentRepresents your source content</p><p>TextSplitterBreaks large content into chunks</p><p>EmbeddingsConverts text into numerical vectors</p><p>VectorStoreStores and searches those vectors</p><p>RetrieverFinds relevant chunks</p><p>PromptCombines question + retrieved context</p><p>LLMGenerates the final answer</p><p>Remember this sequence:</p><pre>Document<br>   ↓<br>Splitter<br>   ↓<br>Embedding<br>   ↓<br>Vector Store<br>   ↓<br>Retriever<br>   ↓<br>Prompt<br>   ↓<br>LLM</pre><h4>21. Embedding vs LLM — don’t confuse them</h4><p>This causes a lot of confusion.</p><h4>Embedding model</h4><p>Purpose:</p><pre>Text → Vector</pre><p>Used primarily for semantic search/retrieval.</p><h4>Chat model</h4><p>Purpose:</p><pre>Context + Question → Answer</pre><p>For example:</p><pre>OpenAIEmbeddings<br>      ↓<br>  similarity search</pre><p>while:</p><pre>ChatOpenAI<br>      ↓<br>   answer</pre><p>So:</p><pre>Embedding model ≠ Chat model</pre><p>They perform different jobs.</p><h4>22. What is a vector?</h4><p>A vector is simply a list of numbers.</p><p>Conceptually:</p><pre>&quot;ERP inventory management&quot;<br>          ↓<br>[0.21, -0.15, 0.72, 0.08, ...]</pre><p>Another sentence:</p><pre>&quot;ERP helps manage stock&quot;<br>          ↓<br>[0.19, -0.12, 0.69, 0.11, ...]</pre><p>Their vectors may be relatively close in vector space because their meanings are related.</p><p>The retriever uses this similarity to find relevant content.</p><p>You don’t need to learn the mathematical details yet.</p><p>For now:</p><blockquote><strong><em>Embedding = a numerical representation of the meaning of text.</em></strong></blockquote><h4>23. Why RAG can reduce hallucination</h4><p>Without retrieval:</p><pre>Question<br>   ↓<br>LLM&#39;s existing knowledge<br>   ↓<br>Answer</pre><p>With RAG:</p><pre>Question<br>   ↓<br>Your data<br>   ↓<br>Relevant context<br>   ↓<br>LLM<br>   ↓<br>Answer</pre><p>This gives the model information from your source material to work from.</p><p>But be careful:</p><p><strong><em>RAG does not guarantee a correct answer.</em></strong></p><p>Problems can still happen if:</p><pre>Wrong chunk retrieved<br>       ↓<br>LLM receives poor context<br>       ↓<br>Poor answer</pre><p>or:</p><pre>Good context<br>       ↓<br>LLM misunderstands it<br>       ↓<br>Incorrect answer</pre><p>That’s why production RAG systems need evaluation, good chunking, retrieval tuning, and often metadata/filtering.</p><h4>24. RAG vs Fine-Tuning</h4><p>Another very important distinction.</p><h4>RAG</h4><p>You give the model information <strong>at query time</strong>.</p><pre>Documents<br> ↓<br>Retrieve<br> ↓<br>Prompt<br> ↓<br>LLM</pre><h3>Fine-tuning</h3><p>You modify model behavior using training examples.</p><pre>Training examples<br> ↓<br>Fine-tuning<br> ↓<br>Modified model</pre><p>So if your goal is:</p><blockquote><em>“I have company documents and want the AI to answer questions about them.”</em></blockquote><p>RAG is a natural approach to learn first.</p><h4>25. Where PDFs fit</h4><p>Eventually you’ll want:</p><pre>PDF<br> ↓<br>PDF Loader<br> ↓<br>Documents<br> ↓<br>Chunks<br> ↓<br>Embeddings<br> ↓<br>Vector Store<br> ↓<br>Retriever<br> ↓<br>LLM</pre><p>For example:</p><pre>Employee_Handbook.pdf<br>        ↓<br>&quot;How many annual leave days?&quot;<br>        ↓<br>Retriever<br>        ↓<br>Relevant page/chunk<br>        ↓<br>LLM<br>        ↓<br>&quot;Employees receive 24 annual leave days.&quot;</pre><p>That’s essentially a <strong>Chat with PDF</strong> application.</p><p>We’ll build one later.</p><h4>26. RAG and Agents are different</h4><p>This is another common source of confusion.</p><h4>RAG</h4><p>The primary workflow is:</p><pre>Question<br> ↓<br>Retrieve documents<br> ↓<br>Answer</pre><h4>Agent</h4><p>The model decides what actions/tools it needs.</p><pre>Question<br> ↓<br>Agent<br> ↓<br>Tool?<br> ↓<br>Another tool?<br> ↓<br>Final answer</pre><p>You can combine them:</p><pre>Agent<br> ├── Calculator<br> ├── Database<br> ├── Web Search<br> └── RAG Retriever</pre><p>Then the agent can decide:</p><blockquote><em>“I need to search the company knowledge base.”</em></blockquote><p>and invoke the retriever as a tool.</p><p>That’s a much more advanced architecture.</p><h4>27. The most important RAG vocabulary</h4><p>Learn these terms well:</p><pre>Document<br>Chunk<br>Embedding<br>Vector<br>Vector Store<br>Retriever<br>Similarity Search<br>Context<br>RAG</pre><p>Here’s the translation:</p><pre>Document = original information<br><br>Chunk = small piece of a document<br><br>Embedding = numerical representation of text<br><br>Vector Store = storage/search system for vectors<br><br>Retriever = finds relevant chunks<br><br>Context = retrieved information given to the LLM<br><br>RAG = retrieve information + give it to LLM + generate answer</pre><h4>28. Your mental model</h4><p>At the beginning of this course:</p><pre>User<br> ↓<br>LLM<br> ↓<br>Answer</pre><p>Now:</p><pre>                   ┌──────────────┐<br>                   │ Your Data    │<br>                   └──────┬───────┘<br>                          ↓<br>                       Chunks<br>                          ↓<br>                      Embeddings<br>                          ↓<br>                    Vector Store<br>                          ↑<br>                          │<br>User Question → Retriever<br>                          │<br>                          ↓<br>                     Relevant Data<br>                          ↓<br>                       Prompt<br>                          ↓<br>                         LLM<br>                          ↓<br>                        Answer</pre><p>That is a major milestone in your LangChain journey.</p><h4>Where you are now</h4><pre>✅ Model<br>✅ Messages<br>✅ Prompt Templates<br>✅ Structured Output<br>✅ Chains<br>✅ Conversation History<br>✅ Tools<br>✅ Agents<br>✅ RAG fundamentals</pre><h3>Next chapter — Lesson 10: RAG in Practice</h3><p>We’ll make the RAG example much more realistic: <strong>load an actual document, split it properly, store metadata, retrieve the relevant chunks, and build a question-answering pipeline</strong>. We’ll also cover the parts that usually cause confusion: <strong>Document, </strong><strong>page_content, metadata, chunk size, chunk overlap, retriever </strong><strong>k, and why retrieval sometimes returns the wrong text</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0c63a41b7a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>