<?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 Aqsa A Malik on Medium]]></title>
        <description><![CDATA[Stories by Aqsa A Malik on Medium]]></description>
        <link>https://medium.com/@aqsaa.malik99?source=rss-3eebb32d955------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RwDen9kTDdDld3e_jDFd1Q.png</url>
            <title>Stories by Aqsa A Malik on Medium</title>
            <link>https://medium.com/@aqsaa.malik99?source=rss-3eebb32d955------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:16:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aqsaa.malik99/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[The $440k Retrieval Error: What Deloitte’s AI Scandal Teaches Us About RAG]]></title>
            <link>https://medium.com/@aqsaa.malik99/the-440k-retrieval-error-what-deloittes-ai-scandal-teaches-us-about-rag-1619f4427a3b?source=rss-3eebb32d955------2</link>
            <guid isPermaLink="false">https://medium.com/p/1619f4427a3b</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[trending]]></category>
            <category><![CDATA[deloitte]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-hallucination-fix]]></category>
            <dc:creator><![CDATA[Aqsa A Malik]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 18:00:32 GMT</pubDate>
            <atom:updated>2026-07-24T18:00:32.191Z</atom:updated>
            <content:encoded><![CDATA[<h4>A government report cited academic papers that were never written. Everyone blamed “AI hallucination” so I ran a retrieval experiment to see if it was actually a pipeline failure wearing a costume.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQx761YIeFAt9BuYwA40Tw.png" /></figure><p>Let’s start with what actually happened, because the headlines undersold it.</p><p>In 2025, Deloitte Australia delivered a 237-page report to the Australian government, reviewing a welfare-penalty system, for roughly $290,000. A university researcher checking the footnotes found citations to academic papers that don’t exist, and a quote attributed to a federal court judge who never said it. Deloitte admitted generative AI had been used in parts of the report and agreed to a partial refund. Months later, a separate Deloitte report for the Canadian government, this one worth over a million dollars, was found to have the same problem: citations pointing to research that was never written.</p><p>Here’s the question that sat in my head after reading about it: <strong>the whole pitch of retrieval-augmented generation is that the model isn’t supposed to be able to do this.</strong> RAG exists specifically so the model answers from real, retrieved documents instead of inventing things from memory. So either these reports weren’t actually using retrieval-grounded generation properly, or more interesting to me retrieval itself has blind spots big enough for a fabricated citation to walk straight through, even in a system that’s technically “grounded.”</p><p><strong>Recap: Retrieval</strong></p><p>Retrieval is the step before generation, where a system searches a document corpus and pulls back the passages most likely to contain the answer, before the LLM ever writes a word. Everything downstream depends on this step working. If the right evidence never makes it into the model’s context, “grounded” is just a word in your slide deck.</p><h3>Setting up the experiment</h3><p>I wanted to know: for the kind of dense, citation-heavy, table-and-appendix-stuffed reports that get commissioned by governments, banks, consulting firms, and legal teams, which retrieval approach actually catches the right evidence, and which one would have let a fabricated citation slide through unnoticed?</p><p>Rather than build this from scratch, I went looking for researchers who’d already run a version of this exact stress test, because it turns out this is now one of the most actively benchmarked questions in enterprise AI.</p><p>Two lines of research turned out to answer two different halves of my question:</p><ul><li><strong>T2-RAGBench (2026)</strong> tested ten retrieval strategies: sparse, dense, hybrid, reranked, query-expanded across 23,088 real queries over 7,318 documents mixing prose and tables, the exact document shape a consulting report or government filing takes.</li><li><strong>ColPali / ViDoRe (Faysse et al., 2024)</strong> tested something structurally different: what happens when a retrieval system stops reading extracted text altogether and instead looks at the actual page image, tables, footnotes, charts, and all, the same way a human fact-checker would.</li></ul><p>Between them, this is close to running the experiment myself: text-based retrieval (sparse, dense, hybrid) on one side, visual page-level retrieval on the other, both tested on exactly the kind of document that got Deloitte in trouble.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdMxzetOEszCw80qvYeFEA.png" /><figcaption>Method 1: Sparse/Dense Hybrid Retrieval</figcaption></figure><h3>Method 1: Sparse/Dense Hybrid Retrieval</h3><blockquote><strong>“One reader is obsessed with exact words. The other cares only about meaning. You put both of them on the same case.”</strong></blockquote><h3>The analogy</h3><p>Picture two fact-checkers reviewing the same 237-page report. The first one only trusts exact matches, she’ll flag a citation as suspicious only if she can’t find that exact paper title, word for word, anywhere in a real database.</p><p>This is <strong>sparse retrieval</strong> (BM25): it scores passages by literal term overlap and is extremely good at catching exact strings, names, and identifiers.</p><p>The second fact-checker works by meaning instead of wording. Ask her to check “a 2019 study on welfare automation” and she’ll happily surface something titled “Automated Decision Systems in Social Services, 2019” even though barely a word matches. This is <strong>dense retrieval</strong>: both the query and the corpus get embedded as vectors, and similarity is measured in meaning-space rather than word-space.</p><p>Put together and fused (usually with Reciprocal Rank Fusion), these two catch almost everything either one would have missed alone.</p><h3>What it actually does, and why it matters here</h3><p>T2-RAGBench found something that cuts against the industry’s default assumption: on real, table-and-citation-heavy documents, plain BM25 actually outperformed a strong commercial dense embedding model on almost every metric tested. These documents are dense with exact names, standardized labels, and specific identifiers, precisely the kind of content dense embeddings tend to blur into “close enough.” The best performer overall wasn’t sparse or dense alone, it was a two-stage pipeline: <strong>hybrid fusion first</strong>,<strong> then a neural reranker on top</strong>, reaching a Recall@5 of 0.816, well ahead of any single-stage method.</p><p>Translate that back to Deloitte</p><blockquote>If the fabricated citation had been checked against a hybrid-retrieval system searching a real academic database, the sparse half alone should have caught it. A paper title that doesn’t exist has zero term overlap with anything real. That’s exactly the failure mode BM25 is built to catch, and exactly the check that appears to have never happened.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzUX5aiVzjfqWhv4_kYY4w.png" /></figure><h3>The Nearest-Neighbor Trap</h3><blockquote><strong>“A police lineup always produces a pick, even when the real suspect isn’t standing in it.”</strong></blockquote><p>Here’s the part that’s easy to skip past when you say dense retrieval “blurs things into close enough,” and it’s the actual mechanism behind a specific kind of hallucination.</p><h3>The analogy</h3><p>A dense retriever is built to always return an answer. Ask it for the nearest neighbor to a made-up concept, “a 2019 study on algorithmic welfare bias in New South Wales” that was never written, and it doesn’t come back empty-handed. There’s no “no match found” option in nearest-neighbor search. It hands back whatever real document sits closest to that fake concept in vector space, the way an eyewitness in a lineup will point to <em>someone</em> even when the actual suspect was never arrested, because the format of the exercise demands a pick.</p><h3>What it actually does, and why it hallucinates</h3><p>This is where the failure stops being a retrieval problem and becomes a generation problem wearing retrieval’s clothes. The generator receives that “closest” document and treats it as ground truth, because that’s the entire contract RAG runs on: <em>trust what retrieval handed you.</em> If the retrieved document doesn’t actually support the query, a well-behaved model should say so. Instead, what commonly happens is the model <strong>anchors</strong> on the retrieved text and contorts its own reasoning to make the citation fit, rewording the fake claim just enough that it now plausibly resembles something the real, retrieved document could have said. The hallucination doesn’t feel invented anymore, it feels <em>sourced</em>, because there’s a real document sitting right behind it in the context window. <strong>That’s a more dangerous failure than an LLM inventing a citation from nothing</strong>, because a real, retrievable document is now backstopping a claim that document never actually made.</p><p>This is very likely what happened somewhere upstream of the Deloitte report: not necessarily a model inventing a paper from pure memory, but a retrieval step returning the closest real document to a query about welfare automation research, and a generator that treated “closest” as “correct” and wrote around it until the citation looked legitimate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uclc57arO0sKpWtQzhTblw.png" /></figure><h3>Method 2: Visual-Semantic Page-Level Retrieval</h3><blockquote><strong>“Instead of asking someone to summarize the page for you, you just look at the page.”</strong></blockquote><h3>The analogy</h3><p>Before either fact-checker above can do her job, someone has to convert the document into words they can search. For scanned exhibits, footnote-heavy PDFs, or appendices with tables and charts, that conversion step (OCR, or an LLM writing a description of a table) is exactly where information quietly goes missing. A misread footnote number. A table column that got flattened out of order. A chart nobody bothered to transcribe.</p><p>Visual-semantic retrieval skips that conversion entirely. <strong>ColPali</strong> treats each page as an image, embeds it directly with a vision-language model, and matches queries against the page’s actual visual structure, no OCR pipeline standing between the document and the search.</p><h3>What it actually does</h3><p>ColPali uses a <strong>late-interaction</strong> mechanism, borrowed from ColBERT: instead of squeezing a whole page into one vector, it keeps many small patch-level vectors and matches your query against the strongest patch, the same way your eye would jump straight to the relevant footnote or table cell on a real page rather than reading top to bottom.</p><p>On the ViDoRe benchmark, built from real documents including financial and technical reports, ColPali substantially outperformed traditional text-extraction pipelines specifically on pages where the relevant information lived in a table, footnote block, or layout rather than clean prose.</p><h3>Real-world build scenario</h3><p>Imagine a fact-checker’s actual job on a report like Deloitte’s: confirm that footnote 47 really points to page 12 of a real cited study, and that the number quoted in the main text matches the number in that study’s table. If the citation itself is fabricated, sparse retrieval catches it instantly, zero exact match, red flag. But if the citation is <em>real</em> and the <em>number</em> being quoted from it is wrong, or misattributed to the wrong table row, that’s a page-layout problem, not a vocabulary problem. That’s the failure mode visual retrieval is built for: it’s comparing the claim against what’s actually printed on the page, not against a paraphrased text extraction of it.</p><h3>The catch nobody puts in the headline</h3><p>Visual retrieval isn’t a strict upgrade, and treating it like one would be its own kind of overclaiming:</p><ul><li><strong>It’s expensive.</strong> Each page produces roughly a thousand patch vectors instead of one, a real storage and compute cost at the scale a consulting firm or bank actually operates at.</li><li><strong>It’s not automatically more accurate.</strong> A large multilingual benchmark, MIRACL-VISION, found visual retrieval models scoring up to 12% lower than text-based retrieval even in English, and far lower elsewhere. Visual embedding models are still younger than text embedding models, and it shows outside cherry-picked chart examples.</li><li><strong>A perfect retrieval doesn’t save you from a bad generator.</strong> One practitioner testing ColPali against a real 10-K found the retriever correctly located the right table, and the vision-language model reading it still misread a digit and fabricated a figure for a year the report didn’t even cover. Retrieval finding the truth and generation reporting the truth are still two separate jobs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PEa1Re_GAPKDuzyjgwsrpg.png" /></figure><h3>The Missing Third Job: Post-Generation Validation</h3><blockquote><strong>“Retrieval finds the pages. Generation writes the sentence. Someone still has to read the sentence back against the pages before it goes out the door.”</strong></blockquote><p>Everything above fixes retrieval. None of it fixes the actual gap that let a fabricated citation survive all the way to a signed-off, paid-for report: nobody checked the <em>finished answer</em> against the <em>retrieved evidence</em> before it shipped.</p><h3>The analogy</h3><p>Think of a newsroom. A reporter (retrieval) goes and finds the source documents. A writer (generation) turns those documents into a story. But no publication ships that story straight from the writer’s desk, there’s a fact-checker whose entire job is to sit down after the draft is written and trace every single claim, quote, and citation back to the actual source material, sentence by sentence, before it’s allowed to publish. Skip that role, and you’re trusting that the reporter and the writer never introduced an error between them, which is exactly the trust that broke in the Deloitte report.</p><h3>What it actually does</h3><p>This is the job <strong>Corrective RAG (CRAG)</strong> and <strong>Self-RAG</strong> are built around: a lightweight second model acts purely as a judge, not a writer. It reads the generated answer alongside the retrieved context and checks, claim by claim, whether each one has a direct, traceable line back to something the retrieved documents actually say. If a citation doesn’t match the text it claims to come from, or a number in the answer doesn’t appear anywhere in the retrieved passage, the judge flags or blocks the generation before a human ever sees it, rather than trusting that retrieval and generation quietly agreed with each other.</p><p>This is the layer that would have caught what hybrid retrieval and visual retrieval, on their own, might still have missed. Good retrieval only guarantees the <em>right documents</em> reached the model. It says nothing about whether the model’s <em>sentence</em> actually stayed faithful to those documents once it started writing. Those are separable failures, and enterprise systems that only invest in retrieval quality are leaving the second half of the pipeline completely unguarded.</p><h3>So would better retrieval have stopped Deloitte?</h3><p>Partially, and the “partially” is the actual finding, not a hedge.</p><ul><li><strong>Fabricated citations: </strong>the paper-that-never-existed kind are almost exactly the failure sparse retrieval is designed to catch. A hybrid retrieval step checking every citation against a real database, before it ever reached the final report, should have flagged zero-match citations automatically. This is a process failure, not a hard research problem; the tooling to catch it already exists and already works.</li><li><strong>Misquoted or misattributed numbers buried in a real, correctly-cited table</strong> are a different animal entirely, and this is where visual, page-level retrieval earns its cost. VisRAG-style approaches report 25–39% accuracy gains over text-only RAG specifically on the subset of questions where the answer lives in a table or chart that text extraction quietly mangles.</li><li>The systems getting the best results in production right now aren’t choosing a side. They run cheap retrieval first (hybrid sparse-dense, or a coarse visual pass) and rerank the survivors with the more expensive method suited to what the question actually needs, exactly the two-stage pattern T2-RAGBench and ColPali-adjacent work converge on independently.</li></ul><h3>The one-paragraph version, if you remember nothing else</h3><p>Deloitte’s fabricated citations weren’t proof that grounding doesn’t work, they were proof that grounding wasn’t actually run as a check, and that the failure can happen at three separate points, each needing its own fix. First, retrieval itself: hybrid sparse-dense retrieval remains the right default for exact, citation-heavy, term-dense enterprise text, because BM25 catches literal mismatches dense embeddings smooth over, and a paper title that doesn’t exist should never have survived a real lexical check. Second, the anchoring trap inside dense retrieval: nearest-neighbor search never returns “nothing,” so a generator that blindly trusts whatever came back closest will contort its own reasoning to fit a document that never actually supported the claim, turning an invented fact into one that looks sourced. Third, visual, page-level retrieval solves a real but different problem, catching a number misattributed to the wrong row of a real table, an error that lives in the layout, not the words, and that no amount of better text search can find. None of those three layers replace the fourth, a post-generation validator that reads the finished answer back against the retrieved evidence, claim by claim, before it ships. Retrieval finding the truth, generation writing it faithfully, and a judge confirming the two still agree are three separate jobs, and Deloitte’s report is what happens when only the first one gets built.</p><p><em>Sources referenced:</em></p><p><em>Deloitte Australia and Deloitte Canada AI-citation reporting (Fortune, Entrepreneur, Guardian, Oct 2025–Jan 2026);</em></p><p><em>“From BM25 to Corrective RAG” / T2-RAGBench (2026); ColPali (Faysse et al., 2024, arXiv:2407.01449) and the ViDoRe benchmark;</em></p><p><em>VisRAG accuracy comparisons; MIRACL-VISION (2025).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1619f4427a3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Storing and Searching Millions of Vectors : The Retrieval Half of RAG, Explained Like You’re…]]></title>
            <link>https://medium.com/@aqsaa.malik99/storing-and-searching-millions-of-vectors-the-retrieval-half-of-rag-explained-like-youre-4f5f08a8d08c?source=rss-3eebb32d955------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f5f08a8d08c</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aqsa A Malik]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 17:26:30 GMT</pubDate>
            <atom:updated>2026-07-12T17:26:30.854Z</atom:updated>
            <content:encoded><![CDATA[<h3>Storing and Searching Millions of Vectors : The Retrieval Half of RAG, Explained Like You’re Actually Building Something</h3><p><em>How vector search finds the right needle in a haystack of millions, without checking every single piece of hay.</em></p><p>Let’s say you’re building a semantic search feature for a documentation site with 5 million chunked paragraphs, each turned into a 768-dimension embedding. A user types a question. Somewhere in those 5 million vectors is the one that actually answers it.</p><p>Here’s the part that trips people up: <strong>how do you actually find it fast?</strong></p><p>This section covers four things, in order:</p><ul><li>Why vector search needs a different kind of storage?</li><li>How vector databases work and what’s available?</li><li>How to search smarter? hybrid search and retrieval strategies</li><li>How to improve precision with re-ranking?</li></ul><p>By the end, you’ll understand the full retrieval half of the RAG pipeline from a stored embedding all the way to the final shortlist of chunks handed to the LLM.</p><h3>Why Vector Search Needs Specialist Indexing</h3><p><strong>“Checking every book in the library one at a time isn’t searching, it’s just reading the whole library.”</strong></p><h3>The analogy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9w5n2G6aUIbXzWmPJrvv6g.png" /></figure><p>Imagine a librarian who, whenever you ask for a book about “dragons,” walks to shelf one, book one, reads the cover, decides no, walks to book two, reads the cover, decides no and keeps doing that for every single book in the building before answering you. She’ll get you the right answer eventually. But if the library has 5 million books, “eventually” might mean hours.</p><p>That librarian is doing <strong>Exact Nearest Neighbour (ENN)</strong> search, comparing your query vector against <em>every single</em> stored vector, one by one, and returning the closest matches with 100% accuracy. It’s not wrong. It’s just too slow to survive contact with real scale.</p><h3>What it actually does</h3><p>ENN computes the exact similarity score (<a href="https://medium.com/@aqsaa.malik99/cosine-dot-product-and-the-mysterious-angle-one-vector-similarity-explained-like-youre-91ed8b40036f?sharedUserId=aqsaa.malik99">cosine, dot product, whatever you picked? </a>) between your query vector and every vector in the database, then sorts and returns the top results. Guaranteed correct but slow, because the amount of work grows in a straight line with how many vectors you have, 10x more vectors means 10x more comparisons, every single time you search.</p><h3>ANN: the librarian who organizes the shelves first</h3><p><strong>Approximate Nearest Neighbour (ANN)</strong> algorithms take a different bet: what if, instead of checking everything, we spend some time <em>organizing</em> the shelves in advance, so that at search time we only need to check a small, promising slice of the library?</p><p>That’s the trade being made:</p><blockquote><em>ANN trades a small, controlled loss of accuracy for orders-of-magnitude speed gains bringing query time down to single-digit milliseconds, even across tens of millions of vectors.</em></blockquote><p>It doesn’t guarantee it found the <em>actual</em> closest match every time. It guarantees it found something <em>very close</em>, almost every time, dramatically faster. In practice, for a search bar or a RAG pipeline, “the 3rd-closest chunk instead of the 1st-closest, 99% of the time” is a trade almost every real system happily makes.</p><h3>Breaking down how ANN organizes the shelves</h3><p>There isn’t one way to do this, a few different strategies exist, and each is basically a different way of pre-sorting the library:</p><ul><li><strong>Tree-based partitioning</strong> (like Annoy): repeatedly splits the vector space in half with random hyperplanes, building a tree structure, so a search only has to walk down one branch instead of checking every leaf.</li><li><strong>Graph-based navigation</strong> (like HNSW — Hierarchical Navigable Small World): connects vectors into a layered graph where each vector “knows” its rough neighbors, so a search starts at a coarse layer and hops closer and closer, the way you’d ask a stranger for directions and get redirected block by block instead of scanning the whole map at once.</li><li><strong>Clustering-based indexing</strong> (like IVF — Inverted File Index) groups vectors into clusters ahead of time (similar to k-means), so a search first figures out <em>which cluster</em> the answer is probably in, then only compares against vectors inside that cluster instead of the whole database.</li></ul><p>Think of it as:</p><blockquote><em>“Do the sorting work once, upfront, so every future search only has to check a small, relevant slice instead of the whole shelf.”</em></blockquote><h3>Real-world build scenario</h3><p>Back to your documentation site with 5 million chunks. If you ran ENN, every single search would need 5 million similarity comparisons noticeably slow, and it gets worse every time you add more docs. With an ANN index like HNSW, a search instead hops through maybe a few hundred comparisons to land on a shortlist of strong candidates, and that number barely grows even if your doc count doubles. That’s the entire reason ANN indexes exist: they let vector search survive the jump from “a demo with 10,000 rows” to “a real product with tens of millions.”</p><h3>When should you use ANN vs. ENN?</h3><p>Use <strong>ENN</strong> when your dataset is small (low thousands of vectors) or when you need guaranteed exact results: some legal, medical, or compliance-driven retrieval systems genuinely can’t tolerate “approximately correct.” Use <strong>ANN</strong> for basically everything else at real-world scale, it’s the default in every major vector database because the accuracy trade-off is tiny and the speed gain is enormous.</p><h3>How Vector Databases Work and What’s Available?</h3><p><strong>“A vector database isn’t a spreadsheet with a fancy name, it’s a librarian who already memorized the shelf-organizing trick.”</strong></p><h3>The analogy</h3><p>A regular database is built to answer questions like “find me the row where user_id = 4521&quot; exact matches on structured fields.</p><p>A vector database is built to answer a fundamentally different question: &quot;find me the rows whose <em>meaning</em> is closest to this one&quot; and it has the ANN indexing machinery built in natively, so you don&#39;t have to hand-build the shelf-organizing system yourself.</p><h3>What it actually does</h3><p>Under the hood, a vector database stores your embeddings, builds and maintains an ANN index (usually HNSW or IVF, sometimes a choice of both) automatically, and lets you query it with a simple “give me the top-k nearest vectors to this one” request, often alongside normal metadata filters, like “closest vectors, but only where category = &#39;billing&#39;.&quot;</p><h3>The options, briefly</h3><ul><li><strong>Pinecone</strong> — fully managed, no infrastructure to run yourself; a common default for teams that want to move fast without operating servers.</li><li><strong>Weaviate</strong> — open-source, supports hybrid search (more on that below) and metadata filtering natively.</li><li><strong>Milvus</strong> — open-source, built for very large-scale deployments, popular when you’re self-hosting at serious volume.</li><li><strong>Qdrant</strong> — open-source, known for strong filtering performance alongside vector search.</li><li><strong>pgvector</strong> — a Postgres extension that bolts vector search onto a database you’re probably already running, a strong choice when you don’t want to introduce an entirely new system just for embeddings.</li><li><strong>FAISS</strong> — not a database at all, but a library (from Meta) for building your own ANN index in-process; the raw engine other tools are often built on top of.</li></ul><h3>Real-world build scenario</h3><p>Let’s say you’re asked to build a RAG chatbot for a company that already runs everything on Postgres, has a small team, and doesn’t want another piece of infrastructure to operate. <strong>pgvector</strong> is the sane choice, it lives inside the database they already run and back up.</p><p>Now let’s say instead you’re asked to build search over 200 million product embeddings for a large e-commerce platform, with a dedicated infra team. That’s when <strong>Milvus</strong> or a self-hosted <strong>Qdrant</strong> cluster starts making sense, you’re trading simplicity for the ability to tune and scale a system built specifically for this job. And if you’re a two-person startup that just wants embeddings to work without babysitting servers, <strong>Pinecone</strong>’s managed model removes that whole category of problem.</p><h3>When should you use which?</h3><blockquote><em>Match the tool to your actual constraints, team size, existing infrastructure, and scale, not to whichever one is trending. A Postgres shop reaching for Milvus, or a 200-million-vector platform trying to survive on a single unmanaged instance, are both solving the wrong problem.</em></blockquote><h3>Searching Smarter: Hybrid Search</h3><p><strong>“Don’t make the model choose between remembering exact words and understanding meaning, let it do both, then combine the votes.”</strong></p><h3>The analogy</h3><p>Recall from the earlier section: sparse embeddings are like a librarian who’s memorized the <em>exact words</em> on every page, while dense embeddings are like a librarian who’s read every book and understood the <em>gist</em>. If someone searches for a specific product code like “SKU-88213X,” the exact-word librarian nails it instantly. If someone searches “why does my order keep failing,” the gist librarian is far more useful, because no page might literally contain those words. Hybrid search means you ask both librarians and merge their answers, instead of picking one and losing the other’s strength.</p><h3>What it actually does</h3><p>Hybrid search runs a sparse search (like BM25 or SPLADE) and a dense search (your usual embedding model) over the same query at the same time, then combines the two ranked lists into one usually with a weighted formula, most commonly <strong>Reciprocal Rank Fusion (RRF)</strong>, which rewards documents that rank highly in <em>either</em> list without needing the two scores to be on the same scale.</p><h3>Real-world build scenario</h3><p>Let’s say you’re building search for an internal engineering wiki. Someone searches “error code E4021.” A pure dense embedding search might return generically similar-sounding troubleshooting docs but miss the one page that literally has “E4021” printed in it, because the semantic model treats that alphanumeric code as noise rather than meaning. A pure sparse search nails the exact code but would fail if someone phrased the same question differently “why is my build showing that four-thousand error.” Hybrid search catches both: the sparse side guarantees the exact-code page surfaces, and the dense side guarantees the paraphrased version still gets found.</p><h3>When should you use it?</h3><blockquote><em>Use hybrid search whenever your queries are a mix of exact terms (IDs, names, codes, acronyms) and natural language questions which, in practice, is almost every real production search system. Pure dense-only search is the exception that works well mainly on clean, conversational queries; the moment codes, names, or jargon enter the picture, hybrid earns its extra complexity.</em></blockquote><h3>Improving Precision with Re-Ranking</h3><p><strong>“Retrieval finds you a reasonable stack of candidates fast. Re-ranking is a second, slower pass that actually reads them carefully before deciding the real order.”</strong></p><h3>The analogy</h3><p>Imagine your ANN search is a fast intern who skims 10,000 resumes in an afternoon and hands you a shortlist of 50 that look promising. That’s genuinely useful but skimming means the intern might rank two similar resumes in the wrong order, or miss subtle context. Re-ranking is what happens when a senior hiring manager takes that shortlist of 50 and actually reads each one carefully, side-by-side with the job description, before deciding the final top 5.</p><h3>What it actually does</h3><p>The first-pass retrieval (your ANN vector search) is optimized for speed across millions of candidates, it uses simple vector math (cosine, dot product) precisely because that math is cheap to compute at scale. A <strong>re-ranker</strong> is a slower, more powerful model usually a <strong>cross-encoder, </strong>that takes the query and <em>each individual candidate</em> together as a single input, and directly scores how relevant they are to each other. Because it looks at the query and the document <em>together</em> rather than as two separate vectors compressed in advance, it captures nuance that a fast vector comparison misses.</p><p>The catch: that’s far more computationally expensive, so you can only afford to run it on a small shortlist, never on the full 5 million.</p><h3>Breaking down the two-stage pipeline</h3><ol><li><strong>Retrieval stage:</strong> ANN vector search over the full corpus, returning a shortlist, say, the top 50 candidates. Fast, approximate, built for scale.</li><li><strong>Re-ranking stage:</strong> A cross-encoder scores those 50 candidates directly against the query, in full detail, and re-sorts them. Slow per-item, but only ever run on a small shortlist, so the total time stays reasonable.</li></ol><p>Think of it as:</p><blockquote><em>“Cast a wide, fast net first. Then carefully re-sort only the fish you actually caught.”</em></blockquote><h3>Real-world build scenario</h3><p>Let’s say you’re building the retrieval step for a RAG-based legal research assistant. Getting the wrong clause into the LLM’s context isn’t a minor inconvenience, it can mean a factually wrong answer with real consequences. Your ANN search pulls back the 50 most vector-similar clauses in under 50 milliseconds. Then a cross-encoder re-ranker, slower, but only run on those 50 re-scores them with much finer precision, and you pass only the top 5 re-ranked clauses into the LLM’s prompt. The end-to-end latency stays low because the expensive step only ever touches 50 items, never 5 million, but your final precision is noticeably better than vector search alone would give you.</p><h3>When should you use it?</h3><blockquote><em>Add a re-ranking stage whenever precision in the final few results genuinely matters more than shaving off the last bit of latency: legal, medical, financial, or any RAG pipeline where a wrong chunk reaching the LLM is costly. Skip it for lower-stakes search (like a casual FAQ widget) where “good enough, instantly” beats “excellent, slightly slower.”</em></blockquote><h3>The one-paragraph version, if you remember nothing else</h3><p>Checking every vector one by one (ENN) is exact but doesn’t survive real scale, ANN indexes (HNSW, IVF, tree-based) pre-organize the space so search only checks a small, promising slice, trading a sliver of accuracy for massive speed. Vector databases (Pinecone, Weaviate, Milvus, Qdrant, pgvector) package that ANN machinery so you don’t build it yourself, pick based on your team’s infrastructure and scale, not hype. Hybrid search runs sparse and dense retrieval together and merges the results, because exact-term matching and semantic matching each catch things the other misses. And re-ranking adds a slower, more careful second pass, a cross-encoder over just the top candidates from that first fast search, buying you real precision exactly where it matters most, without paying that cost across the entire dataset.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f5f08a8d08c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where RAG Breaks and How You’d Actually Know?]]></title>
            <link>https://medium.com/@aqsaa.malik99/where-rag-breaks-and-how-youd-actually-know-ab229cdffe24?source=rss-3eebb32d955------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab229cdffe24</guid>
            <category><![CDATA[enterprise]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aqsa A Malik]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 16:09:17 GMT</pubDate>
            <atom:updated>2026-07-07T16:09:17.481Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Your retrieval pipeline can be technically perfect and your RAG system can still give a wrong answer. Here’s every place that happens, and the numbers that catch it.</em></p><p>Let’s say you’re building a RAG chatbot for internal company policy documents, and after weeks of tuning your embeddings, your ANN index, your hybrid search, and your re-ranker, it still occasionally gives an employee the wrong vacation policy. Everyone on the team is confused, because “the retrieval looks fine.”</p><p>Here’s the uncomfortable truth: <strong>retrieval being fine and the system being right are two different claims.</strong> RAG has multiple independent places it can fail, and most of them have nothing to do with your vector search at all. This section is a map of where those failures happen, and then the actual scorecard you’d use to catch them before your users do.</p><h3>Common RAG Failure Modes</h3><p><strong>“A RAG pipeline is a relay race and it only takes one runner dropping the baton to lose the whole race, no matter how fast the others ran.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOTBK27A124Yd4aEXgCWlA.png" /></figure><h3>The analogy</h3><p>Think of your RAG pipeline as a relay team: retrieval hands off to the prompt, the prompt hands off to the LLM, the LLM hands off the final answer. A perfect first leg doesn’t matter if the second runner drops the baton. That’s the core reason debugging RAG is hard “the answer is wrong” could mean the failure happened at any one of several completely different handoff points, and each one needs a different fix.</p><h3>Failure 1: The LLM ignores the retrieved context</h3><p><strong>What’s actually happening:</strong> You did everything right, the correct chunk got retrieved and landed in the prompt but the LLM answers from its own internal “memory” instead of what you handed it, especially if its trained-in knowledge disagrees with your document.</p><p><strong>Why it happens:</strong> The system prompt isn’t structured firmly enough to say <strong>“prioritize this context over what you already know,”</strong> or the LLM itself is a large, confident model that’s more prone to overriding provided context with what it believes it already knows.</p><p><strong>The fix:</strong> Tighten the system prompt with explicit priority instructions (“Answer using ONLY the provided context; if the context doesn’t contain the answer, say so”). Counter-intuitively, a smaller, more instruction-following model sometimes outperforms a bigger one here, bigger models can be more stubborn about their own “knowledge.”</p><h3>Failure 2: Wrong chunks retrieved</h3><p><strong>What’s actually happening:</strong> The retrieval step itself pulled back the wrong pieces of text, nothing downstream can save you at this point, because the LLM is now reasoning over information that was never relevant to begin with.</p><p><strong>Why it happens:</strong> Usually one of two root causes either your chunks are the wrong <em>size</em> (too big and they bury the relevant sentence in noise, too small and they lose the surrounding context needed to make sense of it), or your embedding model just isn’t strong enough to capture the right semantic match.</p><p><strong>The fix:</strong> Tune your chunk size, upgrade to a stronger embedding model, or add metadata filtering (like restricting search to department: HR before ranking) so irrelevant sections never even enter the candidate pool.</p><h3>Failure 3: Correct chunks retrieved, but the answer is still wrong</h3><p><strong>What’s actually happening:</strong> This is the one that convinces teams “our retrieval must be broken” when actually retrieval did its job perfectly. The right paragraph made it into the prompt. The generation model just failed to reason over it correctly.</p><p><strong>Why it happens:</strong> The generative LLM itself is too weak for the reasoning the task requires, retrieving the right numbers doesn’t help if the model can’t correctly do the arithmetic or comparison the question demands.</p><p><strong>The fix:</strong> Upgrade the generative model. This is a reminder that RAG has two halves, and better retrieval can’t compensate for a generation model that isn’t strong enough for the task.</p><h3>Failure 4: Outdated information returned</h3><p><strong>What’s actually happening:</strong> The system confidently retrieves an old version of a policy that was accurate six months ago and answers with it as if it were current.</p><p><strong>Why it happens:</strong> Your corpus itself is stale, nobody re-indexed it after the source documents changed, so the vector database has no idea the world moved on.</p><p><strong>The fix:</strong> Add a date metadata filter so retrieval can be biased toward the most recent version of a document, and implement incremental re-indexing so new or updated documents get embedded and added continuously, rather than the whole corpus being rebuilt on some slow manual schedule.</p><h3>Failure 5: Conflicting chunks</h3><p><strong>What’s actually happening:</strong> Two retrieved chunks genuinely disagree with each other say, an old policy PDF and a newer one that supersedes it and the LLM has to somehow pick, with no clear signal for which one is right.</p><p><strong>Why it happens:</strong> Multiple documents in your corpus contradict each other, often because old versions were never removed, or because different departments wrote overlapping policies independently.</p><p><strong>The fix:</strong> Add provenance metadata (which document, which version, which date) so the system or the LLM’s prompt, can reason about <em>which</em> source should win, and consider an explicit conflict-detection step that flags contradictions instead of silently picking one.</p><h3>Failure 6: Query-chunk vocabulary mismatch</h3><p><strong>What’s actually happening:</strong> The user asks a totally reasonable question, but phrases it in words that never appear anywhere near the answer in your documents so even a technically well-built retrieval system can’t find the connection.</p><p><strong>Why it happens:</strong> Users describe things in their own words (“my payslip is wrong”) while the documents use formal institutional language (“discrepancies in remuneration statements”) and if your retrieval relies purely on dense embeddings, this vocabulary gap can occasionally beat even a good semantic model.</p><p><strong>The fix:</strong> This is precisely the hybrid search + query expansion case from the <a href="http://re/">previous section </a>adding sparse retrieval (BM25) alongside dense catches literal-term overlaps, and query expansion (having the system rephrase or expand the user’s query into likely document terminology before searching) closes the rest of the gap.</p><h3>When should you look for which failure?</h3><blockquote><em>Work backwards through the pipeline, not forwards. Start by checking whether the </em>right<em> chunks were retrieved at all, if not, the problem is in retrieval (chunking, embeddings, vocabulary mismatch, staleness). If the right chunks </em>were<em> retrieved but the answer is still wrong, the problem has moved downstream into the prompt structure or the generative model itself. Fixing the wrong half of the pipeline is the single most common wasted-effort mistake teams make when debugging RAG.</em></blockquote><h3>Evaluating RAG Systems</h3><p><strong>“You can’t fix what you can’t measure and RAG has two separate report cards, not one.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCM1zIKxHw86o3GdyfihnQ.png" /></figure><h3>The analogy</h3><p>Imagine grading a student on an open-book exam. One grade measures whether they picked the <em>right pages</em> to open the book to. A completely separate grade measures whether they <em>wrote a good answer</em> once they had those pages in front of them. A student can get a perfect score on picking the right pages and still write a terrible answer and a student who grabbed the wrong pages can sometimes still stumble into a decent-sounding answer by luck. RAG evaluation is built the same way: <strong>retrieval quality</strong> and <strong>generation quality</strong> are graded separately, because a system can fail at either one independently.</p><h3>Retrieval quality metrics</h3><p><strong>“A librarian hands you a stack of 5 books for your research question. Precision asks: how many of those 5 were actually worth opening? Recall asks: out of every good book in the whole library, how many did she actually find? And MRR asks: was the best one sitting on top of the stack, or buried underneath four bad ones?”</strong></p><p>That’s the whole idea before any formula shows up, three different questions about the same stack of retrieved documents. Now let’s actually run the numbers.</p><h4>Precision@k</h4><p><strong>Precision@k</strong> asks: of the k documents I retrieved, what fraction were actually relevant?</p><pre>Precision@k = (relevant documents retrieved) / (total documents retrieved)</pre><p><strong>Worked example:</strong> Let’s say your RAG system retrieves 5 documents (k=5) for the query “what is our refund policy for damaged goods.” A human reviewer checks all 5 and finds that only 3 of them actually talk about refunds for damaged goods the other 2 are about unrelated topics (general shipping policy, and a return-window FAQ that doesn’t apply here).</p><pre>Precision@5 = 3 relevant / 5 retrieved = 0.6 → 60%</pre><p>That 60% is telling you something concrete: 2 out of every 5 chunks handed to your LLM were noise. Not catastrophic, but not clean either and it’s exactly the kind of number that explains why an LLM might occasionally get distracted and answer from the wrong document.</p><h4>Recall@k</h4><p><strong>Recall@k</strong> asks a completely different question: of <em>every</em> relevant document that exists anywhere in your whole corpus, what fraction did I actually manage to retrieve?</p><pre>Recall@k = (relevant documents retrieved) / (total relevant documents in the corpus)</pre><p><strong>Worked example:</strong> Same query, same 5 retrieved documents, same 3 of them relevant. But now imagine you (or a human labeler) go check the entire document corpus by hand, and it turns out there are actually <strong>6 total documents</strong> somewhere in the corpus that are genuinely relevant to “refunds for damaged goods” your system only surfaced 3 of them into the top 5.</p><pre>Recall@5 = 3 relevant retrieved / 6 total relevant in corpus = 0.5 → 50%</pre><p>Here’s the important part: this system has <strong>60% precision and 50% recall at the same time</strong>, and that combination tells a specific story of what it <em>did</em> retrieve, most was decent quality (precision), but it left half of the genuinely useful material undiscovered somewhere else in the corpus (recall). That’s a classic sign of a retrieval system that isn’t casting a wide enough net maybe k needs to be raised, or the embedding model isn’t surfacing paraphrased versions of the same policy.</p><blockquote><em>Think of it as: precision asks “was I accurate,” recall asks “was I thorough”, a good retrieval system needs both. You can chase one at the expense of the other (retrieve everything in the corpus and recall hits 100%, but precision collapses because most of it is junk) the real skill is tuning k and your retrieval strategy to keep both reasonably high.</em></blockquote><h4>MRR (Mean Reciprocal Rank)</h4><p><strong>MRR</strong> stops asking “how many” and starts asking “how soon.” It cares about <em>position </em>specifically, where does the <em>first</em> relevant document land in the ranked list?</p><pre>Reciprocal Rank (for one query) = 1 / (position of the first relevant result)<br>MRR = average of the Reciprocal Rank across all your test queries</pre><p><strong>Worked example:</strong> Let’s say you test your system with 3 different queries and check where the first genuinely relevant chunk showed up in each ranked result list:</p><ul><li>Query 1 (“refund for damaged goods”): first relevant chunk was at <strong>position 1</strong> → Reciprocal Rank = 1/1 = <strong>1.0</strong></li><li>Query 2 (“how do I return a broken item”): first relevant chunk was at <strong>position 3</strong> (two irrelevant chunks ranked above it) → Reciprocal Rank = 1/3 = <strong>0.33</strong></li><li>Query 3 (“damaged package compensation”): first relevant chunk was at <strong>position 4</strong> → Reciprocal Rank = 1/4 = <strong>0.25</strong></li></ul><pre>MRR = (1.0 + 0.33 + 0.25) / 3 = 1.58 / 3 ≈ 0.53</pre><p>An MRR of 0.53 tells you that, on average, the useful answer is landing somewhere around position 2 — not bad, but not consistently at the top either. And this is the number that catches a very specific problem: <strong>Query 1 had a perfect result, but Query 2 and 3 buried the right chunk under irrelevant ones.</strong> A system can have solid recall (the right chunks are <em>in</em> the list somewhere) while still having a mediocre MRR (they’re not near the top) and burying the right answer at position 3 or 4 is exactly the kind of thing that feeds Failure Mode 1 from earlier, where the LLM gives more weight to whatever’s sitting at the top of its context and half-ignores what’s buried further down.</p><h3>Generation quality metrics</h3><p><strong>Faithfulness: “Did the student answer using the book, or did they just make something up?”</strong></p><p>This checks whether the generated answer is actually grounded in the retrieved context, or whether the LLM wandered off and hallucinated something beyond what it was given. This is the single most important metric for catching Failure Mode 1 (LLM ignoring context), a low faithfulness score is the numeric fingerprint of that exact failure.</p><p><strong>Answer relevance: “Did the student actually answer the question that was asked?”</strong></p><p>A generated answer can be perfectly faithful to the retrieved context, every word technically true and grounded while still not addressing what the user actually asked. Imagine someone asks “how do I request a refund,” and the system faithfully summarizes the entire refund policy document without ever answering the practical “how do I actually do this” question. High faithfulness, low relevance.</p><p><strong>Context utilisation: “Did the student use the best pages, or just the first ones they flipped to?”</strong></p><p>This checks whether the LLM actually drew on the <em>most</em> relevant retrieved passages, rather than latching onto whichever passage happened to appear first or was easiest to summarize. Low context utilisation is often the fingerprint of Failure Mode 1 wearing a different disguise, the right information was technically present in the prompt, but the model leaned on the wrong part of it.</p><h3>Frameworks to know</h3><p>You don’t have to build these metrics by hand every time: a few open-source frameworks package them up:</p><ul><li><strong>RAGAS</strong> : the most widely used open-source RAG evaluation framework. It computes faithfulness, answer relevance, and context precision/recall automatically, using an LLM itself as the judge (essentially having a second, separate model grade your first model’s homework).</li><li><strong>TruLens</strong> : focuses on what’s often called the “RAG triad”: context relevance, groundedness, and answer relevance, evaluated together as a linked set.</li><li><strong>DeepEval: </strong>takes a unit-test-style approach, letting you write configurable, pass/fail-style test cases for your RAG pipeline the way you’d write software tests — useful when you want evaluation wired directly into a CI/CD pipeline rather than run as a one-off report.</li></ul><h3>Real-world build scenario</h3><p>Let’s say you’re asked to figure out why your company policy chatbot gave someone the wrong vacation-day count. Instead of guessing, you’d run it through this scorecard in order: first check Precision@k and Recall@k -&gt; did the vacation policy chunk even get retrieved? If yes, check MRR — did it land near the top of the list, or was it buried at position 9 next to five irrelevant HR documents? If it was retrieved and ranked well, move to faithfulness, is the generated answer actually consistent with what that chunk says, or did the LLM hallucinate a number? Each of these checks isolates a different possible failure mode from the section above, so instead of re-tuning your embedding model on a hunch, you know exactly which stage of the relay actually dropped the baton.</p><h3>When should you use which metric?</h3><blockquote><em>Retrieval metrics (Precision@k, Recall@k, MRR) tell you if the right information ever made it to the LLM in the first place. Generation metrics (faithfulness, answer relevance, context utilisation) tell you what the LLM did with it once it arrived. If you only measure one half, you’ll misdiagnose problems teams that only look at final-answer quality often “fix” the LLM prompt for weeks when the real problem was retrieval never finding the right chunk to begin with.</em></blockquote><h3>The one-paragraph version, if you remember nothing else</h3><p>RAG fails in specific, separable places, bad chunks retrieved, stale corpus, contradicting documents, vocabulary mismatch between user and documents, or a generation model that ignores or mishandles perfectly good retrieved context and each failure has a distinct fix, so diagnosing “the answer was wrong” starts with figuring out <em>which</em> stage actually broke. Retrieval quality is graded with Precision@k (was what I found relevant), Recall@k (did I find everything relevant), and MRR (how close to the top did the good stuff land); generation quality is graded separately with faithfulness (grounded in context, or hallucinated), answer relevance (did it actually answer the question), and context utilisation (did it use the <em>best</em> retrieved passage, not just the first one). Frameworks like RAGAS, TruLens, and DeepEval automate scoring both halves so instead of guessing why your RAG system is wrong, you can point to the exact number that tells you where.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab229cdffe24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cosine, Dot Product, and the Mysterious “Angle One”, Vector Similarity Explained Like You’re…]]></title>
            <link>https://medium.com/@aqsaa.malik99/cosine-dot-product-and-the-mysterious-angle-one-vector-similarity-explained-like-youre-91ed8b40036f?source=rss-3eebb32d955------2</link>
            <guid isPermaLink="false">https://medium.com/p/91ed8b40036f</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Aqsa A Malik]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 14:02:00 GMT</pubDate>
            <atom:updated>2026-07-12T17:08:43.755Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cosine, Dot Product, and the Mysterious “Angle One”, Vector Similarity Explained Like You’re Actually Building Something</h3><p><em>A no-jargon walkthrough of embeddings and similarity metrics, with real scenarios you’d actually get asked to build.</em></p><p>Let’s start with a scenario, because none of this will make much sense without one.</p><p>You’re asked to build a search bar for a company’s internal helpdesk. An employee types, <em>“My laptop won’t turn on,”</em> and you need the search bar to pull up the right support article. However, the relevant article is titled <em>“Troubleshooting Devices That Fail to Power On.”</em> It shares almost none of the same words as the user’s query.</p><p>To achieve this, comparing text the old way (matching literal words) isn’t enough. Instead, you convert both the user’s query and the article into <strong>vectors</strong>.</p><p><strong>Recap: Vector</strong></p><p>A vector is a long list of numbers produced by an embedding model that represents the semantic meaning of a piece of text. Since both the query and the article become vectors in the same <em>n</em>-dimensional space, we can mathematically measure how close they are to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42rTiJfQNyQMsB4qJJMHEQ.png" /></figure><p>The whole idea behind retrieving the correct article is to convert every query and every article into vectors, then use a similarity metric to determine how semantically similar they are. The closer the vectors are, the more likely the article matches the user’s intent.</p><h3>A Better Example</h3><p>Let’s begin by learning our first similarity method.</p><h3>Cosine Similarity</h3><blockquote><strong><em>“Ignore how loud they’re shouting, just check if they’re pointing in the same direction.”</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aN9T6XzeKBdWpBZwNEyOiA.png" /><figcaption>Analogy for Cosine Similarity</figcaption></figure><p>Picture two people pointing at something across a field. One is whispering, and the other is shouting. If their arms are pointed in exactly the same direction, they’re pointing at the same object. Cosine similarity only cares about the <strong>direction</strong> they’re pointing, not how loudly they’re speaking. Likewise, it only considers the direction of a vector, not its magnitude (length).</p><h3>So what does it actually do?</h3><p>Cosine similarity measures the angle between two vectors while ignoring their length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*wsrJYGag4nx124f8" /></figure><h3>Breaking down the formula</h3><p>Don’t let the formula scare you — it simply performs the same idea mathematically.</p><ul><li><strong>A · B (the dot product)</strong> measures how much the two vectors point in the same direction.</li><li><strong>‖A‖ and ‖B‖</strong> are the lengths (or magnitudes) of each vector.</li><li>Dividing the dot product by the product of the two lengths <strong>normalizes</strong> the result, removing the effect of vector size and leaving only the angle between them.</li></ul><p>Think of it as:</p><blockquote><strong><em>Shared direction ÷ Vector lengths = Pure directional similarity</em></strong></blockquote><p>That’s why the final score is always between <strong>-1 and 1</strong>:</p><ul><li><strong>1</strong> → Exactly the same direction (very similar)</li><li><strong>0</strong> → Perpendicular (no directional similarity)</li><li><strong>-1</strong> → Opposite directions</li></ul><h3>When should you use cosine similarity?</h3><p>Cosine similarity is the default choice for <strong>text embeddings</strong> because it compares <strong>meaning</strong> rather than the size of the embedding. It’s ideal for semantic search, document retrieval, recommendation systems, and question answering.</p><p>A good rule of thumb is:</p><blockquote><strong><em>Use cosine similarity for text embeddings by default, unless the model card explicitly recommends another similarity metric (such as dot product).</em></strong></blockquote><h3>Back to our earlier example</h3><p>Your employee’s query, <em>“laptop won’t turn on,”</em> is short. The matching article title is much longer and more formal:</p><p><em>“Comprehensive Troubleshooting Guide for Devices That Fail to Power On.”</em></p><p>If you compared these using a method that cared about <strong>vector magnitude</strong>, the longer, more detailed article could receive a different score simply because it contains more information. Cosine similarity removes that effect by normalizing both vectors and asking only:</p><blockquote><strong><em>“Are these vectors pointing in roughly the same direction?”</em></strong></blockquote><p>If they are, the texts are considered semantically similar, regardless of their length. That’s why cosine similarity is the default choice for semantic search: document length shouldn’t determine whether two pieces of text mean the same thing.</p><h3>Method 2: Dot Product</h3><blockquote><strong><em>“Both direction AND volume count.”</em></strong></blockquote><h3>The analogy</h3><p>Now imagine you’re not just checking if two people are pointing the same way, you’re also asking how <em>confident</em> or <em>loud</em> each of them is. A confident shout pointing at the right object should count for more than a timid whisper pointing the same way. Dot product keeps that “volume” information instead of throwing it away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ut7RMQJbifLpFN0eNXldPw.png" /></figure><h3>What it actually does</h3><p>Mathematically, dot product multiplies the matching positions in two vectors and adds the results together.</p><p>Unlike cosine similarity, it <strong>doesn’t divide by the vectors’ lengths (magnitudes)</strong>. That means both the <strong>direction</strong> and the <strong>magnitude</strong> of the vectors influence the final score.</p><p>If two vectors point in the same direction but one is much larger, the larger vector will produce a higher dot product.</p><h3>Breaking down the formula</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*5FjRG5sNcPZmFBjL5AR5HQ.png" /><figcaption>Dot product formula</figcaption></figure><p>Don’t let the formula intimidate you, it follows the same idea as cosine but skips the normalization step.</p><ul><li>Multiply each matching value in the two vectors.</li><li>Add all those products together.</li><li>The result is the dot product.</li></ul><p>Since we <strong>don’t divide by the vectors’ lengths</strong>, larger vectors naturally produce larger scores.</p><p>Think of it as:</p><blockquote><strong><em>Shared direction × Vector magnitude = Similarity score</em></strong></blockquote><p>Unlike cosine similarity, the score <strong>isn’t limited to between -1 and 1</strong>. It can be much larger (or smaller) depending on the sizes of the vectors.</p><h3>Real-world build scenario</h3><p>Let’s say you’re building a <strong>product recommendation engine</strong> for an e-commerce site.</p><blockquote><em>Here, “loudness” can be a genuinely useful signal. </em><strong><em>Some embedding models learn to encode useful information in a vector’s magnitude</em></strong><em>, while others expect all embeddings to be normalized to the same length. Whether magnitude carries meaning depends on how the model was trained. If magnitude does carry useful information, throwing it away (like cosine similarity does) would also throw away part of what the model learned. </em><strong><em>Dot product keeps that information, allowing those signals to influence the final ranking.</em></strong></blockquote><p>In that case, throwing away magnitude (as cosine similarity does) would also throw away useful information. Dot product keeps that information, allowing a highly relevant and popular item to rank above another item that’s equally similar but less important according to the model.</p><h3>The efficiency bonus</h3><p>Dot product is also slightly cheaper to compute. Cosine similarity requires an extra normalization step, dividing by the lengths of both vectors every time you compare two embeddings. At the scale of millions of searches, even that small extra computation adds up. A common engineering trick is to <strong>normalize every embedding once</strong>, when it’s first created or stored. After that, every vector has the same length (typically a magnitude of 1). At that point:</p><blockquote><strong><em>Dot Product = Cosine Similarity</em></strong></blockquote><p>because the normalization has already been done. Now you get the same ranking while only calculating a dot product during search, making retrieval a little faster. This is why you’ll often see model documentation say something like:</p><blockquote><strong><em>“Use dot product on normalized embeddings.”</em></strong></blockquote><p>or</p><blockquote><strong><em>“Optimized for dot product similarity.”</em></strong></blockquote><p>It’s usually a hint that the model expects embeddings to be normalized first, allowing you to get cosine-equivalent results with the cheaper dot product calculation.</p><h3>Method 3: Euclidean Distance</h3><blockquote><strong><em>“How far apart are the actual dots?”</em></strong></blockquote><h3>The analogy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*of2ViuEKCcaNgzXCmkkw8A.png" /></figure><p>Forget arrows and angles for a second. Picture two houses on a map. Euclidean distance is simply asking:</p><blockquote><strong><em>How many miles apart are they, in a straight line?</em></strong></blockquote><p>It doesn’t care which direction the houses face or whether one is “longer” than the other, it only cares about the literal distance between them. or in other words I can say <em>“It doesn’t care about the angle between them or which direction they point, it only cares about the literal distance between the two locations.</em></p><h3>What it actually does</h3><p>Euclidean distance measures the straight-line distance between the <strong>endpoints</strong> of two vectors using basic geometry, the same Pythagorean theorem you learned in school, just extended from two or three dimensions to hundreds (or even thousands).</p><p>The <strong>smaller</strong> the distance, the more similar the vectors are considered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*YlkS1IXVxFhjqq9Nyn_4tg.png" /></figure><h3>Breaking down the formula</h3><p>The formula simply measures how far apart two vectors are.</p><ul><li>Subtract each matching value.</li><li>Square each difference (so negatives don’t cancel positives).</li><li>Add them all together.</li><li>Take the square root.</li></ul><p>Think of it as:</p><blockquote><strong><em>“Measure the actual gap between these two points.”</em></strong></blockquote><p>Unlike cosine similarity or dot product, Euclidean distance isn’t measuring how similarly two vectors point, it measures <strong>how physically close they are in the embedding space.</strong></p><h3>Real-world build scenario</h3><p>Euclidean distance is especially useful when you’re interested in <strong>grouping</strong> similar data rather than simply ranking it.</p><p>Imagine you’re building a system that automatically organizes thousands of customer support tickets into categories.</p><p>The most common clustering algorithm, <strong>k-means</strong>, repeatedly asks a simple question:</p><blockquote><strong><em>“Which center point is this ticket physically closest to?”</em></strong></blockquote><p>Since the algorithm is based on finding the nearest center in space, Euclidean distance is the natural choice.</p><p>or for example you could use it in <strong><em>Image embeddings, it tend to work well with Euclidean distance because the notion of ‘closeness’ in image feature space maps more naturally onto literal spatial distance than onto pure direction.” </em></strong><em>but it is worth mentioning that this </em>isn’t universally true. Many modern image embedding models (like CLIP) are actually searched using <strong>cosine similarity</strong> or <strong>dot product on normalized vectors</strong>. It’s not that images are inherently better suited to Euclidean distance.</p><h3>When should you use Euclidean distance?</h3><p>Use Euclidean distance when <strong>actual spatial distance</strong> is meaningful, especially in clustering algorithms like <strong>k-means</strong> or whenever the embedding model was trained with Euclidean distance in mind.</p><p><em>For semantic text search, however, cosine similarity (or dot product on normalized embeddings) is usually the better default because it focuses on semantic similarity rather than absolute distance.</em></p><h3>Method 4: Angular Distance</h3><blockquote><strong>the “theta” one, finally identified</strong></blockquote><p>This is cosine similarity’s more rule-abiding cousin. Cosine similarity gives you a similarity score based on the angle between two vectors, but that score is not itself a proper distance measure. A lot of search algorithms rely on the <strong>triangle inequality</strong> the geometric rule that says “the direct path between two points can never be longer than the sum of two indirect paths.”</p><p>The problem is that the commonly used cosine distance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*vRUFZEv8nNSnplXhjCXhDg.png" /></figure><p>does not always satisfy this rule. Angular distance takes the actual angle (θ) between vectors and converts it into a proper distance value that follows these geometric rules.</p><h3>The Analogy: The Flight Connection Rule</h3><p>Imagine you are comparing three cities: <strong>City A</strong>, <strong>City B</strong>, and <strong>City C</strong>.</p><p>There is a fundamental rule in geometry called the <strong>Triangle Inequality</strong>:</p><blockquote><em>The direct distance from A to C should never be greater than going through an intermediate point B.</em></blockquote><p>In normal geography:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GFeVEoeVA5jPUutyJdlVA.png" /></figure><p>The direct route should always be the shortest possible path.</p><h3>The “Almost Distance” Cousin: Cosine Distance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LvOaocSw2B5jT9kJ7k0SFA.png" /></figure><p>Now imagine instead of measuring the actual miles between cities, you create a strange airline scoring system that only cares about the <strong>direction of travel</strong> from a central reference point.</p><p>Two cities pointing in similar directions receive a low score. Cities pointing in opposite directions receive a high score.</p><p>This system is useful because it captures “similar direction,” but it is not a true geographical distance.</p><p>Sometimes this scoring system can produce a strange situation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*xjOSkp2YAAROE62jq6akjA.png" /></figure><p>The system says:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*bb8isYfLsKJz4wWnFUonXg.png" /></figure><p>The direct route appears longer than the detour. That cannot happen with real distances, so the scoring system does not fully obey the triangle inequality.</p><h3>The “Rule-Abiding” Cousin: Angular Distance</h3><p>Angular Distance fixes this by going back to the actual angle between the two vectors.</p><p>Instead of using a custom similarity score, it asks:</p><blockquote><em>“What is the actual angle θ separating these two directions?”</em></blockquote><p>Formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*OHp6pCJIuNMulRVY4p2Mnw.png" /></figure><p>Now the measurement behaves like a real geometric distance:</p><ul><li>Same direction → distance 0</li><li>90° apart → distance 0.5</li><li>Opposite direction → distance 1</li></ul><p>Because it is based on the actual angle, it satisfies the mathematical rules expected by many nearest-neighbor search algorithms.</p><h3>Real-world connection:</h3><p>When searching through millions of embeddings (songs, images, documents, products), systems such as ANN indexes need a reliable definition of “closest.”</p><p>Cosine similarity tells you:</p><blockquote><em>“Are these vectors pointing in the same direction?”</em></blockquote><p>Angular distance converts that idea into:</p><blockquote><em>“How far apart are these directions?”</em></blockquote><p>That small change makes it suitable for algorithms that require a proper distance metric.</p><h4>What it actually does?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*pMTPpROOt646vARlbHOJKA.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*hxOPHYKypPAU2WWlQuGdPw.png" /></figure><p>converts the cosine similarity score back into the actual angle θ between the vectors. Dividing by π normalizes the value.</p><p>The result:</p><ul><li><strong>0</strong> → vectors point in exactly the same direction (identical orientation)</li><li><strong>0.5</strong> → vectors are perpendicular (90° apart)</li><li><strong>1</strong> → vectors point in opposite directions (180° apart)</li></ul><p>It is literally measuring the angle between two vectors rather than the straight-line gap between them.</p><h3>Example:</h3><p>Imagine two document embeddings:</p><p>Vector A: [1,0]</p><p>Vector B: [0,1]</p><p>Their cosine similarity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*eKGAHhZmg6ectD15JTliNg.png" /></figure><p>Convert it to angular distance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*hJXRcUpYq7jjvRgpY3EHlg.png" /></figure><p>The vectors are halfway apart in angular space because they point 90 degrees away from each other.</p><h3>Real-world example:</h3><p>Let’s say you are building a large-scale recommendation system with <strong>50 million song, podcast, or document embeddings</strong>. Comparing a new query vector against every stored vector would be too slow.</p><p>You would use an <strong>Approximate Nearest Neighbor (ANN)</strong> library such as Annoy. These systems build a search index, similar to a library catalog that lets you jump close to the right results instead of checking every single item.</p><p>For these indexes to work efficiently, the distance function needs to behave like a proper geometric distance. Angular distance works well because it preserves the meaning of cosine similarity while satisfying the mathematical properties required by many indexing methods.</p><p>A practical use case: Spotify-style music recommendation:</p><ul><li>Each song is converted into an embedding vector.</li><li>Songs with similar listening patterns have similar vector directions.</li><li>Angular distance finds songs whose embeddings point in similar directions.</li></ul><h3>The one-paragraph version, if you remember nothing else</h3><p><strong>Cosine checks</strong> if two things <em>point</em> the same way and ignores their size, good for text, the safe default.<strong> Dot product </strong>checks direction <em>and</em> size, good when size means something (like popularity) or when you’ve pre-normalized for speed. Euclidean checks literal distance between points, good for images and clustering. Angular distance is cosine’s angle, repackaged into a proper distance measurement so that speed-optimized search structures can use it safely. And in all four cases: check the model’s documentation before picking one, it already told you which one it was trained to use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91ed8b40036f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is MCP, and Why Do We Actually Need It?]]></title>
            <link>https://medium.com/@aqsaa.malik99/what-is-mcp-and-why-do-we-actually-need-it-1c60a7588b69?source=rss-3eebb32d955------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c60a7588b69</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Aqsa A Malik]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 23:09:33 GMT</pubDate>
            <atom:updated>2026-07-03T23:09:33.857Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A software engineer’s plain-language walkthrough of the protocol quietly becoming the backbone of agentic AI.</em></p><h3>What is MCP?</h3><p>Model Context Protocol, or MCP, is an open standard that lets an AI model connect to outside tools and data: your database, your GitHub repo, your Slack workspace, your internal APIs through one consistent interface instead of a custom-built connector for every single combination.</p><p>Anthropic introduced it in November 2024, and it caught on fast. By 2026 it’s supported by Anthropic, OpenAI, and Google DeepMind, and in December 2025 Anthropic handed governance of the protocol over to the Agentic AI Foundation, a Linux Foundation project co-founded with OpenAI and Block. That’s a meaningful detail: MCP stopped being “Anthropic’s thing” and became neutral, shared infrastructure the same trajectory HTTP, USB, and Kubernetes all went through.</p><p>The comparison you’ll hear most often is</p><blockquote>“USB-C for AI.”</blockquote><p>Before USB-C, every device had its own charger and cable. After it, one connector fits everything. MCP does the same job for AI models and the tools they need to use.</p><h3>Why do we need it?</h3><p>Here’s the situation that makes MCP click if you’ve been building software for a while.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVDMbP9t2HO4gQQOCZj4vQ.png" /></figure><p>Say you’re an engineer, and your team wants an AI assistant that can answer “what’s the status of ticket ENG-4521” by actually checking Jira, not guessing. So you write a Jira integration: authentication, pagination, error handling, a translation layer that turns Jira’s API responses into something the model can reason about. Fine. Then someone asks for the same assistant to check GitHub PRs. New integration, new auth flow, new pagination scheme, new translation layer. Then Confluence. Then your internal billing service. Then someone switches the underlying model from Claude to GPT, and because you wrote each integration as a bespoke wrapper around that specific model’s function-calling format, you get to redo a chunk of it.</p><h3>The N × M problem</h3><p>This is what’s known as the N×M integration problem: N models times M tools equals N×M one-off pieces of glue code, each with its own bugs, its own auth quirks, its own maintenance burden. Engineering teams that got serious about AI assistants in 2023–2024 hit this wall almost immediately. Some shops reported dozens of custom adapters just to give one assistant reasonable reach into their own systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Afgg4u7XtSeRy7WPpHnvvg.png" /></figure><h3>How MCP fixes it</h3><p>MCP flips N×M into N+M. A tool builder writes one MCP server for their tool once. A model or AI application builder writes one MCP client once. Any client can now talk to any server, because they’re speaking the same protocol. You still have to build the individual connectors, but you build one per tool instead of one per (tool, model) pair, and you don’t have to rebuild them when a new model shows up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*EzqjGwQ_WaD-FuOfYPZeTw.png" /></figure><p>One clarification that’s easy to get wrong: <strong>MCP does not replace the APIs that already exist.</strong> GitHub already has REST and GraphQL APIs. Jira already has REST APIs. Slack already has its own. MCP doesn’t touch any of that. Instead, someone writes an MCP server that sits on top of those existing APIs and re-exposes their functionality in a standard, model-readable format. The MCP server is an adapter, not a replacement.</p><h3>Where Google fits in</h3><p>This is where the terminology gets a little muddled, so it’s worth separating two different things that both have “Google” in them.</p><p><strong>First: Google supports MCP itself.</strong> Google DeepMind and Google Cloud both ship MCP-compatible tooling, Gemini can act as an MCP host, and Google’s Agent Development Kit has built-in MCP support. So when people say “Google MCP,” they often just mean Google’s adoption of the same open standard everyone else uses.</p><p><strong>Second, and more interesting: Google built a related but different protocol called A2A/Agent2Agent.</strong> Announced in April 2025 with backing from over 50 partners including Salesforce and Atlassian, A2A solves a problem MCP doesn’t: how multiple <em>agents</em> talk to each other, rather than how one agent talks to a <em>tool</em>. Google’s own framing is useful here, think of a car repair shop.</p><p>MCP is the protocol connecting a repair agent to its structured tools (“raise the platform two meters,” “torque the wrench to spec”). A2A is what lets the customer, or another agent, have an open-ended back-and-forth with the shop “my car’s making a rattling noise,” “send me a picture of the wheel” that isn’t a fixed function call.</p><p>The two aren’t competitors. MCP handles agent-to-tool. A2A handles agent-to-agent. A production system increasingly uses both: an orchestrator agent delegates a sub-task to a specialist agent over A2A, and that specialist then reaches into its own tools and data over MCP.</p><h3>If I were building one tomorrow, what would I actually do?</h3><p>The good news is that if you’ve ever built a REST API, integrated with a third-party service, or written backend business logic, you’ve already done most of the hard work an MCP server requires.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c60a7588b69" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>