<?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 Shailesh Chaudhary on Medium]]></title>
        <description><![CDATA[Stories by Shailesh Chaudhary on Medium]]></description>
        <link>https://medium.com/@shailesh16221?source=rss-6433c74bc518------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2KIrMkveZ-FrTei0n0djLg.png</url>
            <title>Stories by Shailesh Chaudhary on Medium</title>
            <link>https://medium.com/@shailesh16221?source=rss-6433c74bc518------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:50:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shailesh16221/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[OpenClaw — A Detailed Deep Dive]]></title>
            <link>https://medium.com/@shailesh16221/openclaw-a-detailed-deep-dive-902455554ceb?source=rss-6433c74bc518------2</link>
            <guid isPermaLink="false">https://medium.com/p/902455554ceb</guid>
            <category><![CDATA[openclaw]]></category>
            <category><![CDATA[calwbot]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-agents-in-action]]></category>
            <dc:creator><![CDATA[Shailesh Chaudhary]]></dc:creator>
            <pubDate>Wed, 13 May 2026 05:29:32 GMT</pubDate>
            <atom:updated>2026-05-13T05:29:32.633Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A complete conceptual + architectural walkthrough of OpenClaw (a.k.a. Clawd), the self-hosted personal AI agent platform created by Peter Steinberger.</em></p><h3>0. What is OpenClaw, really?</h3><p>OpenClaw is <strong>not a chatbot</strong>, and it is <strong>not a wrapper around an LLM API</strong>. The right mental model is:</p><blockquote><strong><em>OpenClaw is an “operating system” for a personal AI agent.</em></strong><em> The LLM provides the </em>intelligence<em>. OpenClaw provides the </em>execution environment<em> — sessions, memory, tools, sandboxing, routing, and channel integrations.</em></blockquote><p>Concretely, it is a single Node.js process called the <strong>Gateway</strong> that:</p><ol><li>Connects to all the messaging apps you already use (WhatsApp, Telegram, Discord, Slack, iMessage, Signal, Teams, etc.).</li><li>Routes every incoming message through an <strong>AI agent runtime</strong> that calls a model (Claude, GPT, Gemini, or a local model via Ollama) and executes <strong>tools</strong> (run shell, browse the web, edit files, draw on a Canvas, schedule tasks).</li><li>Persists everything — sessions, memory, credentials — on <strong>your</strong> machine. No cloud account required, no walled garden.</li></ol><p>The whole system is <strong>bring-your-own-model</strong>, <strong>bring-your-own-hardware</strong>, and <strong>open source</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMATUyXVewOhEGTPMluL_A.png" /></figure><h3>1. The Five Big Ideas (read these first)</h3><p>Before any architecture diagram makes sense, lock down these five mental models:</p><p><strong>1. Hub-and-spoke around a single Gateway.</strong> Every channel, every UI, every mobile node connects via WebSocket to one process. The Gateway is the single source of truth for sessions, routing, auth, and connections.</p><p><strong>2. Separation of interface from runtime.</strong> “Where the message came from” (WhatsApp, CLI, web, iMessage) is fully decoupled from “what produces the reply” (the Agent Runtime calling a model and tools). One agent — many faces.</p><p><strong>3. Sessions are security boundaries, not just chat threads.</strong> A session ID like agent:main:whatsapp:dm:+1234567890 encodes both <em>whose conversation it is</em> and <em>what trust level it gets</em> (full host access vs. sandboxed Docker).</p><p><strong>4. Composable system prompt, layered tool policy.</strong> The agent’s behavior comes from stacking files (AGENTS.md + SOUL.md + TOOLS.md + skills + memory). Tool permissions narrow as you move from operator → agent → group → sandbox.</p><p><strong>5. Files over databases, where reasonable.</strong> Memory, skills, transcripts, and config are mostly plain files (Markdown, JSON, JSONL, SQLite-with-vectors for memory). You can read them, edit them, version them, back them up.</p><p>If you internalize these five, the rest is detail.</p><h3>2. Architecture at a Glance</h3><pre>                 ┌─────────────────────────────────────────────┐<br>   YOU on        │  Channels: WhatsApp · Telegram · Discord ·  │<br>   your phone ──▶│   Slack · Signal · iMessage · WebChat ...   │<br>                 └────────────────────┬────────────────────────┘<br>                                      │  (Channel Adapters<br>                                      │   normalize messages)<br>                                      ▼<br>   CLI / Web UI / ┌─────────────────────────────────────────────┐<br>   macOS app  ───▶│            GATEWAY  (control plane)         │<br>   iOS/Android    │  WebSocket · 127.0.0.1:18789 (loopback)     │<br>   nodes          │  Auth · Pairing · Routing · Sessions · Health│<br>                  └────────────────────┬────────────────────────┘<br>                                       │  (dispatch by session)<br>                                       ▼<br>                  ┌─────────────────────────────────────────────┐<br>                  │              AGENT RUNTIME                  │<br>                  │  1. Resolve session   2. Assemble context   │<br>                  │  3. Call model+tools  4. Persist state      │<br>                  └────────┬────────────────────────┬───────────┘<br>                           │                        │<br>                           ▼                        ▼<br>                  ┌──────────────────┐    ┌──────────────────────┐<br>                  │  Model Provider  │    │  Tools (built-in +   │<br>                  │  Claude / GPT /  │    │  plugins + skills):  │<br>                  │  Gemini / Ollama │    │  bash · browser ·    │<br>                  └──────────────────┘    │  files · canvas ·    │<br>                                          │  cron · webhooks     │<br>                                          └──────────┬───────────┘<br>                                                     │<br>                                                     ▼<br>                                          ┌──────────────────────┐<br>                                          │  Optional Docker     │<br>                                          │  Sandbox (per session│<br>                                          │   trust level)       │<br>                                          └──────────────────────┘</pre><pre>   State (all on YOUR machine, under ~/.openclaw/):<br>   • openclaw.json   — config (JSON5)<br>   • sessions/       — append-only event logs per conversation<br>   • memory/&lt;id&gt;.sqlite — vector + BM25 hybrid index<br>   • credentials/    — channel tokens, OAuth (chmod 0600)<br>   • workspaces/     — per-agent AGENTS.md / SOUL.md / skills/</pre><p>I’ll walk every box in detail below.</p><h3>3. Core Components, One by One</h3><h3>3.1 Channel Adapters</h3><p>Each messaging platform has a dedicated adapter (e.g. src/whatsapp/, src/telegram/, src/discord/, src/imessage/). Every adapter implements the <strong>same four-method contract</strong>, regardless of the wildly different underlying APIs:</p><p>Responsibility What it does <strong>Authentication</strong> WhatsApp → QR pairing via Baileys library. Telegram/Discord → bot tokens (TELEGRAM_BOT_TOKEN, DISCORD_BOT_TOKEN). iMessage → native macOS integration on a signed Mac. <strong>Inbound parsing</strong> Strip platform quirks. Extract text, media (image/audio/video/docs), reactions, reply context. Output a normalized internal message. <strong>Access control</strong> Allowlists (channels.whatsapp.allowFrom), DM policy (pairing / open / disabled), group rules (requireMention, group allowlists). <strong>Outbound formatting</strong> Translate the agent&#39;s reply into platform markdown, chunk to size limits, upload media, manage typing indicators.</p><p><strong>Why this matters:</strong> The rest of OpenClaw never has to know whether a message came from Slack or Signal. You can write one routing rule (e.g. “only respond when @mentioned in groups”) and it applies everywhere.</p><p>Example WhatsApp config:</p><pre>{<br>  &quot;channels&quot;: {<br>    &quot;whatsapp&quot;: {<br>      &quot;enabled&quot;: true,<br>      &quot;allowFrom&quot;: [&quot;+1234567890&quot;],<br>      &quot;groups&quot;: { &quot;*&quot;: { &quot;requireMention&quot;: true } }<br>    }<br>  }<br>}</pre><h3>3.2 Control Interfaces</h3><p>These are how <em>you</em> (the operator) talk to your Gateway, as opposed to channels (which are how <em>messages</em> enter from the outside):</p><ul><li><strong>Web UI / Control UI</strong> — Lit-based web components served by the Gateway itself at http://127.0.0.1:18789/. Chat, config, session inspector, health monitor — all from the browser. No separate web server.</li><li><strong>CLI</strong> — Built with Commander.js (openclaw.mjs → src/cli/program.ts). Key commands: openclaw onboard, openclaw gateway, openclaw agent, openclaw channels login, openclaw message send, openclaw doctor, openclaw dashboard.</li><li><strong>macOS menu bar app</strong> — Native Swift app (apps/macos/). Manages Gateway lifecycle, embeds WebChat, provides Voice Wake / push-to-talk overlay, can SSH into a remote gateway.</li><li><strong>iOS / Android nodes</strong> — Connect to the Gateway as WebSocket clients with role: &quot;node&quot;. They expose <strong>device-side capabilities</strong> (camera, screen recording, location, Canvas rendering) that the Gateway can invoke via node.invoke. Your phone literally becomes part of the agent&#39;s toolset.</li></ul><h3>3.3 The Gateway (Control Plane)</h3><p>This is the <strong>single most important box</strong> in the whole system. It lives in src/gateway/server.ts, runs on Node 22+, uses the ws WebSocket library, and binds by default to 127.0.0.1:18789 — <strong>loopback only</strong> for security.</p><p>What it does:</p><ul><li>Connects to every messaging platform (channels), every UI (control), and every mobile node.</li><li>For every inbound message: runs access control → resolves session → dispatches to the correct agent.</li><li>Coordinates global system state: sessions, presence indicators, health, cron jobs.</li><li>Enforces auth (token or password) on any non-loopback binding.</li><li>Manages the <strong>device pairing</strong> flow.</li></ul><p>Five non-negotiable design principles of the Gateway:</p><ol><li><strong>Exactly one Gateway per host.</strong> WhatsApp’s protocol is strictly single-device, so you cannot run two. This is enforced at the architectural level.</li><li><strong>Fully typed protocol.</strong> Every WebSocket frame is validated against JSON Schema — and that schema is generated from TypeBox definitions, with Swift models generated from the JSON Schema. Type errors surface immediately.</li><li><strong>Event-driven, not poll-based.</strong> Clients subscribe to events: agent, presence, health, tick. No &quot;what&#39;s new?&quot; polling.</li><li><strong>Idempotency keys on side-effecting operations.</strong> Send/agent calls require an idempotency key, so retries are safe. The server keeps a short-lived dedupe cache.</li><li><strong>Mandatory handshake.</strong> Any non-JSON or non-connect first frame is a hard close.</li></ol><h3>3.4 The Agent Runtime</h3><p>Where AI actually happens. Implemented in src/agents/piembeddedrunner.ts, built on top of the Pi Agent Core library (@mariozechner/pi-agent-core). RPC-style invocation with <strong>streaming responses</strong>.</p><p>Every turn does <strong>four steps</strong>:</p><pre>   ┌─────────────────────────────────────────────────────┐<br>   │ 1. RESOLVE SESSION                                  │<br>   │    Map message → session ID                         │<br>   │    Session ID encodes trust level                   │<br>   ├─────────────────────────────────────────────────────┤<br>   │ 2. ASSEMBLE CONTEXT                                 │<br>   │    • Load session history from JSON                 │<br>   │    • Build dynamic system prompt (composed)         │<br>   │    • Hybrid memory search injection                 │<br>   ├─────────────────────────────────────────────────────┤<br>   │ 3. STREAM MODEL + EXECUTE TOOLS                     │<br>   │    Token-by-token generation                        │<br>   │    Intercept tool calls → run (in sandbox if needed)│<br>   │    Feed results back into the stream                │<br>   ├─────────────────────────────────────────────────────┤<br>   │ 4. PERSIST STATE                                    │<br>   │    Append messages, tool calls, results to disk     │<br>   └─────────────────────────────────────────────────────┘</pre><h4>3.4.1 Session resolution</h4><p>Session IDs are not opaque — they encode <em>who</em> and <em>how much trust</em>:</p><p>Session ID pattern Origin Default trust agent:&lt;agentId&gt;:main You, the operator Full host access (no Docker) agent:&lt;agentId&gt;:&lt;channel&gt;:dm:&lt;id&gt; A direct message from someone else Sandboxed by default agent:&lt;agentId&gt;:&lt;channel&gt;:group:&lt;id&gt; A group chat Sandboxed by default</p><p>So a WhatsApp DM lands in agent:main:whatsapp:dm:+123..., a Discord group chat lands in agent:main:discord:group:120...@g.us, and so on. The session ID alone tells the runtime what permissions to grant.</p><h4>3.4.2 Context assembly — the layered system prompt</h4><p>This is one of the most elegant parts of OpenClaw. The system prompt is <strong>composed</strong> from many sources, every turn:</p><p>Source Path Role AGENTS.md workspace Core rules, what the agent may/may not do, non-negotiable constraints SOUL.md workspace (optional) Personality, voice, tone TOOLS.md workspace (optional) Your environment-specific tool conventions (not a registry — tool defs are auto-generated) skills/&lt;name&gt;/SKILL.md workspace Playbooks for specific tasks. <strong>Selectively injected</strong> — only relevant skills go into the prompt, to avoid bloat Memory search results ~/.openclaw/memory/&lt;agentId&gt;.sqlite Semantically similar past turns Session history ~/.openclaw/sessions/... Recent messages in this conversation Tool definitions auto-generated from pi-tools.ts, openclaw-tools.ts, plugins Built-in + plugin tool schemas Pi Agent Core base library Baseline agent instructions</p><p><strong>Crucial detail:</strong> OpenClaw <em>discovers</em> skills at runtime but does not blindly inject every skill into every prompt — it picks only relevant ones, because long prompts hurt model performance.</p><h4>3.4.3 Execution loop</h4><p>As the model streams tokens back, the runtime watches for tool calls. When one appears:</p><ol><li>The runtime <strong>pauses</strong> the stream.</li><li>It looks up the tool (built-in like bash, browser, read_file, canvas_update, or plugin-provided).</li><li>If the session is sandboxed, it spins up (or reuses) a <strong>Docker container</strong> and runs the tool inside.</li><li>The tool’s result is fed back into the model’s ongoing generation.</li><li>The model continues, possibly making another tool call, possibly producing the final answer.</li></ol><p>This is the classic “ReAct”-style agent loop, but with the runtime — not the model — in control of the dangerous parts.</p><h3>4. Interaction &amp; Coordination Features</h3><p>These sit on top of the core pipeline and unlock the more dramatic capabilities.</p><h3>4.1 Canvas + A2UI (Agent-to-UI)</h3><p><strong>Canvas</strong> is an agent-driven visual workspace. It runs as a <strong>separate server</strong> (default port 18793, isolated from the Gateway — if Canvas crashes, the Gateway keeps running, and the security boundary is different because Canvas serves agent-writable content).</p><p><strong>A2UI</strong> is a declarative framework letting the agent generate <strong>interactive HTML</strong> without writing JavaScript:</p><pre>&lt;div a2ui-component=&quot;task-list&quot;&gt;<br>  &lt;button a2ui-action=&quot;complete&quot; a2ui-param-id=&quot;123&quot;&gt;<br>    Mark Complete<br>  &lt;/button&gt;<br>&lt;/div&gt;</pre><p>Click handling flow: user clicks → client sends action event → Canvas server forwards as a tool call → agent processes → agent calls canvas_update with new state → server pushes update → client refreshes. The agent has effectively built a real, interactive app, just by emitting HTML.</p><p>Canvas renders natively in the macOS app (WebKit), iOS app (SwiftUI wrapper), Android (WebView), and web UI.</p><h3>4.2 Voice Wake &amp; Talk Mode</h3><ul><li><strong>Voice Wake</strong> — “Hey OpenClaw” wake word on macOS/iOS/Android, or push-to-talk hotkey.</li><li>Audio → ElevenLabs (transcription) → agent → reply → ElevenLabs (TTS) → back to your ears.</li><li><strong>Talk Mode</strong> — continuous, hands-free conversation with interruption detection.</li></ul><h3>4.3 Multi-Agent Routing</h3><p>You can map different channels/contacts/groups to <strong>completely separate agent instances</strong> — different workspace, different model, different sandbox policy:</p><pre>{<br>  &quot;agents&quot;: {<br>    &quot;mapping&quot;: {<br>      &quot;group:discord:123456&quot;: {<br>        &quot;workspace&quot;: &quot;~/.openclaw/workspaces/discord-bot&quot;,<br>        &quot;model&quot;: &quot;anthropic/claude-sonnet-4-5&quot;,<br>        &quot;systemPromptOverrides&quot;: { &quot;SOUL.md&quot;: &quot;You are a helpful Discord moderator...&quot; }<br>      },<br>      &quot;dm:telegram:*&quot;: {<br>        &quot;workspace&quot;: &quot;~/.openclaw/workspaces/support-agent&quot;,<br>        &quot;model&quot;: &quot;openai/gpt-4o&quot;,<br>        &quot;sandbox&quot;: { &quot;mode&quot;: &quot;always&quot; }<br>      }<br>    }<br>  }<br>}</pre><p>Use cases: per-community personas, per-context tool access, isolated sandboxes for untrusted users, A/B testing new agent behavior in one channel without breaking another.</p><h3>4.4 Session Tools (Agent-to-Agent Communication)</h3><p>Agents can talk to other agents:</p><ul><li>sessions_list — discover active sessions</li><li>sessions_send — message another session (with announceStep: &quot;ANNOUNCE_SKIP&quot; for silent handoffs)</li><li>sessions_history — fetch transcripts from another session</li><li>sessions_spawn — create new sessions to delegate work</li></ul><p>This is what enables the “agent army” patterns people build (one coordinator dispatching to specialist sub-agents).</p><h3>4.5 Cron Jobs &amp; Webhooks</h3><ul><li><strong>Cron</strong> — schedule actions (e.g. 9 AM daily briefing).</li><li><strong>Webhooks</strong> — external systems (Gmail, Sentry, etc.) trigger agent actions via HTTP POST.</li></ul><p>Both are configuration-only, no custom code required.</p><h3>5. End-to-End Message Flow (Worth Memorizing)</h3><p>When you send a WhatsApp message to OpenClaw, here is exactly what happens, in six phases. This is the single most useful diagram for debugging.</p><h3>Phase 1 — Ingestion</h3><p>Baileys library receives a WebSocket event from WhatsApp’s servers. The WhatsApp adapter parses it: text, attachments, sender metadata.</p><h3>Phase 2 — Access Control &amp; Routing</h3><p>Allowlist check. DM pairing check. If first-time DM, the Gateway <em>responds with a pairing code instead of processing the message</em>. The auto-reply system (src/auto-reply/reply.ts) resolves the session ID — agent:main:whatsapp:dm:+123... — which determines the trust level.</p><h3>Phase 3 — Context Assembly</h3><p>PiEmbeddedRunner loads session JSON from ~/.openclaw/sessions/. Reads AGENTS.md + SOUL.md + TOOLS.md. Injects relevant skills. Runs hybrid memory search (vector + BM25) and adds the top results.</p><h3>Phase 4 — Model Invocation</h3><p>Stream the full context to the configured provider (Anthropic/OpenAI/Gemini/local).</p><h3>Phase 5 — Tool Execution</h3><p>Model emits a tool call → runtime intercepts → executes (in Docker if non-main session) → result streamed back into generation. Repeat as needed.</p><h3>Phase 6 — Response Delivery</h3><p>Reply chunks flow back through the Gateway. WhatsApp adapter formats markdown, splits to size limits, uploads any media, sends via Baileys. Runtime persists the entire turn (your message, model output, all tool calls/results) to the session JSON.</p><p><strong>Approximate latency budget:</strong></p><ul><li>Access control: &lt; 10 ms</li><li>Session load from disk: &lt; 50 ms</li><li>System prompt assembly: &lt; 100 ms</li><li>First model token: 200–500 ms</li><li>Bash tool: &lt; 100 ms</li><li>Browser automation: 1–3 s</li></ul><h3>6. Data &amp; State — Where Everything Lives</h3><p>Everything OpenClaw owns is under ~/.openclaw/:</p><p>Path Contents ~/.openclaw/openclaw.json Main config, JSON5 (comments + trailing commas allowed). Layered: env vars &gt; config file &gt; defaults. ~/.openclaw/sessions/ One file per session. <strong>Append-only event log</strong>, branchable. ~/.openclaw/memory/&lt;agentId&gt;.sqlite Hybrid memory index — vector embeddings + BM25 keyword. ~/.openclaw/credentials/ Channel tokens, OAuth — chmod 0600, gitignored by default. ~/.openclaw/workspaces/&lt;agent&gt;/ Per-agent workspace: AGENTS.md, SOUL.md, TOOLS.md, skills/, MEMORY.md, memory/YYYY-MM-DD.md.</p><h3>6.1 Session compaction</h3><p>Conversations grow without bound, but model context windows don’t. So OpenClaw runs <strong>automatic compaction</strong>: older turns are summarized and persisted, freeing up context. Before compaction, a “memory flush” step promotes durable info into memory files — so important details survive the squashing. Compaction is skipped if the workspace isn’t writable.</p><h3>6.2 Memory search — the killer feature</h3><p>When you talk to the agent, OpenClaw automatically searches your past conversations for <strong>semantically similar</strong> discussions and injects them into the prompt. That is why people say “it remembers things from weeks ago.”</p><p>How it works:</p><ul><li>Storage: SQLite per agent, with vector embeddings.</li><li>Search: <strong>hybrid</strong> — vector similarity (semantic) + BM25 (keyword) — combined for best recall.</li><li>Indexing: as new messages arrive, they are auto-indexed. File watcher reindexes memory files on edit (1.5 s debounce).</li><li><strong>Embedding provider auto-selection:</strong> local model if configured → else OpenAI key → else Gemini key → else memory search disabled.</li><li>sqlite-vec accelerates vector ops if available.</li></ul><p>Two memory file types in your workspace:</p><ul><li>MEMORY.md — long-term curated facts. Loaded <strong>only in private/main sessions</strong> for privacy. Never injected into group chats.</li><li>memory/YYYY-MM-DD.md — daily logs, raw running notes.</li></ul><p>Optional: experimental.sessionMemory: true makes the entire session transcript searchable, not just memory files.</p><h3>7. Skills — The Plugin System for Capabilities</h3><p>A <strong>skill</strong> is a folder under ~/clawd/skills/&lt;skill-name&gt;/ (or your workspace) containing a SKILL.md file that explains, in plain English, how the agent should use some API or perform some workflow.</p><ul><li>Installation = drop a folder. <strong>No recompilation, no restart.</strong></li><li>The agent reads SKILL.md files at runtime to learn what it can do.</li><li>100+ community skills exist on <strong>ClawHub</strong>: Gmail, browser automation, home control, calendar, etc.</li><li>The agent can even <strong>write its own skills</strong> — many tweets in the OpenClaw community describe asking the agent to learn a new capability and watching it create a skill file, then use it.</li></ul><p>This is the secret of the “infinite extensibility” feel. A skill is just a Markdown playbook + (optionally) supporting scripts.</p><h3>8. Plugin Architecture (vs. Skills)</h3><p>Skills extend <em>what the agent knows how to do with existing tools</em>. Plugins extend <em>what tools and integrations exist at all</em>. There are four plugin categories:</p><p>Plugin type What it adds <strong>Channel plugins</strong> New messaging platforms (Microsoft Teams, Matrix, Mattermost…) <strong>Memory plugins</strong> Alternative storage backends (vector DB, knowledge graph) instead of default SQLite <strong>Tool plugins</strong> Custom tools beyond built-in bash/browser/file ops <strong>Provider plugins</strong> Custom or self-hosted LLM providers</p><p>Plugins live in extensions/. The plugin loader (src/plugins/loader.ts) scans workspace packages for an openclaw.extensions field in package.json, validates against declared schemas, and <strong>hot-loads</strong> when configuration is present. The architectural direction is &quot;manifest-first control plane, targeted runtime loaders, no hidden paths around declared contracts.&quot;</p><h3>9. Security Architecture (The Part You Must Get Right)</h3><p>OpenClaw assumes the LLM <strong>can be tricked</strong> (prompt injection is real). Defense in depth, multiple enforcement layers.</p><h3>9.1 Network security</h3><ul><li>Default bind: 127.0.0.1 (loopback only). Never on the public internet by default.</li><li>Remote access: SSH tunnel (recommended), Tailscale Serve (tailnet HTTPS), Tailscale Funnel (public HTTPS, requires password auth).</li></ul><h3>9.2 Authentication &amp; device pairing</h3><ul><li><strong>Token or password auth</strong> required on non-loopback bindings (OPENCLAW_GATEWAY_TOKEN env var, or gateway.auth.mode: &quot;password&quot;).</li><li><strong>Device identity</strong> — every WS client (UI, node, CLI) sends a device ID + crypto keys on connect.</li><li>New device → must sign a <strong>challenge nonce</strong> (remote) or be auto-approved (local loopback) → Gateway issues a <strong>device token</strong> for that device.</li><li>Even with a stolen auth token, an attacker without an approved device cannot connect.</li><li>Caveat: Control UI needs HTTPS or localhost for crypto.subtle. The escape hatch gateway.controlUi.allowInsecureAuth is a <strong>security downgrade</strong>.</li></ul><h3>9.3 Channel access control</h3><ul><li><strong>DM pairing</strong> (default policy pairing): unknown senders get a pairing code, not a reply. You approve via openclaw pairing approve &lt;channel&gt; &lt;code&gt;.</li><li><strong>Allowlists</strong>: explicit numbers/usernames per channel.</li><li><strong>Group rules</strong>: requireMention, group allowlists, mention patterns.</li></ul><h3>9.4 Tool sandboxing (Docker)</h3><ul><li>main session → tools run on host (full access, no Docker overhead).</li><li>DM sessions → sandboxed by default (even for approved contacts).</li><li>Group sessions → sandboxed by default (highest risk: multi-participant inputs).</li><li>Each container: isolated filesystem, optionally no network, configurable CPU/memory limits, ephemeral lifecycle.</li></ul><p>The dimensions you actually have to care about:</p><ul><li><em>What is sandboxed</em> — tools, not the Gateway itself.</li><li><em>Container granularity</em> — per-session (strongest) / per-agent / shared (most efficient, least isolated).</li><li><em>Host exposure</em> — bind mounts can re-introduce risk.</li><li><em>Network access</em> — opt-in; expanded capability vs. expanded risk.</li><li><em>Escape hatches</em> — explicitly host-level tools should be high-trust only.</li></ul><p><strong>Tool policy precedence</strong> (later overrides earlier, but generally narrows):</p><blockquote><em>Tool Profile → Provider Profile → Global Policy → Provider Policy → Agent Policy → Group Policy → Sandbox Policy</em></blockquote><p>Group and sandbox policies should <strong>restrict, not expand</strong>.</p><h3>9.5 Prompt injection defense</h3><ul><li><strong>Context isolation</strong>: user messages, system instructions, and tool results are kept structurally distinct so an attacker’s “ignore previous instructions” embedded in a webpage is harder to confuse with a real system instruction.</li><li><strong>Use the strongest models for tool-using agents</strong>. The docs explicitly recommend Claude Opus 4.5 as a default. Smaller models → narrower blast radius (read-only tools, no network, strict sandbox, tight allowlists).</li><li><strong>Hard controls beat soft prompts.</strong> System-prompt guardrails are <em>guidance</em>, not enforcement. Real enforcement = channel access controls + tool policies + sandbox containment + execution approvals for high-impact actions.</li></ul><h3>10. Deployment Architectures</h3><p>The architecture stays identical across all four. Only “where the Gateway runs” changes.</p><h3>10.1 Local development (macOS/Linux)</h3><p>pnpm dev. Hot reload. Loopback only. Full debug logging. No auth needed.</p><h3>10.2 Production macOS (menu bar app)</h3><p>LaunchAgent → Gateway runs as a background service, auto-starts on login. Native menu bar app. WebChat embedded. Voice Wake. iMessage support (only here, since iMessage requires real macOS). Remote access via SSH or Tailscale.</p><h3>10.3 Linux/VM (remote Gateway)</h3><p>24/7 availability without your laptop on. Two access patterns:</p><p><strong>Option A — SSH tunnel (recommended default):</strong></p><pre>ssh -N -L 18789:127.0.0.1:18789 user@vps</pre><p>Local CLI/UI hits 127.0.0.1:18789, traffic is forwarded encrypted through SSH.</p><p><strong>Option B — Tailscale Serve (tailnet-only HTTPS):</strong> Both VPS and clients on the same tailnet. VPS exposes Gateway as https://vps.tailnet.ts. No SSH key juggling.</p><h3>10.4 Fly.io (container)</h3><p>Docker container managed by Fly. Persistent volume for state. Fly’s managed HTTPS in front. Reachable from public internet — so <strong>strong auth is mandatory</strong> here. Treat it as internet-facing.</p><h3>11. A Suggested Learning Order</h3><p>If you want to actually master this, here’s the order I’d take:</p><ol><li><strong>Install and onboard.</strong> curl -fsSL https://openclaw.ai/install.sh | bash → openclaw onboard --install-daemon → openclaw dashboard. Chat with it locally before connecting any channel.</li><li><strong>Read your </strong><strong>~/.openclaw/openclaw.json.</strong> Understand every key. Modify trivially.</li><li><strong>Open </strong><strong>~/.openclaw/workspaces/&lt;agent&gt;/AGENTS.md</strong> and read it. Then SOUL.md. Edit SOUL.md to change the personality and watch it stick.</li><li><strong>Trace one message end-to-end.</strong> Send a CLI message, then look at the new entries in sessions/. Compare the JSON before and after.</li><li><strong>Add one channel.</strong> Telegram is the easiest (just a bot token). Run through pairing/access control yourself.</li><li><strong>Install a skill from ClawHub.</strong> Read its SKILL.md. Watch the agent use it.</li><li><strong>Write your own skill.</strong> Tiniest possible — e.g. “fetch RSS feed X and summarize.” Just a Markdown file with steps + a tiny script.</li><li><strong>Configure multi-agent routing.</strong> Map a Telegram DM to a different agent with a different persona.</li><li><strong>Turn on sandboxing.</strong> Force a session through Docker. Break things on purpose. See containment.</li><li><strong>Deploy to a VPS</strong> behind an SSH tunnel. Now you have a 24/7 assistant.</li><li><strong>Write a tool plugin.</strong> This is the deepest part of the stack — package.json with openclaw.extensions, schema, hot-load.</li><li><strong>Read the Gateway protocol spec.</strong> TypeBox → JSON Schema → Swift models. This unlocks writing your own clients/nodes.</li></ol><h3>12. Glossary</h3><ul><li><strong>Gateway</strong> — the single Node process; control plane.</li><li><strong>Agent Runtime</strong> — the loop that calls model + tools per turn.</li><li><strong>Channel adapter</strong> — per-platform message in/out shim.</li><li><strong>Session</strong> — a stateful conversation; ID encodes trust level.</li><li><strong>Workspace</strong> — a folder containing one agent’s configuration files (AGENTS.md, SOUL.md, TOOLS.md, skills/).</li><li><strong>Skill</strong> — a Markdown playbook (SKILL.md) telling the agent how to do something with existing tools.</li><li><strong>Plugin / Extension</strong> — code adding new channels, tools, memory backends, or providers.</li><li><strong>Canvas</strong> — separate server rendering agent-generated HTML as interactive UIs.</li><li><strong>A2UI</strong> — declarative attribute system letting agents build interactive UIs without writing JS.</li><li><strong>Pi Agent Core</strong> — the underlying agent-loop library (@mariozechner/pi-agent-core) used by the runtime.</li><li><strong>Pairing</strong> — first-contact approval flow for unknown DM senders.</li><li><strong>Heartbeat</strong> — Gateway’s proactive tick; enables cron, presence, “checking in” behavior.</li><li><strong>ClawHub</strong> — the community skill registry.</li><li><strong>Molty</strong> — the project’s lobster mascot (yes, really).</li></ul><h3>13. Where to go next</h3><ul><li><strong>Official docs:</strong> <a href="https://docs.openclaw.ai/">https://docs.openclaw.ai</a></li><li><strong>GitHub:</strong> <a href="https://github.com/openclaw/openclaw">https://github.com/openclaw/openclaw</a> — read AGENTS.md at the repo root for the engineering contract.</li><li><strong>ClawHub:</strong> <a href="https://clawhub.ai/">https://clawhub.ai</a> — community skills.</li><li><strong>The architecture deep-dive by Paolo Perazzo:</strong> the most detailed third-party writeup; pairs perfectly with the docs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=902455554ceb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PageIndex and RAG Comparative Study]]></title>
            <link>https://medium.com/@shailesh16221/pageindex-and-rag-comparative-study-815db06c92aa?source=rss-6433c74bc518------2</link>
            <guid isPermaLink="false">https://medium.com/p/815db06c92aa</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[pageindex]]></category>
            <dc:creator><![CDATA[Shailesh Chaudhary]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 05:46:01 GMT</pubDate>
            <atom:updated>2026-04-01T05:46:01.360Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. The Problem PageIndex Solves</h3><p>Even though recent LLM models support longer contexts, research such as Chroma’s context rot study has shown that model performance deteriorates as context length grows, making it challenging for LLMs to accurately interpret and reason over long, complex, domain-specific documents such as financial reports or legal filings. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><p>Vector RAG was the dominant answer to this — but conventional vector-based RAG methods depend heavily on static semantic similarity and face several key limitations. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><p>PageIndex, an open-source RAG framework trending on GitHub, achieved 98.7% accuracy on the FinanceBench benchmark by eliminating vector databases and chunking entirely — a 48.7 percentage point improvement over traditional vector RAG’s approximately 50% accuracy on the same benchmark. <a href="https://dextralabs.com/blog/rag-pipeline-explained-diagram-implementation/">Dextra Labs</a></p><p>That gap is striking. Understanding <em>why</em> it exists requires going through each failure mode of vector RAG one by one.</p><p><strong>Vectorless, Reasoning-based RAG</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*D1SpKyKPd-TimO44lOBn4Q.png" /></figure><h3>2. The Five Failure Modes of Vector RAG (detailed)</h3><p>Vector-based RAG relies on semantic embeddings and vector databases to identify relevant text chunks — in the preprocessing stage, the document is first split into smaller chunks, then each chunk is embedded into a vector space using an embedding model, and the resulting vectors are stored in a vector database. During the query stage, the user query is embedded using the same embedding model, the vector database is searched for semantically similar chunks, and the system retrieves the top-k results. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><p>This pipeline has five structural failure modes:</p><p><strong>Failure 1 — Query–knowledge space mismatch.</strong> Vector retrieval assumes that the most semantically similar text to the query is also the most relevant. But this isn’t always true: queries often express intent, not content. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a> A query like “what is the total value of deferred assets?” does not semantically resemble the appendix table that contains the answer — it resembles every paragraph in a financial filing that <em>discusses</em> deferred assets.</p><p><strong>Failure 2 — Semantic similarity ≠ relevance.</strong> This is especially problematic in domain-specific documents such as financial filings, legal documents, and technical manuals, where many passages share near-identical semantics but differ critically in relevance. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a> Ten sections of a 10-K filing may all discuss revenue — but only one of them contains Q3 2024 revenue specifically.</p><p><strong>Failure 3 — Hard chunking destroys context.</strong> Documents are split into fixed-size chunks, often 512 or 1000 tokens, for embedding. This hard chunking often cuts through sentences, paragraphs, or sections, fragmenting meaning and context. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><p><strong>Failure 4 — No chat history integration.</strong> Each query is treated independently. The retriever doesn’t know what’s been asked or answered before. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><p><strong>Failure 5 — Cross-references are invisible.</strong> Documents often contain references such as “see Appendix G” or “refer to Table 5.3”. Since these references don’t share semantic similarity with the referenced content, traditional RAG misses them unless additional preprocessing like a knowledge graph is performed. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><p>A RAG practitioner confirmed this: “Even after optimizing the chunking, embedding, and vector store pipeline, accuracy is usually below 60%.” Traditional RAG treats retrieval as a nearest-neighbor math problem. Real retrieval for professional documents is a reasoning problem. <a href="https://collabnix.com/retrieval-augmented-generation-rag-complete-guide-to-building-intelligent-ai-systems-in-2025/">Collabnix</a></p><h3>3. How PageIndex Works — The Architecture</h3><p>Inspired by AlphaGo, PageIndex proposes a vectorless, reasoning-based RAG system that builds a hierarchical tree index from long documents and uses LLMs to reason over that index for agentic, context-aware retrieval. It simulates how human experts navigate and extract knowledge from complex documents through tree search, enabling LLMs to think and reason their way to the most relevant document sections. <a href="https://www.coursera.org/learn/retrieval-augmented-generation-rag">Coursera</a></p><p>The system has two distinct phases:</p><h3>Phase 1 — Indexing: Building the ToC Tree</h3><p>PageIndex introduces a JSON-based hierarchical structure to represent a Table of Contents (ToC) for unstructured documents. The ToC acts as an index tree that organizes content into hierarchical nodes. Each node represents a logical section — a chapter, paragraph, or page — and may contain metadata, a description, and links to its sub-sections. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><p>The JSON structure looks like this:</p><blockquote>{<br> “node_id”: “0006”,<br> “title”: “Financial Stability”,<br> “start_index”: 21,<br> “end_index”: 22,<br> “summary”: “The Federal Reserve monitors systemic risk…”,<br> “sub_nodes”: [<br> {<br> “node_id”: “0007”,<br> “title”: “Monitoring Financial Vulnerabilities”,<br> “start_index”: 22,<br> “end_index”: 28,<br> “summary”: “The Federal Reserve’s monitoring framework…”<br> },<br> {<br> “node_id”: “0008”,<br> “title”: “Domestic and International Cooperation”,<br> “start_index”: 28,<br> “end_index”: 31,<br> “summary”: “In 2023, the Federal Reserve collaborated…”<br> }<br> ]<br>}</blockquote><p>Each node in the ToC links directly to its corresponding raw content — text, images, tables — via a node_id to node_content mapping. This enables the LLM to select and retrieve specific nodes as needed, facilitating precise and context-aware information access. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><p>The critical architectural insight: unlike a vector database, which stores an external, static embeddings index, the JSON-based ToC index resides within the LLM’s active reasoning context. This is called an in-context index — a structure the model can directly reference, navigate, and reason over during inference. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><h3>Phase 2 — Retrieval: The Reasoning Loop</h3><p>PageIndex’s reasoning-based RAG mimics how humans naturally navigate and extract information from long documents. Unlike traditional vector-based methods that rely on static semantic similarity, this approach uses a dynamic, iterative reasoning process to actively decide where to look next based on the evolving context of the question. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*bIE64Fpj0VrXVQ_DpWh3_A.png" /></figure><p>The cross-reference example from the PageIndex blog makes the power of this loop concrete. In one example, the query asked for the total value of deferred assets. The main section only reported the increase in value, not the total. On page 77, the text read: “Table 5.3 summarizes the income, expenses, and distributions of the Reserve Banks for 2023 and 2022. Appendix G of this report provides more detailed information.” The reasoning-based retriever followed this cue to Appendix G, found the correct table, and returned the total deferred asset value — a task the vector-based retriever would likely fail. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><h3>4. How It Solves Each Failure Mode</h3><p>Instead of relying solely on embedding similarity search, the LLM uses reasoning to infer which section is likely to contain the answer. It can think about document structure: “Debt trends are usually in the financial summary section or Appendix G — let’s look there.” This dynamic inference bridges the gap between query meaning and information location. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><p>Rather than chunking arbitrarily, reasoning-based RAG retrieves semantically coherent sections such as full pages, sections, or chapters. If the model detects that a section is incomplete, it iteratively fetches neighboring sections until context is sufficient. This preserves logical continuity and minimizes hallucination. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><p>Retrieval is context-aware: the model uses prior conversation history to refine its understanding of the current question. For instance, if the user previously asked about financial assets, and now asks “What about liabilities?”, the retriever knows to explore the same report section under liabilities. This enables coherent, multi-step exploration across multiple turns. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a></p><h3>5. Implementation — Working Code</h3><p>PageIndex hit 98.7% accuracy on FinanceBench without a single vector. Here is how vectorless RAG works with working Python code. <a href="https://pageindex.ai/blog/pageindex-intro">pageindex</a></p><blockquote># pip install pageindex</blockquote><blockquote>from pageindex import PageIndexClient<br>import pageindex.utils as utils<br>import asyncio</blockquote><blockquote># Initialize client<br>client = PageIndexClient(api_key=”YOUR_API_KEY”)</blockquote><blockquote>async def build_pageindex(pdf_path: str) -&gt; dict:<br> “””Phase 1: Build the hierarchical ToC tree from a document.”””</blockquote><blockquote># Upload document and trigger index construction<br> with open(pdf_path, “rb”) as f:<br> doc = await client.documents.upload(f, filename=pdf_path)</blockquote><blockquote># Poll until indexing complete (LLM builds the tree)<br> while doc.status != “ready”:<br> await asyncio.sleep(2)<br> doc = await client.documents.get(doc.id)</blockquote><blockquote># Retrieve the generated ToC tree<br> tree = await client.documents.get_tree(doc.id)<br> print(utils.print_tree(tree)) # visualize the hierarchy<br> return {“doc_id”: doc.id, “tree”: tree}</blockquote><blockquote>async def reasoning_retrieve(doc_id: str, query: str) -&gt; dict:<br> “””Phase 2: Reasoning-based retrieval — no vector search.”””</blockquote><blockquote>result = await client.query(<br> document_id=doc_id,<br> question=query,<br> # No embedding, no cosine similarity — LLM reasons over tree<br> )</blockquote><blockquote>return {<br> “answer”: result.answer,<br> “reasoning_trace”: result.reasoning_steps, # full path through tree<br> “nodes_visited”: result.nodes_visited, # which node_ids were read<br> “source_pages”: result.source_pages # exact pages used<br> }</blockquote><blockquote># Vision-based variant — no OCR needed, works directly on PDF images<br>async def vision_pageindex(pdf_path: str, query: str) -&gt; dict:<br> “””OCR-free: embed PDF pages as images, reason over visual structure.”””</blockquote><blockquote>doc = await client.documents.upload_vision(pdf_path)<br> # LLM sees page images directly — no text extraction step<br> result = await client.query(document_id=doc.id, question=query,<br> mode=”vision”)<br> return result</blockquote><blockquote># Self-hosted open-source version<br># git clone <a href="https://github.com/VectifyAI/PageIndex">https://github.com/VectifyAI/PageIndex</a><br># Full pipeline without API dependency:</blockquote><blockquote>from pageindex.core import build_tree, reasoning_search<br>from pageindex.llm import ClaudeProvider # or OpenAI, Gemini</blockquote><blockquote>async def self_hosted_pipeline(pdf_path: str, query: str) -&gt; dict:<br> # Step 1: Parse document into sections<br> sections = parse_pdf_sections(pdf_path)</blockquote><blockquote># Step 2: LLM builds ToC tree from sections<br> llm = ClaudeProvider(model=”claude-sonnet-4–5&quot;)<br> tree = await build_tree(sections, llm=llm)</blockquote><blockquote># Step 3: Reasoning loop — LLM navigates tree to find answer<br> result = await reasoning_search(<br> tree=tree,<br> query=query,<br> llm=llm,<br> max_iterations=5 # loop cap — same concern as agentic RAG<br> )</blockquote><blockquote>return {<br> “answer”: result.answer,<br> “path”: result.reasoning_path,<br> “pages_read”: result.pages_accessed<br> }</blockquote><p><strong>MCP integration</strong> (for use with Claude directly):</p><blockquote># pageindex.ai/mcp — integrate via MCP server<br># In Claude Desktop config:<br>{<br> “mcpServers”: {<br> “pageindex”: {<br> “command”: “npx”,<br> “args”: [“-y”, “<a href="http://twitter.com/pageindex/mcp-server">@pageindex/mcp-server</a>”],<br> “env”: {<br> “PAGEINDEX_API_KEY”: “YOUR_KEY”<br> }<br> }<br> }<br>}<br># Claude can then call PageIndex tools directly during reasoning</blockquote><h3>6. Benchmark Performance</h3><p>PageIndex achieves 98.7% accuracy on FinanceBench — a benchmark requiring precise extraction from SEC filings — a 48.7 percentage point improvement over traditional vector RAG’s approximately 50% accuracy. <a href="https://dextralabs.com/blog/rag-pipeline-explained-diagram-implementation/">Dextra Labs</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*ITm4Ph9aLgMkFPdKqpAjfw.png" /></figure><p>But the picture is more nuanced on multi-document retrieval. A benchmark comparing vector-based retrieval with PageIndex retrieval showed that while vectorless approaches perform well in structured single-document environments, vector retrieval demonstrates stronger robustness across multi-document and noisy retrieval scenarios. Vector retrieval showed approximately 40% better evidence coverage. The findings suggest that embeddings continue to play a critical role in reliable enterprise RAG systems. <a href="https://medium.com/@mehulpratapsingh/2025s-ultimate-guide-to-rag-retrieval-how-to-pick-the-right-method-and-why-your-ai-s-success-2cedcda99f8a">Medium</a></p><h3>7. Critical Analysis — Is It Really a RAG Replacement?</h3><p>The “vectorless” framing drew pushback. As one Hacker News commenter observed, PageIndex “gets there completely and totally with iterative and recursive calls to an LLM.” It’s not eliminating dependencies — it’s replacing vector approximation with LLM reasoning approximation. Both have costs. <a href="https://dextralabs.com/blog/rag-pipeline-explained-diagram-implementation/">Dextra Labs</a></p><p>This is the most important nuance in the whole debate. PageIndex doesn’t eliminate retrieval complexity — it trades one form of approximation for another. Vector search approximates relevance through embedding geometry. PageIndex approximates relevance through LLM reasoning. Both can be wrong. The question is which approximation is better for your specific use case.</p><p>Traditional RAG offers sub-second latency at pennies per query. Meanwhile, long-context LLMs cost significantly more and have higher latency. PageIndex sits somewhere between: query-time reasoning is slower than vector lookup but likely faster than processing millions of tokens. <a href="https://dextralabs.com/blog/rag-pipeline-explained-diagram-implementation/">Dextra Labs</a></p><p>PageIndex isn’t a universal RAG replacement. It’s a specialized tool that makes sense when accuracy justifies higher overhead. <a href="https://dextralabs.com/blog/rag-pipeline-explained-diagram-implementation/">Dextra Labs</a></p><h3>8. Head-to-Head: Vector RAG vs PageIndex</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*gCDCdWbIlhty8tN4GPsqhQ.png" /></figure><h3>9. When to Use Each — The Decision Framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*s6CPTMPKdKCmf9epoL46QQ.png" /></figure><p>Use PageIndex when analyzing long, structured documents where hierarchy matters — financial reports, legal contracts, technical specifications, research papers — and when accuracy and explainability are critical. Traditional vector-based RAG systems are excellent alternatives for semantic search across large document collections. Use vectors for broad search across corpora, use PageIndex for precise analysis within structured documents. <a href="https://www.microsoft.com/en-us/microsoft-cloud/blog/2025/02/04/common-retrieval-augmented-generation-rag-techniques-explained/">Microsoft</a></p><p>Hybrid approaches are also possible: use vector search to find the top 3 relevant documents from a large collection, then use PageIndex to precisely extract answers from each of those documents. <a href="https://www.microsoft.com/en-us/microsoft-cloud/blog/2025/02/04/common-retrieval-augmented-generation-rag-techniques-explained/">Microsoft</a></p><h3>10. Relevance</h3><p>This is directly applicable to your work. Drug discovery pipelines deal with exactly the document types PageIndex was designed for:</p><p><strong>Strong PageIndex fit:</strong> FDA regulatory filings (structured, cross-referenced, precise numerical data), clinical trial protocols and reports (hierarchical sections, appendix cross-references, exact efficacy/safety numbers), patent documents (dense legal structure, specific claims in appendices), and individual research papers where a specific IC50 value in Table 3 needs to be found precisely.</p><p><strong>Strong Vector RAG fit:</strong> searching across 50,000 PubMed abstracts to find relevant papers (multi-document, conceptual queries), broad literature discovery for target identification, and cross-paper synthesis queries.</p><p><strong>Hybrid architecture :</strong> use vector search to surface the relevant 5–10 papers from your corpus, then use PageIndex to precisely extract specific findings, mechanisms, and data points from within each paper. This gives you both breadth (vector) and depth (PageIndex).</p><h3>11. Is PageIndex a RAG Replacement? — The Honest Answer</h3><p>No — not universally. Vectorless approaches like PageIndex introduce a different philosophy: instead of retrieving text that is similar, they retrieve text that is logically relevant by navigating document structure. As RAG architectures evolve, the future may combine both. <a href="https://www.chitika.com/retrieval-augmented-generation-rag-the-definitive-guide-2025/">Chitika</a></p><p>This is RAG’s evolution, not its obituary. PageIndex proves reasoning-based retrieval is viable and accurate, but also exposes the trade-offs. The vector database market isn’t disappearing — it’s being forced to compete on dimensions beyond speed. <a href="https://dextralabs.com/blog/rag-pipeline-explained-diagram-implementation/">Dextra Labs</a></p><p>The more accurate framing: PageIndex is a specialized, high-accuracy retrieval architecture for structured documents where the limitations of vector similarity search are most painful. It adds a new tool to the RAG practitioner’s toolkit — it does not replace the toolkit. The practitioners who will win are those who know when to use which approach, and when to combine them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=815db06c92aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic RAG]]></title>
            <link>https://medium.com/@shailesh16221/agentic-rag-47b1e9672eb9?source=rss-6433c74bc518------2</link>
            <guid isPermaLink="false">https://medium.com/p/47b1e9672eb9</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <dc:creator><![CDATA[Shailesh Chaudhary]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 05:11:00 GMT</pubDate>
            <atom:updated>2026-03-30T05:11:00.503Z</atom:updated>
            <content:encoded><![CDATA[<p>Agentic RAG is where everything you’ve learned converges — retrieval, chunking, embeddings, vector stores, advanced architectures, and evaluation all become tools that an autonomous LLM orchestrates dynamically.</p><p>Let’s build the mental model first.</p><p><strong>The fundamental shift: pipeline → reasoning loop</strong></p><p>In naive and advanced RAG, the pipeline is fixed. Data flows in one direction: query → retrieve → generate → answer. The developer decides the strategy upfront.</p><p>In Agentic RAG, the LLM is the orchestrator. It decides at runtime: do I need to retrieve? What should I search for? Are these results good enough? Do I need to search again with a different query? Should I use a different tool entirely?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*keAKsbU_h9IE1b8J6tRhFQ.png" /></figure><p>The agent operates in a <strong>Think → Act → Observe → Repeat</strong> loop — the ReAct (Reasoning + Acting) pattern. It thinks about what to do, calls a tool, observes the result, and decides whether to act again or produce a final answer.</p><p><strong>The ReAct pattern — the foundation of every RAG agent</strong></p><p>ReAct is what makes an LLM into an agent. The LLM generates interleaved reasoning traces and tool calls, using observations from tools to guide the next reasoning step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*o1W71_Gh-lTUghtO757DTA.png" /></figure><p>This trace shows the agent doing something naive RAG cannot: recognizing that retrieved results are incomplete, deciding to try a different tool, and only answering when it has sufficient evidence.</p><p><strong>Building an Agentic RAG system with LangGraph</strong></p><p>LangGraph is the standard framework for building RAG agents. It models the agent as a stateful graph where nodes are functions (tools, LLM calls) and edges are conditional routing decisions.</p><p>First, understand the state — the shared memory that flows through every node:</p><blockquote>from typing import TypedDict, Annotated, List<br>from langchain_core.messages import BaseMessage<br>import operator</blockquote><blockquote>class AgentState(TypedDict):<br> query: str # original question<br> messages: Annotated[List[BaseMessage], # full conversation + tool calls<br> operator.add]<br> retrieved_docs: List[str] # accumulated context<br> iterations: int # loop counter (prevent infinite loops)<br> answer: str # final answer when ready</blockquote><p>Now define the nodes — each does one job:</p><blockquote>from langgraph.graph import StateGraph, END<br>from langgraph.prebuilt import ToolNode<br>from langchain_core.tools import tool<br>from langchain_anthropic import ChatAnthropic</blockquote><blockquote>llm = ChatAnthropic(model=”claude-sonnet-4–5&quot;)</blockquote><blockquote># — — Tools the agent can call — -</blockquote><blockquote><a href="http://twitter.com/tool">@tool</a><br>def vector_search(query: str) -&gt; str:<br> “””Search the biomedical literature corpus for relevant passages.”””<br> docs = vectorstore.similarity_search(query, k=5)<br> return “\n\n”.join([d.page_content for d in docs])</blockquote><blockquote><a href="http://twitter.com/tool">@tool</a><br>def graph_search(entity: str) -&gt; str:<br> “””Traverse the knowledge graph to find related entities and relationships.”””<br> results = neo4j_graph.query(“””<br> MATCH (n {name: $entity})-[r]-(m)<br> RETURN n.name, type(r), m.name, m.description<br> LIMIT 20<br> “””, {“entity”: entity})<br> return str(results)</blockquote><blockquote><a href="http://twitter.com/tool">@tool</a><br>def web_search(query: str) -&gt; str:<br> “””Search the web for recent information not in the corpus.”””<br> results = tavily_client.search(query, max_results=3)<br> return “\n”.join([r[“content”] for r in results[“results”]])</blockquote><blockquote>tools = [vector_search, graph_search, web_search]<br>tool_node = ToolNode(tools)</blockquote><blockquote># Bind tools to LLM<br>llm_with_tools = llm.bind_tools(tools)</blockquote><p>Now define the agent node and routing logic:</p><blockquote>from langchain_core.messages import SystemMessage</blockquote><blockquote>AGENT_SYSTEM_PROMPT = “””You are a drug discovery research agent with access to:<br>- vector_search: semantic search over biomedical literature<br>- graph_search: knowledge graph traversal for entity relationships <br>- web_search: real-time web search for recent information</blockquote><blockquote>Strategy:<br>1. Start with vector_search for most queries<br>2. Use graph_search when asked about relationships between entities<br>3. Fall back to web_search if corpus results are insufficient or outdated<br>4. Only answer when you have sufficient evidence — cite your sources<br>5. If after 3 retrieval attempts you still lack evidence, say so explicitly”””</blockquote><blockquote>def agent_node(state: AgentState) -&gt; AgentState:<br> messages = [SystemMessage(content=AGENT_SYSTEM_PROMPT)] + state[“messages”]<br> response = llm_with_tools.invoke(messages)<br> return {<br> “messages”: [response],<br> “iterations”: state.get(“iterations”, 0) + 1<br> }</blockquote><blockquote>def should_continue(state: AgentState) -&gt; str:<br> last_message = state[“messages”][-1]<br> # If LLM called a tool → run the tool<br> if hasattr(last_message, “tool_calls”) and last_message.tool_calls:<br> return “tools”<br> # If max iterations reached → force answer<br> if state.get(“iterations”, 0) &gt;= 5:<br> return END<br> # Otherwise → done<br> return END</blockquote><blockquote># Build the graph<br>graph = StateGraph(AgentState)<br>graph.add_node(“agent”, agent_node)<br>graph.add_node(“tools”, tool_node)</blockquote><blockquote>graph.set_entry_point(“agent”)<br>graph.add_conditional_edges(“agent”, should_continue,<br> {“tools”: “tools”, END: END})<br>graph.add_edge(“tools”, “agent”) # after tool call → back to agent</blockquote><blockquote>agent = graph.compile()</blockquote><p>Running it:</p><blockquote>from langchain_core.messages import HumanMessage</blockquote><blockquote>result = agent.invoke({<br> “query”: “What compounds target the same pathway as sotorasib, and are any in clinical trials?”,<br> “messages”: [HumanMessage(content=”What compounds target the same pathway as sotorasib, and are any in clinical trials?”)],<br> “retrieved_docs”: [],<br> “iterations”: 0,<br> “answer”: “”<br>})</blockquote><blockquote># Inspect the full reasoning trace<br>for message in result[“messages”]:<br> print(type(message).__name__, “:”, message.content[:200])</blockquote><p><strong>Multi-agent RAG — specialised agents collaborating</strong></p><p>For complex pipelines , a single agent trying to handle everything becomes unwieldy. The solution is a supervisor pattern: a coordinator agent that routes subtasks to specialised sub-agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*LEQXBkg08ajGWuSH7KiOzQ.png" /></figure><blockquote>from langgraph.graph import StateGraph, END</blockquote><blockquote>class SupervisorState(TypedDict):<br> query: str<br> messages: Annotated[List[BaseMessage], operator.add]<br> sub_results: dict # {agent_name: result}<br> next_agent: str</blockquote><blockquote>def supervisor_node(state: SupervisorState) -&gt; SupervisorState:<br> “””Routes to the right specialist or synthesises if all done.”””<br> SUPERVISOR_PROMPT = f”””<br>You are coordinating a drug discovery research query.<br>Query: {state[‘query’]}<br>Results so far: {state[‘sub_results’]}</blockquote><blockquote>Decide what to do next:<br>- “nuomics” → target/omics/pathway question<br>- “numol” → molecular design/ADMET question <br>- “clinical” → clinical trial/safety question<br>- “web” → needs recent/live information<br>- “synthesise” → you have enough, produce final answer</blockquote><blockquote>Respond with one word only.”””<br> decision = llm.invoke(SUPERVISOR_PROMPT).content.strip().lower()<br> return {“next_agent”: decision}</blockquote><blockquote>def route_supervisor(state: SupervisorState) -&gt; str:<br> return state[“next_agent”]</blockquote><blockquote># Each sub-agent is its own compiled LangGraph<br>def nuomics_node(state):<br> result = nuomics_agent.invoke({“query”: state[“query”], “messages”: []})<br> return {“sub_results”: {**state.get(“sub_results”, {}),<br> “nuomics”: result[“messages”][-1].content}}</blockquote><blockquote>def synthesise_node(state):<br> synthesis_prompt = f”””<br>Synthesise a comprehensive answer to: {state[‘query’]}<br>Using these specialist findings:<br>{state[‘sub_results’]}<br>Cite each finding with its source agent.”””<br> answer = llm.invoke(synthesis_prompt).content<br> return {“messages”: [AIMessage(content=answer)]}</blockquote><blockquote>graph = StateGraph(SupervisorState)<br>graph.add_node(“supervisor”, supervisor_node)<br>graph.add_node(“nuomics”, nuomics_node)<br>graph.add_node(“numol”, numol_node)<br>graph.add_node(“clinical”, clinical_node)<br>graph.add_node(“web”, web_node)<br>graph.add_node(“synthesise”, synthesise_node)</blockquote><blockquote>graph.set_entry_point(“supervisor”)<br>graph.add_conditional_edges(“supervisor”, route_supervisor, {<br> “nuomics”: “nuomics”,<br> “numol”: “numol”,<br> “clinical”: “clinical”,<br> “web”: “web”,<br> “synthesise”: “synthesise”<br>})<br># Each sub-agent returns to supervisor<br>for node in [“nuomics”, “numol”, “clinical”, “web”]:<br> graph.add_edge(node, “supervisor”)<br>graph.add_edge(“synthesise”, END)</blockquote><blockquote>multi_agent = graph.compile()</blockquote><p><strong>Critical engineering concerns in Agentic RAG</strong></p><p>These are what separate a demo from a production system — and exactly what interviewers probe on.</p><p><strong>Loop termination</strong> — agents can get stuck in retrieval loops, keep searching for evidence that doesn’t exist, or call the same tool repeatedly. Always implement a hard iteration cap and a graceful fallback:</p><blockquote>def should_continue(state: AgentState) -&gt; str:<br> if state.get(“iterations”, 0) &gt;= 5:<br> # Force answer regardless<br> return “force_answer”<br> if last_message_has_tool_calls(state):<br> return “tools”<br> return END</blockquote><p><strong>Observability</strong> — with a fixed pipeline you can log inputs and outputs. With an agent you need to log the entire reasoning trace: every thought, every tool call, every observation. LangSmith (LangChain’s tracing tool) captures this automatically:</p><blockquote>import os<br>os.environ[“LANGCHAIN_TRACING_V2”] = “true”<br>os.environ[“LANGCHAIN_API_KEY”] = “your_key”<br># Every agent.invoke() call now logs full traces to LangSmith dashboard</blockquote><p><strong>Tool design</strong> — poorly designed tools break agents. Each tool must have a clear, unambiguous docstring (the LLM reads it to decide when to call), return clean structured output (not raw API responses), and handle errors gracefully without crashing the agent loop:</p><blockquote><a href="http://twitter.com/tool">@tool</a><br>def vector_search(query: str) -&gt; str:<br> “””Search the internal biomedical literature corpus.<br> Use this for questions about drug mechanisms, clinical data,<br> target biology, and published research. Returns relevant passages.”””<br> try:<br> docs = vectorstore.similarity_search(query, k=5)<br> if not docs:<br> return “No relevant documents found for this query.”<br> return “\n\n — -\n\n”.join([<br> f”Source: {d.metadata.get(‘source’, ‘unknown’)}\n{d.page_content}”<br> for d in docs<br> ])<br> except Exception as e:<br> return f”Search failed: {str(e)}. Try rephrasing the query.”</blockquote><p><strong>Latency management</strong> — agentic loops are slow. Each tool call + LLM reasoning step adds 1–3 seconds. A 5-iteration loop can take 15–20 seconds. Mitigations: run independent tool calls in parallel where possible, use streaming to show intermediate results to users, and cache frequent tool call results with a semantic cache.</p><p><strong>Agentic RAG evaluation — different from standard RAG</strong></p><p>Standard RAGAS metrics don’t capture agentic behaviour well. You need additional dimensions:</p><blockquote># Beyond RAGAS — agentic-specific metrics<br>agentic_eval = {<br> “trajectory_correctness”: “Did the agent use the right tools in the right order?”,<br> “tool_call_efficiency”: “How many tool calls to reach the answer? (fewer = better)”,<br> “loop_rate”: “What % of queries hit the iteration cap? (should be &lt; 5%)”,<br> “tool_selection_accuracy”:”Did the agent pick the right tool for each subtask?”,<br> “answer_groundedness”: “Is the final answer grounded in tool observations, not hallucinated?”<br>}</blockquote><p>LangSmith’s evaluation suite and TruLens both support tracing agentic trajectories, which gives you visibility into not just what the answer was but how the agent got there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47b1e9672eb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multimodal RAG]]></title>
            <link>https://medium.com/@shailesh16221/multimodal-rag-dca414b94dc4?source=rss-6433c74bc518------2</link>
            <guid isPermaLink="false">https://medium.com/p/dca414b94dc4</guid>
            <category><![CDATA[multimodal-ai]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[multimodal]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Shailesh Chaudhary]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 05:21:00 GMT</pubDate>
            <atom:updated>2026-03-29T05:21:00.483Z</atom:updated>
            <content:encoded><![CDATA[<p>Multimodal RAG extends everything you’ve learned into a world where your knowledge base isn’t just text — it’s images, tables, figures, molecular structure diagrams, PDFs with mixed content, and video. For drug discovery specifically, this is not optional: a significant fraction of the knowledge in scientific papers lives in figures, not paragraphs.</p><p>Let’s build the mental model first.</p><p><strong>Why multimodal RAG exists — the information gap</strong></p><p>In a standard text-only RAG pipeline, when you ingest a scientific paper, you extract the text and discard everything else. That means:</p><p>A survival curve figure showing treatment response gets dropped. A molecular structure diagram of the compound gets dropped. A results table with IC50 values across 20 compounds gets converted to garbled text or dropped. A Western blot image showing protein expression gets dropped.</p><p>In biomedical literature, estimates suggest 40–60% of scientific information is encoded in non-text elements. A text-only RAG system is working with half the knowledge at best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*XKLxtZc7lCh6GWbzi0dgTA.png" /></figure><p>There are three distinct strategies for handling non-text content. Each has different tradeoffs, and production systems often combine all three depending on content type.</p><p><strong>Strategy 1 — Convert everything to text</strong></p><p>The idea: use vision-language models (VLMs) or OCR to convert every non-text element into a text description during ingestion. Images become captions. Tables become Markdown. Figures become structured summaries. Then the rest of your pipeline is standard text RAG.</p><p>This is the most compatible approach — it works with any text embedding model and any vector store you already have.</p><blockquote>import anthropic, base64<br>from pathlib import Path</blockquote><blockquote>client = anthropic.Anthropic()</blockquote><blockquote>def image_to_text(image_path: str, context: str = “”) -&gt; str:<br> “””Use Claude vision to convert an image to a rich text description.”””<br> image_data = base64.standard_b64encode(<br> Path(image_path).read_bytes()<br> ).decode(“utf-8”)</blockquote><blockquote>suffix = image_path.split(“.”)[-1].lower()<br> media_type_map = {“jpg”: “image/jpeg”, “jpeg”: “image/jpeg”,<br> “png”: “image/png”, “gif”: “image/gif”,<br> “webp”: “image/webp”}<br> media_type = media_type_map.get(suffix, “image/png”)</blockquote><blockquote>response = client.messages.create(<br> model=”claude-sonnet-4–5&quot;,<br> max_tokens=1024,<br> messages=[{<br> “role”: “user”,<br> “content”: [<br> {“type”: “image”,<br> “source”: {“type”: “base64”,<br> “media_type”: media_type,<br> “data”: image_data}},<br> {“type”: “text”,<br> “text”: f”””This figure is from a scientific paper.<br>{f’Paper context: {context}’ if context else ‘’}</blockquote><blockquote>Provide a detailed scientific description including:<br>1. What type of figure this is (graph, diagram, microscopy, etc.)<br>2. All axis labels, units, and scale information<br>3. Key findings or trends shown<br>4. Any numerical values, statistics, or measurements visible<br>5. Legend items and what they represent</blockquote><blockquote>Be precise — this description will be used for scientific retrieval.”””}<br> ]<br> }]<br> )<br> return response.content[0].text</blockquote><blockquote>def table_to_markdown(table_image_path: str) -&gt; str:<br> “””Convert a table image to structured Markdown.”””<br> image_data = base64.standard_b64encode(<br> Path(table_image_path).read_bytes()<br> ).decode(“utf-8”)</blockquote><blockquote>response = client.messages.create(<br> model=”claude-sonnet-4–5&quot;,<br> max_tokens=2048,<br> messages=[{<br> “role”: “user”,<br> “content”: [<br> {“type”: “image”,<br> “source”: {“type”: “base64”,<br> “media_type”: “image/png”,<br> “data”: image_data}},<br> {“type”: “text”,<br> “text”: “””Convert this table to well-formatted Markdown.<br>Preserve all column headers, row labels, units, and values exactly.<br>Add a one-sentence summary of what the table shows above the Markdown.”””}<br> ]<br> }]<br> )<br> return response.content[0].text</blockquote><p>For PDF ingestion specifically, you need to first extract images and tables before passing them through these functions:</p><blockquote>import pymupdf # pip install pymupdf<br>import pdfplumber</blockquote><blockquote>def extract_pdf_elements(pdf_path: str) -&gt; dict:<br> “””Extract text, images, and tables from a PDF separately.”””<br> elements = {“text_chunks”: [], “images”: [], “tables”: []}</blockquote><blockquote># Text extraction with page context<br> doc = pymupdf.open(pdf_path)<br> for page_num, page in enumerate(doc):<br> text = page.get_text()<br> if text.strip():<br> elements[“text_chunks”].append({<br> “content”: text,<br> “page”: page_num + 1,<br> “type”: “text”<br> })</blockquote><blockquote># Extract images with their bounding box context<br> for img_index, img in enumerate(page.get_images()):<br> xref = img[0]<br> base_image = doc.extract_image(xref)<br> elements[“images”].append({<br> “data”: base_image[“image”],<br> “ext”: base_image[“ext”],<br> “page”: page_num + 1,<br> “type”: “image”<br> })</blockquote><blockquote># Table extraction with pdfplumber (better table detection)<br> with pdfplumber.open(pdf_path) as pdf:<br> for page_num, page in enumerate(pdf.pages):<br> tables = page.extract_tables()<br> for table in tables:<br> elements[“tables”].append({<br> “content”: table,<br> “page”: page_num + 1,<br> “type”: “table”<br> })</blockquote><blockquote>return elements</blockquote><blockquote>def ingest_pdf_multimodal(pdf_path: str, paper_title: str = “”) -&gt; list[dict]:<br> “””Full multimodal ingestion pipeline for a scientific paper.”””<br> elements = extract_pdf_elements(pdf_path)<br> chunks = []</blockquote><blockquote># Process text normally<br> for el in elements[“text_chunks”]:<br> chunks.append({<br> “content”: el[“content”],<br> “metadata”: {“source”: pdf_path, “page”: el[“page”],<br> “type”: “text”, “title”: paper_title}<br> })</blockquote><blockquote># Convert images to text descriptions<br> for i, el in enumerate(elements[“images”]):<br> # Save image temporarily<br> img_path = f”/tmp/img_{i}.{el[‘ext’]}”<br> Path(img_path).write_bytes(el[“data”])</blockquote><blockquote>description = image_to_text(img_path, context=paper_title)<br> chunks.append({<br> “content”: f”[FIGURE from page {el[‘page’]}]\n{description}”,<br> “metadata”: {“source”: pdf_path, “page”: el[“page”],<br> “type”: “figure”, “title”: paper_title,<br> “original_image_path”: img_path} # keep original!<br> })</blockquote><blockquote># Convert tables to Markdown<br> for el in elements[“tables”]:<br> if el[“content”]:<br> # Convert raw table to Markdown manually for structured tables<br> headers = el[“content”][0]<br> rows = el[“content”][1:]<br> md = “| “ + “ | “.join([str(h) for h in headers]) + “ |\n”<br> md += “| “ + “ | “.join([“ — -”] * len(headers)) + “ |\n”<br> for row in rows:<br> md += “| “ + “ | “.join([str(c) for c in row]) + “ |\n”</blockquote><blockquote>chunks.append({<br> “content”: f”[TABLE from page {el[‘page’]}]\n{md}”,<br> “metadata”: {“source”: pdf_path, “page”: el[“page”],<br> “type”: “table”, “title”: paper_title}<br> })</blockquote><blockquote>return chunks</blockquote><p><strong>Tradeoff:</strong> VLM captioning costs money and time at ingestion. A corpus of 10,000 papers with 5 figures each = 50,000 VLM calls. Budget and parallelize accordingly. The quality of descriptions is excellent for standard figures but degrades on highly specialized visualizations like cryo-EM maps or complex pathway diagrams — domain-specific prompting helps significantly.</p><p><strong>Strategy 2 — Multimodal embeddings (CLIP and beyond)</strong></p><p>Rather than converting images to text, embed images directly into the same vector space as text. CLIP (Contrastive Language-Image Pretraining) does exactly this — it trains text and image encoders together so that “a bar chart showing IC50 values” and an actual bar chart with IC50 values land near each other in embedding space.</p><blockquote>from PIL import Image<br>import torch<br>from transformers import CLIPProcessor, CLIPModel</blockquote><blockquote>model = CLIPModel.from_pretrained(“openai/clip-vit-large-patch14”)<br>processor = CLIPProcessor.from_pretrained(“openai/clip-vit-large-patch14”)</blockquote><blockquote>def embed_image_clip(image_path: str) -&gt; list[float]:<br> “””Embed an image using CLIP — same space as text embeddings.”””<br> image = Image.open(image_path).convert(“RGB”)<br> inputs = processor(images=image, return_tensors=”pt”)<br> with torch.no_grad():<br> features = model.get_image_features(**inputs)<br> # Normalize to unit vector — matches CLIP text embeddings<br> return (features / features.norm(dim=-1, keepdim=True)).squeeze().tolist()</blockquote><blockquote>def embed_text_clip(text: str) -&gt; list[float]:<br> “””Embed text using CLIP — same space as image embeddings.”””<br> inputs = processor(text=[text], return_tensors=”pt”, padding=True,<br> truncation=True, max_length=77)<br> with torch.no_grad():<br> features = model.get_text_features(**inputs)<br> return (features / features.norm(dim=-1, keepdim=True)).squeeze().tolist()</blockquote><blockquote># Store both text and image embeddings in the same Qdrant collection<br>from qdrant_client.models import PointStruct</blockquote><blockquote>points = []<br># Text chunks<br>for i, chunk in enumerate(text_chunks):<br> points.append(PointStruct(<br> id=i,<br> vector=embed_text_clip(chunk[“content”]),<br> payload={“content”: chunk[“content”], “type”: “text”,<br> “source”: chunk[“metadata”][“source”]}<br> ))</blockquote><blockquote># Images — embed directly, store path to original<br>for j, img_path in enumerate(image_paths):<br> points.append(PointStruct(<br> id=len(text_chunks) + j,<br> vector=embed_image_clip(img_path),<br> payload={“type”: “image”, “image_path”: img_path,<br> “source”: img_path.split(“/”)[0]}<br> ))</blockquote><blockquote>client.upsert(“multimodal_corpus”, points=points)</blockquote><blockquote># Query with text — retrieves both text chunks AND relevant images<br>query_vec = embed_text_clip(“dose response curve sotorasib KRAS G12C”)<br>results = client.search(“multimodal_corpus”, query_vector=query_vec, limit=10)</blockquote><blockquote># Results include both text chunks and image hits<br>for r in results:<br> if r.payload[“type”] == “image”:<br> print(f”Image hit: {r.payload[‘image_path’]} (score: {r.score:.3f})”)<br> else:<br> print(f”Text hit: {r.payload[‘content’][:100]} (score: {r.score:.3f})”)</blockquote><p><strong>ColPali</strong> is the state-of-the-art approach for document-level multimodal retrieval — it embeds entire PDF pages as images using a vision language model, bypassing text extraction entirely. This means layout, figures, tables, and text are all captured in one embedding.</p><blockquote># ColPali: embed entire PDF pages as images<br># pip install colpali-engine<br>from colpali_engine.models import ColPali, ColPaliProcessor<br>from pdf2image import convert_from_path</blockquote><blockquote>colpali_model = ColPali.from_pretrained(“vidore/colpali-v1.2”)<br>colpali_processor = ColPaliProcessor.from_pretrained(“vidore/colpali-v1.2”)</blockquote><blockquote>def embed_pdf_pages_colpali(pdf_path: str) -&gt; list[dict]:<br> “””Embed each PDF page as an image — captures everything.”””<br> pages = convert_from_path(pdf_path, dpi=150)<br> page_embeddings = []</blockquote><blockquote>for page_num, page_image in enumerate(pages):<br> inputs = colpali_processor(images=[page_image], return_tensors=”pt”)<br> with torch.no_grad():<br> embedding = colpali_model(**inputs).embeddings<br> page_embeddings.append({<br> “page_num”: page_num + 1,<br> “embedding”: embedding.squeeze().tolist(),<br> “image”: page_image, # keep original for VLM at query time<br> “source”: pdf_path<br> })<br> return page_embeddings</blockquote><p>ColPali is particularly powerful for drug discovery literature because it handles multi-column layouts, inline chemical structures, and figure-caption relationships — all of which break standard text extraction.</p><p><strong>Strategy 3 — Store raw, retrieve raw</strong></p><p>The cleanest conceptually: during ingestion, just extract and store the original images alongside their metadata and surrounding text context. At query time, retrieve the most relevant images and pass them directly to a vision-language model together with the query.</p><blockquote>def build_multimodal_context(query: str, retrieved_items: list[dict]) -&gt; list[dict]:<br> “””Build a VLM prompt that includes both text chunks and images.”””<br> content = []</blockquote><blockquote># Add the query<br> content.append({<br> “type”: “text”,<br> “text”: f”Question: {query}\n\nRelevant context from scientific literature:\n”<br> })</blockquote><blockquote>for item in retrieved_items:<br> if item[“type”] == “text”:<br> content.append({<br> “type”: “text”,<br> “text”: f”\n[Source: {item[‘source’]}, Page {item[‘page’]}]\n{item[‘content’]}\n”<br> })</blockquote><blockquote>elif item[“type”] == “figure”:<br> # Add the original image directly<br> image_data = base64.standard_b64encode(<br> Path(item[“image_path”]).read_bytes()<br> ).decode(“utf-8”)<br> content.append({<br> “type”: “text”,<br> “text”: f”\n[Figure from: {item[‘source’]}, Page {item[‘page’]}]\n”<br> })<br> content.append({<br> “type”: “image”,<br> “source”: {“type”: “base64”,<br> “media_type”: “image/png”,<br> “data”: image_data}<br> })</blockquote><blockquote>content.append({<br> “type”: “text”,<br> “text”: “\nProvide a detailed answer citing specific figures and sources.”<br> })<br> return content</blockquote><blockquote>def multimodal_rag_query(query: str) -&gt; str:<br> “””Full multimodal RAG pipeline — retrieve then generate with images.”””<br> # Retrieve relevant items (text + images)<br> query_embedding = embed_text_clip(query)<br> results = qdrant_client.search(<br> “multimodal_corpus”,<br> query_vector=query_embedding,<br> limit=8<br> )</blockquote><blockquote>retrieved_items = [r.payload for r in results]</blockquote><blockquote># Build multimodal prompt<br> content = build_multimodal_context(query, retrieved_items)</blockquote><blockquote># Generate with VLM<br> response = client.messages.create(<br> model=”claude-sonnet-4–5&quot;,<br> max_tokens=1500,<br> system=”””You are a drug discovery research assistant.<br>Answer based only on the provided text and figures.<br>When referencing a figure, describe what you see in it specifically.”””,<br> messages=[{“role”: “user”, “content”: content}]<br> )<br> return response.content[0].text</blockquote><p><strong>Handling molecular structures — the drug discovery special case</strong></p><p>Standard image embeddings (CLIP) don’t understand molecular structure. A SMILES string, an InChI representation, and a 2D structure diagram of the same compound have completely different representations in CLIP space. For drug discovery RAG, you need specialized molecular embeddings.</p><blockquote># Molecular-specific embeddings<br># pip install rdkit torch-geometric</blockquote><blockquote>from rdkit import Chem<br>from rdkit.Chem import AllChem<br>import numpy as np</blockquote><blockquote>def smiles_to_morgan_fingerprint(smiles: str, radius: int = 2,<br> n_bits: int = 2048) -&gt; list[float]:<br> “””Morgan fingerprint — captures molecular topology.”””<br> mol = Chem.MolFromSmiles(smiles)<br> if mol is None:<br> return [0.0] * n_bits<br> fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius, nBits=n_bits)<br> return list(fp)</blockquote><blockquote># For graph-based molecular embeddings (better for similarity search)<br># pip install torch-geometric dgl-lifesci<br>from dgllife.utils import AttentiveFPAtomFeaturizer, AttentiveFPBondFeaturizer<br>from dgllife.model import AttentiveFPPredictor</blockquote><blockquote>def embed_molecule_graph(smiles: str, model) -&gt; list[float]:<br> “””Graph neural network embedding of molecular structure.”””<br> mol = Chem.MolFromSmiles(smiles)<br> # Convert to molecular graph, run GNN, get embedding<br> # Returns 200-dim vector capturing 3D chemical properties<br> …</blockquote><blockquote># Store molecular embeddings in a separate collection<br># Use for: “find compounds structurally similar to sotorasib”<br>mol_point = PointStruct(<br> id=compound_id,<br> vector=smiles_to_morgan_fingerprint(“CC1=CC=C(C=C1)NC(=O)…”), # sotorasib SMILES<br> payload={<br> “smiles”: “CC1=CC=C(C=C1)NC(=O)…”,<br> “name”: “sotorasib”,<br> “target”: “KRAS G12C”,<br> “ic50_nm”: 0.098,<br> “type”: “compound”<br> }<br>)</blockquote><p><strong>Putting it all together — the multimodal ingestion architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*1rZwM9EYxl_wWkONoQc8aA.png" /></figure><p><strong>Multimodal retrieval strategies</strong></p><p>At query time, you need to decide how to search across modalities:</p><blockquote>def multimodal_retrieve(query: str, modality_filter: str = None,<br> k: int = 10) -&gt; list[dict]:<br> “””Retrieve across text, figures, tables, and molecules.”””</blockquote><blockquote># Embed query as text — works for cross-modal retrieval with CLIP<br> text_vec = embed_text_clip(query)</blockquote><blockquote># Optional: filter by modality<br> filter_condition = None<br> if modality_filter:<br> from qdrant_client.models import Filter, FieldCondition, MatchValue<br> filter_condition = Filter(must=[<br> FieldCondition(key=”type”,<br> match=MatchValue(value=modality_filter))<br> ])</blockquote><blockquote>results = qdrant_client.search(<br> “multimodal_corpus”,<br> query_vector=text_vec,<br> query_filter=filter_condition,<br> limit=k,<br> with_payload=True<br> )</blockquote><blockquote># Separate by modality for downstream handling<br> text_results = [r for r in results if r.payload[“type”] == “text”]<br> image_results = [r for r in results if r.payload[“type”] == “figure”]<br> table_results = [r for r in results if r.payload[“type”] == “table”]<br> mol_results = [r for r in results if r.payload[“type”] == “compound”]</blockquote><blockquote>return {<br> “text”: text_results,<br> “figures”: image_results,<br> “tables”: table_results,<br> “molecules”: mol_results,<br> “all”: results<br> }</blockquote><blockquote># Usage examples:<br># “What does the dose-response curve look like for sotorasib?”<br>results = multimodal_retrieve(<br> “dose response curve sotorasib”,<br> modality_filter=”figure” # only figures<br>)</blockquote><blockquote># “What compounds are structurally similar to adagrasib?”<br>results = multimodal_retrieve(<br> “KRAS G12C covalent inhibitor pyridopyrimidine scaffold”,<br> modality_filter=”compound”<br>)</blockquote><blockquote># Broad query — all modalities<br>results = multimodal_retrieve(“KRAS G12C clinical outcomes”)</blockquote><p><strong>Multimodal evaluation</strong></p><p>Standard RAGAS metrics don’t cover multimodal quality. Additional dimensions to evaluate:</p><blockquote>multimodal_eval_dimensions = {<br> # Standard text metrics still apply to text portions<br> “faithfulness”: “Are text claims grounded in retrieved context?”,</blockquote><blockquote># Multimodal-specific<br> “figure_relevance”: “Were the retrieved figures actually relevant to the query?”,<br> “figure_description_accuracy”: “Did the VLM caption the figure accurately?”,<br> “cross_modal_coherence”: “Do text and figure answers agree with each other?”,<br> “table_extraction_fidelity”: “Were numerical values from tables preserved correctly?”,<br> “molecule_retrieval_precision”: “For structure queries, were retrieved compounds truly similar?”<br>}</blockquote><p>Human evaluation is essential for figure relevance and cross-modal coherence — automated metrics struggle with “was this figure actually useful for answering the question?”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dca414b94dc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG in Production]]></title>
            <link>https://medium.com/@shailesh16221/rag-in-production-c04349b718fa?source=rss-6433c74bc518------2</link>
            <guid isPermaLink="false">https://medium.com/p/c04349b718fa</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[rag-in-production]]></category>
            <dc:creator><![CDATA[Shailesh Chaudhary]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 05:36:00 GMT</pubDate>
            <atom:updated>2026-03-28T05:36:00.522Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The production reality</strong></p><p>Everything you’ve learned so far assumes a mostly static world: you build the index once, queries come in, answers go out. Production breaks that assumption immediately. Documents get updated. New research gets published. Users ask the same questions repeatedly. Latency SLAs get violated. API bills arrive.</p><p>These four topics address the operational layer of RAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*bytfu-EA4sYz-faO2bk05w.png" /></figure><h3>Topic 1 — Indexing for updates</h3><p><strong>The core problem</strong></p><p>Your RAG index is a snapshot of your knowledge at ingestion time. The moment a document changes, a new paper is published, or a record is corrected, your index is stale. Rebuilding the entire index from scratch every time is too slow and expensive. You need surgical update capabilities.</p><p>There are four operations to handle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*X8YhQvW20VJaPFLypkjsog.png" /></figure><p><strong>Chunk-level document tracking</strong></p><p>The foundation of incremental indexing is a document registry — a mapping from document ID to its current version, hash, and all chunk IDs it produced. Without this, you can’t know which chunks to delete when a document updates.</p><blockquote>import hashlib<br>from datetime import datetime, timezone<br>from dataclasses import dataclass<br>from typing import Optional</blockquote><blockquote><a href="http://twitter.com/dataclass">@dataclass</a><br>class DocumentRecord:<br> doc_id: str<br> source_path: str<br> content_hash: str # MD5/SHA of raw content — change detection<br> version: int<br> chunk_ids: list[str] # all Qdrant point IDs from this document<br> ingested_at: datetime<br> metadata: dict</blockquote><blockquote>class DocumentRegistry:<br> “””Tracks documents and their chunks for incremental updates.”””</blockquote><blockquote>def __init__(self, db_conn):<br> self.db = db_conn # PostgreSQL, SQLite, or Redis</blockquote><blockquote>def compute_hash(self, content: bytes) -&gt; str:<br> return hashlib.sha256(content).hexdigest()</blockquote><blockquote>def is_changed(self, doc_id: str, new_hash: str) -&gt; bool:<br> record = self.get(doc_id)<br> if record is None:<br> return True # new document<br> return record.content_hash != new_hash</blockquote><blockquote>def register(self, doc_id: str, source_path: str,<br> content_hash: str, chunk_ids: list[str],<br> metadata: dict):<br> existing = self.get(doc_id)<br> version = (existing.version + 1) if existing else 1</blockquote><blockquote>self.db.execute(“””<br> INSERT INTO document_registry<br> (doc_id, source_path, content_hash, version,<br> chunk_ids, ingested_at, metadata)<br> VALUES (?, ?, ?, ?, ?, ?, ?)<br> ON CONFLICT(doc_id) DO UPDATE SET<br> content_hash = excluded.content_hash,<br> version = excluded.version,<br> chunk_ids = excluded.chunk_ids,<br> ingested_at = excluded.ingested_at,<br> metadata = excluded.metadata<br> “””, (doc_id, source_path, content_hash, version,<br> str(chunk_ids), datetime.now(timezone.utc), str(metadata)))</blockquote><blockquote>def get_chunk_ids(self, doc_id: str) -&gt; list[str]:<br> record = self.get(doc_id)<br> return record.chunk_ids if record else []</blockquote><blockquote>def get(self, doc_id: str) -&gt; Optional[DocumentRecord]:<br> row = self.db.execute(<br> “SELECT * FROM document_registry WHERE doc_id = ?”, (doc_id,)<br> ).fetchone()<br> return DocumentRecord(**row) if row else None</blockquote><p><strong>The incremental update pipeline</strong></p><blockquote>class IncrementalIndexer:</blockquote><blockquote>def __init__(self, registry: DocumentRegistry,<br> vectorstore, embedder, chunker):<br> self.registry = registry<br> self.vectorstore = vectorstore<br> self.embedder = embedder<br> self.chunker = chunker</blockquote><blockquote>def upsert_document(self, doc_id: str, content: bytes,<br> source_path: str, metadata: dict):<br> new_hash = self.registry.compute_hash(content)</blockquote><blockquote># Skip if content hasn’t changed<br> if not self.registry.is_changed(doc_id, new_hash):<br> print(f”[SKIP] {doc_id} — content unchanged”)<br> return</blockquote><blockquote>print(f”[UPDATE] {doc_id} — content changed, re-indexing”)</blockquote><blockquote># Step 1: Delete old chunks from vector store<br> old_chunk_ids = self.registry.get_chunk_ids(doc_id)<br> if old_chunk_ids:<br> self.vectorstore.delete(ids=old_chunk_ids)<br> print(f” Deleted {len(old_chunk_ids)} old chunks”)</blockquote><blockquote># Step 2: Re-chunk the new content<br> text = content.decode(“utf-8”)<br> new_chunks = self.chunker.split_text(text)</blockquote><blockquote># Step 3: Embed and store new chunks<br> new_chunk_ids = []<br> for i, chunk in enumerate(new_chunks):<br> chunk_id = f”{doc_id}_chunk_{i}_{new_hash[:8]}”<br> embedding = self.embedder.embed_query(chunk)</blockquote><blockquote>self.vectorstore.add_texts(<br> texts=[chunk],<br> embeddings=[embedding],<br> ids=[chunk_id],<br> metadatas=[{**metadata,<br> “doc_id”: doc_id,<br> “chunk_idx”: i,<br> “version”: self.registry.get(doc_id).version + 1<br> if self.registry.get(doc_id) else 1}]<br> )<br> new_chunk_ids.append(chunk_id)</blockquote><blockquote># Step 4: Update registry<br> self.registry.register(doc_id, source_path, new_hash,<br> new_chunk_ids, metadata)<br> print(f” Added {len(new_chunk_ids)} new chunks”)</blockquote><blockquote>def delete_document(self, doc_id: str):<br> chunk_ids = self.registry.get_chunk_ids(doc_id)<br> if chunk_ids:<br> self.vectorstore.delete(ids=chunk_ids)<br> self.registry.delete(doc_id)<br> print(f”[DELETE] {doc_id} — removed {len(chunk_ids)} chunks”)</blockquote><p><strong>Event-driven ingestion — watching for changes</strong></p><p>In production you don’t poll for changes — you react to events. S3, Google Cloud Storage, and most document management systems emit events on file changes.</p><blockquote>import asyncio<br>from watchdog.observers import Observer<br>from watchdog.events import FileSystemEventHandler</blockquote><blockquote>class CorpusWatcher(FileSystemEventHandler):<br> “””Watch a directory for file changes and trigger re-indexing.”””</blockquote><blockquote>def __init__(self, indexer: IncrementalIndexer):<br> self.indexer = indexer<br> self.queue = asyncio.Queue()</blockquote><blockquote>def on_modified(self, event):<br> if not event.is_directory:<br> self.queue.put_nowait((“upsert”, event.src_path))</blockquote><blockquote>def on_deleted(self, event):<br> if not event.is_directory:<br> self.queue.put_nowait((“delete”, event.src_path))</blockquote><blockquote>def on_created(self, event):<br> if not event.is_directory:<br> self.queue.put_nowait((“upsert”, event.src_path))</blockquote><blockquote>async def process_queue(self):<br> while True:<br> action, path = await self.queue.get()<br> doc_id = path.replace(“/”, “_”)</blockquote><blockquote>if action == “upsert”:<br> content = open(path, “rb”).read()<br> self.indexer.upsert_document(<br> doc_id, content, path,<br> {“source”: path, “updated_at”: str(datetime.now())}<br> )<br> elif action == “delete”:<br> self.indexer.delete_document(doc_id)</blockquote><blockquote># For cloud storage, use S3 event notifications → SQS → Lambda → indexer<br># For PubMed updates, use the NCBI E-utilities API with date filtering</blockquote><p><strong>Near-duplicate detection before indexing</strong></p><p>Before adding a new document, check if a near-duplicate already exists. This prevents your index from silently filling with slightly different versions of the same content — a real problem when ingesting multiple databases that aggregate the same papers.</p><blockquote>def is_near_duplicate(new_embedding: list[float],<br> vectorstore,<br> threshold: float = 0.98) -&gt; bool:<br> “””Check if a very similar document already exists in the index.”””<br> results = vectorstore.similarity_search_by_vector(<br> new_embedding, k=1<br> )<br> if results and results[0][1] &gt; threshold: # cosine sim &gt; 0.98<br> print(f”Near-duplicate detected — skipping ingestion”)<br> return True<br> return False</blockquote><h3>Topic 2 — Semantic caching</h3><p><strong>The core idea</strong></p><p>If a user asks “what is the mechanism of sotorasib?” and your system already answered “how does sotorasib inhibit KRAS?” five minutes ago — those queries are semantically equivalent. You don’t need to run the full retrieval + generation pipeline again. Return the cached answer.</p><p>This is different from exact-match caching (which only matches byte-identical queries). Semantic caching matches by embedding similarity — queries that mean the same thing hit the same cache entry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*UDujIxLiSGAzxnhEpU_Tag.png" /></figure><blockquote>import time<br>import redis<br>import numpy as np<br>from dataclasses import dataclass<br>from typing import Optional</blockquote><blockquote><a href="http://twitter.com/dataclass">@dataclass</a><br>class CacheEntry:<br> query: str<br> query_embedding: list[float]<br> answer: str<br> sources: list[dict]<br> created_at: float<br> ttl_seconds: int<br> hit_count: int = 0</blockquote><blockquote>class SemanticCache:</blockquote><blockquote>def __init__(self, embedder, redis_client: redis.Redis,<br> similarity_threshold: float = 0.92,<br> default_ttl: int = 3600):<br> self.embedder = embedder<br> self.redis = redis_client<br> self.threshold = similarity_threshold<br> self.default_ttl = default_ttl<br> # In-memory index of cached query embeddings for fast ANN search<br> self.cached_embeddings: list[tuple[str, list[float]]] = []</blockquote><blockquote>def _cosine_similarity(self, a: list[float], b: list[float]) -&gt; float:<br> a, b = np.array(a), np.array(b)<br> return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))</blockquote><blockquote>def get(self, query: str) -&gt; Optional[CacheEntry]:<br> query_embedding = self.embedder.embed_query(query)</blockquote><blockquote>best_key, best_sim = None, 0.0<br> for cache_key, cached_emb in self.cached_embeddings:<br> sim = self._cosine_similarity(query_embedding, cached_emb)<br> if sim &gt; best_sim:<br> best_sim, best_key = sim, cache_key</blockquote><blockquote>if best_sim &gt;= self.threshold and best_key:<br> raw = self.redis.get(best_key)<br> if raw:<br> entry = CacheEntry(**eval(raw)) # use json in production<br> entry.hit_count += 1<br> self.redis.set(best_key, str(vars(entry)),<br> ex=self.default_ttl)<br> print(f”[CACHE HIT] sim={best_sim:.3f} key={best_key[:20]}”)<br> return entry</blockquote><blockquote>print(f”[CACHE MISS] best_sim={best_sim:.3f}”)<br> return None</blockquote><blockquote>def set(self, query: str, answer: str, sources: list[dict],<br> ttl: Optional[int] = None):<br> query_embedding = self.embedder.embed_query(query)<br> cache_key = f”rag_cache:{hash(query)}”<br> entry = CacheEntry(<br> query=query,<br> query_embedding=query_embedding,<br> answer=answer,<br> sources=sources,<br> created_at=time.time(),<br> ttl_seconds=ttl or self.default_ttl<br> )<br> self.redis.set(cache_key, str(vars(entry)),<br> ex=entry.ttl_seconds)<br> self.cached_embeddings.append((cache_key, query_embedding))</blockquote><blockquote>def invalidate_for_document(self, doc_id: str):<br> “””When a document updates, invalidate cache entries that used it.”””<br> keys_to_delete = []<br> for cache_key, _ in self.cached_embeddings:<br> raw = self.redis.get(cache_key)<br> if raw:<br> entry = CacheEntry(**eval(raw))<br> # Check if any source used this document<br> if any(s.get(“doc_id”) == doc_id for s in entry.sources):<br> keys_to_delete.append(cache_key)</blockquote><blockquote>for key in keys_to_delete:<br> self.redis.delete(key)<br> self.cached_embeddings = [<br> (k, e) for k, e in self.cached_embeddings if k != key<br> ]<br> print(f”Invalidated {len(keys_to_delete)} cache entries for {doc_id}”)</blockquote><blockquote># Wrapping your RAG pipeline with semantic cache<br>def cached_rag_query(query: str, cache: SemanticCache,<br> rag_pipeline) -&gt; dict:<br> # Try cache first<br> cached = cache.get(query)<br> if cached:<br> return {“answer”: cached.answer, “sources”: cached.sources,<br> “from_cache”: True, “latency_ms”: 8}</blockquote><blockquote># Full pipeline on miss<br> start = time.perf_counter()<br> result = rag_pipeline(query)<br> latency = (time.perf_counter() — start) * 1000</blockquote><blockquote># Store in cache<br> cache.set(query, result[“answer”], result[“sources”])</blockquote><blockquote>return {**result, “from_cache”: False, “latency_ms”: latency}</blockquote><p><strong>Cache TTL strategy</strong> — different content types need different expiry windows:</p><blockquote>TTL_STRATEGY = {<br> “factual_science”: 86400 * 30, # 30 days — stable knowledge<br> “clinical_trials”: 86400 * 7, # 7 days — updates frequently<br> “news_recent”: 3600, # 1 hour — rapidly changing<br> “compound_data”: 86400 * 14, # 14 days — moderate stability<br>}</blockquote><p><strong>Cache invalidation is the hard part.</strong> When a document updates (see Topic 1), you must invalidate all cache entries whose answers were derived from that document. The invalidate_for_document method above handles this — but only if you tracked which sources contributed to each cached answer. Store source metadata in every cache entry from day one.</p><p>Real-world cache hit rates for research platforms typically run 25–40% — enough to make a significant dent in both latency and cost. For a drug discovery Q&amp;A system where researchers ask similar questions across a team, hit rates can reach 50–60%.</p><h3>Topic 3 — Latency optimization</h3><p><strong>Where time actually goes in a RAG pipeline</strong></p><p>Before optimizing, you need to know where time is spent:</p><blockquote>import time<br>from contextlib import contextmanager</blockquote><blockquote><a href="http://twitter.com/contextmanager">@contextmanager</a><br>def timer(label: str, timings: dict):<br> start = time.perf_counter()<br> yield<br> timings[label] = round((time.perf_counter() — start) * 1000, 2)</blockquote><blockquote>def profiled_rag_pipeline(query: str) -&gt; dict:<br> timings = {}</blockquote><blockquote>with timer(“embed_query”, timings):<br> query_vec = embedder.embed_query(query)</blockquote><blockquote>with timer(“vector_search”, timings):<br> chunks = vectorstore.similarity_search_by_vector(query_vec, k=20)</blockquote><blockquote>with timer(“rerank”, timings):<br> chunks = reranker.compress_documents(chunks, query)</blockquote><blockquote>with timer(“llm_generate”, timings):<br> answer = llm.invoke(build_prompt(query, chunks)).content</blockquote><blockquote>print(f”Latency breakdown: {timings}”)<br> # Typical output:<br> # embed_query: 45ms · vector_search: 85ms · rerank: 340ms · llm_generate: 1840ms<br> return {“answer”: answer, “timings”: timings}</blockquote><p>The typical breakdown looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*zSw4CFDKVVUdXvyqF-ikEg.png" /></figure><p>LLM generation dominates. That’s where to focus first. Here are the optimizations in order of impact:</p><p><strong>1. Streaming — perceived latency fix</strong></p><p>Streaming doesn’t reduce total latency but transforms the user experience. The user sees tokens arriving within 200ms instead of waiting 2 seconds for the full answer.</p><blockquote>import anthropic</blockquote><blockquote>client = anthropic.Anthropic()</blockquote><blockquote>def stream_rag_answer(query: str, chunks: list) -&gt; str:<br> full_answer = []</blockquote><blockquote>with client.messages.stream(<br> model=”claude-sonnet-4–5&quot;,<br> max_tokens=1024,<br> system=”Answer based only on provided context.”,<br> messages=[{“role”: “user”,<br> “content”: f”Context:\n{format_chunks(chunks)}\n\nQ: {query}”}]<br> ) as stream:<br> for text in stream.text_stream:<br> print(text, end=””, flush=True) # stream to user immediately<br> full_answer.append(text)</blockquote><blockquote>return “”.join(full_answer)</blockquote><p><strong>2. Async parallel retrieval — biggest real latency reduction</strong></p><p>If you run BM25 search, vector search, and query rewriting sequentially, each adds to your wall-clock time. Run them concurrently.</p><blockquote>import asyncio</blockquote><blockquote>async def parallel_retrieve(query: str) -&gt; list:<br> “””Run all retrieval operations concurrently.”””</blockquote><blockquote># Embed query once, reuse across all searches<br> query_embedding = await asyncio.to_thread(<br> embedder.embed_query, query<br> )</blockquote><blockquote># Launch all retrievals simultaneously<br> vector_task = asyncio.to_thread(<br> vectorstore.similarity_search_by_vector,<br> query_embedding, k=15<br> )<br> bm25_task = asyncio.to_thread(<br> bm25_retriever.get_relevant_documents, query<br> )<br> graph_task = asyncio.to_thread(<br> graph_retriever.get_relevant_documents, query<br> )</blockquote><blockquote># Wait for all — total time = slowest single retrieval, not sum<br> vector_results, bm25_results, graph_results = await asyncio.gather(<br> vector_task, bm25_task, graph_task<br> )</blockquote><blockquote>return rrf_fuse([vector_results, bm25_results, graph_results])</blockquote><blockquote># Sequential: 85ms + 120ms + 200ms = 405ms<br># Parallel: max(85ms, 120ms, 200ms) = 200ms ← 2x faster</blockquote><p><strong>3. Vector index tuning — HNSW parameters</strong></p><p>HNSW has two tuning parameters that directly trade off speed vs recall:</p><blockquote>from qdrant_client.models import HnswConfigDiff</blockquote><blockquote># Higher ef = better recall but slower search<br># Default ef=128 is conservative — ef=64 often sufficient with reranker<br>client.update_collection(“papers”,<br> hnsw_config=HnswConfigDiff(<br> m=16, # connections per node — 16 is sweet spot<br> ef_construct=100, # build quality — higher = better index<br> full_scan_threshold=10000 # exact search below this count<br> )<br>)</blockquote><blockquote># At query time — tune ef for your recall/speed tradeoff<br>results = client.search(“papers”,<br> query_vector=query_vec,<br> search_params={“hnsw_ef”: 64}, # lower ef = faster, slight recall drop<br> limit=20<br>)</blockquote><p>4. Quantization — reduce memory and speed up search</p><blockquote>from qdrant_client.models import ScalarQuantizationConfig, QuantizationType</blockquote><blockquote># Scalar quantization: float32 → int8 = 4x memory reduction, ~20% faster search<br>client.update_collection(“papers”,<br> quantization_config=ScalarQuantizationConfig(<br> type=QuantizationType.INT8,<br> quantile=0.99,<br> always_ram=True # keep quantized index in RAM<br> )<br>)<br># Quality loss: typically &lt; 1% on recall@10 with a reranker downstream</blockquote><p><strong>5. Reduce reranker cost — smaller model or fewer candidates</strong></p><p>The cross-encoder reranker is the second-biggest latency contributor. Reduce it by passing fewer candidates (top-10 instead of top-20) or using a smaller model:</p><blockquote># Smaller but still effective cross-encoder<br>from sentence_transformers import CrossEncoder</blockquote><blockquote># ms-marco-MiniLM-L-6-v2: 120ms for 10 pairs — much faster than L-12<br>fast_reranker = CrossEncoder(“cross-encoder/ms-marco-MiniLM-L-6-v2”)</blockquote><blockquote># Only rerank top-10, not top-20<br>scores = fast_reranker.predict(<br> [(query, chunk.page_content) for chunk in candidates[:10]]<br>)</blockquote><p><strong>Topic 4 — Cost management</strong></p><p>The cost breakdown of a RAG query:</p><p>Embedding query: ~$0.00002 (text-embedding-3-small, 50 tokens)<br>Reranker API: ~$0.00010 (Cohere rerank, 10 docs)<br>LLM input tokens: ~$0.00150 (GPT-4o, 1500 tokens context)<br>LLM output tokens: ~$0.00200 (GPT-4o, 400 tokens answer)<br>─────────────────────────────────<br>Per query total: ~$0.00362</p><p>At 10,000 queries/day: $36/day → $1,100/month<br>At 100,000 queries/day: $362/day → $11,000/month</p><p>The LLM generation cost dominates — 93% of total cost. That’s where to focus.</p><p><strong>Strategy 1 — Model tiering</strong></p><p>Route queries to the cheapest model that can handle them adequately. Not every query needs GPT-4o or Claude Sonnet.</p><blockquote>def classify_query_complexity(query: str) -&gt; str:<br> “””Classify query to route to appropriate model tier.”””<br> CLASSIFIER_PROMPT = f”””Classify this RAG query complexity:<br>- simple: factual lookup, single document, straightforward answer<br>- medium: requires synthesis across 2–3 sources, moderate reasoning<br>- complex: multi-hop, contradictory sources, deep domain reasoning needed</blockquote><blockquote>Query: {query}<br>Answer with one word only:”””</blockquote><blockquote># Use cheapest model for classification itself<br> result = cheap_llm.invoke(CLASSIFIER_PROMPT).content.strip().lower()<br> return result</blockquote><blockquote>MODEL_TIERS = {<br> “simple”: {“model”: “gpt-4o-mini”, “cost_per_1k”: 0.00015},<br> “medium”: {“model”: “claude-haiku-4–5”, “cost_per_1k”: 0.00025},<br> “complex”: {“model”: “claude-sonnet-4–5”, “cost_per_1k”: 0.00300},<br>}</blockquote><blockquote>def tiered_generate(query: str, context: str) -&gt; dict:<br> tier = classify_query_complexity(query)<br> model_config = MODEL_TIERS[tier]</blockquote><blockquote>answer = call_llm(model_config[“model”], query, context)<br> return {“answer”: answer, “model_used”: model_config[“model”], “tier”: tier}</blockquote><p>In practice, 50–60% of queries on a research platform are “simple” factual lookups. Routing those to a 20x cheaper model cuts total LLM cost significantly.</p><p><strong>Strategy 2 — Context compression</strong></p><p>You’re paying for every token in the context window. Injecting 5 full chunks of 500 tokens each = 2500 context tokens. If only 30% of each chunk is actually relevant to the query, you’re paying for 1750 tokens of noise.</p><blockquote>from langchain.retrievers.document_compressors import LLMChainExtractor<br>from langchain.retrievers import ContextualCompressionRetriever</blockquote><blockquote># Compression: extract only relevant sentences from each chunk<br>compressor = LLMChainExtractor.from_llm(<br> ChatOpenAI(model=”gpt-4o-mini”, temperature=0) # cheap model for compression<br>)</blockquote><blockquote>compression_retriever = ContextualCompressionRetriever(<br> base_compressor=compressor,<br> base_retriever=base_retriever<br>)</blockquote><blockquote># Before compression: 5 chunks × 500 tokens = 2500 tokens<br># After compression: 5 chunks × 120 tokens = 600 tokens (76% reduction)<br>compressed_docs = compression_retriever.get_relevant_documents(query)</blockquote><p><strong>Strategy 3 — Embedding cost reduction</strong></p><p>Embeddings are cheap per call but add up at ingestion scale. Three lever</p><blockquote># 1. Use smaller dimensions with MRL truncation (OpenAI)<br>embedding = openai_client.embeddings.create(<br> input=text,<br> model=”text-embedding-3-large”,<br> dimensions=512 # truncate 3072 → 512: 6x cheaper storage, ~3% quality loss<br>)</blockquote><blockquote># 2. Batch embedding calls — one API call for many chunks<br>def batch_embed(texts: list[str], batch_size: int = 100) -&gt; list[list[float]]:<br> all_embeddings = []<br> for i in range(0, len(texts), batch_size):<br> batch = texts[i:i + batch_size]<br> response = openai_client.embeddings.create(<br> input=batch,<br> model=”text-embedding-3-small”<br> )<br> all_embeddings.extend([r.embedding for r in response.data])<br> return all_embeddings</blockquote><blockquote># 3. Self-hosted embeddings — zero marginal cost<br># bge-large-en-v1.5 on a single A10G GPU: ~2000 embeddings/second<br># Break-even vs OpenAI API at ~5M embeddings/month</blockquote><p><strong>Strategy 4 — Token budgeting</strong></p><p>Set hard token limits at each stage and monitor them:</p><blockquote>import tiktoken</blockquote><blockquote>enc = tiktoken.encoding_for_model(“gpt-4o”)</blockquote><blockquote>class TokenBudget:<br> def __init__(self, max_context_tokens: int = 3000,<br> max_output_tokens: int = 600):<br> self.max_context = max_context_tokens<br> self.max_output = max_output_tokens</blockquote><blockquote>def fit_chunks_to_budget(self, query: str,<br> chunks: list[str]) -&gt; list[str]:<br> “””Select chunks that fit within context token budget.”””<br> query_tokens = len(enc.encode(query))<br> system_tokens = 200 # approx system prompt<br> available = self.max_context — query_tokens — system_tokens</blockquote><blockquote>selected, used = [], 0<br> for chunk in chunks: # assume chunks are already reranked<br> chunk_tokens = len(enc.encode(chunk))<br> if used + chunk_tokens &lt;= available:<br> selected.append(chunk)<br> used += chunk_tokens<br> else:<br> break # budget exhausted</blockquote><blockquote>print(f”Token budget: {used}/{available} tokens used, “<br> f”{len(selected)}/{len(chunks)} chunks included”)<br> return selected</blockquote><blockquote>budget = TokenBudget(max_context_tokens=3000, max_output_tokens=500)<br>fitted_chunks = budget.fit_chunks_to_budget(query, reranked_chunks)</blockquote><p><strong>The cost optimization hierarchy</strong> — in order of ROI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*Rl98Xl_d4VsvIzgIVz5BqA.png" /></figure><p><strong>Bringing all four topics together — the production operations loop</strong></p><p>In a well-run production RAG system, these four topics work as a continuous loop, not independent concerns:</p><p>A document update fires an incremental indexer event → old chunks are deleted, new chunks ingested → the semantic cache is invalidated for affected entries → the new index is served immediately. Meanwhile, every query hits the semantic cache first — misses run the full pipeline with async parallel retrieval, a tiered LLM, and context compression. Latency and cost metrics are tracked per query and dashboarded, with alerts firing when p95 latency exceeds 4 seconds or cost-per-query exceeds budget thresholds.</p><p>This is the operational maturity level that separates a RAG prototype from a RAG product.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c04349b718fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced RAG architectures]]></title>
            <link>https://medium.com/@shailesh16221/advanced-rag-architectures-16bb39b2b09b?source=rss-6433c74bc518------2</link>
            <guid isPermaLink="false">https://medium.com/p/16bb39b2b09b</guid>
            <category><![CDATA[advanced-rag]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Shailesh Chaudhary]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 04:00:22 GMT</pubDate>
            <atom:updated>2026-03-26T04:00:22.388Z</atom:updated>
            <content:encoded><![CDATA[<p>Advanced RAG architectures are what you reach for when naive RAG hits a quality ceiling. Each architecture solves a specific failure mode — knowing <em>which</em> architecture fixes <em>which</em> problem is both the practical skill and the interview differentiator.</p><p>Let’s start with the map, then go deep on each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*wJAlgm8I5uAxl01DSVeKig.png" /></figure><p><strong>Architecture 1 — Corrective RAG (CRAG)</strong></p><p><strong>The problem it solves:</strong> naive RAG blindly trusts whatever it retrieves. If the top-K chunks are low quality, irrelevant, or ambiguous, the LLM still tries to generate an answer from them — producing confident garbage.</p><p><strong>The core idea:</strong> insert an evaluator between retrieval and generation. The evaluator grades retrieved chunks as Correct, Ambiguous, or Incorrect. Based on that grade, the pipeline takes one of three paths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*XlMDm5sxZigm172jOxXgIg.png" /></figure><p><strong>Implementation with LangGraph:</strong></p><blockquote>from langgraph.graph import StateGraph, END<br>from typing import TypedDict, List</blockquote><blockquote>class CRAGState(TypedDict):<br> query: str<br> chunks: List[str]<br> grade: str # “correct” | “ambiguous” | “incorrect”<br> web_results: List[str]<br> answer: str</blockquote><blockquote>def retrieve(state):<br> chunks = retriever.get_relevant_documents(state[“query”])<br> return {“chunks”: [c.page_content for c in chunks]}</blockquote><blockquote>def grade_retrieval(state):<br> # LLM evaluates relevance of retrieved chunks<br> prompt = f”””Are these documents relevant to the query?<br>Query: {state[‘query’]}<br>Documents: {state[‘chunks’][:2]}<br>Answer with: correct / ambiguous / incorrect”””<br> grade = llm.invoke(prompt).content.strip().lower()<br> return {“grade”: grade}</blockquote><blockquote>def web_search(state):<br> results = tavily_client.search(state[“query”])<br> return {“web_results”: [r[“content”] for r in results[“results”]]}</blockquote><blockquote>def generate(state):<br> context = state[“chunks”] + state.get(“web_results”, [])<br> answer = llm.invoke(f”Context: {context}\nQuery: {state[‘query’]}”).content<br> return {“answer”: answer}</blockquote><blockquote>def route_on_grade(state):<br> if state[“grade”] == “correct”: return “generate”<br> if state[“grade”] == “ambiguous”: return “web_search”<br> return “web_search” # incorrect → discard chunks, web only</blockquote><blockquote># Build graph<br>graph = StateGraph(CRAGState)<br>graph.add_node(“retrieve”, retrieve)<br>graph.add_node(“grade_retrieval”, grade_retrieval)<br>graph.add_node(“web_search”, web_search)<br>graph.add_node(“generate”, generate)</blockquote><blockquote>graph.set_entry_point(“retrieve”)<br>graph.add_edge(“retrieve”, “grade_retrieval”)<br>graph.add_conditional_edges(“grade_retrieval”, route_on_grade,<br> {“generate”: “generate”, “web_search”: “web_search”})<br>graph.add_edge(“web_search”, “generate”)<br>graph.add_edge(“generate”, END)</blockquote><blockquote>crag = graph.compile()</blockquote><p><strong>When to use CRAG:</strong> any domain where your corpus has coverage gaps — drug discovery pipelines where a newly published compound may not yet be in your index, or when users ask questions outside your corpus scope. The web search fallback ensures graceful degradation instead of confident hallucination.</p><p><strong>Architecture 2 — Self-RAG</strong></p><p><strong>The problem it solves:</strong> naive RAG retrieves for every query regardless of whether retrieval is needed. A question like “what is the capital of France?” doesn’t need a vector search — but naive RAG will do one anyway, potentially injecting irrelevant context and degrading the answer.</p><p><strong>The core idea:</strong> a specially fine-tuned LLM generates four reflection tokens inline with its output, making retrieval and self-critique decisions dynamically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*N2x8bfStP6Co55hihCrqPw.png" /></figure><p>The four reflection tokens are:</p><p>[Retrieve] — should I retrieve at all? (yes/no). Prevents unnecessary retrieval for queries the LLM can answer from parametric knowledge.</p><p>[ISREL] — is this retrieved chunk relevant? (relevant/irrelevant). Filters out off-topic chunks before generation.</p><p>[ISSUP] — does the context support this claim? (fully/partially/no). Per-sentence faithfulness check inline with generation.</p><p>[ISUSE] — is this generated segment useful overall? (score 1–5). Used to select the best generation path when multiple are explored.</p><blockquote># Self-RAG requires a specially fine-tuned model<br># selfrag/selfrag_llama2_7b is the reference implementation<br>from transformers import AutoTokenizer, AutoModelForCausalLM</blockquote><blockquote>model = AutoModelForCausalLM.from_pretrained(“selfrag/selfrag_llama2_7b”)<br>tokenizer = AutoTokenizer.from_pretrained(“selfrag/selfrag_llama2_7b”)</blockquote><blockquote>def self_rag_generate(query, retriever, max_new_tokens=256):<br> # Model generates [Retrieve] token first<br> # If yes → fetch chunks → continue with [ISREL], [ISSUP]<br> # If no → generate directly → [ISUSE] score<br> prompt = f”### Instruction:\n{query}\n### Response:\n”<br> inputs = tokenizer(prompt, return_tensors=”pt”)<br> outputs = model.generate(<br> **inputs,<br> max_new_tokens=max_new_tokens,<br> retriever=retriever # custom retrieval hook<br> )<br> return tokenizer.decode(outputs[0], skip_special_tokens=False)<br> # Output contains reflection tokens inline:<br> # “Sotorasib [Retrieve=yes][ISREL=relevant] covalently binds<br> # KRAS G12C [ISSUP=fully][ISUSE=5]”</blockquote><p><strong>When to use Self-RAG:</strong> when your query mix is heterogeneous — some questions need retrieval, some don’t, and unnecessary retrieval actively hurts quality. It’s particularly relevant for conversational RAG where follow-up questions like “can you elaborate?” don’t need fresh retrieval.</p><p><strong>Interview note:</strong> Self-RAG requires a fine-tuned model — you can’t just prompt an off-the-shelf LLM to emit these tokens reliably. The practical alternative for most teams is to simulate Self-RAG behavior using a routing step: a lightweight classifier or prompted LLM that decides pre-retrieval whether the query needs retrieval, which is more deployable without fine-tuning infrastructure.</p><p><strong>Architecture 3 — GraphRAG</strong></p><p><strong>The problem it solves:</strong> standard RAG retrieves isolated text chunks — it has no awareness of relationships between entities. A question like “what compounds target the same pathway as sotorasib?” requires traversing a relationship graph, not finding a similar text chunk.</p><p><strong>The core idea:</strong> extract entities and relationships from your corpus into a knowledge graph. Retrieval becomes graph traversal — following edges between nodes — rather than vector similarity search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*f9vcNOicTKhN8sgHhhYk9A.png" /></figure><p>Microsoft’s GraphRAG (the reference implementation) has two query modes: local search (traverses the graph from a specific entity outward — good for targeted questions) and global search (uses pre-generated community summaries to answer broad thematic questions — good for “what are the main research themes in this corpus?”).</p><blockquote># Microsoft GraphRAG CLI-based workflow<br># pip install graphrag</blockquote><blockquote># 1. Index your corpus — extracts entities, relations, builds graph<br># graphrag index — root ./drug_discovery_corpus</blockquote><blockquote># 2. Query<br>from graphrag.query.api import local_search, global_search</blockquote><blockquote># Local: entity-anchored traversal<br>result = await local_search(<br> config_dir=”./drug_discovery_corpus”,<br> query=”What compounds target the same pathway as sotorasib?”,<br> community_level=2<br>)</blockquote><blockquote># Global: community-summary synthesis<br>result = await global_search(<br> config_dir=”./drug_discovery_corpus”,<br> query=”What are the major themes in KRAS inhibitor research?”<br>)</blockquote><p>GraphRAG with neo4j as the graph backend for custom implementations:</p><blockquote>from neo4j import GraphDatabase<br>from langchain_community.graphs import Neo4jGraph</blockquote><blockquote>graph = Neo4jGraph(url=”bolt://localhost:7687&quot;,<br> username=”neo4j”, password=”password”)</blockquote><blockquote># Extract and store entities from chunks<br>graph.query(“””<br>MERGE (c:Compound {name: $compound})<br>MERGE (t:Target {name: $target})<br>MERGE ©-[:INHIBITS {ic50: $ic50, source: $source}]-&gt;(t)<br>“””, {“compound”: “sotorasib”, “target”: “KRAS G12C”,<br> “ic50”: “0.098 nM”, “source”: “CodeBreaK 100”})</blockquote><blockquote># Multi-hop retrieval: what else inhibits KRAS-pathway targets?<br>results = graph.query(“””<br>MATCH (c:Compound)-[:INHIBITS]-&gt;(t:Target)&lt;-[:INHIBITS]-(c2:Compound)<br>WHERE t.name CONTAINS ‘KRAS’<br>RETURN DISTINCT c2.name AS related_compound, t.name AS shared_target<br>“””)</blockquote><p><strong>When to use GraphRAG:</strong> multi-hop questions (“what compounds share a mechanism with X?”), relationship queries (“which papers cite the same studies?”), thematic analysis over large corpora. Critically relevant for NuOmics — target-gene-pathway-disease relationships are exactly the structure GraphRAG is built for.</p><p><strong>Architecture 4 — Adaptive RAG</strong></p><p><strong>The problem it solves:</strong> different queries have very different complexity levels — a factual lookup, a comparison question, and a multi-step reasoning question all need different retrieval strategies. Using the same strategy for all wastes resources on simple queries and fails on complex ones.</p><p><strong>The core idea:</strong> a classifier routes each query to the appropriate retrieval strategy before retrieval begins.</p><blockquote>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser</blockquote><blockquote># Query complexity classifier<br>ROUTE_PROMPT = ChatPromptTemplate.from_template(“””<br>Classify this query into one of three categories:<br>- simple: factual lookup, single document sufficient<br>- complex: requires reasoning across multiple sources <br>- conversational: no retrieval needed, follow-up or chitchat</blockquote><blockquote>Query: {query}<br>Category (respond with one word only):”””)</blockquote><blockquote>classifier = ROUTE_PROMPT | llm | StrOutputParser()</blockquote><blockquote>def adaptive_rag(query: str) -&gt; str:<br> route = classifier.invoke({“query”: query}).strip()</blockquote><blockquote>if route == “conversational”:<br> # Skip retrieval entirely<br> return llm.invoke(query).content</blockquote><blockquote>elif route == “simple”:<br> # Lightweight: semantic search, top-3, no reranker<br> chunks = vectorstore.similarity_search(query, k=3)<br> return generate(query, chunks)</blockquote><blockquote>elif route == “complex”:<br> # Full stack: hybrid search, top-20, reranker, multi-query<br> chunks = hybrid_retriever.get_relevant_documents(query)<br> chunks = reranker.compress_documents(chunks, query)<br> return generate(query, chunks)</blockquote><p><strong>When to use Adaptive RAG:</strong> production systems with mixed query types where latency and cost matter. Simple queries shouldn’t pay the latency penalty of a full hybrid + rerank pipeline. Complex queries shouldn’t get the lightweight treatment.</p><p><strong>Architecture 5 — Modular RAG</strong></p><p>Modular RAG is less a specific architecture and more a design philosophy: treat every component of the RAG pipeline as a swappable module with a standard interface. Rather than a fixed linear pipeline, you compose modules depending on the task.</p><blockquote># Each module has a standard interface: input → output<br>class RetrievalModule:<br> def retrieve(self, query: str) -&gt; List[Document]: …</blockquote><blockquote>class RerankModule:<br> def rerank(self, query: str, docs: List[Document]) -&gt; List[Document]: …</blockquote><blockquote>class FusionModule:<br> def fuse(self, result_lists: List[List[Document]]) -&gt; List[Document]: …</blockquote><blockquote>class GenerationModule:<br> def generate(self, query: str, context: List[Document]) -&gt; str: …</blockquote><blockquote># Compose into a pipeline for your specific use case<br>pipeline = Pipeline([<br> MultiQueryRewriteModule(), # query rewriting<br> ParallelModule([ # run both in parallel<br> DenseRetrievalModule(k=20),<br> BM25RetrievalModule(k=20),<br> ]),<br> RRFFusionModule(), # merge results<br> CohereRerankModule(top_n=5), # rerank<br> ContextCompressionModule(), # compress chunks<br> ClaudeGenerationModule(), # generate<br>])</blockquote><blockquote>answer = pipeline.run(query)</blockquote><p>The value of thinking in modules: you can swap the retrieval module from Qdrant to Weaviate without touching generation, or add a reranker without rewriting the pipeline, or A/B test two fusion strategies with the same upstream and downstream components.</p><p><strong>All five architectures — when to reach for each</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*bgeKriXAEZ5uVuuaAQYzmQ.png" /></figure><p><strong>How these map to Nuvo AI / Prompt2Drug specifically</strong></p><p>Given that Prompt2Drug is an agentic platform over multi-omics data with NuOmics (target discovery) and NuMol (molecular design) as distinct engines, the architecture recommendation is layered:</p><p>GraphRAG as the knowledge layer — target-gene-pathway-disease-compound relationships are precisely what graph traversal is built for. A query like “what other targets share a pathway with KRAS in NSCLC?” is unsolvable with flat chunk retrieval but trivial with a properly built graph.</p><p>Corrective RAG as the safety net — newly published compounds, unpublished data, and queries outside your corpus scope all benefit from the web fallback. The drug discovery literature moves fast enough that corpus gaps are a real problem.</p><p>Adaptive RAG as the routing layer — Target Discovery queries (broad target discovery) vs Drug discovery queries (specific molecular design) likely need different retrieval strategies, and simple follow-up questions shouldn’t pay the cost of a full pipeline run.</p><p>Modular RAG as the architectural principle — build every component with a clean interface from the start so you can swap embedding models, add rerankers, or integrate new data sources without rewriting the pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16bb39b2b09b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG Evaluation]]></title>
            <link>https://medium.com/@shailesh16221/rag-evaluation-46895b0f9dbd?source=rss-6433c74bc518------2</link>
            <guid isPermaLink="false">https://medium.com/p/46895b0f9dbd</guid>
            <category><![CDATA[raga]]></category>
            <category><![CDATA[rag-evaluation]]></category>
            <dc:creator><![CDATA[Shailesh Chaudhary]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 05:41:56 GMT</pubDate>
            <atom:updated>2026-03-23T05:58:00.961Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why evaluation is the hardest part of RAG</strong></p><p>With a classifier, you have ground truth labels. With RAG, you’re evaluating a pipeline where the “right answer” depends on three moving parts simultaneously: did you retrieve the right chunks? Did the LLM use them faithfully? Did the answer actually address the question? Each can fail independently, and a good overall answer can mask bad retrieval — or vice versa.</p><p>RAGAS (RAG Assessment) is the standard framework that gives you a metric for each failure mode independently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*eKtTXHfsERp6KiE0H81otg.png" /></figure><p><strong>The four inputs RAGAS works with</strong></p><p>Before any metric makes sense, understand what RAGAS needs:</p><blockquote>sample = {<br> “question”: “What is the mechanism of sotorasib?”, # user query<br> “answer”: “Sotorasib covalently binds KRAS G12C…”, # LLM generated answer<br> “contexts”: [“chunk 1 text”, “chunk 2 text”, …], # retrieved chunks<br> “ground_truth”: “Sotorasib irreversibly inhibits KRAS G12C” # reference answer (labelled)<br>}</blockquote><p>Some metrics need ground_truth (labelled). Some don&#39;t — they&#39;re reference-free, which is critical for production monitoring where you can&#39;t label every query.</p><p><strong>Metric 1 — Faithfulness (most important)</strong></p><p>Measures: does every claim in the generated answer have support in the retrieved context? This is your primary hallucination detector.</p><p><strong>How it’s calculated internally:</strong></p><ol><li>The LLM decomposes the answer into atomic statements: [&quot;Sotorasib binds KRAS G12C&quot;, &quot;Binding is covalent&quot;, &quot;The mutation is at codon 12&quot;]</li><li>Each statement is checked against the context using NLI (natural language inference): can this statement be inferred from the context?</li><li>Faithfulness = supported_statements / total_statements</li></ol><blockquote>from ragas.metrics import faithfulness<br>from ragas import evaluate<br>from datasets import Dataset</blockquote><blockquote>data = Dataset.from_list([{<br> “question”: “What is the mechanism of sotorasib?”,<br> “answer”: “Sotorasib covalently binds KRAS G12C, blocking downstream signaling.”,<br> “contexts”: [“Sotorasib is a covalent inhibitor targeting KRAS G12C…”],<br> “ground_truth”: “Sotorasib irreversibly inhibits KRAS G12C”<br>}])</blockquote><blockquote>result = evaluate(data, metrics=[faithfulness])<br>print(result[“faithfulness”]) # 0.0 to 1.0</blockquote><p>Score of 1.0 = every claim is grounded. Score of 0.6 = 40% of claims are hallucinated. In production, anything below 0.85 warrants investigation.</p><p><strong>What low faithfulness tells you:</strong> your LLM is leaking parametric memory into the answer — it’s not sticking to the retrieved context. Fix with stronger system prompt grounding instructions, lower temperature, or a better instruction-following model.</p><p><strong>Metric 2 — Answer Relevancy</strong></p><p>Measures: does the answer actually address the question asked? Penalises answers that are factually correct but vague, incomplete, or off-topic.</p><p><strong>How it’s calculated — this is elegant:</strong></p><ol><li>Generate N reverse questions from the answer using an LLM: “What question does this answer answer?”</li><li>Embed each reverse question and the original question</li><li>Answer Relevancy = mean cosine similarity(reverse_questions, original_question)</li></ol><p>The intuition: if the answer is on-topic, questions generated from it will be semantically close to the original question. If the answer drifts or is vague, the reverse questions diverge.</p><p>This metric is <strong>reference-free</strong> — it doesn’t need ground_truth. You can run it on live production traffic.</p><p><strong>What low answer relevancy tells you:</strong> your generation stage is producing answers that drift from the question — often caused by noisy context containing off-topic chunks that distract the LLM. Fix by improving retrieval precision or adding a reranker.</p><p><strong>Metric 3 — Context Precision</strong></p><p>Measures: of the chunks you retrieved, what fraction were actually useful? This is the signal-to-noise ratio of your retrieval.</p><p><strong>How it’s calculated:</strong></p><p>For each retrieved chunk, an LLM judges whether it was relevant to answering the question. Chunks are ranked, and precision is computed with position weighting — a relevant chunk at rank 1 scores better than one at rank 5.</p><p>Context Precision@K = weighted relevant chunks / K retrieved chunks</p><p><strong>What low context precision tells you:</strong> you’re retrieving too many irrelevant chunks. The relevant signal is diluted by noise. Fix by tightening your retrieval (fewer K, better reranking, metadata filtering) or improving your chunking so chunks are more focused.</p><p><strong>Metric 4 — Context Recall</strong></p><p>Measures: did your retrieval cover all the information needed to answer the question? This catches cases where the answer exists in your corpus but wasn’t retrieved.</p><p><strong>How it’s calculated:</strong></p><p>Requires ground_truth. The ground truth answer is decomposed into statements. Each statement is checked: can it be attributed to at least one retrieved chunk?</p><p>Context Recall = statements_found_in_context / total_statements_in_ground_truth</p><p><strong>What low context recall tells you:</strong> your retriever is missing relevant documents. Fix by increasing K, improving your embedding model (especially for domain-specific text), adding BM25 hybrid search, or reviewing your chunking — the answer may be split across chunk boundaries.</p><p><strong>Metric 5 — Answer Correctness</strong></p><p>Measures: is the answer factually correct compared to the ground truth? This is the end-to-end quality metric.</p><p>It’s a weighted combination of two components: factual overlap (F1 score on atomic facts between answer and ground truth) and semantic similarity (embedding cosine similarity between answer and ground truth).</p><p>Answer Correctness = w1 × factual_F1 + w2 × semantic_similarity</p><p>This requires labelled ground truth and is typically used for offline evaluation on a benchmark set, not live production monitoring.</p><p><strong>The diagnostic matrix — what each metric failure means</strong></p><p>This is the part that separates practitioners from theorists. When metrics are low, they tell you <em>exactly where</em> to fix your pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*LNwRFVZ8opkNkQJtrWx4_g.png" /></figure><p><strong>Building an evaluation dataset — the practical challenge</strong></p><p>RAGAS metrics are only as good as your test set. Here’s a pragmatic approach to building one without manually writing hundreds of QA pairs:</p><p><strong>Synthetic generation (fastest start):</strong></p><blockquote>from ragas.testset.generator import TestsetGenerator<br>from ragas.testset.evolutions import simple, reasoning, multi_context<br>from langchain_openai import ChatOpenAI, OpenAIEmbeddings</blockquote><blockquote>generator = TestsetGenerator.from_langchain(<br> generator_llm=ChatOpenAI(model=”gpt-4o”),<br> critic_llm=ChatOpenAI(model=”gpt-4o”),<br> embeddings=OpenAIEmbeddings()<br>)</blockquote><blockquote># Generate 50 test questions from your corpus<br>testset = generator.generate_with_langchain_docs(<br> documents,<br> test_size=50,<br> distributions={<br> simple: 0.5, # single-chunk answerable<br> reasoning: 0.25, # requires inference<br> multi_context: 0.25 # requires multiple chunks<br> }<br>)</blockquote><p>RAGAS generates questions of three types: simple factual (answerable from one chunk), reasoning (requires inference), and multi-context (requires synthesizing across chunks). A good eval set has all three, because they stress different parts of your pipeline.</p><p><strong>Always manually review ~20% of generated questions.</strong> LLMs generate plausible-sounding but sometimes unanswerable or ambiguous questions. Curating even a small high-quality eval set is worth more than a large noisy one.</p><p><strong>Running a full RAGAS evaluation</strong></p><blockquote>from ragas import evaluate<br>from ragas.metrics import (<br> faithfulness,<br> answer_relevancy,<br> context_precision,<br> context_recall,<br> answer_correctness<br>)</blockquote><blockquote># Your pipeline output — one row per question<br>results_dataset = Dataset.from_list([<br> {<br> “question”: q,<br> “answer”: your_rag_pipeline(q),<br> “contexts”: your_retriever(q),<br> “ground_truth”: gt<br> }<br> for q, gt in test_set<br>])</blockquote><blockquote>scores = evaluate(<br> results_dataset,<br> metrics=[<br> faithfulness,<br> answer_relevancy,<br> context_precision,<br> context_recall,<br> answer_correctness<br> ]<br>)</blockquote><blockquote>scores.to_pandas() # score per question — lets you find failure cases</blockquote><p>The per-question breakdown is more valuable than the aggregate score. Look for questions with faithfulness=0 — those are your hallucination cases to debug individually.</p><p><strong>Production monitoring vs. offline evaluation</strong></p><p>This distinction matters for interviews and for building real systems:</p><p>Offline evaluation runs on a labelled benchmark before deployment — you need ground_truth, you run all five metrics, you use it to compare pipeline versions (did adding a reranker improve context precision?).</p><p>Production monitoring runs on live traffic continuously — you can’t label every query, so you use only the <strong>reference-free</strong> metrics: faithfulness and answer relevancy. These can run asynchronously on sampled traffic to catch regressions without a human in the loop.</p><blockquote># Production monitoring pattern — async, no ground truth needed<br>import asyncio</blockquote><blockquote>async def monitor_query(question, answer, contexts):<br> score = await evaluate_async(<br> Dataset.from_list([{“question”: question,<br> “answer”: answer,<br> “contexts”: contexts}]),<br> metrics=[faithfulness, answer_relevancy]<br> )<br> if score[“faithfulness”] &lt; 0.8:<br> alert(“Low faithfulness detected”, question, answer)</blockquote><p>Tools like <strong>Arize Phoenix, LangSmith, and Weights &amp; Biases</strong> Prompts all provide dashboards to track these metrics over time in production.</p><p><strong>Alternative evaluation frameworks</strong></p><p>All three frameworks measure roughly the same thing — retrieval quality + generation quality — but with different APIs, scoring approaches, and stack integrations. Knowing the landscape matters for interviews and for picking the right tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*FeerHDk7CyQqd-NrH99QHQ.png" /></figure><p><strong>TruLens — the RAG Triad</strong></p><p>TruLens frames evaluation as three pairwise relevance checks that form a triangle. If all three pass, your RAG system is working correctly end-to-end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*CjexjWDCw80Gh64IMakDOg.png" /></figure><ul><li>Context relevance: is the retrieved context relevant to the query?</li><li>Groundedness: is every claim in the answer supported by the context?</li><li>Answer relevance: does the answer actually address the query?</li></ul><blockquote>from trulens_eval import TruChain, Feedback, OpenAI as fOpenAI<br>from trulens_eval.feedback import Groundedness</blockquote><blockquote>openai = fOpenAI()<br>grounded = Groundedness(groundedness_provider=openai)</blockquote><blockquote># Three feedback functions = the RAG triad<br>f_groundedness = Feedback(grounded.groundedness_measure_with_cot_reasons)\<br> .on_input_output()</blockquote><blockquote>f_context_relevance = Feedback(openai.qs_relevance)\<br> .on_input()\<br> .on(TruChain.select_context())\<br> .aggregate(np.mean)</blockquote><blockquote>f_answer_relevance = Feedback(openai.relevance)\<br> .on_input_output()</blockquote><blockquote>tru_recorder = TruChain(<br> your_langchain_chain,<br> feedbacks=[f_groundedness, f_context_relevance, f_answer_relevance]<br>)</blockquote><blockquote># TruLens wraps your pipeline and logs every call with scores<br>with tru_recorder as recording:<br> response = your_langchain_chain.invoke({“query”: “What inhibits KRAS G12C?”})</blockquote><p>TruLens gives you a live dashboard (tru.run_dashboard()) showing every query, its triad scores, and the retrieved context — extremely useful for debugging individual failures in production.</p><p><strong>LlamaIndex Eval — retriever-first</strong></p><p>LlamaIndex separates retrieval evaluation from response evaluation cleanly, which is useful when you want to tune your retriever independently before touching generation.</p><blockquote>from llama_index.core.evaluation import (<br> RetrieverEvaluator,<br> FaithfulnessEvaluator,<br> RelevancyEvaluator,<br> CorrectnessEvaluator,<br> BatchEvalRunner<br>)</blockquote><blockquote># Retriever metrics: hit rate and MRR<br>retriever_evaluator = RetrieverEvaluator.from_metric_names(<br> [“hit_rate”, “mrr”],<br> retriever=your_retriever<br>)</blockquote><blockquote># Hit rate = did the correct chunk appear in top-K results at all?<br># MRR = mean reciprocal rank — how high up was the correct chunk?<br>eval_results = await retriever_evaluator.aevaluate_dataset(<br> dataset # list of {query, expected_ids}<br>)</blockquote><blockquote># Response metrics<br>runner = BatchEvalRunner(<br> {“faithfulness”: FaithfulnessEvaluator(),<br> “relevancy”: RelevancyEvaluator(),<br> “correctness”: CorrectnessEvaluator()},<br> workers=4<br>)<br>results = await runner.aevaluate_queries(<br> query_engine=your_query_engine,<br> queries=test_queries,<br> reference=ground_truth_answers<br>)</blockquote><p>Hit rate and MRR are the two retrieval-specific metrics worth knowing well:</p><ul><li>Hit rate@K: what fraction of queries had the correct chunk appear somewhere in the top-K results? Binary per query — 1 if it appeared, 0 if not.</li><li>MRR (Mean Reciprocal Rank): average of 1/rank for the first correct chunk. If the correct chunk is rank 1, you get 1.0. Rank 2 gives 0.5. Rank 5 gives 0.2. Penalises burying the right answer.</li></ul><p><strong>DeepEval — CI/CD native testing</strong></p><p>DeepEval’s main differentiator is that it’s designed to run in your test suite like pytest — you write test cases with assertions and thresholds, and your CI pipeline fails if RAG quality regresses.</p><blockquote>from deepeval import assert_test<br>from deepeval.test_case import LLMTestCase<br>from deepeval.metrics import (<br> FaithfulnessMetric,<br> ContextualPrecisionMetric,<br> ContextualRecallMetric,<br> HallucinationMetric,<br> GEval<br>)</blockquote><blockquote>def test_rag_answer():<br> test_case = LLMTestCase(<br> input=”What is the mechanism of sotorasib?”,<br> actual_output=your_rag_pipeline(“What is the mechanism of sotorasib?”),<br> expected_output=”Sotorasib covalently inhibits KRAS G12C…”,<br> retrieval_context=your_retriever(“What is the mechanism of sotorasib?”)<br> )<br> assert_test(test_case, metrics=[<br> FaithfulnessMetric(threshold=0.85),<br> ContextualPrecisionMetric(threshold=0.80),<br> HallucinationMetric(threshold=0.15) # max allowed hallucination rate<br> ])</blockquote><p>G-Eval is DeepEval’s most interesting metric — it uses chain-of-thought reasoning inside the LLM judge to score on custom criteria you define in plain English:</p><blockquote>coherence_metric = GEval(<br> name=”Scientific coherence”,<br> criteria=”””Evaluate whether the answer uses scientifically accurate <br> terminology and does not conflate distinct biological mechanisms.”””,<br> evaluation_params=[LLMTestCaseParams.INPUT, LLMTestCaseParams.ACTUAL_OUTPUT],<br> threshold=0.8<br>)</blockquote><p>This is powerful for domain-specific evaluation where RAGAS’s generic metrics don’t capture what matters — for example, evaluating whether a drug discovery answer correctly distinguishes binding affinity from selectivity.</p><p><strong>A/B testing RAG pipelines</strong></p><p>This is how you make principled decisions about pipeline changes — chunking strategy A vs B, embedding model X vs Y, with vs without reranker — rather than guessing. The pattern is always the same: hold the eval set fixed, vary one component, compare metrics.</p><blockquote>from ragas import evaluate<br>from ragas.metrics import faithfulness, answer_relevancy, context_precision, context_recall<br>from datasets import Dataset</blockquote><blockquote>def run_pipeline(pipeline_fn, test_cases):<br> rows = []<br> for case in test_cases:<br> answer, contexts = pipeline_fn(case[“question”])<br> rows.append({<br> “question”: case[“question”],<br> “answer”: answer,<br> “contexts”: contexts,<br> “ground_truth”: case[“ground_truth”]<br> })<br> return Dataset.from_list(rows)</blockquote><blockquote>METRICS = [faithfulness, answer_relevancy, context_precision, context_recall]</blockquote><blockquote># Pipeline A: recursive chunking, 512 tokens, no reranker<br>scores_A = evaluate(run_pipeline(pipeline_A, test_cases), metrics=METRICS)</blockquote><blockquote># Pipeline B: semantic chunking, 400 tokens, + Cohere reranker<br>scores_B = evaluate(run_pipeline(pipeline_B, test_cases), metrics=METRICS)</blockquote><blockquote># Compare<br>import pandas as pd<br>comparison = pd.DataFrame({<br> “metric”: [m.name for m in METRICS],<br> “pipeline_A”: [scores_A[m.name] for m in METRICS],<br> “pipeline_B”: [scores_B[m.name] for m in METRICS],<br>})<br>comparison[“delta”] = comparison[“pipeline_B”] — comparison[“pipeline_A”]<br>print(comparison.sort_values(“delta”, ascending=False))</blockquote><p>The output tells you exactly which metrics improved and by how much. A typical result might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*DHHd8hURsvZ0YkaI2Bn2SA.png" /></figure><p>This kind of result is realistic and instructive — Pipeline B is better overall but answer relevancy slightly dropped, which tells you to investigate whether the reranker is over-filtering and dropping chunks that keep the answer focused on the question. That’s the kind of insight A/B testing surfaces that intuition alone never would.</p><p><strong>Key A/B testing rules:</strong> Only change one variable at a time. Use the same eval set across both runs — never evaluate on different questions. Run on at least 50 questions for the results to be meaningful. Check per-question scores, not just aggregates — sometimes a change helps on most questions but catastrophically fails on a specific query type.</p><p><strong>Human evaluation rubrics</strong></p><p>Automated metrics measure proxies for quality. Human evaluation measures actual quality. They don’t always agree — and knowing when to trust which is important.</p><p>The standard approach is a rubric-based scoring sheet where evaluators rate each answer on multiple dimensions independently:</p><blockquote>Question: “What is the selectivity profile of adagrasib vs sotorasib?”<br>Generated answer: [answer text]<br>Retrieved sources: [source 1], [source 2]</blockquote><blockquote>Rate each dimension 1–5:</blockquote><blockquote>Faithfulness [ ] Claims are all supported by sources<br>Completeness [ ] All aspects of the question are addressed <br>Accuracy [ ] Factually correct based on evaluator knowledge<br>Citation quality [ ] Citations are accurate and relevant<br>Clarity [ ] Answer is well-structured and readable</blockquote><p>For a drug discovery domain, SME (subject matter expert) evaluation is essential for the accuracy dimension — RAGAS can’t tell you if the pharmacology is correct, only if it’s consistent with the retrieved text. The retrieved text itself could be wrong.</p><p>In practice, a mixed evaluation strategy works best: automated metrics run on all queries continuously, human evaluation runs on a sampled 5–10% monthly or after major pipeline changes.</p><p><strong>Latency and cost as evaluation dimensions</strong></p><p>Quality metrics alone don’t tell you if your pipeline is deployable. A RAG system that achieves 0.95 faithfulness but takes 8 seconds per query and costs $0.12 per call is not production-viable at scale.</p><blockquote>import time, tiktoken</blockquote><blockquote>enc = tiktoken.encoding_for_model(“gpt-4o”)</blockquote><blockquote>def evaluate_with_cost(pipeline_fn, test_cases, cost_per_1k_tokens=0.005):<br> results = []<br> for case in test_cases:<br> start = time.perf_counter()<br> answer, contexts, prompt = pipeline_fn(case[“question”])<br> latency = time.perf_counter() — start</blockquote><blockquote>input_tokens = len(enc.encode(prompt))<br> output_tokens = len(enc.encode(answer))<br> cost = (input_tokens + output_tokens) / 1000 * cost_per_1k_tokens</blockquote><blockquote>results.append({<br> “question”: case[“question”],<br> “latency_s”: round(latency, 3),<br> “input_tokens”: input_tokens,<br> “output_tokens”: output_tokens,<br> “cost_usd”: round(cost, 5),<br> “answer”: answer,<br> “contexts”: contexts<br> })<br> return pd.DataFrame(results)</blockquote><p>The dimensions to track and their typical production targets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*DRrkLnkJcnPH2V23prso9g.png" /></figure><p>The most important insight here: <strong>quality and latency/cost are in tension</strong>, and you manage that tension deliberately. Adding a reranker improves context precision but adds 200–400ms. Adding multi-query rewriting improves recall but doubles LLM calls. Semantic caching (storing embeddings of past queries and returning cached answers for near-duplicates) can cut both latency and cost by 30–50% on workloads with repetitive queries — a significant win for a research platform where users often ask similar questions about the same targets.</p><p><strong>The complete evaluation picture — putting it all together</strong></p><p>A production-grade evaluation strategy has three layers running simultaneously:</p><p>Pre-deployment offline eval on a fixed benchmark (RAGAS + DeepEval in CI), catching regressions before they ship. Post-deployment production monitoring on sampled live traffic (TruLens or RAGAS reference-free metrics), catching drift and failure modes that only appear at scale. Periodic human evaluation on a curated sample (monthly or after corpus updates), catching domain-accuracy issues that automated metrics can’t detect.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46895b0f9dbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding RAG]]></title>
            <link>https://medium.com/@shailesh16221/understanding-rag-8be2dce7cac5?source=rss-6433c74bc518------2</link>
            <guid isPermaLink="false">https://medium.com/p/8be2dce7cac5</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[comprehensive]]></category>
            <dc:creator><![CDATA[Shailesh Chaudhary]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 05:25:07 GMT</pubDate>
            <atom:updated>2026-03-23T11:45:06.356Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is RAG?</strong> RAG enhances LLMs by retrieving relevant data from an external knowledge base before generating a response, addressing the fundamental problem of models having a frozen knowledge cutoff and producing hallucinations on topics they weren’t trained on.</p><p>Here’s the full pipeline visualized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*woWEiI6n1AI2qlK1svhyDA.png" /></figure><p><strong>Stage 1 — Data ingestion</strong></p><p>This is where you load your raw knowledge: PDFs, HTML pages, databases, APIs, CSVs, code files. Tools like LangChain’s document loaders and LlamaIndex’s data connectors handle most formats. The key skill here is understanding how to extract clean, structured text before anything else.</p><p><strong>Stage 2 — Chunking</strong></p><p>How you split documents dramatically affects quality. Traditional small-chunk approaches (around 100 words) often fragment narrative context, making it harder for the model to reason over retrieved material. <a href="https://www.edenai.co/post/the-2025-guide-to-retrieval-augmented-generation-rag">Eden AI</a> You’ll want to learn fixed-size chunking, recursive character splitting, and semantic chunking. The sweet spot depends on your domain.</p><p><strong>Stage 3 — Embedding generation</strong></p><p>Chunks are converted to dense vectors using embedding models. The Hugging Face Model Hub offers a wide range of pre-trained embedding models and datasets <a href="https://www.glean.com/blog/rag-retrieval-augmented-generation">Glean</a> to experiment with. Popular choices include sentence-transformers, OpenAI&#39;s text-embedding-3-small, and Cohere&#39;s embedding API.</p><p><strong>Stage 4 — Vector store indexing</strong></p><p>The embedding vectors are stored in a vector database like Pinecone, Weaviate, or FAISS, which enables fast similarity search at query time. <a href="https://www.pinecone.io/learn/retrieval-augmented-generation/">Pinecone</a> Each has different tradeoffs around cost, scale, and local vs. cloud hosting.</p><p><strong>Stage 5 — Retrieval</strong></p><p>This is the most nuanced stage. RAG systems employ multiple retrieval techniques: full-text (BM25) search for keyword matching, vector search for semantic similarity, hybrid search combining both, query rewriting to improve recall, and reranking to score retrieved chunks by relevance before passing them to the LLM. <a href="https://www.microsoft.com/en-us/microsoft-cloud/blog/2025/02/04/common-retrieval-augmented-generation-rag-techniques-explained/">Microsoft</a></p><p><strong>Stage 6 — Augmentation and generation</strong></p><p>The retrieved chunks and user query are combined into a structured prompt, and the LLM generates a grounded answer from that augmented context — significantly reducing hallucination. <a href="https://www.pinecone.io/learn/retrieval-augmented-generation/">Pinecone</a></p><p><strong>What data ingestion actually does</strong></p><p>The goal is to take raw, heterogeneous source material — PDFs, websites, Word docs, databases, code files, emails — and transform it into clean, uniform text that can be chunked and embedded in subsequent stages. It’s essentially an ETL (Extract, Transform, Load) pipeline for your knowledge base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMC46vxtwXqjj8nbreIsww.png" /></figure><p><strong>Document loaders — the tools</strong></p><p>These are the workhorses that extract raw text from files. The two dominant frameworks are:</p><p>LangChain has loaders for 80+ formats: PyPDFLoader, UnstructuredWordDocumentLoader, WebBaseLoader, CSVLoader, NotionDirectoryLoader, GitLoader, and many more. They all share a common interface — call .load() and get back a list of Document objects with .page_content and .metadata.</p><p>LlamaIndex has a concept called &quot;Readers&quot; (from llama-hub) covering similar formats but often with better handling of structured data, Notion, Google Drive, Slack, and scientific corpora. For biomedical use cases relevant to Drug Discovery pipeline, the PubMedReader and ArXivReader are particularly useful.</p><p>Unstructured.io is worth knowing separately — it&#39;s a dedicated parsing library (open source + commercial) that handles messy real-world documents far better than basic loaders. It extracts tables, figures, headers, and footers as separate elements rather than a single blob of text.</p><p><strong>Parsing formats — what’s hard and why</strong></p><p>Different source types have very different parsing challenges:</p><p>PDFs are the most common and the most painful. There are two kinds: text-layer PDFs (which can be parsed directly) and scanned PDFs (which require OCR). PyPDF2, pdfminer.six, and pymupdf (fitz) handle text-layer extraction. For scanned docs, you&#39;ll need pytesseract or a cloud OCR service. The bigger headache is layout — multi-column text, tables, footnotes, and headers get scrambled when you extract naively. Unstructured.io handles this significantly better than raw PDF parsers.</p><p>HTML/web pages need you to strip boilerplate — navigation menus, cookie banners, footers — and keep just the article body. BeautifulSoup works for simple cases; trafilatura is excellent for article extraction specifically. LangChain&#39;s WebBaseLoader uses BeautifulSoup under the hood.</p><p>Tables in PDFs and Word documents are notoriously tricky. Naive extraction turns a table into a jumble of cell values with no relational context. The best current approach is to detect tables, serialize them to Markdown or JSON, and keep that serialization as the chunk — so a financial table becomes readable rows rather than random numbers.</p><p>Images and figures require multi-modal handling — either skip them with a note in metadata, extract their captions, or use a vision model to generate a text description. For scientific papers in drug discovery, figures and molecular structures often carry critical information you’d want in your index.</p><p><strong>Cleaning and normalization — the undervalued step</strong></p><p>Most tutorials skip this, but it has an outsized effect on retrieval quality. Key operations:</p><p>Deduplication matters more than you’d think. Internal wikis, documentation sites, and research databases frequently have near-duplicate content. Embedding duplicates wastes index space and can skew retrieval results. Exact deduplication is easy (hash the text); near-deduplication uses MinHash or SimHash.</p><p>Encoding issues — especially in older PDFs, scraped HTML, or CSVs from non-UTF-8 sources — produce garbage characters that corrupt embeddings. Always decode to UTF-8 and handle chardet for unknown encodings.</p><p>Metadata attachment is crucial and often neglected. Every document you ingest should carry metadata: source URL or file path, document title, author, date, document type, and any domain-specific tags. This metadata travels with your chunks and enables metadata filtering during retrieval — for example, “only search within papers published after 2022” or “only search the clinical-trials corpus.”</p><p>Header/footer stripping for PDFs removes repetitive text (page numbers, document titles repeated on every page) that adds noise to embeddings.</p><p><strong>Best practices</strong></p><p>Keep your raw documents separate from your processed/chunked versions. This lets you re-ingest when your parsing logic improves without losing the originals. Store ingestion metadata — what was loaded, when, with what version of your loader — so you can invalidate and re-index specific documents when the source updates.</p><p>For a production system, treat ingestion as an async pipeline with a job queue. Documents come in via an upload API or S3 event, get queued, and a worker processes them asynchronously. This is especially important for large corpora like PubMed abstracts or patent databases relevant to drug discovery.</p><p><strong>Libraries to know, in order of priority</strong></p><p>LangChain document loaders — best starting point, widest format coverage. LlamaIndex readers — better for scientific and structured data sources. Unstructured.io — best parser for messy real-world documents. pymupdf (fitz) — best PDF text + table extraction library. trafilatura — best web article extractor. pytesseract / easyocr — OCR for scanned documents.</p><p><strong>Chunking</strong></p><p>Chunking is where most RAG systems win or lose. The retriever can only surface what exists as a chunk — if the relevant answer spans two chunks, or is buried in a giant chunk full of irrelevant context, your LLM never sees it cleanly.</p><p>Let’s build up from the simplest strategy to the most sophisticated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwD98ZBglKjiROk5Xlpgjw.png" /></figure><p><strong>Fixed-size chunking</strong></p><p>The simplest approach: split text every N tokens (or characters), with an overlap window. Example: 512-token chunks with 50-token overlap.</p><blockquote>from langchain.text_splitter import CharacterTextSplitter</blockquote><blockquote>splitter = CharacterTextSplitter(<br> chunk_size=512,<br> chunk_overlap=50,<br> separator=”\n”<br>)<br>chunks = splitter.split_text(document)</blockquote><p>The overlap is critical — without it, a sentence split across two chunks becomes unsearchable. With it, each chunk shares some context with its neighbors. The downside: this approach is completely oblivious to meaning. A 512-token window might cut through the middle of a paragraph, a table, or a code block, producing a chunk that starts mid-thought and confuses the retriever.</p><p><strong>Use it when:</strong> your documents are uniform in structure (e.g. all short emails, all product descriptions), or you need fast baseline performance to benchmark against.</p><p><strong>Recursive character splitting</strong></p><p>This is the default recommendation for most RAG systems, and what LangChain’s RecursiveCharacterTextSplitter implements. Instead of cutting blindly at N characters, it tries a hierarchy of separators: [&quot;\n\n&quot;, &quot;\n&quot;, &quot;. &quot;, &quot; &quot;, &quot;&quot;]. It first tries to split on double newlines (paragraph boundaries). If a resulting piece is still too large, it falls back to single newlines, then sentences, then words.</p><blockquote>from langchain.text_splitter import RecursiveCharacterTextSplitter</blockquote><blockquote>splitter = RecursiveCharacterTextSplitter(<br> chunk_size=500,<br> chunk_overlap=50,<br> separators=[“\n\n”, “\n”, “. “, “ “, “”]<br>)<br>chunks = splitter.split_documents(docs)</blockquote><p>The result is chunks that tend to align with paragraph or sentence boundaries rather than arbitrary character counts. Much more coherent than fixed-size, with almost no additional cost. This is what you should default to unless you have a specific reason to do otherwise.</p><p><strong>Semantic chunking</strong></p><p>Rather than splitting on structural cues, semantic chunking uses embeddings to detect topic shifts. The algorithm: embed every sentence, compute cosine similarity between adjacent sentences, and insert a chunk boundary where similarity drops sharply (a “breakpoint”).</p><blockquote>from langchain_experimental.text_splitter import SemanticChunker<br>from langchain_openai.embeddings import OpenAIEmbeddings</blockquote><blockquote>splitter = SemanticChunker(<br> OpenAIEmbeddings(),<br> breakpoint_threshold_type=”percentile”, # or “standard_deviation”<br> breakpoint_threshold_amount=95<br>)<br>chunks = splitter.split_text(document)</blockquote><p>The payoff is chunks that are genuinely topically coherent — each chunk tends to represent one idea. The tradeoff is cost and latency: you’re embedding every sentence in the document during ingestion, which is significantly more expensive than text splitting. For a corpus of millions of documents, this cost adds up. For a specialized domain corpus where retrieval precision matters — like scientific papers in drug discovery — it’s often worth it.</p><p><strong>Document-aware chunking</strong></p><p>When your documents have meaningful structure — Markdown headers, HTML sections, code blocks, LaTeX sections — you can use that structure as your chunking signal rather than inferred boundaries.</p><blockquote>from langchain.text_splitter import MarkdownHeaderTextSplitter</blockquote><blockquote>headers = [(“#”, “H1”), (“##”, “H2”), (“###”, “H3”)]<br>splitter = MarkdownHeaderTextSplitter(headers_to_split_on=headers)<br>chunks = splitter.split_text(markdown_doc)<br># Each chunk carries {“H1”: “Introduction”, “H2”: “Methods”} as metadata</blockquote><p>The huge bonus here is that the headers become chunk metadata. When you retrieve a chunk, you know it came from the “Methods → Cell Culture” section of a paper, which you can use for metadata filtering or to enrich the prompt with context. For technical documentation, research papers, and code — this is the most semantically precise approach.</p><p><strong>Parent-child chunking</strong></p><p>This is an advanced pattern that resolves a fundamental tension in RAG: small chunks are more precise for retrieval (because a small, focused chunk matches a query better), but large chunks give the LLM more context for generation. Parent-child solves this by decoupling the two.</p><p>The idea: index small child chunks (e.g. 128 tokens) for retrieval, but when a child chunk is retrieved, fetch and send its large parent chunk (e.g. 512 tokens) to the LLM. The retriever gets precision; the LLM gets context.</p><blockquote>from langchain.retrievers import ParentDocumentRetriever<br>from langchain.storage import InMemoryStore<br>from langchain.text_splitter import RecursiveCharacterTextSplitter</blockquote><blockquote>parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000)<br>child_splitter = RecursiveCharacterTextSplitter(chunk_size=400)</blockquote><blockquote>store = InMemoryStore() # swap for Redis/MongoDB in production<br>retriever = ParentDocumentRetriever(<br> vectorstore=vectorstore,<br> docstore=store,<br> child_splitter=child_splitter,<br> parent_splitter=parent_splitter,<br>)</blockquote><p>This is one of the highest-impact RAG improvements you can make, and relatively underused.</p><p><strong>How chunk size affects retrieval quality</strong></p><p>This is the part most tutorials gloss over. Here’s the intuition:</p><p>Very small chunks (50–100 tokens) are highly precise but lose surrounding context. A chunk containing just “IC50 = 2.3 nM” will match very specific queries but gives the LLM no information about what compound or assay that number belongs to.</p><p>Very large chunks (1000–2000 tokens) preserve context but hurt retrieval precision. The embedding of a 1500-token chunk is an average of everything in it — a paragraph about ADMET properties buried inside a long methods section gets “diluted” by surrounding text and won’t surface reliably for an ADMET-specific query.</p><p>The sweet spot for most text is 300–600 tokens with 10–15% overlap. For code: chunk at the function or class level regardless of token count. For tables: keep the entire table as one chunk with a header prefix. For scientific abstracts: often best to keep the whole abstract as one chunk since it’s already a dense, focused unit.</p><p>The best practice is to evaluate, not guess. Build a small evaluation set — 20–30 representative queries with known relevant documents — and measure retrieval recall at different chunk sizes. The optimal size is corpus-dependent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*Kq_LAdclinhFa9HFoVILGA.png" /></figure><p><strong>Quick decision guide</strong></p><p>For general text documents (articles, documentation, wikis): start with RecursiveCharacterTextSplitter at 400–500 tokens, 50-token overlap. For structured docs with headers (Markdown, HTML, research papers): use document-aware splitting to preserve section hierarchy as metadata. For high-precision domain corpora (scientific literature, legal documents, clinical trial reports): semantic chunking or parent-child is worth the extra cost. For code: split at function/class boundaries using RecursiveCharacterTextSplitter with language-aware separators. For tables and figures: keep as atomic units with a descriptive prefix.</p><p>The most common mistake is picking a chunk size once and never revisiting it. Chunk size is a hyperparameter — tune it against your actual queries, not against intuition.</p><p><strong>Embedding</strong></p><p>Embeddings are the engine of retrieval. The entire premise of semantic search — finding relevant chunks even when the query uses different words than the document — depends entirely on how well your embedding model captures meaning as geometry.</p><p>Let’s build the intuition first, then go practical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*Ahzw_tPnwmPQ_Qnb2_3wMQ.png" /></figure><p>The core idea: an embedding model maps any piece of text to a point in a high-dimensional vector space (typically 768 to 3072 dimensions). The key property is that semantically similar texts land near each other. “KRAS inhibitor” and “KRAS mutation” are closer together than “KRAS inhibitor” and “phase III trial” — even though none of those share the same words. Retrieval is just nearest-neighbor search in that space.</p><p><strong>How the conversion works</strong></p><p>A modern embedding model is a transformer encoder (like BERT or a fine-tuned variant). When you pass a chunk of text through it:</p><ol><li>The text is tokenized into subword units (e.g. “inhibitor” → [“inhib”, “##itor”])</li><li>Each token gets a contextual representation through the transformer layers — each token’s vector is influenced by every other token in the sequence (attention)</li><li>The token representations are pooled — usually mean-pooled across all tokens — into a single fixed-size vector for the whole chunk</li><li>That vector is your embedding: a dense numerical fingerprint of the text’s meaning</li></ol><blockquote>from sentence_transformers import SentenceTransformer</blockquote><blockquote>model = SentenceTransformer(“BAAI/bge-large-en-v1.5”)</blockquote><blockquote>chunks = [<br> “KRAS G12C mutation drives proliferation in NSCLC.”,<br> “Sotorasib covalently inhibits KRAS G12C.”,<br> “Phase III trial showed improved PFS vs docetaxel.”,<br>]</blockquote><blockquote>embeddings = model.encode(chunks, normalize_embeddings=True)<br># Shape: (3, 1024) — 3 chunks × 1024-dim vectors</blockquote><p><strong>The model landscape</strong></p><p>There are three tiers to know:</p><p><strong>Open-source / self-hosted</strong> — full control, no API costs, can fine-tune.</p><p>BAAI/bge-large-en-v1.5 and bge-m3 (multilingual) are currently among the strongest open models. They consistently top the MTEB leaderboard (the standard embedding benchmark). sentence-transformers/all-MiniLM-L6-v2 is a smaller, faster option good for prototyping. For biomedical text specifically, pritamdeka/BioBERT-mnli-snli-scinli-scitail-mednli-stsb or dmis-lab/biobert-base-cased-v1.2 are pre-trained on PubMed and clinical notes, which matters significantly for domain-specific retrieval in drug discovery pipelines.</p><p><strong>Commercial API</strong> — easiest to start, highest quality ceiling, ongoing cost.</p><p>OpenAI’s text-embedding-3-large (3072 dims) and text-embedding-3-small (1536 dims) are excellent and widely used. The 3-small model is a very strong cost-performance tradeoff. Cohere&#39;s embed-english-v3.0 supports a useful input_type parameter that lets you specify whether you&#39;re embedding a query or a document — which improves retrieval because the model can optimize the representation differently for each role.</p><blockquote>import cohere<br>co = cohere.Client(“YOUR_KEY”)</blockquote><blockquote>doc_embeddings = co.embed(<br> texts=chunks,<br> model=”embed-english-v3.0&quot;,<br> input_type=”search_document” # different from query embedding<br>).embeddings</blockquote><blockquote>query_embedding = co.embed(<br> texts=[“What inhibits KRAS G12C?”],<br> model=”embed-english-v3.0&quot;,<br> input_type=”search_query”<br>).embeddings</blockquote><p><strong>Specialized / fine-tuned</strong> — highest quality for narrow domains, most effort.</p><p>For drug discovery specifically, you will eventually hit the ceiling of general-purpose embedders on queries about binding affinities, ADMET properties, or mechanism of action. Fine-tuning bge or e5 on domain-specific query-document pairs using contrastive learning (via the sentence-transformers library) is the path to production-grade retrieval for Target or Drug Discovery-type workloads.</p><p><strong>Key tradeoffs visualized</strong></p><p>Here’s how the major models stack up across the dimensions that matter most in practice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*IKGEJHFTT6tGfndCp0IPyA.png" /></figure><p><strong>Critical tradeoffs to understand</strong></p><p><strong>Dimensionality vs. storage.</strong> A 3072-dim embedding for 1 million chunks takes ~12GB of float32 storage. text-embedding-3-large supports Matryoshka Representation Learning (MRL), meaning you can truncate its vectors to 256 or 512 dims with modest quality loss — a huge win for large-scale indexes. bge models support this too.</p><blockquote># OpenAI MRL truncation — 8x storage reduction, ~5% quality loss<br>embedding = openai.embeddings.create(<br> input=text,<br> model=”text-embedding-3-large”,<br> dimensions=256 # truncate from 3072 to 256<br>)</blockquote><p><strong>Asymmetric vs. symmetric retrieval.</strong> Some models assume query and document are the same type of text (symmetric). Others are trained to handle the asymmetry: a short question (“what inhibits KRAS?”) retrieving a long technical paragraph. Cohere’s input_type parameter and the bge instruction prefix (&quot;Represent this sentence for searching relevant passages: &quot;) explicitly support asymmetric use. For RAG, always use asymmetric mode when available — it consistently improves recall.</p><p><strong>Context window limits.</strong> Every embedding model has a maximum token limit for input. all-MiniLM-L6-v2 caps at 256 tokens — anything longer is silently truncated, which destroys retrieval quality for long chunks. bge-large handles 512. text-embedding-3-large handles up to 8191 tokens. Always check this against your chunk size.</p><p><strong>Domain gap.</strong> General-purpose models are trained on web text. If your corpus is scientific literature, patents, or clinical notes, there is a measurable domain gap — the model’s vocabulary and learned associations don’t perfectly match your domain. This is where biomedical pre-trained models help, and where fine-tuning on your own query-document pairs can unlock significant gains. Even 1000–2000 labeled pairs is often enough to meaningfully improve a fine-tuned bge over the base model on domain-specific retrieval.</p><p><strong>Practical starting point</strong></p><p>For a new RAG system: start with text-embedding-3-small if you want simplicity, or bge-large-en-v1.5 if you want self-hosted control. Measure retrieval recall (hit rate @ k) on 30–50 representative queries. If you&#39;re building on top of biomedical literature for Drug Discovery pipeline, add a comparison against PubMedBERT — the domain pre-training often outweighs raw benchmark numbers on specialized corpora, even though general leaderboard scores favor the larger general models.</p><p>The MTEB leaderboard (<a href="http://huggingface.co/spaces/mteb/leaderboard">huggingface.co/spaces/mteb/leaderboard</a>) is the authoritative source for up-to-date model comparisons — worth checking before committing to a model, since the field moves fast.</p><p><strong>Vector Databases</strong></p><p>Great timing to go deep on this — the vector DB choice is one of the most consequential infrastructure decisions in a RAG system, and the tradeoffs are non-obvious.</p><p>Let’s start with the mental model, then go into each option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*WOVcJJ1AZpYdgoJXh2G9Aw.png" /></figure><p>The landscape splits cleanly into two axes: how much infrastructure you want to manage, and how production-ready you need to be. Click any node above for a deeper dive. Here’s the full breakdown:</p><p><strong>FAISS — Meta’s similarity search library</strong></p><p>FAISS isn’t a database. It’s a pure in-memory index library — no persistence, no metadata storage, no server, no query language. You load vectors into RAM, run ANN (approximate nearest neighbor) search, get back indices, then manually map those back to your chunks.</p><blockquote>import faiss, numpy as np</blockquote><blockquote>dim = 1024<br>index = faiss.IndexFlatIP(dim) # exact inner product search<br># or: faiss.IndexIVFPQ for billion-scale approximate search</blockquote><blockquote>index.add(embeddings.astype(‘float32’)) # add your vectors<br>D, I = index.search(query_vec, k=5) # D=distances, I=indices</blockquote><p>FAISS shines when you want maximum raw search throughput and are willing to handle the infrastructure yourself — chunk storage, metadata, persistence, and serving are all your problem. Its index types (Flat, IVF, HNSW, PQ, IVFPQ) offer a rich speed/accuracy tradeoff space that more opinionated databases don&#39;t expose directly.</p><p><strong>Use FAISS when:</strong> you’re building a custom system where you need low-level index control, you’re doing research, or you want to embed vector search inside a larger application without running a separate service. Not suitable as a standalone production vector store without significant wrapper code.</p><p><strong>Chroma — the developer-friendly local store</strong></p><p>Chroma is where most people start because it’s the simplest path from “I have chunks” to “I can retrieve chunks” in Python. In-process mode needs zero infrastructure — it’s just a Python package.</p><blockquote>import chromadb</blockquote><blockquote>client = chromadb.Client() # in-memory, or PersistentClient(path)<br>collection = client.create_collection(“papers”)</blockquote><blockquote>collection.add(<br> documents=chunks,<br> embeddings=embeddings,<br> metadatas=[{“source”: “paper_1”, “year”: 2023}] * len(chunks),<br> ids=[f”chunk_{i}” for i in range(len(chunks))]<br>)</blockquote><blockquote>results = collection.query(<br> query_embeddings=[query_vec],<br> n_results=5,<br> where={“year”: {“$gte”: 2022}} # metadata filter<br>)</blockquote><p>Chroma handles both embedding generation and storage if you pass it an embedding function, which makes it genuinely frictionless for prototyping. It persists to SQLite under the hood. It also has a server mode for multi-process use. The limitations show at scale: no native hybrid search, limited operational tooling, and the persistence story is SQLite-based which doesn’t scale to tens of millions of vectors with confidence.</p><p>Use Chroma when: you’re prototyping, building a proof-of-concept, or your corpus is small enough to live comfortably in a single process. The LangChain and LlamaIndex integrations are very clean.</p><p><strong>Qdrant — the production open-source option</strong></p><p>Qdrant is written in Rust, which matters: it’s fast, memory-efficient, and handles production load well. It runs as a standalone Docker container or on Qdrant Cloud, and offers one of the best feature sets among open-source options.</p><p>Its standout feature is payload filtering — you can attach arbitrary JSON metadata (“payload”) to every vector and filter on it during search at query time with no performance penalty. This is critical for RAG systems that need to scope retrieval: “only search within documents tagged corpus=clinical_trials uploaded after 2023.&quot;</p><blockquote>from qdrant_client import QdrantClient<br>from qdrant_client.models import Distance, VectorParams, PointStruct, Filter, FieldCondition, MatchValue</blockquote><blockquote>client = QdrantClient(“localhost”, port=6333)</blockquote><blockquote>client.create_collection(“papers”,<br> vectors_config=VectorParams(size=1024, distance=Distance.COSINE))</blockquote><blockquote>client.upsert(“papers”, points=[<br> PointStruct(id=i, vector=emb.tolist(),<br> payload={“source”: “pubmed”, “year”: 2023, “disease”: “NSCLC”})<br> for i, emb in enumerate(embeddings)<br>])</blockquote><blockquote>results = client.search(“papers”,<br> query_vector=query_vec.tolist(),<br> query_filter=Filter(must=[<br> FieldCondition(key=”disease”, match=MatchValue(value=”NSCLC”))<br> ]),<br> limit=5<br>)</blockquote><p>Qdrant also supports sparse vectors (BM25-style) and hybrid search natively, quantization for memory reduction, and has excellent documentation. It’s the best choice when you want production-grade capabilities without vendor lock-in.</p><p><strong>Use Qdrant when:</strong> you need a production-grade self-hosted vector store, you want payload filtering, or you want hybrid (dense + sparse) search without paying for a managed service.</p><p><strong>Weaviate — the semantic-first database</strong></p><p>Weaviate thinks about data differently — it’s schema-first and treats vector search as one capability within a broader knowledge graph-style data model. You define a class with properties (like a schema), and Weaviate stores objects with both their structured properties and their vector representations.</p><p>Its most powerful features are its hybrid search (combining BM25 keyword search with vector search via a tunable alpha parameter) and its module system — you can plug in embedding models, generative models, rerankers, and summarizers directly into the Weaviate pipeline.</p><blockquote>import weaviate</blockquote><blockquote>client = weaviate.Client(“<a href="http://localhost:8080/">http://localhost:8080</a>&quot;)</blockquote><blockquote>results = client.query.get(“Paper”, [“title”, “abstract”, “year”]) \<br> .with_hybrid(query=”KRAS G12C inhibitor”, alpha=0.5) \<br> .with_where({“path”: [“year”], “operator”: “GreaterThan”, “valueInt”: 2021}) \<br> .with_limit(5) \<br> .do()</blockquote><p>The alpha parameter blends keyword (0.0) and vector (1.0) search, which is one of the cleanest hybrid search APIs in the space. Weaviate also offers a managed cloud version (WCS) and is deeply integrated into the DeepLearning.AI RAG curriculum.</p><p>Use Weaviate when: you want strong hybrid search, a schema-oriented data model, or the ability to plug embedding and generative models directly into your database layer.</p><p><strong>Pinecone — the fully managed option</strong></p><p>Pinecone is serverless vector search with no infrastructure to manage. You create an index, upsert vectors, query — that’s it. It scales automatically, handles replication, and abstracts everything operational away.</p><blockquote>from pinecone import Pinecone</blockquote><blockquote>pc = Pinecone(api_key=”YOUR_KEY”)<br>index = pc.Index(“rag-index”)</blockquote><blockquote>index.upsert(vectors=[<br> {“id”: f”chunk_{i}”, “values”: emb.tolist(),<br> “metadata”: {“source”: “pubmed”, “year”: 2023}}<br> for i, emb in enumerate(embeddings)<br>])</blockquote><blockquote>results = index.query(<br> vector=query_vec.tolist(),<br> top_k=5,<br> filter={“year”: {“$gte”: 2022}},<br> include_metadata=True<br>)</blockquote><p>Pinecone’s namespaces are useful for multi-tenant RAG — you can partition your index by user or corpus without running separate indexes. Metadata filtering is solid. The tradeoffs are real though: it’s proprietary, ongoing API cost at scale can be substantial, and you have less control over the underlying index behavior than with self-hosted options.</p><p>Use Pinecone when: you want zero infrastructure management, you’re building fast and want to avoid DevOps overhead, or you’re on a team without the capacity to operate a self-hosted vector store reliably.</p><p><strong>pgvector — the dark horse</strong></p><p>Worth mentioning: if your application already runs on PostgreSQL, pgvector lets you store and query vectors as a native column type. You get vectors, metadata filtering, joins, transactions, and all of SQL in one system.</p><blockquote>CREATE TABLE chunks (<br> id SERIAL PRIMARY KEY,<br> content TEXT,<br> source TEXT,<br> year INT,<br> embedding VECTOR(1024)<br>);</blockquote><blockquote>SELECT content, source,<br> 1 — (embedding &lt;=&gt; ‘[0.12, 0.34, …]’::vector) AS similarity<br>FROM chunks<br>WHERE year &gt;= 2022<br>ORDER BY embedding &lt;=&gt; ‘[0.12, 0.34, …]’::vector<br>LIMIT 5;</blockquote><p>It doesn’t match dedicated vector databases for raw ANN throughput at very large scale, but for many RAG systems — especially those under a few million vectors — pgvector running on a well-provisioned Postgres instance is entirely sufficient and dramatically simpler to operate.</p><p><strong>Head-to-head comparison</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*J5qbx6aNlUKkfv3f4tqyjw.png" /></figure><p><strong>How to actually choose</strong></p><p>The decision comes down to three questions in order.</p><p>First: do you need to self-host? If your data is sensitive — clinical trial data, proprietary molecular structures, unpublished research — sending embeddings to a managed cloud service may be a non-starter. That rules out Pinecone and points to Qdrant or Weaviate on your own infrastructure.</p><p>Second: do you need hybrid search? Semantic search alone misses exact matches — a query for “IC50 = 2.3 nM sotorasib” needs keyword matching to surface results that contain that exact value, not just semantically similar text. If your corpus has precise technical terminology, drug names, gene identifiers, or assay values, hybrid search is not optional. Weaviate or Qdrant, both of which support dense + sparse search, are the clear choices here.</p><p>Third: what’s your team’s operational capacity? If you have no DevOps support, Pinecone removes all friction. If you have Docker and can handle a container, Qdrant is the best self-hosted option. If you’re still in prototype mode, Chroma or even a local FAISS index is completely fine and swappable later.</p><p>For a drug discovery pipeline — where you have heterogeneous corpora (literature, molecular structures, clinical data), need corpus-scoping (Target vs. Drug contexts), and likely have data sensitivity constraints — Qdrant self-hosted with its payload filtering system is probably the strongest fit. The ability to filter by corpus, date, indication, or data_type at query time without sacrificing search speed is exactly what a multi-domain agentic pipeline needs.</p><ul><li><strong>Retrieval</strong></li></ul><p>Retrieval is where most RAG systems either succeed or quietly fail. You can have perfect chunking and great embeddings — but if your retrieval strategy doesn’t surface the right chunks, none of it matters. And the gap between naive semantic search and a well-tuned hybrid + reranking pipeline is enormous in practice.</p><p>Let’s build each layer up from first principles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*I-7W6i2wkJlnG5ELslDWtw.png" /></figure><p>Each layer adds precision. A production RAG system typically runs all of them. Here’s how each works.</p><p><strong>Semantic search — dense retrieval</strong></p><p>You already know the mechanics from the embedding stage: embed the query, compute cosine similarity against every chunk vector, return the top-K closest. The power is cross-lingual and paraphrase matching — “what blocks KRAS signaling?” retrieves chunks about “KRAS inhibitors” even with no word overlap.</p><p>The practical implementation uses HNSW (Hierarchical Navigable Small World) — a graph-based approximate nearest neighbor index that trades a tiny bit of recall for massive speed gains over exact search at scale.</p><blockquote># With Qdrant<br>results = client.search(<br> collection_name=”papers”,<br> query_vector=query_embedding,<br> limit=20 # retrieve more than you need — reranker will trim<br>)</blockquote><p><strong>Where it fails:</strong> exact technical identifiers. A query for &quot;ENSG00000133703&quot; (the Ensembl ID for KRAS) or &quot;sotorasib AMG 510&quot; will get poor semantic recall because the model has no meaningful geometry for those strings. That&#39;s exactly what BM25 solves.</p><p><strong>BM25 — sparse keyword retrieval</strong></p><p>BM25 (Best Match 25) is a classical information retrieval scoring function built on TF-IDF intuitions. For each query term, it scores documents by how often that term appears (term frequency), discounted by how common the term is across the whole corpus (inverse document frequency), with length normalization to avoid favoring long documents.</p><p>The formula looks intimidating but the intuition is simple: a rare term appearing multiple times in a short document is a strong signal.</p><blockquote>from rank_bm25 import BM25Okapi</blockquote><blockquote>tokenized_corpus = [chunk.lower().split() for chunk in chunks]<br>bm25 = BM25Okapi(tokenized_corpus)</blockquote><blockquote>query_tokens = “sotorasib KRAS G12C inhibitor”.lower().split()<br>scores = bm25.get_scores(query_tokens)<br>top_indices = scores.argsort()[-20:][::-1]</blockquote><p>BM25 excels at exact matches: drug names, gene symbols, assay identifiers, molecular formulas, accession numbers, clinical trial IDs. For biomedical RAG these are everywhere, and pure semantic search will miss them. The weakness is synonymy — BM25 has no notion that “inhibitor” and “blocker” mean the same thing.</p><p>This asymmetry is why you need both.</p><p><strong>Hybrid search — the best of both</strong></p><p>Hybrid search runs both retrievers in parallel and fuses their result lists. The dominant fusion algorithm is Reciprocal Rank Fusion (RRF):</p><blockquote>def rrf(rankings: list[list[int]], k: int = 60) -&gt; dict[int, float]:<br> scores = {}<br> for ranking in rankings:<br> for rank, doc_id in enumerate(ranking):<br> scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank + 1)<br> return dict(sorted(scores.items(), key=lambda x: x[1], reverse=True))</blockquote><blockquote>semantic_ranking = [r.id for r in semantic_results] # e.g. [4, 7, 2, 9, …]<br>bm25_ranking = [top_indices[i] for i in range(20)]</blockquote><blockquote>fused = rrf([semantic_ranking, bm25_ranking])</blockquote><p>RRF is robust because it’s rank-based, not score-based — you don’t need to normalize the raw scores of two completely different systems (cosine similarity vs. BM25 score) onto the same scale. A document that ranks 3rd in semantic search and 5th in BM25 scores higher than one that ranks 1st in only one.</p><p>Weaviate’s hybrid search wraps this neatly with an alpha parameter (0 = pure BM25, 1 = pure vector, 0.5 = equal blend), which you can tune empirically per query type. For a corpus with lots of precise identifiers — as in drug discovery — you&#39;ll often find alpha=0.3–0.4 outperforms pure vector search.</p><p><strong>Query rewriting — fixing the query before retrieval</strong></p><p>This is the most underutilized technique. The raw user query is often a poor search input: it’s short, ambiguous, or assumes context the retriever doesn’t have. Query rewriting uses an LLM to transform the query before it hits the index.</p><p>Three techniques worth knowing:</p><p><strong>Multi-query expansion</strong> generates N rephrased versions of the query, runs them all, and merges the result sets. Different phrasings surface different chunks.</p><blockquote>from langchain.retrievers import MultiQueryRetriever</blockquote><blockquote>retriever = MultiQueryRetriever.from_llm(<br> retriever=vectorstore.as_retriever(search_kwargs={“k”: 5}),<br> llm=llm<br>)<br># Internally generates 3–5 query variants, retrieves for each, deduplicates<br>docs = retriever.get_relevant_documents(“what inhibits KRAS in NSCLC?”)</blockquote><p><strong>HyDE (Hypothetical Document Embeddings)</strong> is counterintuitive but powerful: instead of embedding the query directly, ask the LLM to generate a <em>hypothetical answer</em> to the query, then embed that hypothetical document. The intuition is that a hypothetical answer looks more like the real answer chunks in embedding space than a short question does.</p><blockquote>from langchain.chains import HypotheticalDocumentEmbedder</blockquote><blockquote>hyde_embedder = HypotheticalDocumentEmbedder.from_llm(<br> llm=llm,<br> base_embeddings=embeddings,<br> custom_prompt=”Write a 100-word scientific passage that answers: {question}”<br>)<br>hyde_embedding = hyde_embedder.embed_query(<br> “What is the mechanism of sotorasib?”<br>)<br># This embedding is now searched against the corpus</blockquote><p><strong>Step-back prompting</strong> rewrites a specific query to a more general one before retrieval. “What was the IC50 of compound 7 in the HCT116 assay?” becomes “What are the binding affinity properties of KRAS G12C covalent inhibitors?” — a broader query that surfaces more relevant context, after which the specific answer can be found.</p><p><strong>Reranking — precision after recall</strong></p><p>Retrieval is optimized for recall — get potentially relevant chunks. Reranking is optimized for precision — from those candidates, find the truly relevant ones. They use fundamentally different architectures.</p><p>Bi-encoders (what you use for retrieval) embed query and document independently and compare the vectors. This is fast but lossy — the vectors can’t capture fine-grained query-document interaction.</p><p>Cross-encoders receive both query and document concatenated as input and score their relevance jointly. This is much more powerful (the model can attend across both texts) but ~100x slower — which is why you only run it on the top 20–50 candidates from retrieval, not the whole corpus.</p><blockquote>from sentence_transformers import CrossEncoder</blockquote><blockquote>reranker = CrossEncoder(“cross-encoder/ms-marco-MiniLM-L-6-v2”)</blockquote><blockquote># candidate_chunks: top 20 from hybrid retrieval<br>pairs = [(query, chunk.text) for chunk in candidate_chunks]<br>scores = reranker.predict(pairs)</blockquote><blockquote>reranked = sorted(zip(scores, candidate_chunks),<br> key=lambda x: x[0], reverse=True)<br>top_5 = [chunk for _, chunk in reranked[:5]]</blockquote><p><strong>Cohere Rerank</strong> is the easiest production path — a single API call that takes your query and candidate list and returns a relevance-ranked list. It’s a strong model and requires no infrastructure.</p><blockquote>import cohere<br>co = cohere.Client(“YOUR_KEY”)</blockquote><blockquote>reranked = co.rerank(<br> query=”mechanism of KRAS G12C inhibition”,<br> documents=[c.text for c in candidate_chunks],<br> model=”rerank-english-v3.0&quot;,<br> top_n=5<br>)</blockquote><p>The improvement from adding a reranker is often 10–20% in answer quality on domain-specific queries — one of the highest-leverage single changes you can make to a RAG pipeline.</p><p>Putting it all together: the full retrieval stack</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*TSOoCC-SlvCvDEN5mA70pg.png" /></figure><p><strong>What to implement first vs. later</strong></p><p>You don’t need all of this on day one. A practical build order:</p><p>Start with semantic search alone — it gets you 70% of the way there with minimal code. Add BM25 + RRF hybrid next — this is the single biggest quality jump for technical corpora with precise identifiers, drug names, or gene symbols. Then add a reranker — straightforward to bolt on and consistently improves precision. Query rewriting (especially multi-query) comes last — it adds latency and LLM cost, so validate that the baseline quality warrants it first.</p><p>For drug discovery workloads specifically, the BM25 layer is non-negotiable early. Queries that contain &quot;AMG-510&quot;, &quot;ENSG00000133703&quot;, &quot;IC50 &lt; 10 nM&quot;, or specific SMILES fragments will not retrieve reliably from semantic search alone — BM25 catches the exact string matches that dense embeddings miss.</p><p><strong>Generation</strong></p><p>The generation stage is where everything you’ve built — ingestion, chunking, embeddings, retrieval — finally pays off. But it’s also where a surprising amount can still go wrong. A poorly constructed prompt, too many chunks, the wrong LLM, or no grounding guardrails can produce confident-sounding wrong answers even with perfect retrieval.</p><p>Let’s go layer by layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*8GTjl0KXWxCFWruqO7OuEQ.png" /></figure><p><strong>Prompt assembly — the anatomy of a RAG prompt</strong></p><p>A well-structured RAG prompt has four distinct sections, and their order and wording matter significantly.</p><ol><li>SYSTEM PROMPT : Role, behavior, grounding rules</li><li>CONTEXT BLOCK: Retrieved chunks, labeled and sourced</li><li>CONVERSATION HISTORY (if multi-turn): Previous turns, summarized if long</li><li>USER QUERY: The actual question</li></ol><p>Here’s a concrete template that works well in practice:</p><blockquote>RAG_SYSTEM_PROMPT = “””You are a scientific research assistant with expertise in <br>drug discovery. Answer questions based ONLY on the provided context passages.</blockquote><blockquote>Rules:<br>- If the context does not contain enough information to answer, say so explicitly.<br>- Never invent data, compound names, assay results, or citations.<br>- Cite sources using [Source N] notation after each claim.<br>- If sources contradict each other, note the discrepancy.”””</blockquote><blockquote>def build_rag_prompt(query: str, chunks: list[dict]) -&gt; list[dict]:<br> context_block = “\n\n”.join([<br> f”[Source {i+1}] ({chunk[‘metadata’][‘source’]}, {chunk[‘metadata’][‘year’]})\n{chunk[‘text’]}”<br> for i, chunk in enumerate(chunks)<br> ])</blockquote><blockquote>return [<br> {“role”: “system”, “content”: RAG_SYSTEM_PROMPT},<br> {“role”: “user”, “content”: f”””Context passages:<br>{context_block}</blockquote><blockquote>— -<br>Question: {query}</blockquote><blockquote>Answer based only on the context above, citing [Source N] for each claim.”””}<br> ]</blockquote><p>The labeling of chunks as [Source 1], [Source 2] etc. is load-bearing — it&#39;s what allows the model to produce inline citations and lets you post-process the output to verify each claim against the actual retrieved text.</p><p><strong>Context injection patterns</strong></p><p>There are several ways to arrange the retrieved chunks inside the prompt, each with different tradeoffs:</p><p><strong>Sequential injection</strong> (most common) places chunks one after another in ranked order. Simple, predictable, but susceptible to the “lost in the middle” problem — LLMs systematically attend more strongly to content at the beginning and end of long contexts, and under-weight the middle.</p><p><strong>Reverse-rank injection</strong> places the most relevant chunk last (closest to the query), exploiting the recency bias of most LLMs. Counterintuitively effective.</p><p><strong>Structured injection with metadata</strong> wraps each chunk in a header carrying source, date, and relevance score. This gives the LLM explicit signals for how to weight competing information:</p><blockquote>context = “””<br>=== Source 1 | PubMed 2023 | Relevance: 0.94 ===<br>Sotorasib demonstrated durable clinical benefit in patients with <br>KRAS G12C-mutated NSCLC…</blockquote><blockquote>=== Source 2 | PubMed 2022 | Relevance: 0.87 ===<br>Adagrasib showed an objective response rate of 42.9% in CodeBreaK 100…<br>“””</blockquote><p><strong>Compression before injection</strong> — for large retrieved sets, you can use an LLM to compress each chunk to only the sentences relevant to the query before injecting. LangChain’s ContextualCompressionRetriever does this:</p><blockquote>from langchain.retrievers import ContextualCompressionRetriever<br>from langchain.retrievers.document_compressors import LLMChainExtractor</blockquote><blockquote>compressor = LLMChainExtractor.from_llm(llm)<br>compression_retriever = ContextualCompressionRetriever(<br> base_compressor=compressor,<br> base_retriever=base_retriever<br>)<br># Returns only the relevant sentences from each chunk, not the full chunk<br>compressed_docs = compression_retriever.get_relevant_documents(query)<br>```</blockquote><blockquote>This dramatically reduces token usage and keeps only the signal, not the noise.</blockquote><blockquote>— -</blockquote><blockquote>**The “lost in the middle” problem**</blockquote><blockquote>This is one of the most important and under-appreciated failure modes in RAG generation. Research has shown that when LLMs receive long context windows with multiple documents, they reliably perform worse on information that appears in the middle of the context — regardless of its relevance score.<br>```<br>Position in context: [1st] [2nd] [3rd] [4th] [5th]<br>Recall accuracy: high low low low high</blockquote><p>Practical mitigations: keep the total number of injected chunks small (3–5 is usually better than 10–15), put the most relevant chunk first or last rather than middle, and use compression to shrink each chunk to its core content before injection. For very long contexts, consider a “map-reduce” pattern — generate a partial answer per chunk, then synthesize them.</p><p><strong>Hallucination reduction</strong></p><p>RAG significantly reduces hallucination compared to vanilla LLM use, but doesn’t eliminate it. There are three distinct failure modes to guard against:</p><p><strong>Closed-domain hallucination</strong> — the model answers from its parametric memory instead of the provided context. Guard against this with explicit system prompt instructions (“answer ONLY from the context”) and temperature 0 or near-0.</p><p><strong>Faithfulness errors</strong> — the model synthesizes information across chunks in ways that are technically present in the sources but combined incorrectly. A chunk about compound A’s IC50 and a chunk about compound B’s selectivity get merged into a claim about A’s selectivity.</p><p><strong>Confabulated citations</strong> — the model invents [Source 3] references that don&#39;t exist or attributes a claim to the wrong source.</p><p>The most robust mitigation is post-generation faithfulness checking using a second LLM call:</p><blockquote>FAITHFULNESS_PROMPT = “””Given these source passages and a generated answer, <br>identify any claims in the answer that are NOT supported by the sources.</blockquote><blockquote>Sources:<br>{sources}</blockquote><blockquote>Generated answer:<br>{answer}</blockquote><blockquote>Return JSON: {{“faithful”: true/false, “unsupported_claims”: […]}}”””</blockquote><blockquote>def check_faithfulness(answer: str, chunks: list[dict]) -&gt; dict:<br> sources = “\n\n”.join([c[‘text’] for c in chunks])<br> result = llm.invoke(FAITHFULNESS_PROMPT.format(<br> sources=sources, answer=answer<br> ))<br> return json.loads(result.content)</blockquote><p>For production systems, frameworks like RAGAS provide standardized faithfulness, answer relevancy, and context precision metrics you can run as part of an eval pipeline.</p><p><strong>LLM selection for generation</strong></p><p>The choice of generation model is genuinely consequential and depends on your constraints.</p><p><strong>Context window size</strong> is the first filter. If you’re injecting 5 chunks of 500 tokens each plus a system prompt, you need ~4000 tokens of context headroom — any modern LLM handles this. But if you’re building long-document RAG with many retrieved sources, you need 32k–128k context windows. Most frontier models now support this.</p><p><strong>Instruction-following quality</strong> matters enormously for RAG. The model needs to reliably obey “answer only from the context” and produce inline citations in the format you specify. Claude and GPT-4o are particularly strong here. Smaller open-source models often drift from instructions under pressure.</p><p><strong>Reasoning over conflicting evidence</strong> is critical for scientific RAG. When two retrieved papers contradict each other, you want the model to surface the conflict rather than pick one arbitrarily. This requires genuine reasoning capability, not just fluency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*Y3fdKQ6-d2fkbrJPXTvI5Q.png" /></figure><p>For drug discovery RAG specifically — where the retrieved context is dense scientific text, answers require synthesizing across multiple sources, and errors have real consequences — frontier models (Claude, GPT-4o) are worth the cost over smaller models. The gap in instruction-following and faithfulness under complex retrieval conditions is meaningful.</p><p>If data sovereignty is a requirement (proprietary compound data, unpublished trial results), self-hosted Llama 3.1 70B on A100s is the pragmatic path. It won’t match frontier model quality but is significantly better than it was two years ago.</p><p><strong>Putting it all together — a minimal but complete generation pipeline</strong></p><blockquote>from anthropic import Anthropic</blockquote><blockquote>client = Anthropic()</blockquote><blockquote>def generate_rag_answer(query: str, chunks: list[dict]) -&gt; dict:<br> # 1. Build context block with source labels<br> context = “\n\n”.join([<br> f”[Source {i+1}] {c[‘metadata’][‘source’]} ({c[‘metadata’][‘year’]})\n{c[‘text’]}”<br> for i, c in enumerate(chunks)<br> ])</blockquote><blockquote># 2. Call LLM with grounding instructions<br> response = client.messages.create(<br> model=”claude-sonnet-4–5&quot;,<br> max_tokens=1024,<br> system=”””You are a drug discovery research assistant.<br>Answer ONLY from the provided context. Cite [Source N] for every claim.<br>If the context is insufficient, say: ‘The provided sources do not contain <br>enough information to answer this question.’”””,<br> messages=[{<br> “role”: “user”,<br> “content”: f”Context:\n{context}\n\nQuestion: {query}”<br> }]<br> )<br> answer = response.content[0].text</blockquote><blockquote># 3. Post-process: verify citations exist<br> cited_sources = [int(n) for n in re.findall(r’\[Source (\d+)\]’, answer)]<br> valid = all(1 &lt;= n &lt;= len(chunks) for n in cited_sources)</blockquote><blockquote>return {<br> “answer”: answer,<br> “sources”: [chunks[i-1][‘metadata’] for i in cited_sources if 1 &lt;= i &lt;= len(chunks)],<br> “citations_valid”: valid<br> }</blockquote><p>The key design decisions in this snippet: temperature defaults to 1 for Claude but you may want lower for factual RAG tasks, every claim should carry a citation, and the fallback instruction (“the sources do not contain enough information”) is explicit so the model has a graceful exit rather than hallucinating.</p><p><strong>The generation stage quality checklist</strong></p><p>Before calling your RAG system production-ready, verify each of these holds on a representative eval set: the model cites every claim, citations map to real retrieved chunks, the model declines when context is insufficient rather than guessing, answer quality doesn’t degrade on queries where the most relevant chunk lands in the middle of the context, and a faithfulness check on 50 random outputs shows no confabulated claims.</p><p>The generation stage feels like the easy part — call an LLM, get text back — but the difference between a RAG system that users trust and one they abandon usually lives right here in the prompt structure, grounding instructions, and faithfulness checks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8be2dce7cac5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Smart Resume-Screening System with RAG]]></title>
            <link>https://medium.com/@shailesh16221/building-a-smart-resume-screening-system-with-rag-2358e3d75446?source=rss-6433c74bc518------2</link>
            <guid isPermaLink="false">https://medium.com/p/2358e3d75446</guid>
            <category><![CDATA[chunking-strategies]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[resume-screening-tool]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[indexing]]></category>
            <dc:creator><![CDATA[Shailesh Chaudhary]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 12:20:02 GMT</pubDate>
            <atom:updated>2026-02-14T12:20:02.407Z</atom:updated>
            <content:encoded><![CDATA[<p>Recruiters and hiring teams often face the same painful issues: great candidates are missed because they don’t use the exact keyword, irrelevant resumes get shortlisted, and it’s hard to scale subjective judgments like seniority and domain fit. A Retrieval-Augmented Generation (RAG) approach fixes this by combining <strong>semantic retrieval</strong> (what documents <em>mean</em>) with a precision layer that judges <em>relevance</em> the way a human would.</p><p>This article walks through an end-to-end design for a production RAG resume-screening system. Every tool and library I mention includes a link to docs so you — or any reader — can jump straight into implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*iy16lB5oZWNgtsgC9BgeRQ.png" /></figure><h3>TL;DR (What you’ll build)</h3><ul><li>Parse messy resume PDFs → produce clean, structured text</li><li>Chunk text into meaningful units (skills, job entries, projects)</li><li>Embed chunks with a semantic model and store them in a vector DB</li><li>On a Job Description (JD): filter, retrieve top chunks, re-rank with a cross-encoder, aggregate to resume level, present explainable results</li></ul><h3>1) Ingestion &amp; parsing — turn PDFs into structured text</h3><p><strong>What to do, and why it matters</strong></p><p>Real resumes are inconsistent: multi-column layouts, icons, tables, and scanned images. If you lose section boundaries or mix columns, chunking and embeddings suffer. The goal at this stage is to get <strong>clean text</strong> and <strong>section hints</strong> (headings like EXPERIENCE, SKILLS, PROJECTS).</p><p><strong>Tools (click to docs)</strong></p><ul><li>pdfplumber — reliable PDF text extraction. (<a href="https://github.com/jsvine/pdfplumber">https://github.com/jsvine/pdfplumber</a>)</li><li>PyMuPDF — fast, robust page handling for large pipelines. (<a href="https://pymupdf.readthedocs.io/">https://pymupdf.readthedocs.io/</a>)</li><li>unstructured.io — higher-level layout parsing for multi-column and mixed content. (<a href="https://unstructured-io.github.io/unstructured/">https://unstructured-io.github.io/unstructured/</a>)</li><li>Tesseract OCR — OCR for scanned PDFs when needed. (<a href="https://github.com/tesseract-ocr/tesseract">https://github.com/tesseract-ocr/tesseract</a>)</li></ul><p><strong>Details / best practices</strong></p><ol><li>Attempt native text extraction first (pdfplumber / PyMuPDF).</li><li>If page appears as image or extraction fails, run OCR (Tesseract) and then clean text.</li><li>Preserve headings and bullets; normalize whitespace and remove headers/footers when possible.</li><li>Extract candidate metadata when available (name, email, location) and a best-effort skill list (use simple NER or regex heuristics).</li></ol><p><strong>Alternatives &amp; tradeoffs</strong></p><ul><li>Quick-and-dirty: plain text extraction — fast but fragile.</li><li>Robust: unstructured.io — better layout parsing but heavier to run.</li><li>If you only accept DOCX, parsing is easier — but real world resumes are mostly PDF.</li></ul><h3>2) Chunking — the single most impactful step</h3><p><strong>What to do, and why</strong></p><p>Instead of slicing every N tokens, use <strong>structure-aware chunking</strong>: whole skill lists as one chunk, one job/experience per chunk (role + company + bullets), one project/cert per chunk. Embeddings perform best on coherent semantic units — you will get far more accurate retrieval vs blind token chopping.</p><p><strong>Recommended chunk rules</strong></p><ul><li><strong>Skills</strong>: keep as single chunk so skill matching is precise.</li><li><strong>Experience</strong>: one chunk per job entry (role + company + bullets).</li><li><strong>Projects / Certifications</strong>: one chunk per entry.</li><li><strong>Education</strong>: whole block as one chunk.</li><li>If a single chunk &gt; ~800 tokens, split logically (role summary / responsibilities / achievements), not arbitrarily.</li></ul><p><strong>Why structure-aware beats token windows</strong></p><ul><li>Preserves meaning: a whole job entry often contains the exact evidence a JD needs</li><li>Reduces noisy matches from mixed contexts (e.g., separating skills list from achievements).</li><li>Facilitates metadata tagging (company, dates) for filtering and ranking.</li></ul><p><strong>Fallbacks</strong></p><ul><li>Token-based chunking (500 tokens + overlap) is a simple fallback but yields noisier matches.</li><li>Sliding windows increase recall but multiply vectors and compute costs.</li></ul><h3>3) Embeddings — convert chunks into vectors</h3><p><strong>What to do, and why</strong></p><p>Embeddings turn text into numeric vectors so similar content is nearby in vector space. Choose a model that understands technical and professional language (skills, seniority, role context).</p><p><strong>Recommended open-source model family</strong></p><ul><li>BAAI — BGE family (for example BGE large models on Hugging Face) are strong open-source embeddings for domain text. (See models on Hugging Face: <a href="https://huggingface.co/BAAI">https://huggingface.co/BAAI</a>)</li></ul><p><strong>Other options</strong></p><ul><li>sentence-transformers — many strong, smaller embedding models (MPNet, MiniLM variants) for faster/cheaper embeddings. (<a href="https://www.sbert.net/">https://www.sbert.net/</a> &amp; <a href="https://github.com/UKPLab/sentence-transformers">https://github.com/UKPLab/sentence-transformers</a>)</li><li>Hugging Face — primary model hub to discover and host models. (<a href="https://huggingface.co/">https://huggingface.co/</a>)</li></ul><p><strong>Practical notes</strong></p><ul><li>Choose a single embedding model and use it for both JD and resume chunks. Mixing models breaks similarity.</li><li>Batch embed in pipelines (GPU if available).</li><li>Know the embedding dimension upfront (e.g., 768 or 1024) — this affects DB schema and memory planning.</li><li>Normalize vectors if using cosine similarity (some libraries do this automatically).</li></ul><p><strong>Tradeoffs</strong></p><ul><li>Larger models → better semantic nuance but higher compute &amp; memory cost.</li><li>Smaller models → cheaper and faster but might miss seniority or domain subtlety.</li></ul><h3>4) Storage &amp; indexing — pick and configure your vector DB</h3><p><strong>What to store</strong><br>Store each chunk as a row containing:</p><ul><li>id (primary key)</li><li>resume_id (group chunks to the resume)</li><li>text (chunk text for evidence)</li><li>embedding (float vector)</li><li>section (skills / experience / education)</li><li>metadata fields (candidate_name, skills, years_experience, location, source_file, etc.)</li></ul><p><strong>Recommended vector DB</strong></p><ul><li>Milvus — scalable, production-ready vector database with flexible indexes and partitions. (<a href="https://milvus.io/">https://milvus.io/</a>)</li></ul><p><strong>Other DBs to consider</strong></p><ul><li>FAISS — fast library for local vector search, great for prototyping. (<a href="https://github.com/facebookresearch/faiss">https://github.com/facebookresearch/faiss</a>)</li><li>Weaviate — vector DB with semantic graph features. (<a href="https://weaviate.io/">https://weaviate.io/</a>)</li><li>Pinecone — fully managed vector DB if you prefer hosted service. (<a href="https://www.pinecone.io/">https://www.pinecone.io/</a>)</li><li>Chroma — easy local vector DB for rapid prototyping. (<a href="https://www.trychroma.com/">https://www.trychroma.com/</a>)</li></ul><p><strong>Index choice (high level)</strong></p><ul><li><strong>HNSW</strong> (recommended for resume screening) — high accuracy/low latency, more RAM. Best when recruiter UX requires precision.</li><li><strong>IVF_FLAT</strong> — more memory efficient at large scale, small accuracy tradeoff.</li><li><strong>IVF_PQ</strong> — compressed storage for extreme scale (100M+ vectors) but larger accuracy cost.</li></ul><p><strong>Why this matters</strong><br>Index choice controls the speed vs accuracy vs memory tradeoff. For hiring, missing a relevant candidate is expensive — prefer accuracy (HNSW) unless memory/scale forces another choice.</p><h3>5) Retrieval strategy — hybrid (semantic + metadata)</h3><p><strong>What to do</strong></p><ol><li>For an incoming JD, extract explicit constraints: required skills, minimum years experience, location preferences. Simple parsing or a lightweight extractor helps.</li><li>Embed JD using the same embedding model.</li><li>Apply metadata filters in the vector DB (e.g., years_experience &gt;= 5, location IN [US, Remote], must_have_skill = Python) to reduce candidate pool.</li><li>Run vector search for top K chunks (K = 30–100 depending on re-rank budget).</li><li>Aggregate chunk hits to resume level (we’ll cover scoring next).</li></ol><p><strong>Why hybrid</strong></p><ul><li>Vector search finds semantic matches (synonyms, inferred skills).</li><li>Metadata filtering enforces hard constraints (must-have skills, location) that vectors alone can’t guarantee.</li></ul><p><strong>Aggregation example</strong></p><ul><li>If Milvus returns 50 chunks, group by resume_id and compute resume-level score (max chunk score, or average top-N scores, or weighted by section). Max chunk score often works well: a single strong evidence chunk (e.g., “Built scalable microservices using Python &amp; AWS”) should lift a candidate.</li></ul><h3>6) Re-ranking — the precision layer</h3><p><strong>What it is</strong><br>Re-ranking means taking the top retrieved candidates (chunks or aggregated resumes) and scoring them more precisely with a more expensive model that reads <strong>JD + candidate text together</strong>.</p><p><strong>How it works</strong></p><ul><li>Use a cross-encoder (a model that takes the pair (JD, chunk_text) as input and outputs a relevance score). This is slower than separate embedding comparisons but more precise because the model sees both texts jointly and reasons about fit, responsibilities, seniority, and nuance.</li></ul><p><strong>Model examples</strong></p><ul><li>Cross-encoder models on Hugging Face (e.g., cross-encoder/ms-marco-MiniLM-L-6-v2) are good mid-cost options. (<a href="https://huggingface.co/cross-encoder/ms-marco-MiniLM-L-6-v2">https://huggingface.co/cross-encoder/ms-marco-MiniLM-L-6-v2</a>)</li><li>For the highest precision, consider domain-adapted cross-encoders or LLM re-scoring (LLM prompts that output a fit score). LLMs are more expensive but can be more explainable if prompted carefully.</li></ul><p><strong>Practical tips</strong></p><ul><li>Re-rank only the top N retrieved items (e.g., top 50 chunks). Re-ranking everything is computationally infeasible at scale.</li><li>After re-ranking chunks, aggregate to resume level (max chunk score or weighted combination).</li><li>Optionally use short context windows for the re-rank input (e.g., top chunk + role summary) so the model reads the most relevant evidence without excessive token cost.</li></ul><h3>7) Scoring &amp; aggregation — produce the final shortlist</h3><p><strong>Aggregation strategies</strong></p><ul><li><strong>Max chunk score</strong>: take the single best chunk per resume (works well in hiring).</li><li><strong>Average top-N</strong>: average the top 2–3 chunk scores for each resume to reward breadth.</li><li><strong>Weighted</strong>: weight experience chunks higher than skills chunks.</li></ul><p><strong>Combine signals</strong><br>Final ranking should combine multiple signals:</p><ul><li>reranker_score (cross-encoder)</li><li>vector_similarity_score</li><li>business_rules_score (years experience, seniority, certs)<br>A linear combination with tunable weights, calibrated on labeled data, works well.</li></ul><p><strong>Example formula</strong></p><pre>final_score = 0.45 * reranker_score + 0.4 * max_vector_score + 0.15 * business_rules_score</pre><p>Tune weights with a labeled validation set (human shortlists) and A/B tests.</p><h3>8) Explainability — show recruiters why a candidate matched</h3><p><strong>What to surface</strong></p><ul><li>Highlighted evidence snippet(s) — the exact sentence or bullet that matched.</li><li>Which skills matched and where they were found (skills list vs experience).</li><li>A short human-readable explanation: e.g., “High match because: 5+ yrs backend APIs (Python), AWS Lambda experience, led microservices project.”</li></ul><p><strong>Why it matters</strong><br>Recruiters need to trust the system. A score without evidence leads to low adoption. A short summary + evidence snippet increases speed and confidence.</p><p><strong>How to produce it</strong></p><ul><li>Keep the original chunk text and metadata with each vector so you can show the chunk directly.</li><li>Optionally generate a 1–2 sentence human summary using an LLM (prompt: “Summarize why this resume is a match for this JD in one sentence”).</li></ul><h3>9) Evaluation &amp; metrics — how to measure success</h3><p><strong>Key metrics</strong></p><ul><li><strong>Precision@k</strong>: how many of the top-k results are relevant (very important for recruiter time-savings).</li><li><strong>Recall@k</strong>: how many relevant candidates exist in the top-k — ensure you’re not missing gems.</li><li><strong>MRR (Mean Reciprocal Rank)</strong>: whether the best match appears near the top.</li><li><strong>Human feedback loop</strong>: track whether recruiters progress suggested candidates to interviews or rejects them.</li></ul><p><strong>Evaluation process</strong></p><ul><li>Build a labeled test set: JDs with human-curated shortlists.</li><li>Run ablation studies: retrieval only vs retrieval + metadata vs retrieval + re-rank.</li><li>Iterate on chunking, filters, re-rank thresholds based on real user feedback.</li></ul><h3>10) Scaling &amp; operations</h3><p><strong>Estimate vectors</strong></p><ul><li>Chunks per resume: ~5–20. For 1M resumes expect ~5–20M vectors. Plan storage and index memory accordingly.</li></ul><p><strong>Throughput &amp; latency</strong></p><ul><li>Embed in batches; use GPUs for embeddings &amp; re-ranking if low latency is required.</li><li>Cache frequent queries/embeddings (common job templates).</li><li>Use async ingestion and bulk inserts to the vector DB.</li></ul><p><strong>Index maintenance</strong></p><ul><li>Use incremental indexing for new resumes; rebuild only when you change index parameters (M, efConstruction).</li><li>Partition the collection by domain (engineering, finance) or geography (US, EU) to reduce search scope and improve latency.</li></ul><p><strong>Cost &amp; infra</strong></p><ul><li>Embedding + re-ranking are the expensive pieces; use spot GPUs or a burstable GPU fleet.</li><li>Managed DBs (Pinecone) simplify ops; self-hosted (Milvus) gives control and cost optimization.</li></ul><h3>11) Common pitfalls &amp; how to avoid them</h3><ul><li><strong>Bad chunking</strong> → noisy retrieval. Fix: structure-aware chunking.</li><li><strong>No metadata filtering</strong> → semantic noise. Fix: extract and index core metadata (skills, years, location).</li><li><strong>Re-ranking everything</strong> → too slow / expensive. Fix: re-rank only top K.</li><li><strong>No explainability</strong> → recruiter distrust. Fix: show evidence + short summary.</li></ul><h3>12) Component cheat-sheet (with links)</h3><ul><li>Parsing: pdfplumber (<a href="https://github.com/jsvine/pdfplumber">https://github.com/jsvine/pdfplumber</a>), PyMuPDF (<a href="https://pymupdf.readthedocs.io/">https://pymupdf.readthedocs.io/</a>), unstructured.io (<a href="https://unstructured-io.github.io/unstructured/">https://unstructured-io.github.io/unstructured/</a>), OCR: Tesseract OCR (<a href="https://github.com/tesseract-ocr/tesseract">https://github.com/tesseract-ocr/tesseract</a>)</li><li>Chunking: structure-aware (custom code); fallback token windows.</li><li>Embeddings: BAAI on Hugging Face (<a href="https://huggingface.co/BAAI">https://huggingface.co/BAAI</a>) or models from sentence-transformers (<a href="https://www.sbert.net/">https://www.sbert.net/</a>) via the Hugging Face (<a href="https://huggingface.co/">https://huggingface.co/</a>).</li><li>Vector DB: Milvus (<a href="https://milvus.io/">https://milvus.io/</a>); prototyping: FAISS (<a href="https://github.com/facebookresearch/faiss">https://github.com/facebookresearch/faiss</a>) or Chroma (<a href="https://www.trychroma.com/">https://www.trychroma.com/</a>). Managed: Pinecone (<a href="https://www.pinecone.io/">https://www.pinecone.io/</a>). Alternative product: Weaviate (<a href="https://weaviate.io/">https://weaviate.io/</a>).</li><li>Orchestration / frameworks: LangChain (<a href="https://langchain.com/">https://langchain.com/</a>) — helps wire embeddings, vector stores and LLMs together.</li></ul><p><em>(Each link above points to the primary project/docs for quick reference.)</em></p><h3>Closing notes</h3><p>A RAG approach converts resume screening from brittle keyword matching into human-like semantic evaluation. With structure-aware chunking, a reliable embedding model, Milvus (or similar), and a cross-encoder re-ranker, you get high recall and excellent precision — and the explainability recruiters need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2358e3d75446" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transforming Drug Discovery with AI Agents]]></title>
            <link>https://medium.com/@shailesh16221/transforming-drug-discovery-with-ai-agents-ad9aa0a8eab2?source=rss-6433c74bc518------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad9aa0a8eab2</guid>
            <dc:creator><![CDATA[Shailesh Chaudhary]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 15:34:04 GMT</pubDate>
            <atom:updated>2025-04-07T15:34:04.194Z</atom:updated>
            <content:encoded><![CDATA[<p>The pharmaceutical industry continually seeks innovative ways to streamline drug discovery, reduce costs, and accelerate the path from research to treatment. Artificial Intelligence (AI), specifically AI agents, has emerged as a revolutionary solution, transforming the landscape of drug discovery with unprecedented efficiency and effectiveness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*379ash7H3SyNP2a1cJMGKA.png" /></figure><h3>What Are AI Agents?</h3><p>AI agents are sophisticated software programs that autonomously execute tasks, interpret data, make informed decisions, and adapt their strategies through continuous learning. These agents have become indispensable in drug discovery, dramatically enhancing productivity by automating repetitive tasks, predicting outcomes, and enabling innovative solutions to complex biomedical problems.</p><h3>Key Types of AI Agents in Drug Discovery</h3><p>AI agents are diverse, with each type designed to handle specific aspects of drug discovery:</p><h4>1. Predictive Modeling Agents</h4><p>Predictive agents analyze complex biological data, such as genomic, proteomic, and clinical datasets, to accurately forecast the efficacy, toxicity, and potential side effects of drug candidates. Leveraging machine learning models and deep neural networks, these agents drastically improve decision-making, allowing for early elimination of unsuitable compounds.</p><h4>2. Generative Design Agents</h4><p>Generative agents utilize advanced algorithms like Generative Adversarial Networks (GANs) and transformer models to autonomously design new molecular structures tailored to specific therapeutic targets. These agents explore vast chemical spaces, uncovering novel compounds that might never have been considered using traditional approaches.</p><h4>3. Optimization Agents</h4><p>Optimization agents employ reinforcement learning and other iterative improvement techniques to refine existing compounds, enhancing critical factors like bioavailability, efficacy, and reduced toxicity. These agents systematically iterate through chemical modifications, rapidly converging on optimal drug candidates.</p><h4>4. Data Mining Agents</h4><p>Using advanced Natural Language Processing (NLP) algorithms, these agents effectively mine vast volumes of scientific literature, clinical data, and research databases. They uncover hidden insights and connections among diseases, genes, and chemical compounds, significantly accelerating knowledge discovery and hypothesis generation.</p><h4>5. Automation and Screening Agents</h4><p>Automation agents manage high-throughput screening processes, autonomously evaluating extensive libraries of compounds. These agents rapidly identify viable candidates, considerably reducing human labor and minimizing errors during the initial phases of drug discovery.</p><h3>Real-World Examples of AI Agents in Action</h3><ul><li><strong>Predictive Agents</strong> have successfully forecasted the safety profiles of new antiviral and anticancer drugs, significantly reducing time and financial investment in clinical trials.</li><li><strong>Generative Agents</strong> have designed breakthrough molecules targeting antibiotic-resistant bacteria, addressing critical healthcare challenges.</li><li><strong>Optimization Agents</strong> have improved chemotherapy drugs, reducing adverse side effects and enhancing patient outcomes.</li><li><strong>Data Mining Agents</strong> have revealed previously unnoticed links between certain drugs and disease pathways, leading to new therapeutic opportunities.</li><li><strong>Automation Agents</strong> have streamlined compound screening, rapidly identifying potential drugs for complex diseases like cancer and neurological disorders.</li></ul><h3>The Future of AI Agents in Drug Discovery</h3><p>As AI technology evolves, AI agents will become increasingly sophisticated, integrating diverse functionalities into cohesive, fully automated drug discovery systems. The future promises accelerated drug development processes, reduced costs, and the advent of personalized medicine, where therapies are uniquely tailored to individual genetic profiles, significantly enhancing patient outcomes and treatment efficiency.</p><h3>Conclusion</h3><p>AI agents are a transformative force in pharmaceutical research and development, offering robust solutions to longstanding challenges in drug discovery. By automating complex processes, predicting crucial outcomes, and generating innovative therapeutic solutions, AI agents pave the way for a future where drug discovery is not only faster and more efficient but also profoundly more precise and impactful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad9aa0a8eab2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>