<?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 Himal Mangla on Medium]]></title>
        <description><![CDATA[Stories by Himal Mangla on Medium]]></description>
        <link>https://medium.com/@himalmangla?source=rss-4d5982e3be85------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*LbIVqV4VYgeyGkTA</url>
            <title>Stories by Himal Mangla on Medium</title>
            <link>https://medium.com/@himalmangla?source=rss-4d5982e3be85------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:15:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@himalmangla/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[Does This Decision Really Need an LLM?]]></title>
            <link>https://medium.com/data-science-collective/does-this-decision-really-need-an-llm-54379410d7dc?source=rss-4d5982e3be85------2</link>
            <guid isPermaLink="false">https://medium.com/p/54379410d7dc</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Himal Mangla]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 21:42:55 GMT</pubDate>
            <atom:updated>2026-11-26T21:42:55.543Z</atom:updated>
            <content:encoded><![CDATA[<p><em>When to use an LLM, a decision model like Jev, or a small neural network.</em></p><p>Think about a voice support app. It has to <strong>hear a wake word</strong>, <strong>route a complaint</strong>, and <strong>draft a reply</strong>. An LLM could help with the last two. For the first, I’d put a small neural network on the device and wake the rest of the system only when it fires.</p><p>The model choice changes with the job. To make that trade-off visible, I built a <strong>20,099-parameter</strong> model that plays Snake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*A55_n4VlENbP0cB4XR7Wzg.gif" /></figure><p>The snake can go straight, turn right, or turn left. On the starting board, <strong>right wins</strong>. In mid-game, <strong>straight wins by less than 0.04</strong>. What changed?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6yvabBCQJAMAt2dDTQ3Lg.png" /></figure><p><a href="https://himal-dev.github.io/small-models-matter/"><strong>Try it in the browser →</strong></a> Pick <strong>Game start</strong>, then <strong>Mid-game (scripted)</strong>. Open <strong>Inspect → Output</strong> to see the weights and bias behind each number. A Q-value estimates discounted future reward. The gap between two Q-values is a difference in predicted reward, not a confidence score.</p><h3>1. Give the model a state, not a description</h3><p>The <a href="https://www.nature.com/articles/nature14236">original Deep Q-Network paper</a> learned to play Atari from pixels. Snake already gives me the board, so I can skip vision. I turn its state into <strong>24 numbers</strong>: danger in each direction, heading, distances to food and obstacles, and a few other features.</p><pre>Board → 24 features → two 128-unit ReLU layers<br>      → 3 Q-values → pick the largest</pre><p>That interface is the main design choice. If the input were a screenshot, I’d still need to locate the snake, the walls, and the food. Even with direct access to the game, these 24 features can miss the shape of a trap. Decide what information you can afford to discard before you choose the model.</p><h3>2. Measure speed and quality separately</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SqqgioV3vuGPzXnzVm9b6A.png" /></figure><p>The <strong>37 µs median</strong> covers feature extraction, the PyTorch forward pass, and argmax on one Apple M3 Pro CPU thread. The full headless game step took <strong>61 µs median</strong>. The repeat run barely moved the decision median, but p99 went from <strong>70 to 166 µs</strong>. If the decision has a deadline, that tail matters.</p><p>For quality, I compared the released model with a rule that picks the safe move closest to food. Across <strong>100 seeded games per policy</strong>, the DQN averaged <strong>36.6 food vs. 26.4</strong> for the rule. That’s a useful baseline for this game; it doesn’t establish an advantage over stronger search-based players.</p><h3>3. Work through one learning target</h3><p>Switch the demo back to <strong>Recorded game replay</strong> and look for <strong>One demo transition</strong>. Here’s the arithmetic from the first move of the replay:</p><pre>Predicted value of turning left     8.32<br>Reward for moving closer         +  0.05<br>Target                           ≈  0.05 + 0.90 × 9.52 = 8.62<br>Target − prediction              ≈ +0.30</pre><p>The positive error means this sample pushes the value of that action up. During training, Adam combines gradients from <strong>128 replayed moves</strong>, and a separate target network supplies the next-state value. The browser uses the released checkpoint for both predictions so you can see the math.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8kGh5xIw_Ureu6AlLSeEg.png" /></figure><p>The score and the loss can rise together because the loss tracks prediction error on changing samples and targets. <strong>Measure whether the policy got better by what it did in the game.</strong></p><h3>4. Choose by the job, not the model category</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abrNntsjkw6mu5v3ZLgD4A.png" /></figure><p><strong>Small local network: spot a pattern in a stream.</strong> <a href="https://arxiv.org/abs/2007.10319">MCUNet</a> co-designed the network and inference engine to fit microcontrollers. <a href="https://mlcommons.org/benchmarks/inference-tiny/">MLPerf Tiny</a> tests streaming wake words and machine-sound anomaly detection. For a wake word, measure false wakes per hour and missed activations; for machine monitoring, measure false alarms and detection delay on held-out machines.</p><p><strong>Small vision model: filter camera frames on-device.</strong> A camera can flag frames likely to contain a defect and save the rest of the pipeline for those frames. <a href="https://arxiv.org/abs/2404.10518">MobileNetV4</a> reported <strong>3.8 ms</strong> model runtime on a Pixel 8 Edge TPU at <strong>87% ImageNet top-1 accuracy</strong> for one variant. That’s evidence for efficient mobile vision, not a defect-detection result. Test on your cameras and parts.</p><p><strong>Jev-style decision model: interpret messy evidence, then choose from a fixed set.</strong> Think routing a complaint to <em>billing</em>, <em>technical support</em>, or <em>review</em>. TypeSafe’s <a href="https://typesafe.ai/blog/introducing-system-one-models-and-jev">193.6× claim</a> came from its own workflow evaluations, with other frontier models as the reference. Snake had no hosted baseline. For ticket routing, compare with a classifier trained on your tickets or an LLM with the same output schema. Measure how many tickets each can auto-route at your error limit. The independent <a href="https://artificialanalysis.ai/methodology/decision-index">Artificial Analysis Decision Index</a> also tests calibration and consistency under rewording.</p><p><strong>LLM: do work that benefits from generation or open-ended reasoning.</strong> Draft a response that reconciles a customer’s history with a policy document. Use code for hard constraints, such as checking the refund limit. If some requests genuinely need a stronger model, route those requests separately: <a href="https://arxiv.org/abs/2406.18665">RouteLLM</a> evaluates learned routing between weaker and stronger LLMs as a way to trade cost against response quality.</p><p><strong>Before you pick a model, write down what goes in, what must come out, how late is too late, and what happens when it’s wrong.</strong> Compare candidates on the same cases at the quality you need, then measure p99 from available input to usable output. If a rule is good enough, keep it.</p><p><a href="https://himal-dev.github.io/small-models-matter/">Open the demo</a> · <a href="https://github.com/Himal-dev/small-models-matter">Run the benchmark and policy evaluation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54379410d7dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/does-this-decision-really-need-an-llm-54379410d7dc">Does This Decision Really Need an LLM?</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Voice and Vision-Native AI Agents from SOPs]]></title>
            <link>https://medium.com/@himalmangla/building-voice-and-vision-native-ai-agents-from-sops-af6d2c641738?source=rss-4d5982e3be85------2</link>
            <guid isPermaLink="false">https://medium.com/p/af6d2c641738</guid>
            <category><![CDATA[ai-voice-agent]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Himal Mangla]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 18:28:25 GMT</pubDate>
            <atom:updated>2026-06-07T18:28:25.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Compiled Runtime for Real-World Execution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAe8_G8vOEhVJpSdLz03wQ.png" /></figure><p>It is easy to build a demo of an AI agent. You write a system prompt, paste a few examples, write a regex to parse the LLM’s output, and run it in a loop.</p><p>But it is incredibly hard to build an agent you would deploy in front of a stranger - on a phone, over a flaky cellular network, with API keys that cost real money per call - and have it either <strong>do the exact right thing or say honestly that it cannot.</strong></p><p>This is the story of how a hackathon project evolved into <strong>SOPilot</strong>, a procedure compiler that treats Standard Operating Procedures (SOPs) as compiled code and agent runtimes as framework-agnostic execution engines.</p><h3>The Origin: The “Inspection Jockey”</h3><p>The thesis behind SOPilot was born out of a hackathon. The challenge was to build a mobile voice-and-vision agent to lead a car inspector through a vehicle check. The agent had to act as an “Inspection Jockey” speaking one instruction at a time, instructing the user to snap pictures of the tires and bumpers, analyzing those photos in real-time for dents, and filling out a damage report.</p><p>The naive implementation was what you might expect: a massive system prompt containing the checklist, a LangChain parser, a voice loop, and a prayer.</p><p>In practice, it failed instantly:</p><ul><li><strong>LLM Drift:</strong> The model would skip steps, get excited, and ask for a photo of the rear windshield before confirming the front bumper was inspected.</li><li><strong>Orchestration Spaghetti:</strong> Writing branching logic in Python code to handle user retries or bad photos resulted in hundreds of lines of nested if-else loops.</li><li><strong>Evidence Hallucination:</strong> The agent would confidently write “No scratches detected on bumper” in the final JSON, but when audited, there was no record of which photo backed up that claim.</li></ul><p>The realization was immediate: <strong>Expertise lives in SOPs, not prompts.</strong> Mechanics, field technicians, nurses, and insurance adjusters already work off written checklists and runbooks. The procedure is the product surface; the prompts and graphs are just runtime implementation details.</p><p>What if the SOP itself was the program, and the agent was just its runtime?</p><h3>The Core Thesis of SOPilot</h3><p>SOPilot is built on three architectural assertions:</p><ol><li><strong>The SOP is a compilable artifact.</strong> Adding a new use case or changing an inspection protocol should mean updating a text document, not writing Python orchestration code.</li><li><strong>Multimodality is the primary interface, not a tool.</strong> A plant triage or vehicle inspection isn’t text-in / text-out. It is a stateful conversation over visual evidence. Treating voice and vision as bolt-on tools is a category error; they must be modeled as the primary I/O seams.</li><li><strong>Trust requires an Evidence Ledger.</strong> A confident-sounding LLM answer without a traceable observation behind it is a liability. Every conclusion must trace back to a verifiable observation (a photo ID, a raw voice utterance, or an API response) recorded in an append-only ledger.</li></ol><p>Here is the high-level architecture of SOPilot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHSi1no8s8qJp0ibG3cIPg.png" /></figure><h3>1. The Compiler Step: Markdown as Source Code</h3><p>Instead of feeding a raw 2,000-word SOP markdown file into a prompt window, SOPilot uses a <strong>Procedure Compiler</strong>. The compiler parses markdown headings, list items, and annotations into a strictly typed, inspectable CompiledWorkflow JSON object.</p><p>The SOP author writes the procedure using standard markdown list items, guided by semantic inline tags:</p><pre># Plant Health Check<br><br>A single-plant care SOP. <br><br>## Identify<br>- Capture the whole plant in frame [vision] [evidence: whole_plant_photo] [produces: plant]<br><br>## Examine<br>- Capture a close-up of the affected leaves [vision] [evidence: closeup_photo] [produces: symptoms] [min_confidence: 0.6]<br><br>## Interview<br>- Ask the gardener about care habits [voice] [evidence: care_habits_audio] [produces: care_habits] [ask: What is your watering routine?; What light does the plant get?]<br><br>## Diagnose<br>- Determine the likely cause [reason] [produces: diagnosis]<br><br>## Finalize<br>- Submit the plant care report [reason] [review: final_submit] [produces: care_report]</pre><p>At compile time, sop_compiler turns this into a structured JSON definition. Here is the magic: <strong>SOPilot can compile this locally and deterministically using regex parsers with zero API dependencies.</strong> It also supports an LLM-compiler hook for complex document parsing, but it fails closed back to the local parser if API keys are missing.</p><p>By compiling the SOP, you gain a critical advantage: <strong>you can inspect the execution plan before running it</strong>. You can run:</p><pre>python -m sopilot compile examples/plant_doctor_agent</pre><p>You receive a compiled workflow JSON containing steps, preconditions, required evidence keys, validation rules, decision points, and human-in-the-loop review points. You can review it, check it into git, diff it across commits, and run CI tests against it. Swapping an agent’s behavior becomes a git-diff.</p><h3>2. Structured Central State: The Thinking State</h3><p>Many developer-centric agent frameworks represent the world as a chat history list: messages: list[Message]. But for structured procedures, chat history is noise.</p><p>SOPilot models the agent’s world using a typed <strong>Central State - </strong>a structured Pydantic object that stores the state of the procedure, completed steps, pending steps, tool results, risks, and output payloads.</p><p>Here is the central state schema:</p><pre>class State(BaseModel):<br>    goal: str = &quot;&quot;<br>    sop_version: str = &quot;v1&quot;<br>    current_step: Optional[str] = None<br>    completed_steps: Annotated[List[str], operator.add] = Field(default_factory=list)<br>    pending_steps: List[str] = Field(default_factory=list)<br>    observations: Annotated[List[Dict[str, Any]], operator.add] = Field(default_factory=list)<br>    evidence: Annotated[List[Dict[str, Any]], operator.add] = Field(default_factory=list)<br>    tool_results: Annotated[List[Dict[str, Any]], operator.add] = Field(default_factory=list)<br>    risks: Annotated[List[Dict[str, Any]], operator.add] = Field(default_factory=list)<br>    human_overrides: Annotated[List[Dict[str, Any]], operator.add] = Field(default_factory=list)<br>    step_outputs: Dict[str, Any] = Field(default_factory=dict)<br>    final_output: Optional[Dict[str, Any]] = None<br>    status: str = Field(default=&quot;running&quot;)  # running | completed | rejected</pre><p>Because list fields utilize Pydantic’s annotations with operator.add reducers, graph execution nodes are completely side-effect free. They return only <em>new</em> observations or risks, and the underlying graph framework (in this case, LangGraph) appends them automatically.</p><h3>The LangGraph Isolation Principle</h3><p>An important architectural detail in SOPilot is that <strong>LangGraph is an implementation detail</strong>.</p><p>LangGraph imports are strictly confined to core/state_runtime/graph.py and core/planner/planner.py. The adapters, tool connectors, compilers, and schemas are entirely unaware of LangGraph. This isolation ensures that if the team ever needs to swap the underlying execution engine to a different graph tool, a custom state machine, or a hosted service, the core product codebase remains untouched.</p><pre>def build_graph(planner: Planner):<br>    graph = StateGraph(State)<br>    graph.add_node(PLAN, planner.plan_node)<br>    graph.add_node(EXECUTE, planner.execute_node)<br>    graph.add_node(REVIEW, planner.review_node)<br>    graph.add_node(FINALIZE, planner.finalize_node)<br><br>    graph.add_edge(START, PLAN)<br>    graph.add_conditional_edges(PLAN, planner.route_after_plan)<br>    graph.add_conditional_edges(EXECUTE, planner.route_after_execute)<br>    graph.add_conditional_edges(REVIEW, planner.route_after_review)<br>    graph.add_edge(FINALIZE, END)<br>    return graph</pre><h3>3. The Evidence Ledger: Auditing by Default</h3><p>In high-stakes applications - like vehicle inspections, health checks, or compliance auditing - eloquence is dangerous. A confident agent outputting “Everything is fine” without proof is a liability.</p><p>SOPilot solves this by enforcing an <strong>Evidence Ledger</strong>. Every time the vision, voice, or tool adapters perform an action, the planner writes a record to the ledger. When the final output generator constructs the structured JSON report, it does not just output string values; it outputs fields mapped directly to the evidence entries that generated them.</p><p>An evidence record contains:</p><pre>{<br>  &quot;id&quot;: &quot;ev_08f1b9&quot;,<br>  &quot;step_id&quot;: &quot;capture_a_close_up_of_the_affected_leaves_or_ste&quot;,<br>  &quot;claim&quot;: &quot;Yellowing leaf margins and brown spots visible on leaves.&quot;,<br>  &quot;evidence&quot;: [&quot;closeup_photo&quot;],<br>  &quot;model&quot;: &quot;gpt-4o&quot;,<br>  &quot;confidence&quot;: 0.88,<br>  &quot;timestamp&quot;: &quot;2026-06-07T03:07:12Z&quot;<br>}</pre><h3>Failing Closed</h3><p>If a step has a defined threshold (e.g., [min_confidence: 0.6]) and the vision adapter returns an observation with 0.4 confidence (due to a blurry camera or bad lighting), the planner doesn&#39;t ignore it. It flags a <strong>Risk</strong> and appends it to the central state.</p><p>Furthermore, when the configuration require_live: true is enabled, the runtime will <strong>fail closed</strong> if a live API call fails, rather than silently falling back to placeholder strings or demo fixtures. The run halts, providing the browser client or downstream consumer with a structured block of missing requirements and next steps.</p><h3>4. Voice and Vision: Adapters with Backpressure</h3><p>Many agent architectures treat voice and vision as tools inside a toolset. They give the LLM a take_photo tool and let it decide when to use it. This is a recipe for chaotic user experiences.</p><p>SOPilot models voice and vision as <strong>first-class adapters</strong>. The planner controls the conversation flow.</p><h3>Spoken Backpressure</h3><p>A voice SOP is not a free-flowing chatbot transcript. It is a structured interview with <em>backpressure</em>. The agent must ask one question, verify the answer satisfies the SOP step, write the evidence, and only then proceed.</p><p>SOPilot’s voice adapter integrates directly with <strong>ElevenLabs Conversational AI</strong> (ConvAI).</p><p>Instead of hardcoding a dialogue tree into ElevenLabs, SOPilot compiles the SOP manifest, extracts the media and question requirements, and programmatically generates dynamic system instructions and client-side tools for the ElevenLabs runtime:</p><pre># Programmatic instructions generated for the voice model:<br>&quot;If submitPlantDoctorRun reports failure... do not ask the care routine again; &quot;<br>&quot;ask only for the missing or low-confidence photo retry. &quot;<br>&quot;When retry_photo_fields includes whole_plant_photo, ask for the whole plant &quot;<br>&quot;again and call captureWholePlantPhoto...&quot;</pre><p>By generating these instructions from the SOP compiler, the voice model is bound to the state of the graph. If the user uploads a blurry photo, the voice model receives feedback from the backend tool and politely asks: <em>“It looks like the close-up photo was a bit blurry. Could you please retake a clear shot of the affected leaves?”</em></p><h3>5. Case Study: The Plant Doctor</h3><p>The flagship reference implementation of SOPilot is the <strong>Plant Doctor</strong> (examples/plant_doctor_agent). It is a voice-guided, mobile-first web app that walks a gardener through diagnosing plant health issues.</p><pre># Start the FastAPI server locally<br>uvicorn app.server:app --reload</pre><p>The application demonstrates the ultimate separation of concerns:</p><ul><li><strong>The Web Shell is Generic:</strong> The HTML/JS frontend consumes the compiled agent manifest. It doesn’t know about plants, cars, or runbooks. It simply reads the media requirements (two photo uploads, one voice field) and renders the corresponding UI camera buttons and the ElevenLabs WebRTC microphone.</li><li><strong>HITL Interrupt:</strong> In sop.md, the final step is [review: final_submit]. During execution, the graph runs through photo capture and voice interview, drafts the diagnosis report, and then hits a LangGraph interrupt. The server holds the run state open in a temporary SQLite checkpointer. The user can view the draft report, edit the text, and click &quot;Submit Care Report,&quot; which resumes the graph to write the final record.</li><li><strong>Low-Cost Serverless Deployment:</strong> To prove it is ready for production, the Plant Doctor demo is packaged to run on AWS Lambda via Mangum behind an API Gateway URL, with static assets hosted on S3. Invite codes are verified at the gateway edge to prevent unauthorized API billing.</li></ul><h3>What We Learned</h3><p>Building SOPilot taught us that the key to reliable agent systems is <strong>harnessing the LLM inside a deterministic scaffolding</strong>.</p><p>By compiling written procedures, keeping the central state strictly structured, enforcing an evidence ledger, and treating voice/vision as framework seams, we can build agents that run on a mobile browser, handle network disconnects, pause for human edits, and never lie about why they reached a conclusion.</p><p>If you are currently building production agents, consider moving away from prompt chaining. Build a compiler. Define your seams. And let the SOP be the code.</p><p><em>SOPilot is open source and structured as a set of modules under </em><em>core/ (compiler, planner, adapters, tool router) and </em><em>sopilot/ (CLI and runtime helpers). Explore the codebase under </em><a href="https://github.com/Himal-dev/SOPilot"><em>SOPilot Repo</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af6d2c641738" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your RAG System is Failing: Vector Search vs Cross-Encoders]]></title>
            <link>https://medium.com/data-science-collective/why-your-rag-system-is-failing-vector-search-vs-cross-encoders-c239048afe7d?source=rss-4d5982e3be85------2</link>
            <guid isPermaLink="false">https://medium.com/p/c239048afe7d</guid>
            <category><![CDATA[reranking]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[production-ml]]></category>
            <category><![CDATA[cross-encoder]]></category>
            <dc:creator><![CDATA[Himal Mangla]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 00:21:58 GMT</pubDate>
            <atom:updated>2025-09-03T10:46:04.996Z</atom:updated>
            <content:encoded><![CDATA[<h4>How a Hybrid Search Architecture Transformed Our Search Relevance from 47% to 91%</h4><p>You’re building a RAG system. User searches for “monsoon weather patterns”, your vector search confidently returns documents about… parliamentary sessions?</p><figure><img alt="Photo by Google DeepMind" src="https://cdn-images-1.medium.com/max/1024/1*SGHRGN8yapnfa2EJ6xERCQ.jpeg" /></figure><p><strong>This actually happened.</strong> Our system was matching “Heavy monsoon rains expected this week” with “The monsoon session of Lok Sabha will happen this week” - similarity score: 0.7.</p><p>Why? Some shared words: “monsoon”, “this week”</p><p>Here’s why, and how to fix it.</p><h4>Why Vector Search Alone Falls Short in RAG</h4><p>The issue lies in the architectural limitation of <strong>bi-encoder systems operating in isolation</strong>. Queries and documents are encoded independently into fixed vectors. Cosine similarity then approximates relevance</p><pre>from sentence_transformers import SentenceTransformer<br>from sklearn.metrics.pairwise import cosine_similarity<br><br>model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)<br><br># Traditional approach - encode separately, compare vectors<br>query_embedding = model.encode(&quot;monsoon weather patterns&quot;)<br>doc_embedding = model.encode(&quot;monsoon session of parliament&quot;)<br><br>similarity = cosine_similarity(query_embedding, doc_embedding)<br># Result: 0.6  # &quot;highly similar, but totally unrelated&quot; </pre><blockquote>Vector search gets fooled by homonyms, shared vocabulary, and keyword overlap without semantic relationship.</blockquote><h4>Cross-Encoders: Processing Texts Together</h4><p>Cross-encoders solve this by processing both texts <strong>jointly:</strong></p><pre>from sentence_transformers import CrossEncoder<br><br>cross_encoder = CrossEncoder(&#39;cross-encoder/ms-marco-MiniLM-L-6-v2&#39;)<br><br>score = cross_encoder.predict([(&quot;monsoon weather patterns&quot;, <br>                               &quot;monsoon session of parliament&quot;)])<br># Result: -5.26  # correctly identifies no relevance! </pre><h4>Architecture Difference: Bi-encoder vs Cross-Encoder</h4><pre>#VectorSearch(Bi-Encoder):<br><br>Text A → Encoder → Vector A ┐<br>                            ├→ Cosine Similarity<br>Text B → Encoder → Vector B ┘<br><br>#Cross-Encoder:<br>[CLS] Text A [SEP] Text B [SEP] → Joint Encoder → Similarity Score</pre><p><strong>Key difference</strong>: Cross-attention between all tokens across both texts. The model sees relationships, not just individual meanings.</p><h3>Production Architecture: Two-Stage Retrieval</h3><p>We combine the bi-encoder efficiency with cross-encoder precision through staged retrieval architecture:</p><p><strong>Stage 1 (Dense Vector Search)</strong>: Vector search provides high-recall candidate retrieval, processing millions of documents in sub-50ms latency to identify the top 20-50 candidates.</p><p><strong>Stage 2 (Cross-Encoder Reranking)</strong>: Cross-encoder evaluation reorders candidates based on contextual relevance, delivering high-precision results through joint processing.</p><pre>import numpy as np<br>from sentence_transformers import SentenceTransformer, CrossEncoder<br>from sklearn.metrics.pairwise import cosine_similarity<br><br># Load models once<br>embedding_model = SentenceTransformer(&#39;all-MiniLM-L6-v2&#39;)<br>cross_encoder = CrossEncoder(&#39;cross-encoder/ms-marco-MiniLM-L-6-v2&#39;)<br><br>def production_search(query: str, documents: List[str], <br>                     stage1_k: int = 20, final_k: int = 5):<br>    &quot;&quot;&quot;Two-stage retrieval: fast vector search + precise reranking&quot;&quot;&quot;<br>    <br>    # Stage 1: Fast vector retrieval<br>    query_embedding = embedding_model.encode([query])<br>    doc_embeddings = embedding_model.encode(documents)<br>    vector_scores = cosine_similarity(query_embedding, doc_embeddings)[0]<br>    <br>    # Get top candidates<br>    top_indices = np.argsort(vector_scores)[::-1][:stage1_k]<br>    candidates = [documents[i] for i in top_indices]<br>    <br>    # Stage 2: Cross-encoder reranking<br>    cross_scores = cross_encoder.predict([(query, doc) for doc in candidates])<br>    <br>    # Final ranking<br>    final_results = list(zip(top_indices, cross_scores))<br>    final_results.sort(key=lambda x: x[1], reverse=True)<br>    <br>    return final_results[:final_k]</pre><h4>Why This Works</h4><p><strong>Stage 1</strong>: Fast vector search casts a wide net (high recall)<br><strong>Stage 2</strong>: Cross-encoder filters precisely (high precision)</p><p><strong>Performance</strong>: Search millions of documents in ~70ms with 90%+ relevance.</p><h4>What’s next / Engineering Best Practices for RAG Retrieval</h4><ul><li><strong>Model Selection Strategy</strong>: Deploy proven architectures like cross-encoder/ms-marco-MiniLM-L6-v2 for general domains. For specialized applications, fine-tune on domain-specific relevance data. Recent benchmarks indicate MiniLM-based models provide optimal accuracy-to-latency ratios</li><li>Score Caching: Cache top reranking scores for repeated queries; 40-60% of queries are common patterns.</li><li>Deploy cross-encoders on GPU clusters for faster inferences</li><li><strong>Dense retrieval: </strong>For non-generic use cases, use models like SimCSE for better embeddings</li></ul><h4>Final Thoughts</h4><p>Cross-encoders provide the contextual precision that embedding similarity approximates but cannot deliver reliably.</p><p>Production data consistently demonstrates that users value accuracy over speed. The 3-5x computational cost of hybrid retrieval delivers 10x precision improvements that translate directly to improved user experience and business outcomes.</p><p><em>If this helped you fix your search relevance, clap and share with your team!</em></p><p>#RAG #SemanticSearch #CrossEncoders #VectorSearch #InformationRetrieval #ProductionML</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c239048afe7d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/why-your-rag-system-is-failing-vector-search-vs-cross-encoders-c239048afe7d">Why Your RAG System is Failing: Vector Search vs Cross-Encoders</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>