<?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 Pariv Shah on Medium]]></title>
        <description><![CDATA[Stories by Pariv Shah on Medium]]></description>
        <link>https://medium.com/@pariv.shah?source=rss-8f93b51293b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rK_JTx6T4Euxvq-eoCIVfQ.jpeg</url>
            <title>Stories by Pariv Shah on Medium</title>
            <link>https://medium.com/@pariv.shah?source=rss-8f93b51293b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:43:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pariv.shah/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[I Built a Hybrid RAG App That Talks to My PDF — and Knows When to Say “I Don’t Know”]]></title>
            <link>https://pub.towardsai.net/i-built-a-hybrid-rag-app-that-talks-to-my-pdf-and-knows-when-to-say-i-dont-know-5e4044a54921?source=rss-8f93b51293b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e4044a54921</guid>
            <category><![CDATA[hybrid-rag]]></category>
            <category><![CDATA[anti-hallucination]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Pariv Shah]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 00:01:02 GMT</pubDate>
            <atom:updated>2026-07-16T00:01:02.673Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LB_nxT_zozB2G_TKB0IHQ.png" /></figure><p>Imagine you upload an insurance policy PDF and ask:</p><p><em>“What is my wind/hail deductible?”</em></p><p>A good RAG system should find the exact clause and answer from it.</p><p>Now ask:</p><p><em>“What is the capital of France?”</em></p><p>A <em>confident</em> RAG system is dangerous here. The document has nothing about France. But a chatty LLM will happily invent an answer unless you stop it.</p><p>That tension — <strong>find the right passage</strong> and <strong>refuse when there is none</strong> — is what this article is about.</p><p>I built a full-stack <strong>Talk to your PDF</strong> app on my laptop: React UI, FastAPI backend, Ollama (llama3 + nomic-embed-text), ChromaDB, and <strong>BM25 reranking</strong>. The twist is hybrid retrieval plus a simple anti-hallucination gate, so out-of-scope questions get a polite decline instead of a confident guess.</p><h3>What is hybrid RAG, in plain English?</h3><p><strong>RAG</strong> means: find relevant pieces of your documents, then ask an LLM to answer using those pieces.</p><p><strong>Hybrid RAG</strong> means: do not rely on only one way of finding those pieces.</p><p>Think of searching a library two ways at once:</p><ol><li><strong>Semantic search (vectors)</strong> — “find sections that <em>mean</em> something like my question”</li><li><strong>Keyword search (BM25)</strong> — “find sections that contain the <em>exact words</em> I care about”</li></ol><p>Semantic search is great when you ask about “storm damage” and the policy says “wind/hail.” Keyword search is great when you need the word deductible, a section number, or a precise policy term.</p><p>Hybrid RAG uses both strengths. In this article, that looks like:</p><ol><li>Cast a wide semantic net (top 20 chunks from <strong>ChromaDB</strong>)</li><li>Re-rank those candidates with <strong>BM25</strong></li><li>Send only the best few (top 4) to the <strong>LLM</strong></li></ol><p>Meaning finds the neighborhood. Exact terms pick the right house.</p><h3>What is anti-hallucination, in plain English?</h3><p><strong>Hallucination</strong> is when an AI answers with confidence even though it does not actually know — or when the answer is not supported by your document.</p><p><strong>Anti-hallucination</strong> is the set of guardrails that reduce that behavior.</p><p>In plain English: it is how you teach the system to say <em>“I don’t know from this document”</em> instead of making something up.</p><p>In this app, anti-hallucination is not one magic trick. It is three simple layers:</p><ol><li><strong>Retrieval gate</strong> — if the best retrieved chunks look weakly related (by semantic distance and BM25 score), refuse <em>before</em> calling the LLM</li><li><strong>Strict prompt</strong> — tell the model to answer only from the excerpts, and to say it cannot answer otherwise</li><li><strong>Post-check</strong> — if the model still replies with “cannot answer,” mark the response as refused</li></ol><p>You still see source excerpts in the UI. That matters. Trust comes from evidence, not from a fluent paragraph.</p><h3>Why I cared about this</h3><p>Earlier local RAG experiments taught me the basic loop: ingest → chunk → embed → retrieve → generate.</p><p>That loop works. But two practical problems kept showing up with real policy-style documents:</p><ol><li><strong>Semantic-only retrieval missed exact terms.</strong> Questions about deductibles, exclusions, and section numbers needed keyword precision.</li><li><strong>Small models love to fill gaps.</strong> If retrieval was weak, the LLM still tried to sound helpful.</li></ol><p>So I built a demo that feels closer to a real product:</p><ul><li>Upload a PDF in the browser</li><li>Ask questions in a chat-style UI</li><li>See grounded answers with source snippets</li><li>Watch out-of-scope questions get declined</li></ul><p>Still fully local. Still no API keys.</p><h3>A real example: hybrid retrieval in action</h3><p>Suppose your policy PDF contains something like:</p><pre>Section 4.2 — Wind/Hail Deductible<br>For losses caused by windstorm or hail, a separate deductible of $2,500 applies.<br>This deductible is independent of the standard all-peril deductible in Section 3.1.<br>Mold remediation is excluded except where resulting from a covered water peril.</pre><p><strong>Question A:</strong> <em>“What is my wind/hail deductible?”</em></p><ul><li>Semantic search finds conceptually related coverage sections</li><li>BM25 boosts chunks that literally contain wind, hail, and deductible</li><li>Llama 3 answers from the top excerpts: <strong>$2,500</strong>, with the section context</li></ul><p><strong>Question B:</strong> <em>“What is the capital of France?”</em></p><ul><li>Retrieved chunks are about insurance language, not geography</li><li>Relevance scores fail the gate</li><li>The app refuses without inventing Paris — or pretending the policy somehow mentioned it</li></ul><p>That second case is the demo moment I care about most. A RAG demo that only answers in-document questions is incomplete. A RAG demo that <strong>declines</strong> out-of-scope questions is teaching the right instinct.</p><h3>What changed in this project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rM-9PRkERi_DEPl5855Cug.png" /></figure><p>The big idea is not “more models.” It is <strong>better retrieval + clearer refusal</strong>.</p><h3>Two search methods, one pipeline</h3><h3>1. Semantic search — ChromaDB + nomic-embed-text</h3><p>The embedding model turns each chunk (and your question) into a vector. ChromaDB finds the nearest neighbors by meaning.</p><p>This is how <em>“storm damage”</em> can still find <em>“wind/hail”</em> language.</p><h3>2. BM25 re-rank — exact-term boost</h3><p>BM25 is a classic keyword ranking method. It rewards chunks that contain the query terms, with sensible weighting for term rarity and document length.</p><p>In policy documents, that helps questions like:</p><ul><li>“mold coverage”</li><li>“Section 4.2”</li><li>“wind/hail deductible”</li></ul><h3>3. Why retrieve-then-rerank?</h3><p>I used a simple pattern:</p><pre>Question<br>  → embed<br>  → semantic top-20 candidates<br>  → BM25 rerank<br>  → top-4 chunks<br>  → anti-hallucination gate<br>  → llama3 answer (or polite refusal)</pre><p>Semantic search casts a wide net. BM25 chooses the best fish. The LLM only sees a short, high-signal context window.</p><p>You can disable reranking (use_rerank: false / --no-rerank) to compare quality side by side. That comparison alone is a useful learning exercise.</p><h3>The architecture I built</h3><p>I kept the RAG core small and wrapped it with a web API and React frontend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*edbXiEVPavWofqS0orkA0Q.png" /></figure><h4><strong>Component roles</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5wiT4f83o__JuvERfU4sw.png" /></figure><p>Everything runs on one machine. No Docker required for the demo. No documents leave your laptop.</p><h3>How the pipeline works</h3><h3>Step 1: Upload and ingest</h3><p>PDF → extract text → recursive chunk (~500 chars, 50 overlap) → embed → store in ChromaDB → rebuild BM25 index</p><p>From the UI, this is a drag-and-drop upload. Under the hood, FastAPI calls the same ingest path the CLI uses.</p><h3>Step 2: Ask an in-document question</h3><p>Question → semantic candidates → BM25 rerank → relevance gate passes → Llama 3 answers from excerpts → UI shows answer + source snippets (semantic rank, BM25 score, distance)</p><h3>Step 3: Ask an out-of-scope question</h3><p>Same retrieval path — but the gate fails. The API returns a refusal message and marks refused: true. No invented facts. No fake confidence.</p><h3>Step 4: Inspect sources</h3><p>Every answer (and many refusals) can show the chunks that were considered. That is how you debug RAG honestly: look at what was retrieved before blaming the model.</p><h3>The core code</h3><h4>Hybrid retrieve-then-rerank</h4><pre>def retrieve(question, store, bm25, *, top_k=4, use_rerank=True):<br>    candidates = store.query(question, top_k=20)<br>    if not candidates:<br>        return []<br><br>if not use_rerank:<br>        return candidates[:top_k]<br>    return bm25.rerank(question, candidates, top_k=top_k)</pre><p>Wide semantic recall first. Precise keyword ordering second.</p><h4>Anti-hallucination relevance gate</h4><pre>def assess_relevance(chunks):<br>    if not chunks:<br>        return False, REFUSAL_MESSAGE<br>best_distance = min(chunk[&quot;distance&quot;] for chunk in chunks)<br>    if best_distance &lt;= STRONG_SEMANTIC_DISTANCE:<br>        return True, &quot;&quot;<br>    if best_distance &gt; MAX_SEMANTIC_DISTANCE:<br>        return False, REFUSAL_MESSAGE<br>    best_bm25 = max(<br>        (chunk.get(&quot;bm25_score&quot;) or 0.0) for chunk in chunks<br>    )<br>    if best_bm25 &lt; MIN_BM25_SCORE:<br>        return False, REFUSAL_MESSAGE<br>    return True, &quot;&quot;</pre><p>If retrieval looks strong, proceed. If it looks off-topic, refuse early. If it is borderline, require some keyword overlap before trusting the LLM.</p><h4>Strict generation prompt</h4><pre>SYSTEM_PROMPT = &quot;&quot;&quot;You are a document Q&amp;A assistant.<br>Answer questions using ONLY the provided document excerpts.<br>If the answer is not stated in the excerpts, respond with exactly:<br>&quot;I cannot answer that based on the document.&quot;<br>Do not use outside knowledge. Do not guess or invent facts.<br>&quot;&quot;&quot;</pre><p>Prompting alone is not enough. Combined with the retrieval gate, it becomes a practical safety net for a local demo.</p><h4>Tunable knobs in one place</h4><pre>LLM_MODEL = &quot;llama3&quot;<br>EMBED_MODEL = &quot;nomic-embed-text&quot;<br>CHUNK_SIZE = 500<br>CHUNK_OVERLAP = 50<br>RETRIEVAL_CANDIDATES = 20<br>TOP_K = 4<br>STRONG_SEMANTIC_DISTANCE = 280<br>MAX_SEMANTIC_DISTANCE = 450<br>MIN_BM25_SCORE = 0.5</pre><p>Tighten the distance thresholds if you want fewer hallucinations and more refusals. Loosen them if you want fewer false declines on paraphrased questions.</p><h3>What the app looks like to use</h3><h4>Web demo</h4><ol><li>Start the API: uvicorn api.main:app --reload --port 8000</li><li>Start the UI: npm run dev in frontend/</li><li>Open <a href="http://localhost:5173/">http://localhost:5173</a></li><li>Upload data/sample-policy.pdf</li><li>Ask 2–3 in-document questions</li><li>Ask one out-of-scope question and watch it decline</li></ol><h4>CLI (still useful for debugging)</h4><pre>python main.py ingest data/sample-policy.pdf<br>python main.py ask &quot;What is my wind/hail deductible?&quot; --show-sources<br>python main.py search &quot;mold coverage&quot; --no-rerank<br>python main.py status</pre><p>I kept the CLI because retrieval debugging is faster in the terminal. The React UI is for the product story. Both share the same core services.</p><h3>Project structure</h3><pre>hybrid-rag-pdf/<br>├── api/                      # FastAPI REST layer<br>│   ├── main.py<br>│   └── schemas.py<br>├── frontend/                 # React + Vite SPA<br>├── rag/<br>│   ├── config.py             # models, chunking, retrieval thresholds<br>│   ├── chunker.py            # recursive splitting + overlap<br>│   ├── document_loader.py    # PDF/TXT loading<br>│   ├── embedder.py           # Ollama embeddings<br>│   ├── vector_store.py       # ChromaDB<br>│   ├── bm25_index.py         # build, persist, rerank<br>│   ├── retriever.py          # semantic + BM25 orchestration<br>│   ├── anti_hallucination.py # relevance gate<br>│   ├── query.py              # prompt + generate + sources<br>│   └── services/<br>│       ├── ingest_service.py<br>│       └── chat_service.py<br>├── main.py                   # CLI<br>├── data/sample-policy.pdf<br>└── docs/architecture.md</pre><p>Clear layers made the project easier to explain — and easier to extend later.</p><h3>What I noticed while building this</h3><p><strong>BM25 is surprisingly useful on policy language.</strong> Exact terms matter. Vector search alone often got “close enough.” Reranking made “exactly right” more common.</p><p><strong>Refusal is a feature, not a failure.</strong> Early versions of RAG demos feel broken when they say “I cannot answer.” For document Q&amp;A, that is often the correct product behavior.</p><p><strong>Sources make the demo trustworthy.</strong> Showing excerpts, ranks, and scores turns a black-box answer into something a reader can verify in seconds.</p><p><strong>Llama 3 raised answer quality</strong>, but retrieval and gating still did the heavy lifting. A stronger model on weak context is still a confident storyteller.</p><p><strong>A web UI changes how people understand RAG.</strong> Watching upload → ask → grounded answer → refusal is more memorable than reading CLI output.</p><h3>Who is this for?</h3><p>This kind of project is great if you are:</p><ul><li>Learning <strong>hybrid retrieval</strong> (semantic + BM25) with a real demo</li><li>Building a <strong>Talk to your PDF</strong> experience on a laptop</li><li>Exploring <strong>anti-hallucination</strong> as practical engineering, not buzzwords</li><li>Preparing for interviews where RAG architecture and grounding come up</li><li>Looking for a local stack: Python, React, Ollama, ChromaDB</li></ul><p>You do not need a GPU farm. You need Python, Node.js, Ollama, and one text-based PDF.</p><h3>What is next?</h3><p>Natural extensions from here:</p><ul><li><strong>Conversation memory</strong> — follow-up questions across turns</li><li><strong>Streaming answers</strong> — token-by-token responses in the UI</li><li><strong>Stronger re-rankers</strong> — cross-encoders when keyword boost is not enough</li><li><strong>OCR for scanned PDFs</strong> — so image-only policies work too</li><li><strong>Eval harness</strong> — a golden Q&amp;A set that measures grounded answers <em>and</em> correct refusals</li></ul><p>Even without those upgrades, the current demo already teaches the lesson I wanted: <strong>good RAG is retrieval quality plus the courage to refuse.</strong></p><h3>Final thought</h3><p>Vector search finds meaning. Keyword search finds precision. Together they make retrieval sharper.</p><p>But the quiet hero of this project is the refusal path.</p><p>Anyone can build a chatbot that always answers. The more interesting system is the one that answers from your PDF when the evidence is there — and says <em>“I cannot answer that based on the document”</em> when it is not.</p><p>If you try this yourself, do one complete loop:</p><ol><li>Upload one policy PDF</li><li>Ask one question you know is in the document</li><li>Read the source excerpts</li><li>Ask one question that is clearly outside the document</li><li>Confirm it declines</li></ol><p>That five-minute exercise teaches more about trustworthy RAG than another hour of model shopping.</p><p>You can download the complete source code from GitHub: <a href="https://github.com/parivshah/hybrid-rag-pdf">https://github.com/parivshah/hybrid-rag-pdf</a></p><p>The repository includes setup instructions, architecture notes, a sample policy PDF, and both the web demo and CLI. Please let me know if you liked this article or have any questions, feedback, or suggestions. You can connect with me on <a href="https://www.linkedin.com/in/pariv-shah/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e4044a54921" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/i-built-a-hybrid-rag-app-that-talks-to-my-pdf-and-knows-when-to-say-i-dont-know-5e4044a54921">I Built a Hybrid RAG App That Talks to My PDF — and Knows When to Say “I Don’t Know”</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Exposed My Local RAG as MCP Tools in Cursor — Now I Query My Private PDFs Without Leaving the IDE]]></title>
            <link>https://pub.towardsai.net/i-exposed-my-local-rag-as-mcp-tools-in-cursor-now-i-query-my-private-pdfs-without-leaving-the-ide-41af4bbd0f91?source=rss-8f93b51293b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/41af4bbd0f91</guid>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Pariv Shah]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 13:39:56 GMT</pubDate>
            <atom:updated>2026-06-16T07:52:29.664Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0b58WfxsekSLW6xfhloIg.png" /></figure><p>Across my first two articles, I built a fully local RAG pipeline on my laptop — <strong>Ollama</strong>, <strong>ChromaDB</strong>, and <strong>TinyLlama </strong>for private PDF Q&amp;A — then improved how documents are split by moving from fixed-size chunking to recursive chunking with overlap.</p><p>Both projects worked well from the terminal. I could ingest a document and ask questions. But I kept running into the same friction:</p><p>I had to leave my editor, open a terminal, copy questions back and forth, and remember which commands to run.</p><p>That led me to my next experiment: expose the same RAG pipeline as an <strong>MCP server</strong> so Cursor can query my private documents as tools — while also trying a different local embedding model, <strong>all-MiniLM-L6-v2</strong>, instead of Ollama for search vectors.</p><p>This article is about what I built, how MCP fits in, and what changed when embeddings moved from Ollama to sentence-transformers.</p><h3>What is MCP, in plain English?</h3><p><strong>MCP</strong> stands for Model Context Protocol.</p><p>Think of it like a standard plug for AI tools. Instead of every app inventing its own way to call your code, MCP gives assistants like Cursor a consistent way to discover and invoke <strong>tools</strong> you define — search a database, read a file, call your RAG pipeline.</p><p>For this project, MCP is the bridge between:</p><ul><li><strong>Cursor chat</strong> — where you ask questions in natural language</li><li><strong>Your local RAG code</strong> — ingest, search, and answer from your own indexed PDFs</li></ul><p>You still own the data. It still runs on your machine. Cursor just gets a clean way to call it.</p><h3>Why I cared about this</h3><p>My earlier RAG demos were CLI-first. That is great for learning. It is less great when you are already inside an IDE and want answers from an internal PDF without context switching.</p><p>I wanted three things:</p><ol><li><strong>Keep everything local</strong> — no cloud API, no documents leaving my laptop</li><li><strong>Reuse my RAG logic</strong> — not a rewrite, just a new entry point</li><li><strong>Learn MCP hands-on</strong> — a practical step toward agent-style workflows</li></ol><p>So I built a third project that adds:</p><ul><li>A shared <strong>service layer</strong> (rag/service.py) used by both CLI and MCP</li><li>An <strong>MCP server</strong> (mcp_server.py) with three tools</li><li><strong>MiniLM embeddings</strong> via Hugging Face instead of Ollama nomic-embed-text</li></ul><p>Same recursive chunking. Same ChromaDB. Same llama3 for answers. New interfaces and a new embedding path.</p><h3>What changed from my earlier RAG projects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*pf_Kt4G365GzeOj32vTxlg.png" /></figure><p><strong>Important:</strong> do not reuse an old .chroma/ folder when you switch embedding models. Different models produce different vector sizes. Mixing them breaks search.</p><h3>Two models, two jobs (plus MCP)</h3><p>A common point of confusion in RAG: you usually need <strong>more than one model</strong>.</p><h4>1. Embedding model — all-MiniLM-L6-v2</h4><p>This model does not write answers. It converts text into numbers (vectors) that capture meaning.</p><p>In my first two projects, I pulled embeddings through Ollama. Here I use <strong>sentence-transformers</strong> instead:</p><ul><li>Downloads once from Hugging Face (~80 MB)</li><li>Runs locally in Python — no Ollama needed for ingest or search</li><li>Produces <strong>384-dimensional</strong> vectors</li><li>Fast on CPU for learning-sized documents</li></ul><p>When you ask <em>“What is the MFA policy?”</em> and your document says <em>“Multi-Factor Authentication must be configured before access is granted”</em>, the embedding model helps the system understand those are related — even when the words differ.</p><h4>2. Chat model — llama3 (Ollama)</h4><p>llama3 is ~8B parameters. It is not GPT-4. For learning and simple Q&amp;A on your own docs, it is enough.</p><p>It is used only when you want a <strong>written answer</strong> — CLI ask or MCP ask_documents.</p><h4>3. MCP tools — the new interface</h4><p>Instead of typing terminal commands, Cursor can call:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEIa1_RFjWFhc_qS71yEaQ.png" /></figure><p>That split matters. <strong>Search</strong> is fast and great for debugging retrieval. <strong>Ask</strong> adds the LLM on top.</p><h3>A real example: search vs ask</h3><p>Suppose I indexed an internal monthly expense PDF and asked:</p><p><em>“What is highest expense in month of March-2026?”</em></p><p><strong>Step 1 — </strong><strong>search_documents (retrieval only)</strong></p><p>The tool returns the top chunks with source file, chunk index, and a short excerpt. I can verify retrieval found the right section — without trusting an LLM summary.</p><p><strong>Step 2 — </strong><strong>ask_documents (full RAG)</strong></p><p>The same question goes through retrieval, then llama3 writes an answer grounded in those chunks. I also get source excerpts so I can spot when the small model adds extra detail not in the text.</p><p>That workflow taught me something my earlier CLI-only projects did not surface as clearly: <strong>always look at retrieved chunks before blaming the model.</strong></p><h3>The architecture I built</h3><p>I kept the pipeline small and added a shared service layer plus MCP on top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ITA8vY_m7LXUiRHyVw7Cg.png" /></figure><h3>How the pipeline works</h3><h3>Step 1: Ingest a document (CLI)</h3><p>Document (.txt or .pdf) → extract text → recursive split with overlap → MiniLM embed → store in ChromaDB</p><p>I use ~500-character chunks with 50-character overlap — same tuning as my chunking article. First ingest downloads MiniLM automatically.</p><p>Ollama is <strong>not</strong> required for this step.</p><h3>Step 2: Preview or search (optional, no LLM)</h3><p><strong>Preview:</strong> see how a file splits before embedding anything</p><pre>python main.py preview data/monthly-expense-data.pdf</pre><p><strong>Search:</strong> test retrieval without calling llama3.</p><pre>python main.py search &quot;What is a total expense in a month of March- 2026?&quot;</pre><p>From Cursor, the same idea is:</p><pre>Use search_documents &quot;Give me highest expense in month of January?&quot;</pre><h3>Step 3: Ask a question (CLI or MCP)</h3><p>Question → MiniLM embed → top-K similarity search → prompt llama3 → answer + sources</p><p>CLI:</p><pre>python main.py ask &quot;What MCP tools are available?&quot; --show-sources</pre><p>Cursor:</p><pre>Use ask_documents: &quot;What MCP tools are available?&quot;</pre><h3>Step 4: Connect MCP in Cursor</h3><ol><li>Ingest at least one document via CLI first</li><li>Add the server to ~/.cursor/mcp.json</li><li>Restart Cursor</li><li>Call rag_status, search_documents, or ask_documents from chat</li></ol><h3>The Core Code</h3><h4>Embeddings with MiniLM</h4><p>The main embedding change is in rag/embedder.py:</p><pre>from sentence_transformers import SentenceTransformer<br><br>from rag.config import EMBED_MODEL<br>_model = None<br>def _get_model() -&gt; SentenceTransformer:<br>    global _model<br>    if _model is None:<br>        _model = SentenceTransformer(EMBED_MODEL)<br>    return _model<br>def embed_texts(texts: list[str]) -&gt; list[list[float]]:<br>    if not texts:<br>        return []<br>    model = _get_model()<br>    vectors = model.encode(texts, convert_to_numpy=True, show_progress_bar=False)<br>    return vectors.tolist()</pre><p>Model name and chunk settings live in one place — rag/config.py:</p><pre>EMBED_MODEL = &quot;all-MiniLM-L6-v2&quot;<br>LLM_MODEL = &quot;llama3&quot;<br>CHUNK_SIZE = 500<br>CHUNK_OVERLAP = 50<br>TOP_K = 4</pre><h3>MCP tools with FastMCP</h3><p>The MCP server reuses the same service functions as the CLI:</p><pre>from mcp.server.fastmcp import FastMCP<br>from rag import service<br><br>mcp = FastMCP(&quot;local-rag-mcp-minilm&quot;)<br>@mcp.tool()<br>def search_documents(question: str, top_k: int = 4) -&gt; dict:<br>    &quot;&quot;&quot;Search indexed documents and return matching chunks (no LLM answer).&quot;&quot;&quot;<br>    result = service.search_documents(question, top_k=top_k)<br>    return {&quot;ok&quot;: True, **result}<br>@mcp.tool()<br>def ask_documents(question: str, top_k: int = 4) -&gt; dict:<br>    &quot;&quot;&quot;Ask a question and get an answer grounded in indexed documents.&quot;&quot;&quot;<br>    result = service.ask_documents(question, top_k=top_k)<br>    return {&quot;ok&quot;: True, **result}<br>@mcp.tool()<br>def rag_status() -&gt; dict:<br>    &quot;&quot;&quot;Return how many chunks are indexed and which source files exist.&quot;&quot;&quot;<br>    result = service.get_index_status()<br>    return {&quot;ok&quot;: True, **result}</pre><p>Roughly <strong>50 lines</strong> of MCP wiring on top of RAG code I already understood. That was the surprise — MCP felt abstract until I mapped three CLI operations to three tools.</p><h3>Cursor MCP config</h3><p>Add this to ~/.cursor/mcp.json (adjust paths for your machine):</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;local-rag-mcp-minilm&quot;: {<br>      &quot;command&quot;: &quot;C:\\path\\to\\local-rag-mcp-minilm\\.venv\\Scripts\\python.exe&quot;,<br>      &quot;args&quot;: [&quot;C:\\path\\to\\local-rag-mcp-minilm\\mcp_server.py&quot;]<br>    }<br>  }<br>}</pre><p>Restart Cursor. The tools show up in chat.</p><h3>What the CLI looks like</h3><p>The app is still command-line driven for ingest and testing:</p><pre># Preview how a document is split (no model download needed)<br>python main.py preview data/monthly-expense-data.txt<br><br># Index a text or PDF file (downloads MiniLM on first run)<br>python main.py ingest data/monthly-expense-data.txt<br><br># Search without calling the LLM<br>python main.py search &quot;Summerize expense for April month?&quot;<br><br># Ask a question<br>python main.py ask &quot;Summerize expense for April month?&quot;<br><br># Show retrieved sources with the answer<br>python main.py ask &quot;What is recursive chunking?&quot; --show-sources<br><br># Check status<br>python main.py status<br><br># Clear the vector store<br>python main.py reset</pre><p>That is it. No web server. No cloud API. MCP is an extra entry point — not a replacement for the CLI while learning.</p><h3>Project structure</h3><p>I organized the code into small, focused modules:</p><pre>local-rag-mcp-minilm/<br>├── main.py                      # CLI: ingest, preview, search, ask, status, reset<br>├── mcp_server.py                # FastMCP tools for Cursor<br>├── requirements.txt<br>├── README.md<br>├── docs/<br>│   └── architecture.md          # Diagrams and pipeline breakdown<br>├── rag/<br>│   ├── config.py                # models, chunk size, overlap, top_k<br>│   ├── chunker.py               # RecursiveCharacterTextSplitter<br>│   ├── document_loader.py       # .txt and .pdf support<br>│   ├── embedder.py              # all-MiniLM-L6-v2<br>│   ├── vector_store.py          # ChromaDB<br>│   ├── query.py                 # Retrieve + generate + source excerpts<br>│   └── service.py               # Shared logic for CLI + MCP<br>├── examples/<br>│   └── cursor-mcp.json          # MCP config snippet<br>└── data/<br>    └── monthly-expense-data.pdf # Demo document</pre><p>Each file has one responsibility. The <strong>service.py</strong> layer is the key design choice — CLI and MCP both call the same functions, so behavior stays in sync.</p><h3>What I learned building this</h3><ol><li><strong>MCP is simpler than the hype suggests.</strong> If you already have working functions, tools are mostly wrappers with descriptions. Start with read-only tools like search_documents and rag_status.</li><li><strong>Search and ask are different products.</strong> Exposing both as MCP tools made retrieval debugging much easier. Search shows what the index actually found. Ask adds LLM synthesis on top.</li><li><strong>Small LLMs need source checking.</strong> TinyLlama sometimes smooths or blends details. Returning source excerpts alongside answers (--show-sources / MCP JSON) helped me trust the pipeline more.</li><li><strong>Embedding model choice is a fresh index.</strong> Switching from Ollama embeddings to MiniLM meant re-ingesting documents. That is expected — not a bug.</li></ol><h3>Who is this for?</h3><p>This kind of project is great if you are:</p><ul><li>Building on local RAG from my earlier articles</li><li>Learning <strong>MCP</strong> with a real project, not a hello-world only</li><li>Exploring <strong>sentence-transformers</strong> as an alternative to Ollama embeddings</li><li>Using <strong>Cursor</strong> and want your private docs callable as tools</li><li>Preparing for interviews where RAG, embeddings, and tool calling come up</li></ul><p>You do not need a GPU farm. You need Python, Ollama (for ask only), and at least one document to index.</p><h3>What is next?</h3><p>From here, the natural extensions in this series are:</p><ul><li><strong>Hybrid RAG</strong> — combine keyword search (BM25) with vector similarity</li><li><strong>Ingest via MCP</strong> — with path allowlists for safety</li><li><strong>Conversation memory</strong> — multi-turn questions across chat sessions</li><li><strong>Stronger local chat model</strong> — swap TinyLlama for phi3:mini or similar</li><li><strong>Source-first answers</strong> — return chunks only unless the user explicitly asks for synthesis</li></ul><p>But even in its current form, this project already shows the core lesson: <strong>your RAG pipeline can be a tool, not just a script.</strong></p><h3>Final thought</h3><p>My first RAG article taught me the loop — ingest, embed, retrieve, generate.</p><p>My second taught me that retrieval quality starts with chunking.</p><p>This one taught me that once the loop works, the next step is making it <strong>callable</strong> — from your IDE, through MCP, on your own machine, on your own documents.</p><p>If you are starting with MCP and RAG together, my advice is the same as before: build the smallest version first. Ingest one PDF. Call rag_status. Run search_documents on one question. Then try ask_documents. Compare the chunks to the answer.</p><p>That one end-to-end pass teaches more than reading ten protocol diagrams.</p><p>You can download the complete source code from GitHub: <a href="https://github.com/parivshah/local-rag-mcp-minilm">https://github.com/parivshah/local-rag-mcp-minilm</a></p><p>The repository includes setup instructions, architecture diagrams, and an MCP config example. Please let me know if you liked this article or have any questions, feedback, or suggestions. You can connect with me on <a href="https://www.linkedin.com/in/parivshah">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41af4bbd0f91" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/i-exposed-my-local-rag-as-mcp-tools-in-cursor-now-i-query-my-private-pdfs-without-leaving-the-ide-41af4bbd0f91">I Exposed My Local RAG as MCP Tools in Cursor — Now I Query My Private PDFs Without Leaving the IDE</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring RAG Techniques: Smarter Chunking for Better Retrieval on My Laptop]]></title>
            <link>https://pub.towardsai.net/exploring-rag-techniques-from-basics-to-deeper-insights-7c0138877913?source=rss-8f93b51293b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c0138877913</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Pariv Shah]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 15:18:14 GMT</pubDate>
            <atom:updated>2026-06-05T05:17:39.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ffdBIE8NHppSEAscDizBnw.png" /></figure><p>In my <a href="https://medium.com/towards-artificial-intelligence/i-built-a-private-ai-that-answers-questions-from-my-own-pdfs-entirely-on-my-laptop-3b4122daa946">previous article</a>, I built a local RAG system that answers questions from my own PDFs using <strong>Ollama</strong>, <strong>ChromaDB</strong>, and <strong>TinyLlama</strong>.</p><p>It worked. I could ingest a document and ask questions. But as I started testing more queries, I noticed something important:</p><p>The model was fine. The embeddings were fine. The answers were still sometimes wrong — because the document was split in the wrong places.</p><p>That led me to explore chunking more deeply. This article is about what I learned, what I built next, and why how you split text often matters more than which model you pick.</p><h3>What is chunking, in plain English?</h3><p>Before you embed a document, you have to break it into smaller pieces called <strong>chunks</strong>.</p><p>Think of it like highlighting sections of a textbook before an exam. If you highlight half a sentence on one page and the other half on the next, neither highlight helps you answer the question.</p><p>Chunking is the same idea. You are creating retrieval units — pieces small enough to match a specific question, but complete enough to actually answer it.</p><p>RAG does two things:</p><ol><li><strong>Retrieve</strong> — Find the most relevant chunks in your documents</li><li><strong>Generate</strong> — Use an LLM to write an answer based on that context</li></ol><p>If your chunks are mid-sentence fragments, retrieval fails — even when the answer is clearly in the document.</p><h3>Why I cared about this</h3><p>In my first project, I used fixed-size chunking: cut the text every ~500 characters with a small overlap.</p><p>That is a common starting point. It is simple and fast. But it does not care about paragraphs, sentences, or meaning. It just counts characters.</p><p>The more I queried my own documents, the more I saw retrieval miss facts that were split across chunk boundaries.</p><p>So I built a follow-up project focused on one upgrade: <strong>recursive chunking with overlap</strong>, using LangChain’s RecursiveCharacterTextSplitter.</p><p>Same local stack. Smarter splits.</p><h3>A real example</h3><p>Imagine this short refund policy:</p><pre>Refund Policy<br><br>We offer full refunds within 30 days of purchase.<br>Contact support at help@company.com for assistance.<br>Items must be unused and in original packaging.<br>Digital products are non-refundable after download.</pre><p>For clarity, the examples below use roughly <strong>80 characters</strong> per chunk so you can see every cut. My demo app uses <strong>500 characters with 50 overlap</strong> for real documents — more on that later.</p><h3>1. Fixed-size chunking (no overlap)</h3><p>Walk through the text and cut every N characters. Structure does not matter.</p><p>The cuts might look like this:</p><p><strong>Chunk 1:</strong> Refund Policy\n\nWe offer full refunds within 30 days of purchase.\nContact support at</p><p><strong>Chunk 2:</strong> help@company.com for assistance.\n\nItems must be unused and in original packaging.\nDig</p><p><strong>Chunk 3:</strong> ital products are non-refundable after download.</p><p>Problems you can see right away:</p><ul><li>Chunk 1 ends mid-sentence (Contact support at)</li><li>Chunk 2 starts mid-word and splits Dig / ital</li><li>A question like <em>“How do I get a refund?”</em> might match Chunk 1, but the email address is in Chunk 2</li></ul><p>The answer exists. Retrieval just cannot find it in one piece.</p><h3>2. Overlap chunking (fixed-size + overlap)</h3><p>Same fixed cuts, but each chunk repeats the last few characters of the previous one — like a sliding window.</p><p>With 80 characters and 20 overlap, Chunk 2 might start 20 characters before a pure fixed cut would begin:</p><p><strong>Chunk 1:</strong> …purchase.\nContact support at help@company.com for assistance.\n\nItems must be</p><p><strong>Chunk 2:</strong> …support at help@company.com for assistance.\n\nItems must be unused and in original</p><p>What overlap fixes:</p><ul><li>Boundary content appears in two chunks</li><li>If a fact sits on a cut line, retrieval is more likely to find at least one chunk with the full idea</li></ul><p>What overlap does not fix:</p><ul><li>You can still cut mid-sentence or mid-word</li><li>You store more chunks and duplicate text — slightly more storage and embedding cost</li></ul><p>Like reading a book where each page repeats the last paragraph of the previous page. You do not lose context at the page break, but pages can still break in awkward places.</p><h3>3. Recursive chunking</h3><p>Instead of counting characters blindly, try to split at natural breaks first. Only fall back to smaller cuts when needed.</p><p><strong><em>Typical order:</em></strong></p><ol><li>Paragraphs (\n\n)</li><li>Lines (\n)</li><li>Sentences (.)</li><li>Words ( )</li><li>Characters</li></ol><p>Same document, target ~80 characters:</p><p><strong>Chunk 1:</strong> Refund Policy\n\nWe offer full refunds within 30 days of purchase.</p><p><strong>Chunk 2:</strong> Contact support at help@company.com for assistance.</p><p><strong>Chunk 3:</strong> Items must be unused and in original packaging.</p><p><strong>Chunk 4:</strong> Digital products are non-refundable after download.</p><p>Why this is nicer for RAG:</p><ul><li>Each chunk is mostly a complete thought</li><li>Embeddings represent meaningful units, not random fragments</li><li>A search for <em>“refund within 30 days”</em> lands on a clean chunk with the full rule</li></ul><p>Chunk sizes will vary. That is normal. You are optimizing for semantic coherence, not uniform length.</p><h3>4. Recursive chunking + overlap (what I built)</h3><p>Recursive splitting respects document structure. Overlap adds a safety net when an answer spans two chunks.</p><p>With ~80 characters and 20 overlap, you might get:</p><p><strong>Chunk 1:</strong> Refund Policy\n\nWe offer full refunds within 30 days of purchase.</p><p><strong>Chunk 2:</strong> within 30 days of purchase.\n\nContact support at help@company.com for assistance.</p><p><strong>Chunk 3:</strong> help@company.com for assistance.\n\nItems must be unused and in original packaging.</p><p>Notice Chunk 2: the refund window and the support sentence share overlap text. A query about refunds or the contact email can match a single coherent chunk.</p><p>This is the combination I implemented in my demo — recursive splitting plus overlap, with settings I can tune in one config file.</p><h3>Does it actually improve retrieval?</h3><p>Chunking quality shows up at query time — not just in prettier splits.</p><p><strong>Query:</strong> <em>“What email do I contact for refunds?”</em></p><ul><li><strong>Fixed-size (no overlap):</strong> Top chunk ends at <em>“Contact support at”</em> — no email in context</li><li><strong>Fixed + overlap:</strong> Email might appear — depends on where the cut landed</li><li><strong>Recursive + overlap:</strong> Top chunk is the full support sentence — reliable retrieval</li></ul><p>That is why I added a preview command. You can inspect how a document splits before embedding anything or blaming the LLM for a bad answer.</p><h3>The architecture I kept</h3><p>I kept the same local stack from my first project. The only major change was how documents are split.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2l93uJelMUGm4FLEH0SJ7w.png" /></figure><p>Total model size: still under ~1 GB. Still runs on a normal laptop.</p><h3>How the pipeline works</h3><h4>Step 1: Ingest a document</h4><p>Document (.txt or .pdf) → extract text → recursive split with overlap → embed → store in ChromaDB</p><p>I use ~500-character chunks with 50-character overlap in the demo. The splitter tries paragraphs and sentences first, then falls back to words and characters only when needed.</p><h4>Step 2: Preview splits (no Ollama required)</h4><p>Document → recursive split → print chunks to the terminal</p><p>This step is new compared to my first project. It let me see exactly how a file would be broken before spending time on embeddings.</p><h4>Step 3: Ask a question</h4><p>Question → embed → find top similar chunks → send to LLM → answer</p><p>The system retrieves the top 4 most relevant chunks, passes them as context to TinyLlama, and generates a grounded response — same flow as before, but with better chunks going in.</p><h3>The core code</h3><p>The heart of the upgrade is in rag/chunker.py:</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br><br>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=500,<br>    chunk_overlap=50,<br>    length_function=len,<br>    separators=[&quot;\n\n&quot;, &quot;\n&quot;, &quot;. &quot;, &quot; &quot;, &quot;&quot;],<br>)<br>chunks = splitter.split_text(document_text)</pre><ul><li><strong>chunk_size</strong> — target maximum length per chunk</li><li><strong>chunk_overlap</strong> — shared text between consecutive chunks (~10% of chunk size)</li><li><strong>separators</strong> — tried in order; smaller separators only when a piece is still too long</li></ul><p>You can change defaults in rag/config.py without touching the rest of the pipeline.</p><h3>What the CLI looks like</h3><p>The app is command-line driven and easy to use:</p><pre># Preview how a document is split (no Ollama needed)<br>python main.py preview data/sample.txt<br><br># Index a text or PDF file<br>python main.py ingest data/sample.txt<br><br># Ask a question<br>python main.py ask &quot;What is recursive chunking?&quot;<br><br># Check status<br>python main.py status<br><br># Clear the vector store<br>python main.py reset</pre><p>That is it. No web server, no Docker, no complex setup.</p><h3>Project structure</h3><p>I organized the code into small, focused modules:</p><pre>recursive-chunk-rag/<br>├── main.py                 # CLI: ingest, preview, ask, status, reset<br>├── requirements.txt<br>├── README.md<br>├── rag/<br>│   ├── config.py           # chunk_size, overlap, models, top_k<br>│   ├── chunker.py          # RecursiveCharacterTextSplitter<br>│   ├── document_loader.py  # .txt and .pdf support<br>│   ├── embedder.py         # Ollama embeddings<br>│   ├── vector_store.py     # ChromaDB<br>│   └── query.py            # Retrieve + generate<br>└── data/<br>    └── sample.txt          # Demo document about recursive chunking</pre><p>Each file has one responsibility. That made debugging and extending the project much easier.</p><h3>What I learned building this</h3><ol><li><strong>Chunking is an under-rated part of RAG.</strong> Before you swap models or add a web UI, look at how your documents are split. Bad chunks create bad retrieval — no LLM can fix that.</li><li><strong>Fixed-size chunking is fine for learning, not for relying on.</strong> It gets you running fast. Recursive splitting is a small upgrade with a noticeable retrieval improvement on real documents.</li><li><strong>Overlap and structure solve different problems.</strong> Overlap helps at boundaries. Recursive splitting helps with meaning. Together, they are a strong default.</li><li><strong>Preview before you embed.</strong> Inspecting splits on one sample file saved me time and made tuning chunk size much less guesswork.</li></ol><h3>Who is this for?</h3><p>This kind of project is great if you are:</p><ul><li>Building on a <strong>local RAG</strong> setup like my first article</li><li>Learning how retrieval quality depends on document splitting</li><li>Exploring <strong>LangChain </strong>text splitters with <strong>Ollama </strong>and <strong>ChromaDB</strong></li><li>Preparing for interviews where RAG pipeline details come up</li></ul><p>You do not need new hardware. You need <strong>Python</strong>, <strong>Ollama</strong>, and <strong>a document</strong> to test on.</p><h3>What is next?</h3><p>From here, the natural extensions in this RAG series are:</p><ul><li><strong>Semantic chunking</strong> — split when meaning shifts, not just when length runs out</li><li><strong>Parent-child chunking</strong> — small chunks for search, larger chunks for LLM context</li><li><strong>Hybrid RAG</strong> — combine keyword search with vector similarity</li><li><strong>Memory RAG</strong> — carry conversation context across turns</li><li><strong>Graph RAG</strong> — connect related facts across documents</li></ul><p>But even in its current form, this project already shows the core lesson: <strong>retrieval quality starts with how you split your documents.</strong></p><h3>Final thought</h3><p>My first RAG project taught me the full loop — ingest, embed, retrieve, generate.</p><p>This one taught me that the loop is only as good as the chunks you put into it.</p><p>If you are improving a RAG system, my advice is the same as before: start small, run one document end to end, and look at what retrieval actually finds before changing anything else.</p><p>Run preview on one file. Ask one question. Compare the chunks to the answer you get back.</p><p>That one exercise teaches more about RAG quality than tuning model names.</p><p>You can download the complete source code from GitHub: <a href="https://github.com/parivshah/recursive-chunk-rag">https://github.com/parivshah/recursive-chunk-rag</a></p><p>The repository includes detailed instructions to run everything locally. Please let me know if you liked this article or have any questions, feedback, or suggestions. You can connect with me on <a href="https://www.linkedin.com/in/parivshah">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c0138877913" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/exploring-rag-techniques-from-basics-to-deeper-insights-7c0138877913">Exploring RAG Techniques: Smarter Chunking for Better Retrieval on My Laptop</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Private AI That Answers Questions From My Own PDFs — Entirely on My Laptop]]></title>
            <link>https://pub.towardsai.net/i-built-a-private-ai-that-answers-questions-from-my-own-pdfs-entirely-on-my-laptop-3b4122daa946?source=rss-8f93b51293b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b4122daa946</guid>
            <category><![CDATA[dataengineering-future]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[ai-machinelearning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Pariv Shah]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 10:52:23 GMT</pubDate>
            <atom:updated>2026-06-04T04:27:31.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbS434lnqAnh_YZHud0k1g.png" /></figure><p><strong>No cloud API. No subscription. No data leaving my machine.</strong></p><p>That was the goal.</p><p>Like many people, I wanted to ask questions about my own documents — reports, notes, personal PDFs — and get useful answers back. ChatGPT-style tools are powerful, but sending private files to the cloud is not always comfortable.</p><p>So I built a simple <strong>RAG (Retrieval-Augmented Generation)</strong> application in Python that runs <strong>100% locally</strong> using <strong>Ollama</strong>, a <strong>vector database</strong>, and a small language model.</p><p>This article walks through what I built, why it matters, and how the pieces fit together.</p><h3>What is RAG, in plain English?</h3><p><strong>RAG </strong>stands for <strong>Retrieval-Augmented Generation</strong>.</p><p>Instead of asking an AI to answer from memory alone, RAG works in two steps:</p><ol><li><strong>Retrieve </strong>— Find the most relevant parts of your documents</li><li><strong>Generate </strong>— Use an LLM to write an answer based on that context</li></ol><p>Think of it like an open-book exam. The model does not need to memorize your PDF. It looks up the right pages first, then answers using what it found.</p><p>That makes answers more accurate, more grounded, and less prone to hallucination.</p><h3>Why go local?</h3><p>Cloud AI is convenient, but local RAG has real advantages:</p><ul><li><strong>Privacy </strong>— Your documents never leave your machine</li><li><strong>Cost </strong>— No per-token API bills</li><li><strong>Control </strong>— You choose the models, chunk size, and retrieval logic</li><li><strong>Learning </strong>— You see how RAG actually works under the hood</li></ul><p>For personal documents, prototypes, or experimentation, local RAG is a great starting point.</p><h3>The architecture I chose</h3><p>I kept the stack intentionally small:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vko2Qp8ocwG1Iu_S" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IUabHZ-59EmlIuH0" /></figure><p>Total model size: <strong>under ~1 GB</strong>. That is small enough to run on a normal laptop.</p><h3>Two models, two jobs</h3><p>A common point of confusion in RAG: you usually need two different models.</p><h3>1. Embedding model — nomic-embed-text</h3><p>This model does not write answers. It converts text into numbers (vectors) that capture meaning.</p><p>When you ask <em>“How do I get a refund?”</em> and your document says <em>“Return policy and reimbursement process”</em>, the embedding model helps the system understand those are related — even though the words differ.</p><h3>2. Chat model — TinyLlama</h3><p>This is the model that <strong>reads your question + retrieved context</strong> and writes the final answer.</p><p>TinyLlama is only ~1.1B parameters — small, fast, and good enough for learning and simple Q&amp;A. For better quality later, you can swap in models like phi3:mini or gemma:2b.</p><h3>How the pipeline works</h3><h3>Step 1: Ingest a PDF</h3><p>PDF → extract text → split into chunks → embed → store in ChromaDB</p><p>I split documents into ~500-character chunks with a small overlap so context is not lost at chunk boundaries.</p><h3>Step 2: Ask a question</h3><p>Question → embed → find top similar chunks → send to LLM → answer</p><p>The system retrieves the top 4 most relevant chunks, passes them as context to TinyLlama, and generates a grounded response.</p><h3>What the CLI looks like</h3><p>The app is command-line driven and easy to use:</p><pre># Index your PDF <br>python main.py ingest &quot;my-document.pdf&quot; <br><br># Ask a question <br>python main.py ask &quot;What is the main topic of this document?&quot; <br><br># Check status <br>python main.py status<br><br># Clear the vector store <br>python main.py reset</pre><p>That is it. No web server, no Docker, no complex setup.</p><h3>Project structure</h3><p>I organized the code into small, focused modules:</p><pre>rag-local/<br>├── main.py # CLI entry point<br>├── rag/<br>│ ├── pdf_loader.py # PDF → text → chunks<br>│ ├── embedder.py # Ollama embeddings<br>│ ├── vector_store.py # ChromaDB wrapper<br>│ └── query.py # Retrieve + generate answer<br>├── .chroma/ # Local vector database<br>└── data/ # Stored PDF copies</pre><p>Each file has one responsibility. That made debugging and extending the project much easier.</p><h3>What I learned building this</h3><p>1. <strong>RAG is simpler than it sounds</strong> Once you understand retrieve → augment → generate, the pattern clicks quickly.</p><p>2. <strong>Embeddings are the secret sauce</strong> Good retrieval depends on turning text into meaningful vectors. The LLM only works well if you feed it the right context.</p><p>3. <strong>Small models are underrated for learning</strong> TinyLlama will not beat GPT-4, but it is perfect for understanding the RAG flow without heavy hardware.</p><p>4. <strong>Start minimal, then iterate</strong> A CLI with one PDF, one vector store, and one local model is enough to learn the full stack. You can add a web UI, multi-PDF support, or better chunking later.</p><h3>Who is this for?</h3><p>This kind of project is great if you are:</p><ul><li>Learning <strong>AI engineering</strong> hands-on</li><li>Exploring <strong>local LLMs</strong> with Ollama</li><li>Building <strong>private document Q&amp;A</strong> for personal use</li><li>Preparing for interviews where RAG and vector search come up</li></ul><p>You do not need a GPU farm. You need Python, Ollama, and curiosity.</p><h3>What is next?</h3><p>From here, the natural extensions are:</p><ul><li>Support for <strong>multiple PDFs</strong> in one index</li><li>A simple <strong>web UI</strong> for non-technical users</li><li>Smarter <strong>chunking </strong>(by paragraph or section)</li><li>Swapping in a <strong>stronger local model</strong> for better answers</li></ul><p>But even in its current form, the project already demonstrates the core idea: <strong>your documents, your machine, your AI assistant</strong>.</p><h3>Final thought</h3><p>We often think AI means sending data to the cloud. It does not have to.</p><p>With open-source tools like Ollama and ChromaDB, you can build meaningful AI applications on your own hardware — privately, affordably, and transparently.</p><p>If you are getting started with RAG, my advice is simple: <strong>build the smallest version first</strong>. Ingest one PDF. Ask one question. See the full loop work end to end.</p><p>That one working pipeline teaches more than reading ten architecture diagrams.</p><p>You can download the complete source code from <a href="https://github.com/parivshah/rag-local">GitHub</a>. The repository includes detailed instructions to run everything locally. Please let me know if you liked this article or have any questions, feedback, or suggestions. You can connect with me on <a href="https://www.linkedin.com/in/pariv-shah/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b4122daa946" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/i-built-a-private-ai-that-answers-questions-from-my-own-pdfs-entirely-on-my-laptop-3b4122daa946">I Built a Private AI That Answers Questions From My Own PDFs — Entirely on My Laptop</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>