RAG Series (2): Building Your First RAG Pipeline with LangChain
WonderLab
·
2026-05-01
·
via DEV Community
<h2> From 100 Lines to a Production Pipeline </h2> <p>In the last article, we built a minimal RAG system in 100 lines of pure Python. It worked. It demonstrated the core idea. But if you tried to productionize that code, you'd quickly run into a wall.</p> <p><strong>Loading a PDF?</strong> You need <code>PyPDF2</code> or <code>pdfplumber</code>, and you'll discover that tables, headers, and footers are a nightmare to parse cleanly.</p> <p><strong>Splitting text?</strong> Your naive <code>text.split("\n\n")</code> will cut sentences in half, break code blocks, or create chunks so large they blow past the token limit.</p> <p><strong>Swapping the vector database?</strong> Say goodbye to your afternoon — every database has a different API, different distance metrics, different metadata handling.</p> <p><strong>Switching LLM providers?</strong> OpenAI's client, Anthropic's client, local models via <code>llama.cpp</code> — each has its own message format, its own token counting, its own error handling.</p> <p>This is exactly why <strong>LangChain</strong> exists. It doesn't do anything magical. It doesn't replace the underlying models or databases. What it does is simple and valuable: <strong>it gives you a uniform interface for plugging components together</strong>, so you can focus on the logic of your RAG system instead of the plumbing.</p> <p>In this article, we'll rebuild our RAG pipeline using LangChain's modern API. By the end, you'll have a complete, runnable project that loads PDFs, splits them intelligently, stores them in ChromaDB, and answers questions using a multi-provider LLM — with about 30 lines of actual pipeline code.</p> <blockquote> <p><strong>LangChain Version Note:</strong> The code in this article is based on <code>langchain 1.x</code> (current stable). LangChain 1.x performed a breaking reorganization of <code>0.3.x</code> — high-level APIs like <code>create_retrieval_chain</code> were removed. We use <strong>LCEL native syntax</strong> (<code>|</code> pipe operator) instead, which is functionally equivalent and version-agnostic. Full source code: <a href="https://github.com/chendongqi/llm-in-action/tree/main/02-langchain-basic" rel="noopener noreferrer">https://github.com/chendongqi/llm-in-action/tree/main/02-langchain-basic</a></p> </blockquote> <h2> The Six Moving Parts of a RAG Pipeline </h2> <p>LangChain decomposes RAG into six components. Understanding what each one does — and where the quality risks hide — is the key to debugging RAG systems later.</p> <div class="table-wrapper-paragraph"><table> <thead> <tr> <th>Component</th> <th>Role</th> <th>The Quality Risk</th> </tr> </thead> <tbody> <tr> <td><strong>Document Loader</strong></td> <td>Reads raw files (PDF, Word, Markdown, HTML) and extracts text</td> <td>Tables, images, and weird formatting get mangled</td> </tr> <tr> <td><strong>Text Splitter</strong></td> <td>Cuts long documents into semantically coherent chunks</td> <td>Chunks too large = low precision; too small = lost context</td> </tr> <tr> <td><strong>Embedding Model</strong></td> <td>Converts text chunks into high-dimensional vectors</td> <td>Poor model choice = semantically unrelated texts cluster together</td> </tr> <tr> <td><strong>Vector Store</strong></td> <td>Persists vectors and enables fast similarity search</td> <td>Wrong distance metric or no metadata filtering = bad retrieval</td> </tr> <tr> <td><strong>Retriever</strong></td> <td>Accepts a query, searches the vector store, returns relevant chunks</td> <td>Top-K too low = missing information; too high = noisy context</td> </tr> <tr> <td><strong>Chain</strong></td> <td>Orchestrates the full flow: query → retrieve → prompt → LLM → answer</td> <td>Prompt design and context assembly determine answer quality</td> </tr> </tbody> </table></div> <p>Think of these six components as an assembly line in a factory. The Document Loader is the raw material intake. The Text Splitter is the precision cutting station. The Embedding Model and Vector Store form the warehouse and inventory system. The Retriever is the picker who fetches the right parts. The Chain is the foreman who coordinates everything and delivers the final product.</p> <p>If any station on the line is misconfigured, the final product suffers — and the tricky part is that <strong>the failure often looks like an LLM problem when it's actually a retrieval problem</strong>.</p> <h2> Hands-On: A Complete LangChain RAG Project </h2> <p>Let's build it. We'll create a RAG system that reads a directory of PDF files, indexes them, and lets you ask questions in natural language.</p> <h3> Project Structure </h3> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>rag-project/ ├── requirements.txt ├── data/ │ └── sample.pdf # Your PDF documents go here └── rag_pipeline.py </code></pre> </div> <h3> Step 0: Dependencies </h3> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>langchain>=0.3.0 langchain-text-splitters>=0.3.0 langchain-openai>=0.2.0 langchain-chroma>=0.1.0 langchain-community>=0.3.0 pypdf>=4.0.0 python-dotenv>=1.0.0 </code></pre> </div> <blockquote> <p><strong>Full source code (ready to run):</strong> <a href="https://github.com/chendongqi/llm-in-action/tree/main/02-langchain-basic" rel="noopener noreferrer">https://github.com/chendongqi/llm-in-action/tree/main/02-langchain-basic</a><br> Supports Zhipu AI / OpenAI / Ollama for LLM, SiliconFlow and local Ollama for Embedding.</p> </blockquote> <p>Install them:<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight shell"><code>pip <span class="nb">install</span> <span class="nt">-r</span> requirements.txt </code></pre> </div> <p>Configure your API keys (copy <code>.env.example</code> to <code>.env</code>):<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight shell"><code><span class="nb">cp</span> .env.example .env <span class="c"># Edit .env to fill in LLM_API_KEY and EMBEDDING_API_KEY</span> </code></pre> </div> <p>Supported Providers:</p> <ul> <li> <strong>LLM</strong>: Zhipu AI (default), OpenAI, SiliconFlow, Ollama, Azure</li> <li> <strong>Embedding</strong>: SiliconFlow (default), OpenAI, Ollama</li> </ul> <h3> Step 1: Load Documents </h3> <p>The <code>PyPDFLoader</code> handles PDF parsing for us. It extracts text page by page and returns a list of <code>Document</code> objects, each containing the page content and metadata (page number, source file, etc.).<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight python"><code><span class="kn">from</span> <span class="n">langchain_community.document_loaders</span> <span class="kn">import</span> <span class="n">PyPDFLoader</span> <span class="kn">from</span> <span class="n">pathlib</span> <span class="kn">import</span> <span class="n">Path</span> <span class="k">def</span> <span class="nf">load_pdfs</span><span class="p">(</span><span class="n">data_dir</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="sh">"</span><span class="s">./data</span><span class="sh">"</span><span class="p">):</span> <span class="sh">"""</span><span class="s">Load all PDF files from the data directory.</span><span class="sh">"""</span> <span class="n">documents</span> <span class="o">=</span> <span class="p">[]</span> <span class="n">pdf_paths</span> <span class="o">=</span> <span class="nf">list</span><span class="p">(</span><span class="nc">Path</span><span class="p">(</span><span class="n">data_dir</span><span class="p">).</span><span class="nf">glob</span><span class="p">(</span><span class="sh">"</span><span class="s">*.pdf</span><span class="sh">"</span><span class="p">))</span> <span class="k">for</span> <span class="n">pdf_path</span> <span class="ow">in</span> <span class="n">pdf_paths</span><span class="p">:</span> <span class="n">loader</span> <span class="o">=</span> <span class="nc">PyPDFLoader</span><span class="p">(</span><span class="nf">str</span><span class="p">(</span><span class="n">pdf_path</span><span class="p">))</span> <span class="n">pages</span> <span class="o">=</span> <span class="n">loader</span><span class="p">.</span><span class="nf">load</span><span class="p">()</span> <span class="n">documents</span><span class="p">.</span><span class="nf">extend</span><span class="p">(</span><span class="n">pages</span><span class="p">)</span> <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Loaded </span><span class="sh">'</span><span class="si">{</span><span class="n">pdf_path</span><span class="p">.</span><span class="n">name</span><span class="si">}</span><span class="sh">'</span><span class="s">: </span><span class="si">{</span><span class="nf">len</span><span class="p">(</span><span class="n">pages</span><span class="p">)</span><span class="si">}</span><span class="s"> pages</span><span class="sh">"</span><span class="p">)</span> <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Total documents loaded: </span><span class="si">{</span><span class="nf">len</span><span class="p">(</span><span class="n">documents</span><span class="p">)</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span> <span class="k">return</span> <span class="n">documents</span> </code></pre> </div> <blockquote> <p><strong>Real-world note:</strong> PDFs are the wild west of document formats. If your PDFs contain scanned images, you'll need OCR (via <code>pdfplumber</code> with Tesseract or Azure Document Intelligence). If they contain tables, consider <code>UnstructuredPDFLoader</code> which preserves table structure better than raw text extraction.</p> </blockquote> <h3> Step 2: Split Documents into Chunks </h3> <p>Remember the chunking problem from Part 1? LangChain's <code>RecursiveCharacterTextSplitter</code> is the industry default for good reason. It tries to split on natural boundaries — paragraphs first, then newlines, then sentences, then words — so it avoids cutting mid-sentence whenever possible.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight python"><code><span class="kn">from</span> <span class="n">langchain_text_splitters</span> <span class="kn">import</span> <span class="n">RecursiveCharacterTextSplitter</span> <span class="k">def</span> <span class="nf">split_documents</span><span class="p">(</span><span class="n">documents</span><span class="p">,</span> <span class="n">chunk_size</span><span class="o">=</span><span class="mi">200</span><span class="p">,</span> <span class="n">chunk_overlap</span><span class="o">=</span><span class="mi">30</span><span class="p">):</span> <span class="sh">"""</span><span class="s"> Split documents into overlapping chunks. chunk_overlap ensures context continuity between adjacent chunks. </span><span class="sh">"""</span> <span class="n">splitter</span> <span class="o">=</span> <span class="nc">RecursiveCharacterTextSplitter</span><span class="p">(</span> <span class="n">chunk_size</span><span class="o">=</span><span class="n">chunk_size</span><span class="p">,</span> <span class="n">chunk_overlap</span><span class="o">=</span><span class="n">chunk_overlap</span><span class="p">,</span> <span class="n">length_function</span><span class="o">=</span><span class="nb">len</span><span class="p">,</span> <span class="n">separators</span><span class="o">=</span><span class="p">[</span><span class="sh">"</span><span class="se">\n\n</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="se">\n</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">. </span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s"> </span><span class="sh">"</span><span class="p">,</span> <span class="sh">""</span><span class="p">]</span> <span class="p">)</span> <span class="n">chunks</span> <span class="o">=</span> <span class="n">splitter</span><span class="p">.</span><span class="nf">split_documents</span><span class="p">(</span><span class="n">documents</span><span class="p">)</span> <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Split into </span><span class="si">{</span><span class="nf">len</span><span class="p">(</span><span class="n">chunks</span><span class="p">)</span><span class="si">}</span><span class="s"> chunks (chunk_size=</span><span class="si">{</span><span class="n">chunk_size</span><span class="si">}</span><span class="s">, overlap=</span><span class="si">{</span><span class="n">chunk_overlap</span><span class="si">}</span><span class="s">)</span><span class="sh">"</span><span class="p">)</span> <span class="k">return</span> <span class="n">chunks</span> </code></pre> </div> <p><strong>Why <code>chunk_overlap</code> matters:</strong> If a key concept spans two chunks — say, "The API rate limit is 100 requests per minute. Exceeding this limit returns a 429 status code" — an overlap of 50 characters ensures the second chunk still contains "100 requests per minute" as context. Without overlap, the retriever might fetch only one chunk and miss the causal relationship.</p> <p><strong>Chunk size trade-offs:</strong></p> <div class="table-wrapper-paragraph"><table> <thead> <tr> <th>Chunk Size</th> <th>Precision</th> <th>Context</th> <th>Best For</th> </tr> </thead> <tbody> <tr> <td>256 tokens</td> <td>High</td> <td>Minimal</td> <td>Fact lookup, Q&A over structured docs</td> </tr> <tr> <td>512 tokens</td> <td>Balanced</td> <td>Moderate</td> <td>General-purpose RAG (good default)</td> </tr> <tr> <td>1024 tokens</td> <td>Lower</td> <td>Rich</td> <td>Long-form summarization, narrative documents</td> </tr> <tr> <td>2048+ tokens</td> <td>Low</td> <td>Very rich</td> <td>Only when the LLM context window is large and queries are broad</td> </tr> </tbody> </table></div> <p>For most use cases, <strong>512 tokens with 50-token overlap</strong> is a safe starting point.</p> <h3> Step 3: Embed and Store in ChromaDB </h3> <p>Now we convert each chunk into a vector and store them. ChromaDB is our choice here because it's persistent (data survives restarts), supports metadata filtering, and requires zero setup — it runs locally as an embedded database.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight python"><code><span class="kn">from</span> <span class="n">langchain_openai</span> <span class="kn">import</span> <span class="n">OpenAIEmbeddings</span> <span class="kn">from</span> <span class="n">langchain_chroma</span> <span class="kn">import</span> <span class="n">Chroma</span> <span class="kn">import</span> <span class="n">os</span> <span class="n">persist_directory</span> <span class="o">=</span> <span class="sh">"</span><span class="s">./chroma_db</span><span class="sh">"</span> <span class="k">def</span> <span class="nf">build_vector_store</span><span class="p">(</span><span class="n">chunks</span><span class="p">):</span> <span class="sh">"""</span><span class="s">Create embeddings and store in ChromaDB.</span><span class="sh">"""</span> <span class="n">embeddings</span> <span class="o">=</span> <span class="nc">OpenAIEmbeddings</span><span class="p">(</span> <span class="n">model</span><span class="o">=</span><span class="sh">"</span><span class="s">BAAI/bge-large-zh-v1.5</span><span class="sh">"</span><span class="p">,</span> <span class="c1"># SiliconFlow Chinese model </span> <span class="n">api_key</span><span class="o">=</span><span class="n">os</span><span class="p">.</span><span class="nf">getenv</span><span class="p">(</span><span class="sh">"</span><span class="s">EMBEDDING_API_KEY</span><span class="sh">"</span><span class="p">),</span> <span class="n">base_url</span><span class="o">=</span><span class="sh">"</span><span class="s">https://api.siliconflow.cn/v1</span><span class="sh">"</span><span class="p">,</span> <span class="n">dimensions</span><span class="o">=</span><span class="mi">1024</span><span class="p">,</span> <span class="n">chunk_size</span><span class="o">=</span><span class="mi">32</span> <span class="c1"># SiliconFlow limit: max 32 per batch </span> <span class="p">)</span> <span class="k">if</span> <span class="n">os</span><span class="p">.</span><span class="n">path</span><span class="p">.</span><span class="nf">exists</span><span class="p">(</span><span class="n">persist_directory</span><span class="p">):</span> <span class="kn">import</span> <span class="n">shutil</span> <span class="n">shutil</span><span class="p">.</span><span class="nf">rmtree</span><span class="p">(</span><span class="n">persist_directory</span><span class="p">)</span> <span class="n">vector_store</span> <span class="o">=</span> <span class="n">Chroma</span><span class="p">.</span><span class="nf">from_documents</span><span class="p">(</span> <span class="n">documents</span><span class="o">=</span><span class="n">chunks</span><span class="p">,</span> <span class="n">embedding</span><span class="o">=</span><span class="n">embeddings</span><span class="p">,</span> <span class="n">persist_directory</span><span class="o">=</span><span class="n">persist_directory</span> <span class="p">)</span> <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Vector store built: </span><span class="si">{</span><span class="n">vector_store</span><span class="p">.</span><span class="n">_collection</span><span class="p">.</span><span class="nf">count</span><span class="p">()</span><span class="si">}</span><span class="s"> vectors persisted</span><span class="sh">"</span><span class="p">)</span> <span class="k">return</span> <span class="n">vector_store</span> </code></pre> </div> <p><strong>Embedding model note:</strong> We use <code>BAAI/bge-large-zh-v1.5</code> on SiliconFlow (excellent for Chinese). Access via the OpenAI-compatible interface in <code>langchain_openai</code>. Switch to <code>text-embedding-3-small</code> for OpenAI. The <code>chunk_size=32</code> parameter is critical — it's SiliconFlow's batch limit (max 32 per request), while most other providers default to 1000.</p> <h3> Step 4: Build the Retriever </h3> <p>The retriever is a thin wrapper around the vector store that handles the search logic. By default, it performs similarity search and returns the top-K most relevant chunks.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight python"><code><span class="k">def</span> <span class="nf">get_retriever</span><span class="p">(</span><span class="n">vector_store</span><span class="p">,</span> <span class="n">search_k</span><span class="o">=</span><span class="mi">4</span><span class="p">):</span> <span class="sh">"""</span><span class="s">Configure retriever with similarity search.</span><span class="sh">"""</span> <span class="n">retriever</span> <span class="o">=</span> <span class="n">vector_store</span><span class="p">.</span><span class="nf">as_retriever</span><span class="p">(</span> <span class="n">search_type</span><span class="o">=</span><span class="sh">"</span><span class="s">similarity</span><span class="sh">"</span><span class="p">,</span> <span class="n">search_kwargs</span><span class="o">=</span><span class="p">{</span><span class="sh">"</span><span class="s">k</span><span class="sh">"</span><span class="p">:</span> <span class="n">search_k</span><span class="p">}</span> <span class="p">)</span> <span class="k">return</span> <span class="n">retriever</span> </code></pre> </div> <h3> Step 5: Build the RAG Chain </h3> <p>Here's where LangChain's modern API shines. Instead of the older <code>RetrievalQA</code> class, we use <strong>LCEL</strong> (LangChain Expression Language) to compose a chain that is explicit, debuggable, and easy to modify.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight python"><code><span class="kn">from</span> <span class="n">langchain_openai</span> <span class="kn">import</span> <span class="n">ChatOpenAI</span> <span class="kn">from</span> <span class="n">langchain_core.prompts</span> <span class="kn">import</span> <span class="n">ChatPromptTemplate</span> <span class="kn">from</span> <span class="n">langchain_core.output_parsers</span> <span class="kn">import</span> <span class="n">StrOutputParser</span> <span class="kn">from</span> <span class="n">langchain_core.runnables</span> <span class="kn">import</span> <span class="n">RunnablePassthrough</span> <span class="k">def</span> <span class="nf">build_rag_chain</span><span class="p">(</span><span class="n">retriever</span><span class="p">):</span> <span class="sh">"""</span><span class="s"> Build the full RAG chain using LCEL (langchain 1.x compatible). retrieve → format_docs → assemble prompt → LLM → StrOutputParser </span><span class="sh">"""</span> <span class="n">llm</span> <span class="o">=</span> <span class="nc">ChatOpenAI</span><span class="p">(</span> <span class="n">model</span><span class="o">=</span><span class="sh">"</span><span class="s">glm-4-flash</span><span class="sh">"</span><span class="p">,</span> <span class="c1"># Zhipu AI, via SiliconFlow or direct </span> <span class="n">api_key</span><span class="o">=</span><span class="n">os</span><span class="p">.</span><span class="nf">getenv</span><span class="p">(</span><span class="sh">"</span><span class="s">LLM_API_KEY</span><span class="sh">"</span><span class="p">),</span> <span class="n">base_url</span><span class="o">=</span><span class="sh">"</span><span class="s">https://open.bigmodel.cn/api/paas/v4</span><span class="sh">"</span><span class="p">,</span> <span class="n">temperature</span><span class="o">=</span><span class="mi">0</span> <span class="p">)</span> <span class="c1"># System prompt. {context} filled by format_docs, {question} by the user's input. </span> <span class="n">system_prompt</span> <span class="o">=</span> <span class="p">(</span> <span class="sh">"</span><span class="s">You are a precise knowledge assistant. Answer the user</span><span class="sh">'</span><span class="s">s question </span><span class="sh">"</span> <span class="sh">"</span><span class="s">based solely on the provided reference content below. </span><span class="sh">"</span> <span class="sh">"</span><span class="s">If the reference content does not contain the answer, say so clearly </span><span class="sh">"</span> <span class="sh">"</span><span class="s">— do not make anything up.</span><span class="se">\n\n</span><span class="sh">"</span> <span class="sh">"</span><span class="s">Reference content:</span><span class="se">\n</span><span class="s">{context}</span><span class="sh">"</span> <span class="p">)</span> <span class="n">prompt</span> <span class="o">=</span> <span class="n">ChatPromptTemplate</span><span class="p">.</span><span class="nf">from_messages</span><span class="p">([</span> <span class="p">(</span><span class="sh">"</span><span class="s">system</span><span class="sh">"</span><span class="p">,</span> <span class="n">system_prompt</span><span class="p">),</span> <span class="p">(</span><span class="sh">"</span><span class="s">human</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">{question}</span><span class="sh">"</span><span class="p">)</span> <span class="p">])</span> <span class="c1"># Helper: convert Document list to a single string for {context} </span> <span class="k">def</span> <span class="nf">format_docs</span><span class="p">(</span><span class="n">docs</span><span class="p">:</span> <span class="nb">list</span><span class="p">)</span> <span class="o">-></span> <span class="nb">str</span><span class="p">:</span> <span class="k">return</span> <span class="sh">"</span><span class="se">\n\n</span><span class="sh">"</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="n">doc</span><span class="p">.</span><span class="n">page_content</span> <span class="k">for</span> <span class="n">doc</span> <span class="ow">in</span> <span class="n">docs</span><span class="p">)</span> <span class="c1"># LCEL Chain: compose components with the pipe operator </span> <span class="c1"># 1. {"context": retriever | format_docs, "question": RunnablePassthrough()} </span> <span class="c1"># → retriever fetches docs, format_docs converts them to a string </span> <span class="c1"># 2. | prompt → assembles into a full prompt </span> <span class="c1"># 3. | llm → generates the answer </span> <span class="c1"># 4. | StrOutputParser() → returns plain text (not an AIMessage object) </span> <span class="n">rag_chain</span> <span class="o">=</span> <span class="p">(</span> <span class="p">{</span> <span class="sh">"</span><span class="s">context</span><span class="sh">"</span><span class="p">:</span> <span class="n">retriever</span> <span class="o">|</span> <span class="n">format_docs</span><span class="p">,</span> <span class="sh">"</span><span class="s">question</span><span class="sh">"</span><span class="p">:</span> <span class="nc">RunnablePassthrough</span><span class="p">()</span> <span class="p">}</span> <span class="o">|</span> <span class="n">prompt</span> <span class="o">|</span> <span class="n">llm</span> <span class="o">|</span> <span class="nc">StrOutputParser</span><span class="p">()</span> <span class="p">)</span> <span class="k">return</span> <span class="n">rag_chain</span> </code></pre> </div> <p><strong>What's happening here?</strong> We're using <strong>LCEL</strong> (LangChain Expression Language) native syntax — the pipe <code>|</code> operator — instead of the high-level <code>create_retrieval_chain</code> (which was removed in langchain 1.x). The key line is <code>retriever | format_docs</code>: the retriever outputs a list of <code>Document</code> objects, <code>format_docs</code> converts them to a string that fills the <code>{context}</code> placeholder. <code>RunnablePassthrough()</code> passes the user's raw question through to the <code>{question}</code> placeholder. Three lines of declarative code that are functionally equivalent to the 50 lines of imperative Python from Part 1.</p> <h3> Step 6: Query the Pipeline </h3> <div class="highlight js-code-highlight"> <pre class="highlight python"><code><span class="k">def</span> <span class="nf">query</span><span class="p">(</span><span class="n">rag_chain</span><span class="p">,</span> <span class="n">question</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">retriever</span><span class="p">):</span> <span class="sh">"""</span><span class="s">Run a question through the RAG pipeline, print answer and sources.</span><span class="sh">"""</span> <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="se">\n</span><span class="s">Question: </span><span class="si">{</span><span class="n">question</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span> <span class="n">answer</span> <span class="o">=</span> <span class="n">rag_chain</span><span class="p">.</span><span class="nf">invoke</span><span class="p">(</span><span class="n">question</span><span class="p">)</span> <span class="c1"># LCEL chain returns plain text directly </span> <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="se">\n</span><span class="s">Answer:</span><span class="se">\n</span><span class="si">{</span><span class="n">answer</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span> <span class="c1"># Retrieve docs separately to show sources (rag_chain doesn't expose them) </span> <span class="n">docs</span> <span class="o">=</span> <span class="n">retriever</span><span class="p">.</span><span class="nf">invoke</span><span class="p">(</span><span class="n">question</span><span class="p">)</span> <span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="se">\n</span><span class="s">Retrieved sources:</span><span class="sh">"</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">doc</span> <span class="ow">in</span> <span class="nf">enumerate</span><span class="p">(</span><span class="n">docs</span><span class="p">,</span> <span class="mi">1</span><span class="p">):</span> <span class="n">source</span> <span class="o">=</span> <span class="n">doc</span><span class="p">.</span><span class="n">metadata</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="sh">"</span><span class="s">source</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">unknown</span><span class="sh">"</span><span class="p">)</span> <span class="n">page</span> <span class="o">=</span> <span class="n">doc</span><span class="p">.</span><span class="n">metadata</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="sh">"</span><span class="s">page</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">?</span><span class="sh">"</span><span class="p">)</span> <span class="n">preview</span> <span class="o">=</span> <span class="n">doc</span><span class="p">.</span><span class="n">page_content</span><span class="p">[:</span><span class="mi">120</span><span class="p">].</span><span class="nf">replace</span><span class="p">(</span><span class="sh">"</span><span class="se">\n</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s"> </span><span class="sh">"</span><span class="p">)</span> <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s"> [</span><span class="si">{</span><span class="n">i</span><span class="si">}</span><span class="s">] </span><span class="si">{</span><span class="n">source</span><span class="si">}</span><span class="s"> (page </span><span class="si">{</span><span class="n">page</span><span class="si">}</span><span class="s">): </span><span class="si">{</span><span class="n">preview</span><span class="si">}</span><span class="s">...</span><span class="sh">"</span><span class="p">)</span> <span class="k">return</span> <span class="n">answer</span> </code></pre> </div> <h3> Putting It All Together </h3> <div class="highlight js-code-highlight"> <pre class="highlight python"><code><span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="sh">"</span><span class="s">__main__</span><span class="sh">"</span><span class="p">:</span> <span class="c1"># 1. Load </span> <span class="n">docs</span> <span class="o">=</span> <span class="nf">load_pdfs</span><span class="p">(</span><span class="sh">"</span><span class="s">./data</span><span class="sh">"</span><span class="p">)</span> <span class="c1"># 2. Split (smaller chunk_size for short PDF pages) </span> <span class="n">chunks</span> <span class="o">=</span> <span class="nf">split_documents</span><span class="p">(</span><span class="n">docs</span><span class="p">,</span> <span class="n">chunk_size</span><span class="o">=</span><span class="mi">200</span><span class="p">,</span> <span class="n">chunk_overlap</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span> <span class="c1"># 3. Embed & Store </span> <span class="n">vector_store</span> <span class="o">=</span> <span class="nf">build_vector_store</span><span class="p">(</span><span class="n">chunks</span><span class="p">)</span> <span class="c1"># 4. Retrieve </span> <span class="n">retriever</span> <span class="o">=</span> <span class="nf">get_retriever</span><span class="p">(</span><span class="n">vector_store</span><span class="p">,</span> <span class="n">search_k</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span> <span class="c1"># 5. Build Chain (LCEL) </span> <span class="n">rag_chain</span> <span class="o">=</span> <span class="nf">build_rag_chain</span><span class="p">(</span><span class="n">retriever</span><span class="p">)</span> <span class="c1"># 6. Interactive Q&A </span> <span class="k">while</span> <span class="bp">True</span><span class="p">:</span> <span class="n">user_input</span> <span class="o">=</span> <span class="nf">input</span><span class="p">(</span><span class="sh">"</span><span class="se">\n</span><span class="s">Your question (quit to exit): </span><span class="sh">"</span><span class="p">).</span><span class="nf">strip</span><span class="p">()</span> <span class="k">if</span> <span class="n">user_input</span><span class="p">.</span><span class="nf">lower</span><span class="p">()</span> <span class="ow">in</span> <span class="p">(</span><span class="sh">"</span><span class="s">quit</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">exit</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">q</span><span class="sh">"</span><span class="p">):</span> <span class="k">break</span> <span class="k">if</span> <span class="n">user_input</span><span class="p">:</span> <span class="nf">query</span><span class="p">(</span><span class="n">rag_chain</span><span class="p">,</span> <span class="n">user_input</span><span class="p">,</span> <span class="n">retriever</span><span class="p">)</span> </code></pre> </div> <h2> Running the Pipeline </h2> <p>Place a PDF in <code>data/sample.pdf</code> and run:<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight shell"><code>python rag_pipeline.py </code></pre> </div> <p><strong>Sample output:</strong><br> </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>RAG Pipeline 启动 LLM Provider : zhipu LLM Model : glm-4-flash Embedding : openai / BAAI/bge-large-zh-v1.5 数据目录 : ./data 向量库 : ./chroma_db ================================================== 已加载 'Automotive-SPICE-PAM-v40.pdf':153 页 共加载 153 个文档片段 切分为 2000 个块(chunk_size=200,overlap=30) [Embedding] Provider: openai | Model: BAAI/bge-large-zh-v1.5 | Base: https://api.siliconflow.cn/v1 已清除旧向量库:./chroma_db 向量库构建完成:2000 个向量已持久化 ================================================== RAG Pipeline 构建完成!输入问题开始问答(输入 'quit' 退出) ================================================== 你的问题:What is Automotive SPICE? ================================================== 问题:What is Automotive SPICE? ================================================== 答案: Automotive SPICE(Automotive Software Process Improvement and Capability Determination)是一种用于评估和改进汽车软件 开发过程能力的框架。它定义了软件开发生命周期中的关键 过程域,并建立了过程能力的等级评估标准... 检索到的来源: [1] ./data/Automotive-SPICE-PAM-v40.pdf(第 5 页):Automotive SPICE Process Assessment Model The Process Assessment Model (PAM) defines the processes... </code></pre> </div> <p>Notice how the answer includes <strong>citations</strong> — we know exactly which pages the information came from. This traceability is critical for production RAG systems where users need to verify claims.</p> <h2> What Changed From Our 100-Line Version? </h2> <p>Let's compare the hand-written RAG from Part 1 with our LangChain pipeline:</p> <div class="table-wrapper-paragraph"><table> <thead> <tr> <th>Aspect</th> <th>Hand-written (Part 1)</th> <th>LangChain (Part 2)</th> </tr> </thead> <tbody> <tr> <td><strong>PDF loading</strong></td> <td>Not supported</td> <td>One-line <code>PyPDFLoader</code> </td> </tr> <tr> <td><strong>Text splitting</strong></td> <td>None (whole docs)</td> <td> <code>RecursiveCharacterTextSplitter</code> with smart boundaries</td> </tr> <tr> <td><strong>Vector persistence</strong></td> <td>In-memory only, lost on restart</td> <td>ChromaDB persists to disk</td> </tr> <tr> <td><strong>Embedding model swap</strong></td> <td>Rewrite API calls</td> <td>One-line parameter change</td> </tr> <tr> <td><strong>LLM swap</strong></td> <td>Rewrite client code</td> <td>One-line parameter change</td> </tr> <tr> <td><strong>Vector DB swap</strong></td> <td>Rewrite storage + search</td> <td>Swap <code>Chroma</code> for <code>Qdrant</code> / <code>Pinecone</code> </td> </tr> <tr> <td><strong>Prompt engineering</strong></td> <td>Raw string formatting</td> <td>Templated prompts with <code>ChatPromptTemplate</code> </td> </tr> <tr> <td><strong>Source citations</strong></td> <td>Manual tracking</td> <td>Automatic metadata propagation</td> </tr> <tr> <td><strong>Chain construction</strong></td> <td>Manual <code>retrieve + generate</code> </td> <td>LCEL `</td> </tr> <tr> <td><strong>Lines of pipeline code</strong></td> <td>~80</td> <td>~25</td> </tr> </tbody> </table></div> <p>The abstraction doesn't hide complexity — it <strong>isolates</strong> it.</p> <blockquote> <p><strong>LangChain Version Compatibility:</strong> The code in this article targets {% raw %}<code>langchain 1.x</code> (current stable). LangChain 1.x performed a breaking reorganization of <code>0.3.x</code> — <code>create_retrieval_chain</code> and <code>create_stuff_documents_chain</code> were removed. We use LCEL native syntax (<code>|</code> pipe operator) instead, which is functionally equivalent and version-agnostic. When you need to debug retrieval quality, you know exactly which component to tune. When you need to swap the embedding model for a cheaper alternative, you change one line. When your data grows beyond ChromaDB's capabilities, you switch to Qdrant without touching the rest of the pipeline.</p> </blockquote> <h2> Common Pitfalls at Each Stage </h2> <h3> Loader Pitfall: "My PDF has tables and they come out garbled" </h3> <p>Raw PDF text extraction flattens tables into a stream of numbers. For table-heavy documents, use <code>UnstructuredPDFLoader</code> or <code>AzureAIDocumentIntelligenceLoader</code> which preserves structural relationships.</p> <h3> Splitter Pitfall: "The answer is split across two chunks and the model only sees half" </h3> <p>Increase <code>chunk_overlap</code> to 100-150 tokens, or reduce <code>chunk_size</code> so that key concepts fit within a single chunk. Better yet, use <strong>Parent-Document Retrieval</strong> (covered in a later article) which retrieves small chunks but returns the full parent document for context.</p> <h3> Embedding Pitfall: "Questions and documents don't match even though they should" </h3> <p>This is the "asymmetric retrieval" problem. A user asks "How do I reset my password?" but the document says "To reset your password, navigate to Settings → Security." The question and the answer embed to different vectors because their surface text differs. Solutions: use a model fine-tuned for Q&A retrieval (like BGE-M3), or generate hypothetical answers for retrieval (HyDE — also covered later).</p> <h3> Retriever Pitfall: "Top-K=4 isn't enough for complex questions" </h3> <p>If a question requires synthesizing information from five different sections of a document, <code>k=4</code> will miss one. But increasing <code>k</code> blindly adds noise. A better approach: use <strong>Multi-Query Retrieval</strong> (generate 3 variants of the question, retrieve for each, deduplicate) or <strong>Reranking</strong> (retrieve 20, then use a cross-encoder to pick the best 5).</p> <h3> Chain Pitfall: "The model ignores the context and hallucinates" </h3> <p>Your prompt matters. The system prompt must explicitly instruct the model to use only the provided context. Adding "If the reference content does not contain the answer, say so clearly — do not make anything up" dramatically improves faithfulness. We'll measure this quantitatively with RAGAS in the evaluation articles.</p> <h2> Summary </h2> <p>In this article, we took the raw RAG concept from Part 1 and wrapped it in a production-ready framework. Here's what we covered:</p> <ol> <li> <strong>The six components</strong> of a LangChain RAG pipeline — Loader, Splitter, Embedding, Vector Store, Retriever, and Chain — and what quality risk hides in each one.</li> <li> <strong>A complete, runnable project</strong> that loads PDFs, splits them with <code>RecursiveCharacterTextSplitter</code>, embeds them with OpenAI, stores them in ChromaDB, and answers questions via a LangChain LCEL chain.</li> <li> <strong>The chunk size trade-off</strong> — in real projects, PDF pages may be very short (e.g., 200 chars). A <code>chunk_size=512</code> default can produce 0 chunks. 200 + 30 overlap is the safe default.</li> <li> <strong>Common pitfalls</strong> at each pipeline stage, from mangled PDF tables to asymmetric retrieval mismatches.</li> </ol> <p>The code in this article is a solid foundation. It handles real PDFs, persists data, and gives you source citations. But it's still a <strong>naive RAG</strong> pipeline — one query, one retrieval pass, one answer. In the next articles, we'll add the components that separate toy demos from production systems: hybrid search, reranking, query optimization, and evaluation frameworks.</p> <h2> References </h2> <ul> <li> <a href="https://python.langchain.com/docs/tutorials/rag/" rel="noopener noreferrer">LangChain RAG Tutorial</a> — Official LangChain RAG quickstart</li> <li> <a href="https://python.langchain.com/docs/concepts/lcel/" rel="noopener noreferrer">LangChain Expression Language (LCEL)</a> — Why and how to use LCEL for composable chains</li> <li> <a href="https://docs.trychroma.com/" rel="noopener noreferrer">ChromaDB Documentation</a> — Vector store setup, persistence, and querying</li> </ul>
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。