<?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 Saurav Paul on Medium]]></title>
        <description><![CDATA[Stories by Saurav Paul on Medium]]></description>
        <link>https://medium.com/@SauravEvan?source=rss-803008333c2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_JZmAy91xwawWwaq.jpg</url>
            <title>Stories by Saurav Paul on Medium</title>
            <link>https://medium.com/@SauravEvan?source=rss-803008333c2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:42:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SauravEvan/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[Kill the God Agent: Architecting Multi-Agent Systems That Can’t Betray You
Google’s three-persona…]]></title>
            <link>https://medium.com/@SauravEvan/kill-the-god-agent-architecting-multi-agent-systems-that-cant-betray-you-google-s-three-persona-1b0916535dfd?source=rss-803008333c2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b0916535dfd</guid>
            <category><![CDATA[ai-security]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[google-cloud]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Saurav Paul]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 20:54:02 GMT</pubDate>
            <atom:updated>2026-11-09T23:51:39.250Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kill the God Agent: Architecting Multi-Agent Systems That Can’t Betray You<br>Google’s three-persona reference build shows what separation of duties actually looks like in production</h3><p>One agent with a master key is the prototype. Three agents that can’t trust each other is the architecture.</p><p>The anti-pattern keeps coming back to is the God Agent: one all-powerful agent under one shared credential, talking to users, reading internal databases, calling external APIs. If a prompt injection lands in that agent, the compromised agent has direct lateral access to dump customer records or trigger unauthorized external actions. It’s the default shape of nearly every agent demo — and it’s the shape you have to kill first when you go to production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*BM92MA07eYKpH-a0Hf8kTQ.gif" /></figure><h4>Separation of duties, enforced by architecture</h4><p>Google’s reference build — a multi-agent warranty claims system on the Gemini Enterprise Agent Platform — splits the job across three compartmentalized personas, and the interesting part is that each one is deliberately crippled.</p><p>The Case Manager orchestrates sanitized warranty claims. It has no direct access to customer databases or shipping APIs, and its only permitted network path is an agent-to-agent handoff routed through Agent Gateway. The Data Vault lives in an isolated Financial Silo, holds exclusive read-only access to BigQuery warranty tables, and never talks to users. The Logistics Liaison runs in an isolated Cloud Run execution zone, is completely blind to customer databases, and invokes shipping, discount, and fraud-alert MCP tools only after a human clicks approve. A prompt injection that compromises any one of them lands inside a narrow, walled room — not the whole building.</p><h4>The vault answers in four words</h4><p>The detail I keep coming back to: the Data Vault doesn’t just have fewer tools, it has a different contract with the outside world. It accepts exactly one input — a 12-digit serial number — validated by deterministic code in an ADK BeforeToolCallback before the tool ever fires. Indirect SQL injection is stopped mechanically, outside the LLM. And it never returns raw database rows. It returns a distilled status: Covered, Not Covered, Expired, or Suspicious. That data minimization does double duty: nothing sensitive leaks across the A2A boundary, and the downstream executor can’t hallucinate unauthorized PII into a shipping label because it never sees any.</p><h4>Goal bounding makes failures cheap</h4><p>Each agent’s goal is scoped so tightly that a failure has nowhere expensive to go. The Case Manager’s system-level goal is strictly workflow routing — it cannot access the tools to execute real-world actions or query backend databases. So its primary risk, misclassifying a claim, degrades to a routing error instead of a financial loss. The Data Vault can only do read-only retrieval; it can’t make routing decisions. The Logistics Liaison can only execute fulfillment; it can’t query the core database or override the Case Manager’s classification. And even the executor’s money moves go through a confirmation primitive: shipping labels require an asynchronous human-in-the-loop approve click, and any “Suspicious” flag bypasses automation entirely and routes the claim to a Fraud &amp; Alerts queue.</p><h4>Every hop goes through the gateway</h4><p>No peer-to-peer agent communication is permitted. Every lateral A2A call is routed through Agent Gateway, which intercepts it, verifies the calling agent’s SPIFFE identity, evaluates IAP allow-policies on the network traffic itself, and runs Model Armor over the payload. The part I’d been underestimating: Model Armor doesn’t just scrub the final response back to the user — it inspects all egress payloads, including lateral traffic between agents and outbound MCP calls. That’s what neutralizes a prompt injection trying to travel sideways from the Data Vault to the Logistics Liaison. Anything not registered in the Agent Registry is denied by default.</p><p>This sits on top of the control planes you already know: registries dictating what may run and with what permissions, observability capturing structured logs of every user and agent action so trajectories can be audited in real time, and VPC Service Controls wrapping the whole thing so that even hijacked credentials can’t exfiltrate data. Deployment follows the same discipline — each agent ships through its own pipeline with SLSA Level 3 provenance, Binary Authorization as the admission gatekeeper, and a 5% canary of claims before cutover.</p><p>Previously in this series: threat-modeling a single agent with SAIF <a href="https://medium.com/@SauravEvan/prompt-injection-isnt-the-vulnerability-it-s-the-delivery-mechanism-1acd02e22209">https://medium.com/@SauravEvan/prompt-injection-isnt-the-vulnerability-it-s-the-delivery-mechanism-1acd02e22209</a></p><p>Next up: the governance maturity model — how to score your agent estate across five layers, from Foundation to Continuous Alignment, and turn the result into a staged 90-day roadmap.</p><p>Which agent in your stack has the widest tool permissions right now — and what would it lose if you applied the vault’s four-word contract to it?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b0916535dfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Injection Isn’t the Vulnerability. It’s the Delivery Mechanism.]]></title>
            <link>https://medium.com/@SauravEvan/prompt-injection-isnt-the-vulnerability-it-s-the-delivery-mechanism-1acd02e22209?source=rss-803008333c2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1acd02e22209</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-ethics]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Saurav Paul]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 09:35:34 GMT</pubDate>
            <atom:updated>2026-10-22T09:35:34.304Z</atom:updated>
            <content:encoded><![CDATA[<p>I used to file prompt injection under “the vulnerability.” Studying how Google threat-models agents with SAIF reframed it for me: injection is just the delivery mechanism. What it reaches is your agent’s tools, memory, and identity, and that’s where the damage actually happens.</p><p>SAIF, Google’s Secure AI Framework, breaks an agent app into the pieces that make it agentic: the perception layer that gathers context, the reasoning core that plans, the orchestration that calls tools, and the rendering that answers the user. Then it maps each risk three ways — where it’s introduced, where it’s exposed, and where you can mitigate it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*mhvQNeq_c4DKh5jIIfdhsQ@2x.jpeg" /></figure><blockquote>Perception: the quiet, dangerous layer</blockquote><p>Perception is doing quiet, dangerous work. The agent blends your explicit instructions with whatever it passively picks up — app state, open documents, sensor readings. SAIF calls that handoff a critical security juncture, because it’s the last chance to separate trusted commands from untrusted data before both end up in the same context. Skip that separation and the rest of the threat model is decoration.</p><blockquote>The reasoning loop is an attack surface</blockquote><p>The core plans, acts, reads the result, and replans — so poisoned tool output or retrieved data arriving mid-loop becomes indirect prompt injection steering the plan. SAIF’s severity rule is blunt: how bad a failure gets is directly proportional to how much autonomy the agent has. Threat-model the tool list and the permissions, not just the model.</p><blockquote>Exfiltration rarely looks like exfiltration</blockquote><p>Agents leak through shared docs, emails, data baked into URLs, even markdown images that phone home when they’re rendered. And there’s a subtler one SAIF calls context hijacking — tricking the agent into pulling data from the wrong context, like surfacing health details while it’s booking a restaurant for you. Most monitoring watches the response body. The leak leaves through an image tag.</p><blockquote>SAIF is code, not a PDF</blockquote><p>One more thing I hadn’t realized: SAIF isn’t just a document. Google publishes the risk map as a machine-readable YAML catalog (github.com/google/saif-data) with controls and JSON schemas, and the tutorial queries it to generate a live threat report for a real project. That’s the difference between a framework you cite in a slide deck and one you can wire into a pipeline.</p><blockquote>The service account is the new root</blockquote><p>And the line I’d put in front of any team shipping agents: Google’s CISO office advises against broad-access service accounts for agents. Propagate the end user’s real identity and permissions to every backend tool the agent touches. Every pilot gets tempted to skip this, because one wide-open service account is simply easier and that’s exactly how it quietly becomes the new root.</p><p>This is based on a hands-on tutorial on threat modeling with SAIF, which you can work through here:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1acd02e22209" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Agent demo worked perfectly. That turned out to be 
the problem.]]></title>
            <link>https://medium.com/@SauravEvan/my-agent-demo-worked-perfectly-that-turned-out-to-be-the-problem-4fb19c0572f0?source=rss-803008333c2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fb19c0572f0</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Saurav Paul]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 15:12:51 GMT</pubDate>
            <atom:updated>2026-10-21T15:16:46.026Z</atom:updated>
            <content:encoded><![CDATA[<h3>My agent demo worked perfectly. That turned out to be the problem.</h3><p>Demos are the easy part — you control the inputs, the data is clean, nothing unexpected happens. Production agents live in the opposite world: probabilistic, stateful, and very good at finding the edge cases you never tested. Google’s answer is a lifecycle built for that reality — the ADLC: Scope, Build, Evaluate, Deploy, Optimize, in a loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*iq3zczhs6Qmp0H-QrLEm4w@2x.jpeg" /></figure><h3>Scope: write the “must not” list</h3><p>The phase most teams underthink is the first one. Scoping an agent isn’t writing down what it should do; it’s writing down what it must never do. Google’s workflow starts with a spec that includes safety constraints and success criteria before there’s any code. If the scope doc doesn’t have a “must not” list, it’s not really a scope — it’s a wish.</p><h3>Build: the easy 10%</h3><p>Build is the part everyone funds, and honestly it’s become the easy part: pick a model, write instructions, wire up tools. The expensive parts are what come after.</p><h3>Evaluate: a phase, not a step</h3><p>Evaluate gets its own phase, separate from Build, and that separation is the point. Google’s guidance says to expect five to ten-plus rounds of the eval — fix loop before an agent passes consistently. And you’re not just grading the final answer — you’re grading the trajectory: which tools it called, in what order, with what arguments. An agent can land on the right answer through a terrible path, and that path is what breaks in production.</p><h3>Deploy: the midpoint, not the finish line</h3><p>Deploy isn’t the end either. If traces and prompt/response logging aren’t switched on before go-live, you’ve shipped a black box.</p><h3>Optimize: where the loop closes</h3><p>Optimize is where live traffic — token usage, latency, judge scores on real requests — feeds straight back into the scope for the next round. If your lifecycle diagram has an end point, it’s the wrong diagram.</p><h3>The loop is the product</h3><p>The uncomfortable bit for planning: most project plans I’ve seen put most of the budget into Build. The ADLC basically inverts that. The loop is the product; the first build is just the entry fee.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fb19c0572f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Production-Grade Multi-Modal Search at Scale]]></title>
            <link>https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-8293c0c61370?source=rss-803008333c2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8293c0c61370</guid>
            <dc:creator><![CDATA[Saurav Paul]]></dc:creator>
            <pubDate>Wed, 19 Nov 2025 04:35:35 GMT</pubDate>
            <atom:updated>2025-11-19T04:35:35.910Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 5: Production Operations, MLOps &amp; Lessons Learned</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-GXUUcdLPmz-iG3p.png" /></figure><h3>Series Navigation</h3><p>- <a href="https://medium.com/@SauravEvan/feae31b04e5c">Part 1: Architecture &amp; Design Decisions</a><br>- <a href="https://medium.com/@SauravEvan/elasticsearch-vector-search-a9083ba9c95a">Part 2: ElasticSearch &amp; Vector Search<br></a>- <a href="https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-e69b9342dc72">Part 3: RAG &amp; Multi-Modal Search</a><br>- <a href="https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-a12380ebdd90">Part 4: Latency &amp; Cost Optimization</a><br>- Part 5: Production Operations &amp; Lessons Learned</p><h3>Quick Context</h3><p>Over the past four posts, we’ve built a sophisticated multi-modal search system serving 30–50M daily active users with sub-200ms latency and $0.03/query cost. But building the system is only half the challenge-running it reliably at scale while iterating rapidly requires operational excellence.</p><p>This final post covers MLOps, compliance, deployment automation, monitoring, and the hard-won lessons from 18 months in production.</p><h3>The Operations Challenge</h3><p>Production systems serving millions of users need:</p><ul><li><strong>Rapid iteration</strong>: Deploy model updates weekly, not quarterly</li><li><strong>Zero downtime</strong>: 99.9%+ uptime despite continuous changes</li><li><strong>Comprehensive monitoring</strong>: Detect issues before users notice</li><li><strong>Automated response</strong>: Rollback bad deployments automatically</li><li><strong>Compliance</strong>: GDPR/CCPA requirements at scale</li><li><strong>Data governance</strong>: Full lineage from raw data to predictions</li></ul><p>Our initial deployment process took <strong>2 weeks</strong> from model training to production. We optimized it to <strong>4 hours</strong> while improving reliability.</p><h4>MLOps Pipeline: Vertex AI Automation</h4><h4>Automated Training Pipeline</h4><pre>from kfp import dsl<br>from kfp.v2 import compiler<br>from google.cloud import aiplatform<br><br>@dsl.pipeline(<br>    name=&quot;fashion-clip-training-pipeline&quot;,<br>    description=&quot;End-to-end training pipeline for fashion CLIP model&quot;<br>)<br>def training_pipeline(<br>    project_id: str,<br>    training_data_path: str,<br>    model_output_path: str<br>):<br>    &quot;&quot;&quot;Automated ML training with validation and deployment.&quot;&quot;&quot;<br>    <br>    # Step 1: Data validation<br>    validate_data_op = dsl.ContainerOp(<br>        name=&quot;validate-training-data&quot;,<br>        image=&quot;gcr.io/project/data-validator:latest&quot;,<br>        arguments=[<br>            &quot;--input-path&quot;, training_data_path,<br>            &quot;--validation-suite&quot;, &quot;fashion_training_data&quot;<br>        ]<br>    )<br>    <br>    # Step 2: Train model<br>    train_op = aiplatform.CustomTrainingJobOp(<br>        display_name=&quot;train-fashion-clip&quot;,<br>        container_uri=&quot;gcr.io/project/clip-trainer:latest&quot;,<br>        args=[<br>            &quot;--training-data&quot;, training_data_path,<br>            &quot;--epochs&quot;, &quot;10&quot;,<br>            &quot;--batch-size&quot;, &quot;256&quot;<br>        ],<br>        machine_type=&quot;n1-highmem-8&quot;,<br>        accelerator_type=&quot;NVIDIA_TESLA_V100&quot;,<br>        accelerator_count=4<br>    ).after(validate_data_op)<br>    <br>    # Step 3: Evaluate model<br>    evaluate_op = dsl.ContainerOp(<br>        name=&quot;evaluate-model&quot;,<br>        image=&quot;gcr.io/project/model-evaluator:latest&quot;,<br>        arguments=[<br>            &quot;--model-path&quot;, train_op.outputs[&quot;model&quot;],<br>            &quot;--test-data&quot;, &quot;/gcs/test-data&quot;<br>        ]<br>    ).after(train_op)<br>    <br>    # Step 4: Bias detection<br>    bias_check_op = dsl.ContainerOp(<br>        name=&quot;bias-detection&quot;,<br>        image=&quot;gcr.io/project/bias-detector:latest&quot;,<br>        arguments=[<br>            &quot;--model-path&quot;, train_op.outputs[&quot;model&quot;],<br>            &quot;--protected-attributes&quot;, &quot;gender,age,ethnicity&quot;<br>        ]<br>    ).after(evaluate_op)<br>    <br>    # Step 5: Model registration (conditional on quality gates)<br>    with dsl.Condition(<br>        evaluate_op.outputs[&quot;accuracy&quot;] &gt; 0.94,<br>        name=&quot;quality-gate&quot;<br>    ):<br>        register_op = dsl.ContainerOp(<br>            name=&quot;register-model&quot;,<br>            image=&quot;gcr.io/project/model-registry:latest&quot;,<br>            arguments=[<br>                &quot;--model-path&quot;, train_op.outputs[&quot;model&quot;],<br>                &quot;--model-name&quot;, &quot;fashion-clip&quot;,<br>                &quot;--version&quot;, &quot;{{workflow.name}}&quot;,<br>                &quot;--accuracy&quot;, evaluate_op.outputs[&quot;accuracy&quot;]<br>            ]<br>        ).after(bias_check_op)<br>    <br>    return register_op<br><br># Schedule to run weekly<br>aiplatform.PipelineJob(<br>    display_name=&quot;fashion-clip-weekly-training&quot;,<br>    template_path=&quot;fashion_training_pipeline.json&quot;,<br>    enable_caching=True<br>).run(schedule=&quot;0 0 * * 0&quot;)  # Every Sunday</pre><p>This pipeline runs automatically every week, training new models on fresh data. If quality gates fail (accuracy &lt;94%), the pipeline stops and alerts the team.</p><h4>A/B Testing Framework</h4><p>We run <strong>50+ concurrent A/B tests</strong> to validate model changes before full rollout.</p><pre>class ABTestFramework:<br>    &quot;&quot;&quot;Run A/B tests for model changes.&quot;&quot;&quot;<br>    <br>    def create_experiment(self, name, control, treatment, traffic_split):<br>        &quot;&quot;&quot;<br>        Create new A/B test experiment.<br>        <br>        Args:<br>            control: Control model version<br>            treatment: Treatment model version<br>            traffic_split: {&quot;control&quot;: 0.5, &quot;treatment&quot;: 0.5}<br>        &quot;&quot;&quot;<br>        experiment_id = f&quot;exp_{name}_{int(time.time())}&quot;<br>        <br>        self.experiments[experiment_id] = {<br>            &quot;control&quot;: control,<br>            &quot;treatment&quot;: treatment,<br>            &quot;traffic_split&quot;: traffic_split,<br>            &quot;start_time&quot;: datetime.utcnow(),<br>            &quot;metrics&quot;: {<br>                &quot;control&quot;: {&quot;requests&quot;: 0, &quot;errors&quot;: 0, &quot;latency&quot;: []},<br>                &quot;treatment&quot;: {&quot;requests&quot;: 0, &quot;errors&quot;: 0, &quot;latency&quot;: []}<br>            }<br>        }<br>        <br>        return experiment_id<br>    <br>    def assign_variant(self, experiment_id, user_id):<br>        &quot;&quot;&quot;Assign user to control or treatment variant.&quot;&quot;&quot;<br>        exp = self.experiments[experiment_id]<br>        <br>        # Consistent hashing for stable assignment<br>        hash_val = int(hashlib.md5(f&quot;{user_id}{experiment_id}&quot;.encode()).hexdigest(), 16)<br>        rand = (hash_val % 100) / 100.0<br>        <br>        cumulative = 0<br>        for variant, split in exp[&quot;traffic_split&quot;].items():<br>            cumulative += split<br>            if rand &lt; cumulative:<br>                return variant<br>        <br>        return &quot;control&quot;<br>    <br>    def analyze_experiment(self, experiment_id):<br>        &quot;&quot;&quot;Analyze with statistical significance.&quot;&quot;&quot;<br>        from scipy import stats<br>        <br>        exp = self.experiments[experiment_id]<br>        control_metrics = exp[&quot;metrics&quot;][&quot;control&quot;]<br>        treatment_metrics = exp[&quot;metrics&quot;][&quot;treatment&quot;]<br>        <br>        # Latency comparison (t-test)<br>        t_stat, p_value = stats.ttest_ind(<br>            control_metrics[&quot;latency&quot;],<br>            treatment_metrics[&quot;latency&quot;]<br>        )<br>        <br>        return {<br>            &quot;statistical_significance&quot;: p_value &lt; 0.05,<br>            &quot;p_value&quot;: p_value,<br>            &quot;recommendation&quot;: self._get_recommendation(<br>                control_metrics, treatment_metrics, p_value<br>            )<br>        }</pre><h4>Canary Deployments with Automated Rollback</h4><p><strong>Gradual Rollout Strategy:</strong></p><pre>Stage 1: 5% traffic   → Monitor for 2 hours<br>Stage 2: 25% traffic  → Monitor for 4 hours<br>Stage 3: 50% traffic  → Monitor for 8 hours<br>Stage 4: 100% traffic → Full rollout<br><br>At each stage: Check error rate, latency, business metrics<br>If any metric degrades &gt;10%: Automatic rollback</pre><p><strong>Implementation:</strong></p><pre>class CanaryDeployment:<br>    &quot;&quot;&quot;Gradual rollout with automated rollback.&quot;&quot;&quot;<br>    <br>    def __init__(self, model_name, new_version):<br>        self.model_name = model_name<br>        self.current_version = get_current_version(model_name)<br>        self.new_version = new_version<br>        self.stages = [0.05, 0.25, 0.50, 1.0]<br>    <br>    async def execute_rollout(self):<br>        &quot;&quot;&quot;Execute canary deployment with health checks.&quot;&quot;&quot;<br>        for stage_idx, traffic_pct in enumerate(self.stages):<br>            logger.info(f&quot;Stage {stage_idx + 1}: {traffic_pct*100}% traffic&quot;)<br>            <br>            # Update traffic split<br>            self.set_traffic_split({<br>                self.current_version: 1.0 - traffic_pct,<br>                self.new_version: traffic_pct<br>            })<br>            <br>            # Wait for monitoring period<br>            monitor_duration = [7200, 14400, 28800, 0][stage_idx]  # seconds<br>            if monitor_duration &gt; 0:<br>                await asyncio.sleep(monitor_duration)<br>            <br>            # Health check<br>            health = await self.check_health()<br>            <br>            if not health[&quot;healthy&quot;]:<br>                logger.error(f&quot;Health check failed: {health[&#39;reason&#39;]}&quot;)<br>                await self.rollback()<br>                return False<br>            <br>            self.current_stage = stage_idx + 1<br>        <br>        logger.info(f&quot;Rollout complete: {self.new_version} at 100%&quot;)<br>        return True<br>    <br>    async def check_health(self):<br>        &quot;&quot;&quot;Check if new version is healthy.&quot;&quot;&quot;<br>        metrics = await get_metrics(self.new_version, duration_minutes=10)<br>        baseline = await get_metrics(self.current_version, duration_minutes=60)<br>        <br>        # Compare error rates<br>        if metrics[&quot;error_rate&quot;] &gt; baseline[&quot;error_rate&quot;] * 1.10:<br>            return {<br>                &quot;healthy&quot;: False,<br>                &quot;reason&quot;: f&quot;Error rate increased: {metrics[&#39;error_rate&#39;]:.2%}&quot;<br>            }<br>        <br>        # Compare latency<br>        if metrics[&quot;latency_p95&quot;] &gt; baseline[&quot;latency_p95&quot;] * 1.15:<br>            return {<br>                &quot;healthy&quot;: False,<br>                &quot;reason&quot;: f&quot;Latency degraded: {metrics[&#39;latency_p95&#39;]}ms&quot;<br>            }<br>        <br>        # Compare conversion rate<br>        if metrics[&quot;conversion_rate&quot;] &lt; baseline[&quot;conversion_rate&quot;] * 0.95:<br>            return {<br>                &quot;healthy&quot;: False,<br>                &quot;reason&quot;: f&quot;Conversion dropped: {metrics[&#39;conversion_rate&#39;]:.2%}&quot;<br>            }<br>        <br>        return {&quot;healthy&quot;: True}<br>    <br>    async def rollback(self):<br>        &quot;&quot;&quot;Rollback to previous version.&quot;&quot;&quot;<br>        logger.critical(f&quot;Rolling back from {self.new_version} to {self.current_version}&quot;)<br>        <br>        # Immediately set traffic to 100% old version<br>        self.set_traffic_split({<br>            self.current_version: 1.0,<br>            self.new_version: 0.0<br>        })<br>        <br>        # Alert team<br>        send_alert(<br>            severity=&quot;HIGH&quot;,<br>            message=f&quot;Automatic rollback triggered for {self.model_name}&quot;,<br>            details=f&quot;From {self.new_version} to {self.current_version}&quot;<br>        )</pre><p>Deployment Time: 2 Weeks → 4 Hours</p><p><strong>Before (Manual Process):</strong></p><ol><li>Train model: 3 days</li><li>Evaluate model: 1 day</li><li>Deploy to staging: 2 days</li><li>Staging tests: 3 days</li><li>Production deployment: 2 days</li><li>Monitoring: 3 days <strong>Total: 14 days</strong></li></ol><p><strong>After (Automated Pipeline):</strong></p><ol><li>Train model: 6 hours (automated)</li><li>Evaluate model: 30 minutes (automated)</li><li>Deploy to staging: 15 minutes (automated)</li><li>Staging tests: 1 hour (automated)</li><li>Canary deployment: 2 hours</li><li>Monitoring: Continuous (automated) <strong>Total: 4 hours</strong></li></ol><h4>Data Governance &amp; Compliance</h4><p><strong>GDPR/CCPA Implementation</strong></p><p><strong>Key Requirements:</strong></p><ol><li>Right to access (users can request all their data)</li><li>Right to deletion (complete data removal)</li><li>Right to portability (export user data)</li><li>Consent management</li><li>Data minimization</li><li>Purpose limitation</li><li>Breach notification (within 72 hours)</li></ol><p><strong>Data Access Request Handler:</strong></p><pre>async def handle_data_access_request(user_id):<br>    &quot;&quot;&quot;<br>    Compile all user data from across systems.<br>    GDPR Article 15: Right of access.<br>    &quot;&quot;&quot;<br>    # Collect from all data sources<br>    user_data = {<br>        &quot;personal_info&quot;: await get_user_profile(user_id),<br>        &quot;search_history&quot;: await get_search_logs(user_id),<br>        &quot;purchase_history&quot;: await get_purchases(user_id),<br>        &quot;preferences&quot;: await get_user_preferences(user_id),<br>        &quot;feature_store&quot;: await get_feature_data(user_id),<br>        &quot;ml_predictions&quot;: await get_ml_inferences(user_id)<br>    }<br>    <br>    # Generate downloadable package<br>    package_id = generate_data_package(user_data)<br>    <br>    # Log access request (audit trail)<br>    log_compliance_event(<br>        event_type=&quot;DATA_ACCESS_REQUEST&quot;,<br>        user_id=user_id,<br>        package_id=package_id<br>    )<br>    <br>    return {<br>        &quot;package_id&quot;: package_id,<br>        &quot;download_url&quot;: f&quot;https://privacy.example.com/download/{package_id}&quot;,<br>        &quot;expires_at&quot;: datetime.utcnow() + timedelta(days=7)<br>    }</pre><h4>PII Detection with Cloud DLP</h4><p><strong>Automated PII Detection:</strong></p><pre>from google.cloud import dlp_v2<br><br>def detect_and_mask_pii(text):<br>    &quot;&quot;&quot;Detect and mask PII using Cloud DLP.&quot;&quot;&quot;<br>    dlp = dlp_v2.DlpServiceClient()<br>    <br>    # Configure detection<br>    inspect_config = {<br>        &quot;info_types&quot;: [<br>            {&quot;name&quot;: &quot;EMAIL_ADDRESS&quot;},<br>            {&quot;name&quot;: &quot;PHONE_NUMBER&quot;},<br>            {&quot;name&quot;: &quot;CREDIT_CARD_NUMBER&quot;},<br>            {&quot;name&quot;: &quot;STREET_ADDRESS&quot;},<br>            {&quot;name&quot;: &quot;PERSON_NAME&quot;}<br>        ],<br>        &quot;min_likelihood&quot;: dlp_v2.Likelihood.POSSIBLE<br>    }<br>    <br>    # Configure de-identification<br>    deidentify_config = {<br>        &quot;info_type_transformations&quot;: {<br>            &quot;transformations&quot;: [{<br>                &quot;primitive_transformation&quot;: {<br>                    &quot;character_mask_config&quot;: {<br>                        &quot;masking_character&quot;: &quot;*&quot;<br>                    }<br>                }<br>            }]<br>        }<br>    }<br>    <br>    # Detect and mask<br>    item = {&quot;value&quot;: text}<br>    response = dlp.deidentify_content(<br>        request={<br>            &quot;parent&quot;: f&quot;projects/{PROJECT_ID}&quot;,<br>            &quot;deidentify_config&quot;: deidentify_config,<br>            &quot;inspect_config&quot;: inspect_config,<br>            &quot;item&quot;: item<br>        }<br>    )<br>    <br>    return response.item.value, response.overview.transformation_summaries<br><br># Example<br>query = &quot;Email me at jane@example.com&quot;<br>masked, findings = detect_and_mask_pii(query)<br># Result: &quot;Email me at ******************&quot;</pre><p><strong>PII Detection Metrics:</strong></p><ul><li>Accuracy: <strong>99.99%</strong> (10 false positives, 1 false negative in 100K tests)</li><li>Latency: 45ms p95</li><li>Volume: 2.3M texts scanned per day</li><li>Cost: $0.0001 per text</li></ul><p><strong>End-to-End Lineage:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fT5s0Zk5GELvGJjw90xfA.png" /></figure><p><strong>Lineage Query:</strong></p><pre>def query_data_lineage(data_element_id):<br>    &quot;&quot;&quot;Query complete lineage for a data element.&quot;&quot;&quot;<br>    lineage_chain = []<br>    current_element = data_element_id<br>    <br>    while current_element:<br>        entry = dataplex_client.get_entry(name=current_element)<br>        <br>        lineage_chain.append({<br>            &quot;element&quot;: current_element,<br>            &quot;source&quot;: entry.lineage.source,<br>            &quot;transformations&quot;: entry.lineage.transformations,<br>            &quot;timestamp&quot;: entry.lineage.timestamp<br>        })<br>        <br>        current_element = entry.lineage.source<br>        if current_element == &quot;root&quot;:<br>            break<br>    <br>    return lineage_chain</pre><h4>Comprehensive Monitoring</h4><p><strong>Multi-Dimensional Monitoring</strong></p><pre>class ModelMonitoring:<br>    &quot;&quot;&quot;Monitor deployed models for various issues.&quot;&quot;&quot;<br>    <br>    def monitor_data_drift(self):<br>        &quot;&quot;&quot;Detect drift in input data distribution.&quot;&quot;&quot;<br>        from scipy.stats import ks_2samp<br>        <br>        # Get training vs production data<br>        training_data = load_training_data_sample()<br>        production_data = load_production_data(days=7)<br>        <br>        drift_detected = []<br>        <br>        for feature in training_data.columns:<br>            # Kolmogorov-Smirnov test<br>            stat, p_value = ks_2samp(<br>                training_data[feature],<br>                production_data[feature]<br>            )<br>            <br>            if p_value &lt; 0.05:  # Significant drift<br>                drift_detected.append({<br>                    &quot;feature&quot;: feature,<br>                    &quot;p_value&quot;: p_value,<br>                    &quot;severity&quot;: &quot;HIGH&quot; if p_value &lt; 0.01 else &quot;MEDIUM&quot;<br>                })<br>        <br>        if drift_detected:<br>            send_alert(<br>                message=f&quot;Data drift detected in {len(drift_detected)} features&quot;,<br>                details=drift_detected<br>            )<br>    <br>    def monitor_prediction_drift(self):<br>        &quot;&quot;&quot;Detect drift in model predictions.&quot;&quot;&quot;<br>        baseline_predictions = get_predictions(days_ago=30, duration_days=7)<br>        current_predictions = get_predictions(days_ago=0, duration_days=7)<br>        <br>        baseline_mean = np.mean(baseline_predictions)<br>        current_mean = np.mean(current_predictions)<br>        <br>        drift_pct = ((current_mean - baseline_mean) / baseline_mean) * 100<br>        <br>        if abs(drift_pct) &gt; 10:  # 10% drift threshold<br>            send_alert(<br>                message=f&quot;Prediction drift detected: {drift_pct:+.1f}%&quot;,<br>                severity=&quot;HIGH&quot;<br>            )</pre><p><strong>Monitoring Schedule:</strong></p><ul><li>Data drift: Every hour</li><li>Prediction drift: Every 6 hours</li><li>Bias monitoring: Daily</li><li>Performance degradation: Continuous</li></ul><h4>Real-World Results</h4><p>Business Impact</p><p><strong>Revenue &amp; Conversion:</strong></p><ul><li>Annual revenue impact: <strong>$18.5M</strong> (measured via A/B test)</li><li>Conversion rate improvement: <strong>+47%</strong> (semantic vs keyword search)</li><li>Average order value: <strong>+$23</strong> with RAG recommendations</li><li>Cart abandonment: <strong>-18%</strong></li><li>Return rate: <strong>-12%</strong> (better size/style matching)</li></ul><p><strong>User Engagement:</strong></p><ul><li>Search satisfaction: <strong>90%</strong> (up from 76%)</li><li>Time to purchase: <strong>-8 minutes</strong> average</li><li>Repeat search rate: <strong>-34%</strong> (finding right product faster)</li><li>Visual search adoption: <strong>23%</strong> of all searches</li><li>Voice search adoption: <strong>3.5%</strong> and growing</li></ul><p><strong>Performance:</strong></p><ul><li>p95 latency: <strong>195ms</strong> (target &lt;200ms) ✓</li><li>Throughput: <strong>10,800 QPS</strong> peak (target 10K) ✓</li><li>Uptime: <strong>99.94%</strong> (target 99.9%) ✓</li><li>Cache hit rate: <strong>73%</strong></li></ul><p><strong>ML Quality:</strong></p><ul><li>Fashion detection: <strong>95.2%</strong> accuracy</li><li>Semantic search hit@10: <strong>0.87</strong></li><li>RAG hallucination rate: <strong>1.1%</strong></li><li>Model bias score: <strong>0.08</strong> (threshold 0.10)</li></ul><p><strong>Cost:</strong></p><ul><li>Per-query cost: <strong>$0.03</strong> (target &lt;$0.05) ✓</li><li>Monthly infrastructure: <strong>$27.6K</strong></li><li>Annual cost: <strong>$45M</strong> (1.5B queries)</li><li>Cost reduction vs initial: <strong>75%</strong></li><li>ROI: <strong>41x</strong> ($18.5M revenue / $0.45M incremental infrastructure)</li><li>Data access requests: 12,847 (avg response: 4.2 days, SLA: 7 days)</li><li>Deletion requests: 3,201 (avg completion: 2.8 days, SLA: 5 days)</li><li>PII incidents: <strong>0</strong></li><li>Data breaches: <strong>0</strong></li><li>Regulatory fines: <strong>$0</strong></li><li>Bias audits: 52 weekly audits, 3 issues found and mitigated</li></ul><h4>Lessons Learned</h4><p><strong>1. Hybrid Search (0.7 × Semantic + 0.3 × Keyword)</strong><br> Pure semantic failed on exact matches. Pure keyword missed intent. Hybrid gave us best of both worlds. Our single biggest accuracy improvement.</p><p><strong>2. Aggressive Caching (73% Hit Rate)</strong><br> We initially resisted caching due to staleness concerns. But 5-minute TTLs with intelligent invalidation achieved 73% hit rate while keeping results fresh. Saved<strong>$161M annually</strong>.</p><p><strong>3. Model Quantization (INT8)</strong><br> FP32 to INT8 reduced size 74%, inference time 39%, cost 60% with only 0.4% accuracy loss. Should have done this on day one.</p><p><strong>4. Vertex AI for RAG</strong><br> Building our own RAG would have taken 6 months and required dedicated staff. Vertex AI gave us production-grade RAG in 2 weeks. Premium absolutely worth it.</p><p><strong>5. Compliance from Day One</strong><br> Building GDPR/CCPA into architecture from start saved costly retrofits. PII detection, lineage, audits were cheap when built-in, expensive when bolted-on.</p><p><strong>6. Automated MLOps</strong><br> 2 weeks → 4 hours deployment enabled rapid iteration. We deployed <strong>47 model updates</strong> in 12 months vs 6 the previous year. Velocity matters.</p><h4>What We’d Do Differently</h4><p><strong>1. Start with Simpler Models</strong><br> Spent 3 months fine-tuning CLIP when off-the-shelf sentence transformers would have been 80% as good for text-only search. Ship v1 fast, then optimize.</p><p><strong>2. Optimize for Latency Earlier</strong><br> Hit 780ms p95 in v1 by optimizing for accuracy first. If we’d set &lt;200ms as hard requirement from day one, we’d have made different architectural choices.</p><p><strong>3. More Feature Flags</strong><br> Had A/B testing but not enough feature flags. When we needed to disable RAG for cost, we had to deploy code. Feature flags would have let us toggle instantly.</p><p><strong>4. Better Observability from Day One</strong><br> Added detailed tracing after latency problems. If we’d instrumented everything from start, we’d have caught issues earlier. Observability isn’t optional at scale.</p><p><strong>5. Load Test with 10x Target</strong><br> Tested at expected peak (10K QPS) and hit limits immediately. Should have tested at 100K QPS to find bottlenecks before production.</p><p><strong>6. Document the “Why”</strong><br> Docs explained how to configure Elasticsearch but not why. 6 months later, nobody remembered why refresh_interval=30s. Document decision rationale.</p><h4>Recommendations for Others</h4><p><strong>1. Latency Budget Everything</strong><br> 200ms budget? Allocate: 40ms embedding, 50ms search, 80ms RAG, 30ms buffer. Every component owner knows their budget. Measure obsessively.</p><p><strong>2. Cache Aggressively, Invalidate Intelligently</strong><br> Caching is cheapest performance optimization. But stale data kills trust. Invest in smart invalidation-worth it.</p><p><strong>3. Hybrid Search &gt; Pure Semantic</strong><br> For e-commerce and most real-world applications, hybrid (semantic + keyword) beats pure semantic. Users still use exact terms; respect that.</p><p><strong>4. Quantize Models Without Fear</strong><br> INT8 typically loses &lt;1% accuracy while saving 60%+ cost. Test it; you’ll adopt it.</p><p><strong>5. Compliance is Cheaper Upfront</strong><br> PII detection, lineage, audit trails-build them in from day one. Retrofitting is 10x more expensive.</p><p><strong>6. MLOps is Not Optional at Scale</strong><br> Automated training, testing, deployment, monitoring are the difference between deploying once per quarter and once per week. Velocity compounds.</p><p><strong>7. Observability Before Scale</strong><br> Detailed tracing, metrics, logging from day one. You cannot optimize what you cannot measure.</p><p><strong>8. Cost Matters from Day One</strong><br> At $0.12/query, our system would cost $180M/year. We’d never have gotten budget. Design for cost efficiency from start, not afterthought.</p><h3>Conclusion</h3><p>Building production-grade multi-modal search at 30–50M DAU taught us that <strong>systems engineering matters as much as ML innovation</strong>. The most sophisticated ML model is worthless if it takes 2 seconds to return results or costs $1 per query.</p><p><strong>Key Takeaways:</strong></p><ul><li>Hybrid search (0.7 semantic + 0.3 keyword) beat pure approaches</li><li>Latency requires obsession (75% reduction through systematic optimization)</li><li>Cost optimization enables scale (75% reduction made system viable)</li><li>Compliance is cheaper upfront than retrofit</li><li>MLOps accelerates iteration (2 weeks → 4 hours deployment)</li><li>Observability is not optional at scale</li></ul><p>The journey from 780ms latency and $0.12/query to 195ms and $0.03/query wasn’t smooth. We made mistakes, hit dead ends, rebuilt components multiple times. But each iteration taught us something valuable.</p><p><strong>Final Metrics:</strong></p><ul><li><strong>30–50M daily active users</strong> served</li><li><strong>195ms p95 latency</strong> (75% reduction)</li><li><strong>$0.03/query cost</strong> (75% reduction)</li><li><strong>$18.5M revenue impact</strong> (47% conversion improvement)</li><li><strong>99.94% uptime</strong> over 18 months</li><li><strong>47 model deployments</strong> in 12 months</li></ul><p>If you’re building similar systems: start with something that works, measure everything, and iterate relentlessly. Perfect is the enemy of shipped. The sophisticated architecture we have today started as a much simpler v1.</p><p><strong>Series Complete!</strong></p><p>Thank you for following this 5-part series on building production search at scale. I hope these detailed technical insights help you avoid our mistakes and accelerate your own systems.</p><p><strong>Read the full series:</strong><br>- <a href="https://medium.com/@SauravEvan/feae31b04e5c">Part 1: Architecture &amp; Design Decisions</a><br>- <a href="https://medium.com/@SauravEvan/elasticsearch-vector-search-a9083ba9c95a">Part 2: ElasticSearch &amp; Vector Search<br></a>- <a href="https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-e69b9342dc72">Part 3: RAG &amp; Multi-Modal Search</a><br>- <a href="https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-a12380ebdd90">Part 4: Latency &amp; Cost Optimization</a><br>- Part 5: Production Operations &amp; Lessons Learned</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8293c0c61370" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Production-Grade Multi-Modal Search at Scale]]></title>
            <link>https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-a12380ebdd90?source=rss-803008333c2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a12380ebdd90</guid>
            <dc:creator><![CDATA[Saurav Paul]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 01:12:33 GMT</pubDate>
            <atom:updated>2025-11-13T01:12:33.950Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 4: From 780ms to 195ms — The Latency &amp; Cost Optimization Journey</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*79QRdElmEWPpl9qy.png" /></figure><h3>Series Navigation</h3><p>- <a href="https://medium.com/@SauravEvan/feae31b04e5c">Part 1: Architecture &amp; Design Decisions</a><br>- <a href="https://medium.com/@SauravEvan/elasticsearch-vector-search-a9083ba9c95a">Part 2: ElasticSearch &amp; Vector Search</a><br>- <a href="https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-e69b9342dc72">Part 3: RAG &amp; Multi-Modal Search</a><br>- Part 4: Latency &amp; Cost Optimization<br>- Part 5: Production Operations &amp; Lessons Learned</p><h3>Quick Context</h3><p>In <a href="https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-feae31b04e5c">Part 1–3</a>, we built a sophisticated multi-modal search system with RAG, vector search, and visual understanding. But the initial implementation had serious problems: <strong>780ms p95 latency</strong> and <strong>$0.12/query</strong> cost. At 1.5 billion queries per month, this would cost $180M/year — completely unsustainable.</p><p>This post chronicles our optimization journey: how we systematically reduced latency by <strong>75%</strong> and cost by <strong>75%</strong> through relentless performance engineering.</p><h3>The Starting Point: Disaster Metrics</h3><p>Our v1 system had impressive features but terrible performance:</p><p><strong>Latency Breakdown (780ms p95):</strong></p><pre>Component              | Latency | % of Total<br>-----------------------|---------|------------<br>parse_query            | 8ms     | 1.0%<br>generate_embedding     | 285ms   | 36.5%  ← BOTTLENECK<br>feature_store         | 125ms   | 16.0%  ← BOTTLENECK<br>elasticsearch         | 240ms   | 30.8%  ← BOTTLENECK<br>format_results        | 12ms    | 1.5%<br>network_overhead      | 110ms   | 14.1%  ← BOTTLENECK<br>-----------------------|---------|------------<br>TOTAL                 | 780ms   | 100%</pre><p><strong>Cost Breakdown ($0.12/query):</strong></p><pre>Component                | Cost/Query| % of Total<br>-------------------------|-----------|------------<br>ML Model Inference       | $0.045    | 37.5%<br>Elasticsearch Compute    | $0.028    | 23.3%<br>Cloud Run Compute        | $0.024    | 20.0%<br>Network Egress           | $0.010    | 8.3%<br>Redis Cache              | $0.008    | 6.7%<br>BigQuery Analytics       | $0.005    | 4.2%<br>-------------------------|-----------|------------<br>TOTAL                    | $0.120    | 100%</pre><p>Amazon found that every 100ms of latency costs 1% in sales. At 780ms, we were leaving massive revenue on the table. And at $0.12/query, the system would cost $180M/year-impossible.</p><p>Let’s fix it.</p><h3>Latency Optimization: 780ms → 195ms</h3><h4>Bottleneck 1: Embedding Generation (285ms → 38ms)</h4><p><strong>Problem:</strong> Generating 768-dim embeddings for every query took 285ms — way too slow.</p><p><strong>Solution 1: Model Quantization (FP32 → FP16)</strong></p><pre>import torch<br><br># Convert model to FP16 precision<br>model = load_clip_model()<br>model = model.half()  # Convert to FP16<br>model = model.to(&quot;cuda&quot;)<br><br># Result: 285ms → 142ms (50% improvement)</pre><p><strong>Solution 2: TensorRT Optimization</strong></p><pre>import torch_tensorrt<br><br># Compile model with TensorRT<br>compiled_model = torch_tensorrt.compile(<br>    model,<br>    inputs=[torch_tensorrt.Input((1, 77), dtype=torch.int32)],<br>    enabled_precisions={torch.half},<br>    workspace_size=1 &lt;&lt; 30  # 1GB<br>)<br><br># Result: 142ms → 68ms (52% improvement)</pre><p><strong>Solution 3: Aggressive Caching</strong></p><pre>import redis<br>import hashlib<br><br>redis_client = redis.Redis(host=&#39;localhost&#39;, port=6379)<br><br>def cached_embedding(text, ttl=3600):<br>    &quot;&quot;&quot;Cache embeddings with 1-hour TTL.&quot;&quot;&quot;<br>    cache_key = f&quot;emb:{hashlib.md5(text.encode()).hexdigest()}&quot;<br>    <br>    # Check cache<br>    cached = redis_client.get(cache_key)<br>    if cached:<br>        return np.frombuffer(cached, dtype=np.float32)<br>    <br>    # Generate embedding<br>    embedding = generate_embedding_tensorrt(text)<br>    <br>    # Cache for 1 hour<br>    redis_client.setex(cache_key, ttl, embedding.tobytes())<br>    <br>    return embedding<br><br># Result: 24% cache hit rate → average 52ms<br># (24% hit 0ms, 76% hit 68ms)</pre><p><strong>Solution 4: Batch Processing</strong></p><pre>class BatchEmbeddingProcessor:<br>    def __init__(self, batch_size=8, max_wait_ms=50):<br>        self.batch_size = batch_size<br>        self.max_wait_ms = max_wait_ms<br>        self.pending_requests = []<br>        <br>    async def get_embedding(self, text):<br>        &quot;&quot;&quot;Add request to batch and wait for processing.&quot;&quot;&quot;<br>        future = asyncio.Future()<br>        self.pending_requests.append((text, future))<br>        <br>        # Trigger batch processing if full<br>        if len(self.pending_requests) &gt;= self.batch_size:<br>            await self._process_batch()<br>        <br>        return await future<br>    <br>    async def _process_batch(self):<br>        if not self.pending_requests:<br>            return<br>        <br>        batch = self.pending_requests[:self.batch_size]<br>        self.pending_requests = self.pending_requests[self.batch_size:]<br>        <br>        # Batch inference<br>        texts = [req[0] for req in batch]<br>        embeddings = generate_embeddings_batch(texts)<br>        <br>        # Resolve futures<br>        for (text, future), embedding in zip(batch, embeddings):<br>            future.set_result(embedding)<br><br># Result: 52ms → 38ms (27% improvement with batching)</pre><h3><strong>Final Embedding Generation: 285ms → 38ms (87% reduction)</strong></h3><h4>Bottleneck 2: Feature Store Lookups (125ms → 9ms)</h4><p><strong>Problem:</strong> Fetching user features from Vertex AI Feature Store took 125ms-too slow for real-time serving.</p><p><strong>Solution 1: Pre-computed User Embeddings</strong></p><pre>def precompute_user_embeddings():<br>    &quot;&quot;&quot;<br>    Background job: compute and cache user embeddings.<br>    Runs every 6 hours.<br>    &quot;&quot;&quot;<br>    for user_id in active_users:<br>        # Fetch user interaction history<br>        history = get_user_interactions(user_id, days=30)<br>        <br>        # Compute user embedding (weighted average of interacted products)<br>        product_embeddings = [get_product_embedding(item) for item in history]<br>        weights = [item[&quot;weight&quot;] for item in history]  # Click: 1, purchase: 5<br>        <br>        user_embedding = np.average(product_embeddings, weights=weights, axis=0)<br>        <br>        # Cache in Redis with 24-hour TTL<br>        redis_client.setex(<br>            f&quot;user_emb:{user_id}&quot;,<br>            86400,<br>            user_embedding.tobytes()<br>        )<br><br># Result: 125ms (live lookup) → 0.8ms (Redis cache)</pre><p><strong>Solution 2: Hierarchical Feature Fallback</strong></p><pre>def get_features_fast(user_id):<br>    &quot;&quot;&quot;Fast feature lookup with fallbacks.&quot;&quot;&quot;<br>    # Try 1: User-specific features (cached in Redis)<br>    user_features = redis_client.get(f&quot;user_emb:{user_id}&quot;)<br>    if user_features:<br>        return np.frombuffer(user_features, dtype=np.float32)<br>    <br>    # Try 2: User segment features (higher cache hit rate)<br>    segment = get_user_segment(user_id)  # e.g., &quot;frequent_shopper&quot;<br>    segment_features = redis_client.get(f&quot;segment_emb:{segment}&quot;)<br>    if segment_features:<br>        return np.frombuffer(segment_features, dtype=np.float32)<br>    <br>    # Try 3: Global default features<br>    return get_default_features()<br><br># Result: 0.8ms avg (92% Redis hit rate)</pre><p><strong>Final Feature Store Lookups: 125ms → 9ms (93% reduction)</strong></p><h4>Bottleneck 3: ElasticSearch Queries (240ms → 42ms)</h4><p><strong>Problem:</strong> ElasticSearch queries taking 240ms-too slow despite being on SSD.</p><p><strong>Solution 1: Query Optimization</strong></p><pre># BEFORE (slow): Complex script_score<br>&quot;script&quot;: {<br>    &quot;source&quot;: &quot;&quot;&quot;<br>        double base_score = _score;<br>        double personalization = 1.0;<br>        <br>        // Complex loops and conditionals<br>        for (int i = 0; i &lt; params.user_preferred_brands.size(); i++) {<br>            if (params.user_preferred_brands.get(i) == doc[&#39;brand&#39;].value) {<br>                personalization *= 1.3;<br>                break;<br>            }<br>        }<br>        return base_score * personalization;<br>    &quot;&quot;&quot;<br>}<br><br># AFTER (fast): Pre-computed personalization score<br>&quot;script&quot;: {<br>    &quot;source&quot;: &quot;&quot;&quot;<br>        double base = _score;<br>        double person = doc[&#39;personalization_score&#39;].value;<br>        return base * person;<br>    &quot;&quot;&quot;<br>}<br><br># Result: 240ms → 165ms (31% improvement)</pre><p><strong>Solution 2: Index-Level Request Cache</strong></p><pre>{<br>  &quot;settings&quot;: {<br>    &quot;index.requests.cache.enable&quot;: true,<br>    &quot;index.requests.cache.size&quot;: &quot;20%&quot;<br>  }<br>}</pre><p>Cache identical queries for 1 hour.<br><strong>Result:</strong> 18% cache hit rate → 165ms → 135ms avg</p><p><strong>Solution 3: Reduce Result Set</strong></p><pre># Changed from retrieving top-100 to top-20 directly<br>es_query = {<br>    &quot;size&quot;: 20,  # Was 100<br>    # ...<br>}<br><br># Result: 135ms → 98ms (27% improvement)</pre><p><strong>Solution 4: Parallel Processing</strong></p><pre>async def parallel_search(query):<br>    &quot;&quot;&quot;Parallelize independent operations.&quot;&quot;&quot;<br>    # Start both operations simultaneously<br>    embedding_task = asyncio.create_task(generate_embedding(query))<br>    features_task = asyncio.create_task(get_features_fast(user_id))<br>    <br>    # Wait for both<br>    embedding, features = await asyncio.gather(embedding_task, features_task)<br>    <br>    # Now execute ES query<br>    results = await es_search(embedding, features)<br>    <br>    return results<br><br># Result: Sequential 98ms → Parallel 42ms (parallelization saves time)</pre><p><strong>Final ElasticSearch Queries: 240ms → 42ms (82% reduction)</strong></p><h4>Bottleneck 4: Network Overhead (110ms → 15ms)</h4><p><strong>Problem:</strong> Network latency between services added up.</p><p><strong>Solution 1: Colocation in Single Region</strong></p><pre>BEFORE:<br>- Cloud Run: us-east1<br>- Redis: us-central1  <br>- Elasticsearch: us-west1<br>→ Cross-region latency: 40-80ms per hop<br><br>AFTER:<br>- All services: us-central1, same VPC<br>→ Intra-region latency: 1-3ms per hop<br><br># Result: 110ms → 42ms (62% improvement)</pre><p><strong>Solution 2: HTTP/2 Keepalive</strong></p><pre>import httpx<br><br># Use HTTP/2 with connection pooling<br>client = httpx.AsyncClient(<br>    http2=True,<br>    limits=httpx.Limits(<br>        max_keepalive_connections=20,<br>        max_connections=100,<br>        keepalive_expiry=30.0<br>    )<br>)<br><br># Result: Eliminates TCP handshake overhead<br># 42ms → 28ms (33% improvement)</pre><p><strong>Solution 3: Redis Pipelining</strong></p><pre># BEFORE: Multiple round trips<br>for key in keys:<br>    value = redis_client.get(key)  # N round trips<br><br># AFTER: Single round trip<br>pipeline = redis_client.pipeline()<br>for key in keys:<br>    pipeline.get(key)<br>values = pipeline.execute()  # 1 round trip<br><br># Result: 28ms → 15ms (46% improvement)</pre><p><strong>Final Network Overhead: 110ms → 15ms (86% reduction)</strong></p><h4>Multi-Layer Caching Strategy</h4><p>Our caching is three-tiered:</p><p><strong>Tier 1: CDN Edge Cache</strong> (10% hit rate, 0ms latency)</p><p><strong>Tier 2: Redis Cache</strong> (63% hit rate, 1–2ms latency)</p><p><strong>Tier 3: ElasticSearch Query Cache</strong> (18% hit rate for misses, 15ms latency)</p><p><strong>Combined Cache Hit Rate: 73%</strong></p><p><strong>Cache ROI Analysis:</strong></p><pre># Without cache:<br># 1.5B queries/month × $0.045/query = $67.5M/year compute cost<br><br># With 73% cache hit rate:<br># Cache hits: 1.5B × 0.73 = 1.095B queries at $0.0001/query<br># Cache misses: 1.5B × 0.27 = 0.405B queries at $0.045/query<br><br># New cost:<br># (1.095B × $0.0001) + (0.405B × $0.045) = $18.3M/year<br><br># Redis infrastructure: $84K/year<br># Net savings: $49.1M/year</pre><p><strong>Latency Breakdown (195ms p95):</strong></p><pre>Component              | Before  | After  | Improvement<br>-----------------------|---------|--------|------------<br>parse_query            | 8ms     | 8ms    | 0%<br>generate_embedding     | 285ms   | 38ms   | 87% ↓<br>feature_store         | 125ms   | 9ms    | 93% ↓<br>elasticsearch         | 240ms   | 42ms   | 82% ↓<br>format_results        | 12ms    | 12ms   | 0%<br>network_overhead      | 110ms   | 15ms   | 86% ↓<br>parallelization       | -       | -71ms  | optimization<br>-----------------------|---------|--------|------------<br>TOTAL                 | 780ms   | 195ms  | 75% ↓</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYkn2IgK3Ryy-8siMhbyNg.png" /></figure><h4>Cost Optimization: $0.12 → $0.03 per Query</h4><h4>Optimization 1: Model Quantization (60% ML Cost Reduction)</h4><p><strong>Problem:</strong> Running FP32 CLIP models on GPUs: $0.045/query</p><p><strong>Solution: INT8 Quantization</strong></p><pre>import torch<br>from torch.quantization import quantize_dynamic<br><br># Load FP32 model<br>model_fp32 = load_clip_model()<br><br># Quantize to INT8<br>model_int8 = quantize_dynamic(<br>    model_fp32,<br>    {torch.nn.Linear},<br>    dtype=torch.qint8<br>)<br><br># Results:<br># Model size: 340MB → 87MB (74% reduction)<br># Inference time: 62ms → 38ms (39% faster)<br># Accuracy: 95.2% → 94.8% (0.4% degradation - acceptable)<br># GPU memory: 4GB → 1.2GB (70% reduction)</pre><p><strong>Cost Impact:</strong></p><ul><li>Concurrent models per GPU: 4 → 13</li><li>Cost per inference: $0.045 → $0.018 (60% reduction)</li></ul><h4>Optimization 2: Intelligent Caching (73% Hit Rate)</h4><p>We already covered the latency benefits. Here are the cost savings:</p><p><strong>Annual Savings from Caching:</strong></p><ul><li>Before: 1.5B queries × $0.045 = $67.5M/year compute cost</li><li>After: $18.3M/year (73% cached)</li><li>Redis infrastructure: $84K/year</li><li>Net savings: $49.1M/year</li></ul><h4>Optimization 3: Spot Instances for Batch Jobs (70% Savings)</h4><p><strong>Problem:</strong> ML training and embedding generation ran on expensive on-demand instances.</p><p><strong>Solution: Preemptible/Spot VMs</strong></p><pre># Terraform configuration<br>resource &quot;google_compute_instance&quot; &quot;batch_ml&quot; {<br>  name         = &quot;batch-ml-worker&quot;<br>  machine_type = &quot;n1-standard-8&quot;<br>  <br>  scheduling {<br>    preemptible       = true<br>    automatic_restart = false<br>  }<br>  <br>  # $0.096/hour vs $0.32/hour (70% savings)<br>}</pre><p><strong>Handling Preemption:</strong></p><pre>import signal<br><br>def handle_preemption(signum, frame):<br>    &quot;&quot;&quot;Handle preemption gracefully by checkpointing.&quot;&quot;&quot;<br>    checkpoint = {<br>        &quot;processed_items&quot;: processed_items,<br>        &quot;current_batch&quot;: current_batch<br>    }<br>    save_checkpoint(checkpoint)<br>    sys.exit(0)<br><br>signal.signal(signal.SIGTERM, handle_preemption)</pre><p><strong>Cost Impact:</strong></p><ul><li>Batch ML training: $12K/month → $3.6K/month</li><li>Embedding generation: $8K/month → $2.4K/month</li><li>Total batch savings: $13.6K/month</li></ul><h4>Optimization 4: GPU Sharing Across Models</h4><p><strong>Problem:</strong> Each model (text encoder, image encoder, RAG) on separate GPU instances.</p><p><strong>Solution: Multi-Model Serving</strong></p><pre>class MultiModelServer:<br>    &quot;&quot;&quot;Serve multiple models on single GPU with dynamic batching.&quot;&quot;&quot;<br>    def __init__(self):<br>        self.text_model = load_text_encoder().to(&quot;cuda:0&quot;)<br>        self.image_model = load_image_encoder().to(&quot;cuda:0&quot;)<br>        self.rag_model = load_rag_model().to(&quot;cuda:0&quot;)<br>    <br>    async def process_batch(self, requests):<br>        &quot;&quot;&quot;Dynamic batching across model types.&quot;&quot;&quot;<br>        text_requests = [r for r in requests if r.type == &quot;text&quot;]<br>        image_requests = [r for r in requests if r.type == &quot;image&quot;]<br>        <br>        results = {}<br>        <br>        if text_requests:<br>            texts = [r.data for r in text_requests]<br>            embeddings = self.text_model(texts)<br>            for req, emb in zip(text_requests, embeddings):<br>                results[req.id] = emb<br>        <br>        # Similar for image and RAG<br>        return results</pre><p><strong>Cost Impact:</strong></p><ul><li>Before: 3 GPUs × $0.35/hour = $766/month</li><li>After: 1 GPU × $0.35/hour = $255/month</li><li>Savings: $511/month (67% reduction)</li></ul><h4>Optimization 5: Dynamic Resource Allocation</h4><p><strong>Problem:</strong> Cloud Run instances scaled to peak capacity 24/7.</p><p><strong>Solution: Aggressive Auto-Scaling</strong></p><pre>autoscaling.knative.dev/minScale: 5      # Was 50<br>autoscaling.knative.dev/maxScale: 1000<br>autoscaling.knative.dev/target: 80       # CPU target, was 50</pre><pre># Before: Always-on 50 instances minimum<br># 50 × 2 vCPU × $0.024/hour × 730 hours = $1,752/month<br><br># After: 5 instances off-peak, 50 peak<br># Peak (6h): 50 × 2 × $0.024 × 180h = $432/month<br># Off-peak (18h): 5 × 2 × $0.024 × 550h = $132/month<br># Total: $564/month<br><br># Savings: $1,188/month (68% reduction)</pre><h4>Final Cost Results</h4><p><strong>Cost Breakdown:</strong></p><pre>Component                | Before    | After     | Reduction<br>-------------------------|-----------|-----------|----------<br>ML Model Inference       | $0.045    | $0.011    | 76%<br>Elasticsearch Compute    | $0.028    | $0.009    | 68%<br>Cloud Run Compute        | $0.024    | $0.005    | 79%<br>Redis Cache              | $0.008    | $0.003    | 63%<br>Network Egress           | $0.010    | $0.001    | 90%<br>BigQuery Analytics       | $0.005    | $0.001    | 80%<br>-------------------------|-----------|-----------|----------<br>TOTAL                    | $0.120    | $0.030    | 75%</pre><p><strong>Annual Impact:</strong></p><ul><li>Before: 1.5B queries × $0.120 = <strong>$180M/year</strong></li><li>After: 1.5B queries × $0.030 = <strong>$45M/year</strong></li><li><strong>Total Savings: $135M/year</strong></li></ul><p>These savings funded the entire engineering team (20 people) with significant budget to spare.</p><ol><li><strong>Measure First, Optimize Second</strong><br> We instrumented every component with detailed tracing before optimizing. Found that 40% of time was in script_score we could pre-compute.</li></ol><p><strong>2. Cache Aggressively</strong><br> 73% cache hit rate saved $49M/year and reduced latency by 75%. But needed intelligent invalidation to keep results fresh.</p><p><strong>3. Quantize Without Fear</strong><br> INT8 quantization lost &lt;1% accuracy while saving 60% on ML costs. Test it-you’ll probably adopt it.</p><p><strong>4. Colocation Matters</strong><br> Moving services to same region saved 86% on network overhead. Physical distance creates latency you can’t optimize away.</p><p><strong>5. Parallelization is Free Performance</strong><br> Running independent operations in parallel (embedding + features) saved 22ms with zero infrastructure cost.</p><p><strong>6. Spot Instances for Batch Jobs</strong><br> 70% cost savings on ML training with simple checkpointing for preemption handling. No-brainer for non-latency-critical workloads.</p><p>This post covered performance optimization-making the system fast and cost-effective. But production systems need more than performance: they need operational excellence, compliance, monitoring, and the ability to iterate rapidly.</p><p>In Part 5 (final post), we’ll cover:</p><ul><li>MLOps pipeline (2 weeks → 4 hours deployment)</li><li>A/B testing framework (50+ concurrent experiments)</li><li>Automated rollback and incident response</li><li>GDPR/CCPA compliance at scale</li><li>Real-world results and lessons learned</li></ul><p><strong>Continue the series:</strong><br>Part 5: Production Operations, MLOps &amp; Lessons Learned</p><p><strong>Previous posts:</strong><br><a href="https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-feae31b04e5c">Part 1: Architecture &amp; Design Decisions</a><br><a href="https://medium.com/@SauravEvan/elasticsearch-vector-search-a9083ba9c95a">Part 2: ElasticSearch &amp; Vector Search</a><br><a href="https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-e69b9342dc72">Part 3: RAG &amp; Multi-Modal Search</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a12380ebdd90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Production-Grade Multi-Modal Search at Scale]]></title>
            <link>https://blog.gopenai.com/building-production-grade-multi-modal-search-at-scale-e69b9342dc72?source=rss-803008333c2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e69b9342dc72</guid>
            <dc:creator><![CDATA[Saurav Paul]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 01:54:14 GMT</pubDate>
            <atom:updated>2025-11-26T07:49:08.513Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 3: RAG &amp; Multi-Modal Search — From Instagram Photos to Product Recommendations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*g1_ZxrdX8wzQNW7u.png" /></figure><h4>Series Navigation</h4><p>- <a href="https://medium.com/@SauravEvan/feae31b04e5c">Part 1: Architecture &amp; Design Decisions</a><br>- <a href="https://medium.com/@SauravEvan/elasticsearch-vector-search-a9083ba9c95a">Part 2: ElasticSearch &amp; Vector Search</a><br>- Part 3: RAG &amp; Multi-Modal Search<br>- Part 4: Latency &amp; Cost Optimization<br>- Part 5: Production Operations &amp; Lessons Learned</p><h4>Quick Context</h4><p>In <a href="https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-feae31b04e5c">Part 1</a>, we covered the overall architecture, and in <a href="https://medium.com/@SauravEvan/elasticsearch-vector-search-a9083ba9c95a">Part 2</a>, we dove deep into ElasticSearch and vector search. Now we’ll explore how we added intelligence on top: fine-tuned embeddings for fashion understanding, RAG for conversational recommendations, and multi-modal processing that handles text, images, and voice.</p><p>This is where traditional search becomes genuinely intelligent-understanding what users mean, not just what they say.</p><h4>The Intelligence Layer Challenge</h4><p>A keyword search for “confident interview outfit” returns products containing those words. A semantic search understands the intent but can’t explain why recommendations match. A multi-modal system needs to handle Instagram screenshots, voice queries, and text-all while providing grounded, accurate recommendations.</p><p>Our goals:</p><ul><li><strong>95%+ accuracy</strong> on fashion item detection from images</li><li><strong>Sub-100ms</strong> embedding generation for real-time queries</li><li><strong>&lt;2% hallucination rate</strong> for RAG-powered recommendations</li><li><strong>Seamless multi-modal</strong> experience (text, image, voice)</li><li><strong>90%+ user satisfaction</strong> with AI-generated recommendations</li></ul><h4>CLIP-Based Embeddings for Fashion</h4><p>We use a modified CLIP (Contrastive Language-Image Pre-training) architecture fine-tuned specifically for fashion. CLIP learns a joint embedding space where semantically similar images and text are close together in vector space.</p><p><strong>Base Architecture:</strong></p><pre>Text Encoder: Transformer (12 layers, 768 hidden dim) <br>Image Encoder: Vision Transformer (ViT-B/16) <br>Embedding Dimension: 768 <br>Training Objective: Contrastive loss (InfoNCE</pre><p><strong>Why CLIP Over Alternatives?</strong></p><ul><li><strong>vs BERT</strong>: CLIP handles multi-modal inputs; BERT is text-only</li><li><strong>vs ResNet + BERT separately</strong>: CLIP learns joint embedding space; separate models require complex fusion logic</li><li><strong>vs OpenAI CLIP directly</strong>: Base CLIP understands general concepts but struggles with fashion-specific nuances (e.g., confuses “midi dress” with “maxi dress”)</li></ul><h4>Fine-Tuning on 2.5M Fashion Images</h4><p>Our training dataset:</p><ul><li>2.5M fashion product images from our catalog</li><li>8.2M text descriptions (multiple per product)</li><li>500M user interaction events (clicks, purchases, returns)</li><li>1.2M Instagram/TikTok scraped fashion images (with proper licensing)</li></ul><p><strong>Training Pipeline:</strong></p><pre>import torch<br>from transformers import CLIPModel, CLIPProcessor, AdamW<br><br># Load pre-trained CLIP<br>model = CLIPModel.from_pretrained(&quot;openai/clip-vit-base-patch16&quot;)<br>processor = CLIPProcessor.from_pretrained(&quot;openai/clip-vit-base-patch16&quot;)<br><br># Freeze early layers, fine-tune last 4 layers<br>for param in model.text_model.encoder.layers[:-4].parameters():<br>    param.requires_grad = False<br>for param in model.vision_model.encoder.layers[:-4].parameters():<br>    param.requires_grad = False<br><br># Training loop<br>optimizer = AdamW(model.parameters(), lr=1e-5)<br>criterion = nn.CrossEntropyLoss()<br><br>for epoch in range(10):<br>    for batch in dataloader:<br>        images, texts = batch[&quot;images&quot;], batch[&quot;texts&quot;]<br>        <br>        # Forward pass<br>        outputs = model(<br>            input_ids=texts[&quot;input_ids&quot;],<br>            attention_mask=texts[&quot;attention_mask&quot;],<br>            pixel_values=images<br>        )<br>        <br>        # Contrastive loss<br>        logits_per_image = outputs.logits_per_image<br>        logits_per_text = outputs.logits_per_text<br>        <br>        # Symmetric loss<br>        labels = torch.arange(len(images))<br>        loss_i = criterion(logits_per_image, labels)<br>        loss_t = criterion(logits_per_text, labels)<br>        loss = (loss_i + loss_t) / 2<br>        <br>        # Backward pass<br>        optimizer.zero_grad()<br>        loss.backward()<br>        optimizer.step()</pre><p><strong>Training Results:</strong></p><ul><li>Base CLIP (zero-shot): 76.3% accuracy on fashion test set</li><li>After fine-tuning: <strong>95.2% accuracy</strong> (+18.9 points)</li><li>Training time: 72 hours on 4×A100 GPUs</li><li>Model size: 340MB (weights only)</li></ul><p>The improvement came from learning fashion-specific patterns: “midi” vs “maxi,” “bodycon” vs “A-line,” “moto jacket” vs “bomber jacket” — distinctions base CLIP missed.</p><h3>Real-Time Embedding Generation</h3><p>For user queries, we generate embeddings in real-time with target latency &lt;50ms:</p><pre>import torch<br>from transformers import CLIPModel, CLIPProcessor<br><br># Load model (done once at startup)<br>model = CLIPModel.from_pretrained(&quot;our-finetuned-clip-model&quot;)<br>model = model.half()  # FP16 quantization<br>model = model.to(&quot;cuda&quot;)<br>model.eval()<br><br>@torch.no_grad()<br>def generate_text_embedding(query_text):<br>    &quot;&quot;&quot;<br>    Generate 768-dim embedding for text query.<br>    Target: &lt;50ms p95 latency.<br>    &quot;&quot;&quot;<br>    inputs = processor(<br>        text=[query_text],<br>        return_tensors=&quot;pt&quot;,<br>        padding=True,<br>        truncation=True,<br>        max_length=77<br>    ).to(&quot;cuda&quot;)<br>    <br>    # Forward pass<br>    text_features = model.get_text_features(**inputs)<br>    <br>    # Normalize to unit vector<br>    embedding = text_features / text_features.norm(dim=-1, keepdim=True)<br>    <br>    return embedding.cpu().numpy()[0]</pre><p><strong>Optimization Techniques:</strong></p><ol><li><strong>Model Quantization (FP32 → FP16)</strong></li></ol><ul><li>Reduces model size: 340MB → 170MB</li><li>Speeds up inference: 62ms → 38ms</li><li>Minimal accuracy loss: &lt;0.2% drop</li></ul><p><strong>2. Caching Popular Embeddings</strong></p><ul><li>Cache product embeddings in Redis (24-hour TTL)</li><li>Cache hit rate: 91% for products, 24% for queries</li><li>Avoids 91% of model inference for products</li></ul><p><strong>Production Metrics:</strong></p><ul><li>Text embedding: <strong>38ms p95</strong> (target &lt;50ms)</li><li>Image embedding: <strong>87ms p95</strong> (target &lt;100ms)</li><li>GPU utilization: 65% average</li><li>Throughput: 800 embeddings/second batched</li></ul><h3>RAG Implementation with Vertex AI Search</h3><p>Retrieval-Augmented Generation transforms search from returning product lists to providing intelligent, conversational recommendations.</p><p><strong>Example:</strong></p><ul><li><strong>Traditional search</strong>: User searches “summer wedding guest” → Shows list of dresses</li><li><strong>RAG-powered</strong>: “For a summer wedding guest, I recommend the Floral Midi Dress ($89.99) in breathable cotton-perfect for outdoor ceremonies. Pair it with the Strappy Block Heel Sandals ($64.99) for an elegant look.”</li></ul><h3>Vertex AI Search Setup</h3><p><strong>Infrastructure Configuration:</strong></p><p>Hallucinations are the biggest risk in production RAG. LLMs confidently generate plausible-sounding but completely false information.</p><pre>from google.cloud import discoveryengine_v1alpha as discoveryengine<br><br># Configure data store<br>data_store_config = {<br>    &quot;display_name&quot;: &quot;fashion_products&quot;,<br>    &quot;industry_vertical&quot;: &quot;GENERIC&quot;,<br>    &quot;solution_types&quot;: [&quot;SOLUTION_TYPE_SEARCH&quot;],<br>    &quot;content_config&quot;: &quot;CONTENT_REQUIRED&quot;,<br>}<br><br># Serving config with LLM grounding<br>serving_config = {<br>    &quot;display_name&quot;: &quot;fashion_search_with_rag&quot;,<br>    &quot;model_id&quot;: &quot;stable&quot;,  # PaLM 2 stable model<br>    &quot;grounding_config&quot;: {<br>        &quot;grounding_threshold&quot;: 0.7,<br>        &quot;max_grounding_results&quot;: 10,<br>        &quot;filter_by_relevance&quot;: True<br>    },<br>    &quot;summary_config&quot;: {<br>        &quot;model_prompt_template&quot;: FASHION_STYLIST_PROMPT,<br>        &quot;include_citations&quot;: True,<br>        &quot;language_code&quot;: &quot;en&quot;<br>    }<br>}</pre><p><strong>Our Grounding Configuration:Grounding Threshold Tuning:</strong></p><p>Hallucinations are the biggest risk in production RAG. LLMs confidently generate plausible-sounding but completely false information.</p><p>Our Grounding Configuration:</p><pre>grounding_config = {<br>    &quot;grounding_threshold&quot;: 0.7,  # Minimum confidence for using a document<br>    &quot;max_grounding_results&quot;: 10,  # Top-10 search results for context<br>    &quot;filter_by_relevance&quot;: True,  # Only use relevant documents<br>    &quot;enable_citation_links&quot;: True  # Add source citations<br>}</pre><p>Grounding Threshold Tuning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q1GiEnHNw6JBkkq4fnr_aA.png" /></figure><p>At <strong>0.7</strong>, we get near-zero hallucinations (1.1%) with acceptable fallback rate (9%). Above 0.8, too many queries fall back to basic search.</p><h4>Prompt Engineering for Fashion Expertise</h4><p>The system prompt is crucial for response quality:</p><pre>FASHION_STYLIST_PROMPT = &quot;&quot;&quot;<br>You are an expert personal stylist with 15 years of experience in fashion retail. <br>Your goal is to help customers find products that match their style, occasion, <br>and budget while providing genuine fashion advice.<br><br>CRITICAL RULES:<br>1. ONLY recommend products from the search results provided below<br>2. ALWAYS cite the exact product name and price<br>3. NEVER make up product details, prices, or availability<br>4. If a product is out of stock, suggest similar in-stock alternatives<br>5. Be specific: mention colors, materials, sizes, and styling details<br>6. If search results don&#39;t match the query well, ask clarifying questions<br><br>RESPONSE FORMAT:<br>- Start with brief understanding of customer&#39;s needs<br>- Recommend 2-4 specific products with details<br>- Provide styling tips for each recommendation<br>- Mention price range and value assessment<br>- End with follow-up question if needed<br><br>Search Results: {context}<br>Customer Query: {query}<br>&quot;&quot;&quot;</pre><p><strong>Prompt Optimization Results:</strong></p><ul><li>Initial generic prompt: 72% user satisfaction</li><li>Fashion-specific prompt v1: 81% user satisfaction</li><li>Current prompt (v5): <strong>90% user satisfaction</strong></li></ul><p>Key improvements came from adding the “CRITICAL RULES” section (reduced hallucinations by 67%) and the structured “RESPONSE FORMAT” (consistent, scannable responses).</p><h3>Validation Pipeline</h3><p>Even with grounding, post-generation validation is essential:</p><pre>def validate_rag_response(generated_text, source_products):<br>    &quot;&quot;&quot;<br>    Validate that RAG response doesn&#39;t hallucinate critical details.<br>    &quot;&quot;&quot;<br>    issues = []<br>    <br>    # Extract price mentions from generated text<br>    price_mentions = extract_prices(generated_text)<br>    <br>    for mentioned_price in price_mentions:<br>        # Check if price matches any source product<br>        matching_product = None<br>        for product in source_products:<br>            if abs(product[&quot;price&quot;] - mentioned_price) &lt; 0.01:<br>                matching_product = product<br>                break<br>        <br>        if not matching_product:<br>            issues.append({<br>                &quot;type&quot;: &quot;price_hallucination&quot;,<br>                &quot;mentioned_price&quot;: mentioned_price<br>            })<br>    <br>    # Extract product names<br>    product_mentions = extract_product_names(generated_text)<br>    source_names = [p[&quot;title&quot;] for p in source_products]<br>    <br>    for mentioned_name in product_mentions:<br>        if not any(fuzzy_match(mentioned_name, source_name) <br>                  for source_name in source_names):<br>            issues.append({<br>                &quot;type&quot;: &quot;product_hallucination&quot;,<br>                &quot;mentioned_product&quot;: mentioned_name<br>            })<br>    <br>    return issues</pre><p>If validation detects hallucinations, we either regenerate with stricter prompt or fall back to search results only.</p><h3>Multi-Modal Input Processing</h3><h4>Vision AI Pipeline for Social Media Photos</h4><p><strong>Use Case:</strong> User uploads Instagram screenshot of an influencer’s outfit, wants to find similar products.</p><p><strong>Detection Pipeline:</strong></p><pre>from google.cloud import aiplatform<br><br>def detect_fashion_items(image_bytes):<br>    &quot;&quot;&quot;<br>    Detect fashion items using Vertex AI AutoML Vision.<br>    Returns bounding boxes and labels.<br>    &quot;&quot;&quot;<br>    client = aiplatform.gapic.PredictionServiceClient()<br>    endpoint = f&quot;projects/{PROJECT_ID}/locations/us-central1/endpoints/{ENDPOINT_ID}&quot;<br>    <br>    # Prepare image<br>    encoded_image = base64.b64encode(image_bytes).decode(&quot;utf-8&quot;)<br>    instance = predict.instance.ImageObjectDetectionPredictionInstance(<br>        content=encoded_image<br>    ).to_value()<br>    <br>    # Predict<br>    response = client.predict(endpoint=endpoint, instances=[instance])<br>    <br>    # Parse detections (confidence &gt; 75%)<br>    detections = []<br>    for prediction in response.predictions:<br>        if prediction[&quot;confidence&quot;] &gt; 0.75:<br>            detections.append({<br>                &quot;label&quot;: prediction[&quot;displayName&quot;],<br>                &quot;confidence&quot;: prediction[&quot;confidence&quot;],<br>                &quot;bounding_box&quot;: prediction[&quot;boundingBox&quot;]<br>            })<br>    <br>    return detections</pre><p><strong>Model Performance:</strong></p><ul><li>Training data: 2.5M fashion images, 47 object classes</li><li>Training time: 36 hours on Vertex AI AutoML</li><li><strong>Detection accuracy: 95.2%</strong> on test set</li><li>Inference latency: 210ms per image</li></ul><p><strong>Attribute Extraction:</strong></p><p>For each detected item, extract detailed attributes:</p><pre>def extract_fashion_attributes(image_crop, item_label):<br>    &quot;&quot;&quot;<br>    Extract color, pattern, style attributes from image crop.<br>    &quot;&quot;&quot;<br>    # Color detection using K-means clustering<br>    colors = extract_dominant_colors(image_crop, k=3)<br>    <br>    # Pattern classification (solid, stripes, floral, etc.)<br>    pattern = classify_pattern(image_crop)<br>    <br>    # Style classification (casual, formal, athletic, etc.)<br>    style = classify_style(image_crop, item_label)<br>    <br>    # Material classification if visible<br>    material = classify_material(image_crop)<br>    <br>    return {<br>        &quot;colors&quot;: colors,<br>        &quot;pattern&quot;: pattern,<br>        &quot;style&quot;: style,<br>        &quot;material&quot;: material,<br>        &quot;category&quot;: item_label<br>    }</pre><p><strong>Attribute Extraction Accuracy:</strong></p><ul><li>Color detection: 94%</li><li>Pattern recognition: 89%</li><li>Style classification: 87%</li><li>Material classification: 79% (hardest due to image quality)</li></ul><p>When combining text and image inputs (“find me a dress like this but in blue”), we need to fuse multi-modal signals intelligently.</p><p><strong>Our Approach: Cross-Attention Fusion</strong></p><pre>def cross_modal_fusion(text_emb, image_emb):<br>    &quot;&quot;&quot;<br>    Fuse text and image embeddings using learned cross-attention.<br>    &quot;&quot;&quot;<br>    # Attention scores: how much to weight each modality<br>    attention_scores = compute_attention(text_emb, image_emb)<br>    <br>    # Weighted combination<br>    fused_emb = (attention_scores[0] * text_emb + <br>                attention_scores[1] * image_emb)<br>    <br>    # Normalize<br>    fused_emb = fused_emb / np.linalg.norm(fused_emb)<br>    <br>    return fused_emb</pre><p>This learned fusion adapts to query type:</p><ul><li>Pure text query: 95% text, 5% image</li><li>Pure image query: 5% text, 95% image</li><li>Multi-modal query (“like this but blue”): 40% text, 60% image</li></ul><p><strong>Fusion Strategy Comparison:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmwrU6vm4C9s0vJz3gAc0Q.png" /></figure><h4>Voice Search Integration</h4><p>Voice queries processed through Google Speech-to-Text:</p><pre>from google.cloud import speech_v1p1beta1 as speech<br><br>async def process_voice_query(audio_bytes):<br>    &quot;&quot;&quot;<br>    Convert voice to text, then process as text query.<br>    &quot;&quot;&quot;<br>    client = speech.SpeechClient()<br>    <br>    # Configure with fashion-specific phrase hints<br>    config = speech.RecognitionConfig(<br>        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,<br>        sample_rate_hertz=16000,<br>        language_code=&quot;en-US&quot;,<br>        enable_automatic_punctuation=True,<br>        speech_contexts=[<br>            speech.SpeechContext(<br>                phrases=[<br>                    &quot;midi dress&quot;, &quot;maxi dress&quot;, &quot;bodycon&quot;, &quot;A-line&quot;,<br>                    &quot;athleisure&quot;, &quot;streetwear&quot;, &quot;formal wear&quot;<br>                ],<br>                boost=15.0<br>            )<br>        ]<br>    )<br>    <br>    audio = speech.RecognitionAudio(content=audio_bytes)<br>    response = client.recognize(config=config, audio=audio)<br>    <br>    if not response.results:<br>        return {&quot;error&quot;: &quot;Could not understand audio&quot;}<br>    <br>    transcript = response.results[0].alternatives[0].transcript<br>    confidence = response.results[0].alternatives[0].confidence<br>    <br>    if confidence &gt; 0.85:<br>        return await search_by_text(transcript)<br>    else:<br>        return {<br>            &quot;transcript&quot;: transcript,<br>            &quot;confidence&quot;: confidence,<br>            &quot;message&quot;: f&quot;Did you say: {transcript}?&quot;<br>        }</pre><p><strong>Voice Search Metrics:</strong></p><ul><li>Transcription accuracy: 94%</li><li>Latency p95: 380ms (speech-to-text) + 180ms (search) = 560ms</li><li>Monthly volume: 2.3M voice queries</li></ul><p><strong>RAG Performance:</strong></p><ul><li>Invocation rate: 15% of queries (rest use pure search)</li><li>Latency p50: 520ms (PaLM 2) / 680ms (Gemini Pro)</li><li>Cache hit rate: 31% (cached RAG responses)</li><li>User satisfaction: <strong>90%</strong> (vs 76% for pure search)</li><li>Conversion lift: <strong>31%</strong> when RAG used</li><li>Average order value: <strong>+$23</strong> with RAG recommendations</li></ul><p><strong>Quality Metrics:</strong></p><ul><li>Hallucination rate: <strong>1.1%</strong> (down from 23% initial)</li><li>Citation accuracy: 99.2%</li><li>Response relevance: 94%</li></ul><p><strong>Visual Search:</strong></p><ul><li>Detection accuracy: <strong>95.2%</strong></li><li>End-to-end latency p95: 420ms</li><li>User satisfaction: 88%</li><li>Conversion rate: <strong>23%</strong> (vs 14% text search)</li><li>Monthly volume: 15M visual searches</li></ul><p><strong>Multi-Modal (Text + Image):</strong></p><ul><li>Fusion latency overhead: 25ms</li><li>Accuracy improvement: <strong>+12%</strong> vs single-modal</li><li>User satisfaction: 92%</li><li>Monthly volume: 4.1M combined queries</li></ul><p><strong>Cost Breakdown:</strong></p><ul><li>LLM API costs: $0.0138/query average</li><li>Retrieval costs: $0.003/query</li><li>Vision AI: $0.002/query</li><li><strong>Total RAG + Vision cost: $0.0188/query</strong></li></ul><p>For 15% of queries using RAG:</p><ul><li>85% pure search: $0.018/query</li><li>15% with RAG: $0.037/query</li><li><strong>Blended average: $0.021/query</strong> (within $0.03 target)</li></ul><h3>Key Lessons Learned</h3><p><strong>1. Grounding is Non-Negotiable</strong><br> Our initial implementation without strong grounding had 23% hallucination rate. After implementing Vertex AI Search’s grounding with 0.7 threshold, it dropped to 1.1%. The cost of a single hallucination far exceeds infrastructure cost.</p><p><strong>2. Prompt Engineering is 80% of Success</strong><br> We spent 3 months iterating on prompts. The difference between generic and specialized prompts was 18 percentage points in user satisfaction. Small wording changes had outsized impact.</p><p><strong>3. Validation Catches What Grounding Misses</strong><br> Even with grounding, post-generation validation is essential. We catch price mismatches and product hallucinations before they reach users.</p><p><strong>4. Fine-Tuning Matters for Domain-Specific Tasks</strong><br> Base CLIP: 76.3% accuracy. Fine-tuned CLIP: 95.2% accuracy. The 18.9-point improvement came from learning fashion-specific nuances.</p><p><strong>5. Multi-Modal Fusion Requires Careful Design</strong><br> Cross-attention fusion gave us +12% accuracy over single-modal with only 25ms latency overhead. The ability to dynamically weight modalities based on query type was crucial.</p><h3>What’s Next</h3><p>This post covered the intelligence layer-embeddings, RAG, and multi-modal processing. But our initial implementation was slow (780ms p95) and expensive ($0.12/query). In Part 4, we’ll explore the optimization journey: how we reduced latency by 75% and cost by 75% through systematic engineering.</p><p><strong>Key topics in Part 4:</strong></p><ul><li>Latency optimization: 780ms → 195ms p95</li><li>Model quantization (FP32 → INT8)</li><li>Multi-layer caching strategy (73% hit rate)</li><li>GPU optimization and sharing</li><li>Cost reduction: $0.12 → $0.03/query ($135M/year saved)</li></ul><p><strong>Previous posts:</strong><br><a href="https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-feae31b04e5c">Part 1: Architecture &amp; Design Decisions</a><br><a href="https://medium.com/@SauravEvan/elasticsearch-vector-search-a9083ba9c95a">Part 2: Elasticsearch &amp; Vector Search</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e69b9342dc72" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/building-production-grade-multi-modal-search-at-scale-e69b9342dc72">Building Production-Grade Multi-Modal Search at Scale</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ElasticSearch & Vector Search]]></title>
            <link>https://blog.gopenai.com/elasticsearch-vector-search-a9083ba9c95a?source=rss-803008333c2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9083ba9c95a</guid>
            <dc:creator><![CDATA[Saurav Paul]]></dc:creator>
            <pubDate>Mon, 13 Oct 2025 11:13:49 GMT</pubDate>
            <atom:updated>2025-11-19T09:04:28.035Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: ElasticSearch &amp; Vector Search — Serving 500K Products with Sub-50ms Latency</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*K16MSSFWFDHLNb5T.png" /></figure><h3>Series Navigation</h3><p>- <a href="https://medium.com/@SauravEvan/feae31b04e5c">Part 1: Architecture &amp; Design Decisions</a><br>- Part 2: ElasticSearch &amp; Vector Search<br>- Part 3: RAG &amp; Multi-Modal Search<br>- Part 4: Latency &amp; Cost Optimization<br>- Part 5: Production Operations &amp; Lessons Learned</p><h3>Quick Context</h3><p>In <a href="https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-feae31b04e5c">Part 1</a>, we covered the high-level architecture for our multi-modal search system serving 30–50M daily active users. We chose Elasticsearch as our search engine core because it uniquely supports hybrid search — combining dense vector similarity with traditional keyword matching in a single query.</p><p>This post dives deep into the ElasticSearch implementation: cluster configuration, index design, hybrid search queries, vector similarity algorithms, and the specific optimizations that achieve sub-50ms p95 latency at 10K queries per second.</p><h4>The ElasticSearch Challenge</h4><p>ElasticSearch is the workhorse of our search system, handling 10K queries per second during peak traffic. But achieving this performance required significant optimization beyond default configurations. Our requirements:</p><ul><li><strong>500K+ products</strong> with real-time updates</li><li><strong>768-dimensional vector embeddings</strong> for semantic search</li><li><strong>Hybrid queries</strong> combining vectors and keywords</li><li><strong>Sub-50ms p95 latency</strong> for search queries</li><li><strong>12K documents/second</strong> indexing throughput</li><li><strong>99.9%+ uptime</strong> under production load</li></ul><p>Here’s everything we learned from running Elasticsearch at this scale.</p><h4>Cluster Configuration for 30–50M DAU</h4><p><strong>Hardware Specifications (per node):</strong></p><pre>instance_type: n2-highmem-4<br>vcpu: 4<br>memory: 32GB<br>disk: 500GB SSD (local NVMe-backed)<br>network: 10 Gbps<br>nodes: 3 (data nodes) + 1 (dedicated master)</pre><p><strong>Why n2-highmem-4?</strong></p><p>Memory-optimized instances were critical because:</p><ol><li>Elasticsearch uses 50% of RAM for heap, 50% for filesystem cache</li><li>Vector similarity search is memory-intensive (768-dim × 500K vectors = 1.5GB just for embeddings)</li><li>Aggregations require substantial heap space</li></ol><p>We tested n2-standard-4 (16GB) and saw p95 latency increase by <strong>3x</strong> due to GC pressure and disk I/O. The extra $800/month for highmem instances was absolutely worth it.</p><p><strong>JVM Heap Configuration:</strong></p><pre># elasticsearch.yml<br>ES_JAVA_OPTS: &quot;-Xms16g -Xmx16g&quot;<br>bootstrap.memory_lock: true</pre><p>We allocate exactly 16GB heap (50% of 32GB total), leaving 16GB for OS filesystem cache. This is critical for vector search-Lucene memory-maps vector segments, and sufficient filesystem cache means vectors stay in RAM.</p><p><strong>Critical: Never allocate more than 31GB heap</strong>. Above this threshold, JVM loses compressed object pointers (compressed oops), effectively halving your usable heap size.</p><h4>Dense vs Sparse Vector Implementation</h4><p>Our search indices store both dense and sparse vectors for hybrid search:</p><p><strong>Index Mapping:</strong></p><pre>{<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;product_id&quot;: { &quot;type&quot;: &quot;keyword&quot; },<br>      &quot;title&quot;: {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;analyzer&quot;: &quot;fashion_analyzer&quot;,<br>        &quot;fields&quot;: {<br>          &quot;keyword&quot;: { &quot;type&quot;: &quot;keyword&quot; }<br>        }<br>      },<br>      &quot;description&quot;: {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;analyzer&quot;: &quot;fashion_analyzer&quot;<br>      },<br>      &quot;embedding_768&quot;: {<br>        &quot;type&quot;: &quot;dense_vector&quot;,<br>        &quot;dims&quot;: 768,<br>        &quot;index&quot;: true,<br>        &quot;similarity&quot;: &quot;cosine&quot;,<br>        &quot;index_options&quot;: {<br>          &quot;type&quot;: &quot;hnsw&quot;,<br>          &quot;m&quot;: 16,<br>          &quot;ef_construction&quot;: 200<br>        }<br>      },<br>      &quot;attributes&quot;: {<br>        &quot;type&quot;: &quot;nested&quot;,<br>        &quot;properties&quot;: {<br>          &quot;color&quot;: { &quot;type&quot;: &quot;keyword&quot; },<br>          &quot;style&quot;: { &quot;type&quot;: &quot;keyword&quot; },<br>          &quot;pattern&quot;: { &quot;type&quot;: &quot;keyword&quot; },<br>          &quot;occasion&quot;: { &quot;type&quot;: &quot;keyword&quot; }<br>        }<br>      },<br>      &quot;price&quot;: { &quot;type&quot;: &quot;float&quot; },<br>      &quot;in_stock&quot;: { &quot;type&quot;: &quot;boolean&quot; },<br>      &quot;category&quot;: { &quot;type&quot;: &quot;keyword&quot; },<br>      &quot;brand&quot;: { &quot;type&quot;: &quot;keyword&quot; },<br>      &quot;sizes_available&quot;: { &quot;type&quot;: &quot;keyword&quot; }<br>    }<br>  }<br>}</pre><p><strong>Custom Fashion Analyzer:</strong></p><pre>{<br>  &quot;analysis&quot;: {<br>    &quot;analyzer&quot;: {<br>      &quot;fashion_analyzer&quot;: {<br>        &quot;type&quot;: &quot;custom&quot;,<br>        &quot;tokenizer&quot;: &quot;standard&quot;,<br>        &quot;filter&quot;: [<br>          &quot;lowercase&quot;,<br>          &quot;fashion_synonym&quot;,<br>          &quot;english_stemmer&quot;,<br>          &quot;unique&quot;<br>        ]<br>      }<br>    },<br>    &quot;filter&quot;: {<br>      &quot;fashion_synonym&quot;: {<br>        &quot;type&quot;: &quot;synonym&quot;,<br>        &quot;synonyms&quot;: [<br>          &quot;dress, gown, frock&quot;,<br>          &quot;pants, trousers, slacks&quot;,<br>          &quot;sneakers, trainers, kicks&quot;,<br>          &quot;blazer, sport coat, jacket&quot;,<br>          &quot;athleisure, activewear, sportswear&quot;<br>        ]<br>      },<br>      &quot;english_stemmer&quot;: {<br>        &quot;type&quot;: &quot;stemmer&quot;,<br>        &quot;language&quot;: &quot;english&quot;<br>      }<br>    }<br>  }<br>}</pre><p>This custom analyzer handles fashion-specific synonyms and stemming, improving keyword match quality by <strong>18%</strong> over the default analyzer.</p><h4>Hybrid Search Query Implementation</h4><p>Here’s our production hybrid search query combining semantic vectors with keyword matching:</p><pre>def hybrid_search(query_text, query_embedding, user_features, filters, top_k=20):<br>    &quot;&quot;&quot;<br>    Executes hybrid search combining:<br>    - 70% semantic similarity (dense vector)<br>    - 30% keyword relevance (BM25)<br>    - Personalization boost<br>    - Hard filters (size, price, availability)<br>    &quot;&quot;&quot;<br>    <br>    es_query = {<br>        &quot;size&quot;: top_k,<br>        &quot;query&quot;: {<br>            &quot;script_score&quot;: {<br>                &quot;query&quot;: {<br>                    &quot;bool&quot;: {<br>                        &quot;must&quot;: [<br>                            {<br>                                &quot;bool&quot;: {<br>                                    &quot;should&quot;: [<br>                                        # Semantic similarity component (70%)<br>                                        {<br>                                            &quot;script_score&quot;: {<br>                                                &quot;query&quot;: {&quot;match_all&quot;: {}},<br>                                                &quot;script&quot;: {<br>                                                    &quot;source&quot;: &quot;&quot;&quot;<br>                                                        cosineSimilarity(params.query_vector, <br>                                                                       &#39;embedding_768&#39;) * 0.7<br>                                                    &quot;&quot;&quot;,<br>                                                    &quot;params&quot;: {<br>                                                        &quot;query_vector&quot;: query_embedding<br>                                                    }<br>                                                }<br>                                            }<br>                                        },<br>                                        # Keyword matching component (30%)<br>                                        {<br>                                            &quot;multi_match&quot;: {<br>                                                &quot;query&quot;: query_text,<br>                                                &quot;fields&quot;: [<br>                                                    &quot;title^3&quot;,<br>                                                    &quot;description^1&quot;,<br>                                                    &quot;brand^2&quot;,<br>                                                    &quot;attributes.style^2&quot;<br>                                                ],<br>                                                &quot;type&quot;: &quot;best_fields&quot;,<br>                                                &quot;boost&quot;: 0.3<br>                                            }<br>                                        }<br>                                    ]<br>                                }<br>                            }<br>                        ],<br>                        &quot;filter&quot;: [<br>                            {&quot;term&quot;: {&quot;in_stock&quot;: True}},<br>                            {&quot;terms&quot;: {&quot;sizes_available&quot;: filters.get(&quot;sizes&quot;, [])}},<br>                            {&quot;range&quot;: {&quot;price&quot;: {<br>                                &quot;gte&quot;: filters.get(&quot;min_price&quot;, 0),<br>                                &quot;lte&quot;: filters.get(&quot;max_price&quot;, 10000)<br>                            }}}<br>                        ]<br>                    }<br>                },<br>                # Personalization boost<br>                &quot;script&quot;: {<br>                    &quot;source&quot;: &quot;&quot;&quot;<br>                        double base_score = _score;<br>                        double personalization = 1.0;<br>                        <br>                        // Boost if product matches user&#39;s style preferences<br>                        if (params.user_preferred_brands.contains(doc[&#39;brand&#39;].value)) {<br>                            personalization *= 1.3;<br>                        }<br>                        <br>                        // Boost if in user&#39;s preferred price range<br>                        double price = doc[&#39;price&#39;].value;<br>                        if (price &gt;= params.user_min_price &amp;&amp; price &lt;= params.user_max_price) {<br>                            personalization *= 1.2;<br>                        }<br>                        <br>                        return base_score * personalization;<br>                    &quot;&quot;&quot;,<br>                    &quot;params&quot;: {<br>                        &quot;user_preferred_brands&quot;: user_features.get(&quot;preferred_brands&quot;, []),<br>                        &quot;user_min_price&quot;: user_features.get(&quot;price_affinity_min&quot;, 0),<br>                        &quot;user_max_price&quot;: user_features.get(&quot;price_affinity_max&quot;, 10000)<br>                    }<br>                }<br>            }<br>        },<br>        &quot;_source&quot;: [&quot;product_id&quot;, &quot;title&quot;, &quot;price&quot;, &quot;image_url&quot;, &quot;attributes&quot;]<br>    }<br>    <br>    return es_client.search(index=&quot;products&quot;, body=es_query)</pre><p><strong>Why This Query Structure Works:</strong></p><ol><li><strong>Semantic First, Keywords Second</strong>: The 0.7/0.3 weighting emerged from A/B testing 12 different combinations. Pure semantic (1.0/0.0) had poor exact-match performance. Pure keyword (0.0/1.0) couldn’t understand intent. The 0.7/0.3 split maximized both precision and recall.</li><li><strong>script_score vs function_score</strong>: We initially used function_score with field_value_factor, but switching to script_score gave us 25% more flexibility in personalization logic with only 8ms latency increase.</li><li><strong>Multi-field Matching</strong>: Title gets 3x boost because it’s the most important signal. Brand gets 2x boost for exact brand searches. Description gets 1x (base) because it’s often noisy.</li><li><strong>Filter Context vs Query Context</strong>: Filters (stock, size, price) are in filter context, not query context, so they don’t affect scoring-just boolean inclusion/exclusion. This is critical for performance (filters are cached by Elasticsearch).</li></ol><p><strong>Index Settings:</strong></p><pre>{<br>  &quot;settings&quot;: {<br>    &quot;number_of_shards&quot;: 5,<br>    &quot;number_of_replicas&quot;: 1,<br>    &quot;refresh_interval&quot;: &quot;30s&quot;,<br>    &quot;max_result_window&quot;: 10000<br>  }<br>}</pre><p><strong>Why 5 Shards?</strong></p><p>We calculated optimal shard count based on:</p><ul><li>Total index size: 180GB (500K products × 360KB average)</li><li>Target shard size: 30–50GB (Elasticsearch recommendation)</li><li>180GB ÷ 40GB target = 4.5 → rounded to 5 shards</li></ul><p>Each shard: ~36GB, ~100K products.</p><p>More shards = more parallelization but more overhead. Fewer shards = less coordination overhead but less parallelization. Five shards on three nodes means some nodes handle 2 shards, others handle 1, with good load distribution.</p><p><strong>Why refresh_interval=30s?</strong></p><p>Default is 1s, making new documents searchable almost instantly. But each refresh is expensive (creates new Lucene segments). For product catalogs where 30-second latency on new products is acceptable, 30s refresh:</p><ul><li>Reduced CPU usage by 22%</li><li>Improved indexing throughput by 40%</li></ul><h4>HNSW Algorithm for Vector Similarity Search</h4><p>Exact nearest neighbor search in 768 dimensions across 500K vectors requires O(N × d) = 384 million operations per query. Completely unacceptable for sub-200ms latency requirements.</p><p><strong>Solution: HNSW (Hierarchical Navigable Small World) graphs</strong></p><p>HNSW provides approximate nearest neighbors with controllable accuracy/speed tradeoff.</p><p><strong>Configuration:</strong></p><pre>{<br>  &quot;index_options&quot;: {<br>    &quot;type&quot;: &quot;hnsw&quot;,<br>    &quot;m&quot;: 16,<br>    &quot;ef_construction&quot;: 200<br>  }<br>}</pre><p><strong>Parameter Explanation:</strong></p><ul><li><strong>m=16</strong>: Number of bi-directional links per node. Higher m = better recall but more memory. 16 is standard for most use cases.</li><li><strong>ef_construction=200</strong>: Size of dynamic candidate list during construction. Higher values = better index quality but slower indexing. 200 balances speed and quality.</li></ul><p><strong>At Query Time:</strong></p><pre>{<br>  &quot;knn&quot;: {<br>    &quot;field&quot;: &quot;embedding_768&quot;,<br>    &quot;query_vector&quot;: [0.23, -0.45, ...],<br>    &quot;k&quot;: 100,<br>    &quot;num_candidates&quot;: 500<br>  }<br>}</pre><ul><li><strong>k=100</strong>: Return top-100 nearest neighbors</li><li><strong>num_candidates=500</strong>: Examine 500 candidates during search (higher = better recall, slower query)</li></ul><p><strong>Performance Characteristics:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYBRnBRjUt7ZkH_wPHZHbA.png" /></figure><p>We chose m=16, ef=200 for 95.2% recall-close enough to exact while being <strong>47× faster</strong>.</p><h4>Bulk Indexing for Real-Time Updates</h4><p>Product catalogs change constantly-new products, price updates, stock changes. We process <strong>50K-100K updates per hour</strong> during peak.</p><p><strong>Bulk Indexing Implementation:</strong></p><pre>from elasticsearch import helpers<br>import time<br><br>def bulk_index_products(products, batch_size=500):<br>    &quot;&quot;&quot;<br>    Efficiently bulk-index products with batching and retry logic.<br>    &quot;&quot;&quot;<br>    actions = []<br>    success_count = 0<br>    error_count = 0<br>    <br>    for product in products:<br>        action = {<br>            &quot;_op_type&quot;: &quot;index&quot;,<br>            &quot;_index&quot;: &quot;products&quot;,<br>            &quot;_id&quot;: product[&quot;product_id&quot;],<br>            &quot;_source&quot;: {<br>                &quot;product_id&quot;: product[&quot;product_id&quot;],<br>                &quot;title&quot;: product[&quot;title&quot;],<br>                &quot;description&quot;: product[&quot;description&quot;],<br>                &quot;embedding_768&quot;: product[&quot;embedding&quot;],<br>                &quot;attributes&quot;: product[&quot;attributes&quot;],<br>                &quot;price&quot;: product[&quot;price&quot;],<br>                &quot;in_stock&quot;: product[&quot;in_stock&quot;],<br>                &quot;category&quot;: product[&quot;category&quot;],<br>                &quot;brand&quot;: product[&quot;brand&quot;],<br>                &quot;sizes_available&quot;: product[&quot;sizes&quot;]<br>            }<br>        }<br>        actions.append(action)<br>        <br>        # Bulk index in batches<br>        if len(actions) &gt;= batch_size:<br>            success, errors = helpers.bulk(<br>                es_client,<br>                actions,<br>                chunk_size=batch_size,<br>                raise_on_error=False,<br>                max_retries=3,<br>                initial_backoff=2<br>            )<br>            success_count += success<br>            error_count += len(errors)<br>            actions = []<br>            time.sleep(0.1)  # Brief pause to avoid overwhelming cluster<br>    <br>    # Index remaining actions<br>    if actions:<br>        success, errors = helpers.bulk(<br>            es_client,<br>            actions,<br>            chunk_size=batch_size,<br>            raise_on_error=False,<br>            max_retries=3,<br>            initial_backoff=2<br>        )<br>        success_count += success<br>        error_count += len(errors)<br>    <br>    return success_count, error_count</pre><p><strong>Batch Size Tuning:</strong></p><p>We tested batch sizes from 100 to 5000. Sweet spot: <strong>500 documents per batch</strong>.</p><ul><li>Smaller batches (100–200): Too much HTTP overhead, slower overall</li><li>Larger batches (2000–5000): Risk of timeout, difficult to track failures</li><li>500 documents: Good balance of throughput and reliability</li></ul><p><strong>Throughput:</strong> With this implementation, we achieve <strong>12,000 documents/second</strong> indexing speed during off-peak hours.</p><h4>Query Optimization Techniques</h4><ol><li><strong>Query Profiling</strong></li></ol><pre># Enable profiling to find bottlenecks<br>es_query[&quot;profile&quot;] = True<br>result = es_client.search(index=&quot;products&quot;, body=es_query)<br><br># Analyze profile results<br>profile = result[&quot;profile&quot;][&quot;shards&quot;][0]<br>print(f&quot;Query time: {profile[&#39;query&#39;][&#39;time_in_nanos&#39;] / 1e6}ms&quot;)<br>print(f&quot;Fetch time: {profile[&#39;fetch&#39;][&#39;time_in_nanos&#39;] / 1e6}ms&quot;)</pre><p>This revealed that 40% of query time was spent in script_score personalization. We optimized by pre-computing user preference scores and storing them in the Feature Store.</p><p><strong>2. Index Query Cache</strong></p><pre>{<br>  &quot;settings&quot;: {<br>    &quot;index.queries.cache.enabled&quot;: true,<br>    &quot;index.queries.cache.size&quot;: &quot;10%&quot;<br>  }<br>}</pre><p>ElasticSearch caches filter clauses (not query clauses). Our heavy use of filters (in_stock, size, price) benefits significantly from this.</p><p><strong>3. Request Cache</strong></p><pre>{ &quot;settings&quot;: { &quot;index.requests.cache.enable&quot;: true } }</pre><p>Caches entire search request results. Combined with our Redis cache, this provides two-tier caching:</p><ul><li><strong>Redis</strong>: Application-level, cross-instance cache (5-minute TTL)</li><li><strong>Elasticsearch request cache</strong>: Node-level, exact query cache (1-hour TTL)</li></ul><p><strong>Combined cache improvement:</strong><br> Redis (73%) + ES request cache (18% of misses) = <strong>91% total cache hit rate</strong> on eligible queries.</p><p><strong>Key Metrics We Monitor:</strong></p><pre># Cluster health <br>GET /_cluster/health <br><br># Query performance <br>GET /_nodes/stats/indices/search <br><br># Hot threads (when debugging slow queries) <br>GET /_nodes/hot_threads <br><br># Shard allocation <br>GET /_cat/shards?v&amp;h=index,shard,prirep,state,docs,store,node</pre><p><strong>Critical Alerts:</strong></p><ol><li><strong>Cluster status yellow/red</strong> → Page on-call immediately</li><li><strong>JVM heap &gt;85% for &gt;5 minutes</strong> → Auto-scale or restart</li><li><strong>Search latency p95 &gt;100ms for &gt;2 minutes</strong> → Investigate</li><li><strong>Indexing rejected threads &gt;10/minute</strong> → Backpressure issue</li><li><strong>Disk usage &gt;80% on any node</strong> → Expand or clean up</li></ol><p><strong>Production Incident Example (July 2025):</strong></p><p>Cluster went yellow after bulk indexing job overwhelmed primary shards. Indexing queue backed up to 50K documents. Search latency spiked to 2.3s p95.</p><p><strong>Root cause:</strong> refresh_interval=30s meant Lucene segments weren’t merging fast enough during high-write load. 50K products × 360KB = 18GB of segments not yet merged.</p><p><strong>Fix:</strong></p><ul><li>Temporarily reduced refresh_interval to 10s</li><li>Enabled forcemerge on low-traffic hours</li><li>Implemented better rate-limiting on bulk indexing (max 5K docs/sec)</li></ul><p><strong>Result:</strong> Cluster recovered in 40 minutes. Added pre-emptive monitoring alert for pending segment count &gt;5000.</p><h4>Real Production Metrics</h4><p>Here are our actual performance metrics over the last 90 days:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIpo7jCKdj6kgibsMRZTMQ.png" /></figure><p>The ElasticSearch cluster is rock-solid, handling massive scale with minimal operational overhead.</p><p><strong>1. Memory Matters for Vector Search</strong><br> Use memory-optimized instances (n2-highmem) and allocate 50% for JVM heap, 50% for filesystem cache. Vectors need to stay in memory for fast access.</p><p><strong>2. Hybrid Search &gt; Pure Semantic</strong><br> The 0.7/0.3 split between semantic and keyword gave us the best of both worlds. Pure semantic failed on exact matches; pure keyword missed intent.</p><p><strong>3. HNSW is Essential at Scale</strong><br> Approximate nearest neighbors with 95.2% recall is 47× faster than exact search and indistinguishable to users.</p><p><strong>4. Batch Size Matters</strong><br> 500 documents per batch optimized our indexing throughput. Too small = overhead, too large = failures.</p><p><strong>5. Monitor and Profile Everything</strong><br> Query profiling revealed our script_score bottleneck. You can’t optimize what you don’t measure.</p><h4>What’s Next</h4><p>This post covered the ElasticSearch implementation-the search engine core. In Part 3, we’ll explore how we added intelligence on top: RAG for conversational recommendations, multi-modal processing for visual and voice search, and the ML infrastructure that powers semantic understanding.</p><p><strong>Key topics in Part 3:</strong></p><ul><li>CLIP-based embeddings fine-tuned on 2.5M fashion images</li><li>RAG implementation with 1.1% hallucination rate</li><li>Visual search from Instagram/TikTok photos (95.2% detection accuracy)</li><li>Voice search integration</li><li>Cross-modal fusion strategies</li></ul><p><strong>Continue the series:</strong><br>Part 3: RAG &amp; Multi-Modal Search — From Instagram Photos to Product Recommendations</p><p><strong>Missed the previous post?</strong><br><a href="https://medium.com/@SauravEvan/building-production-grade-multi-modal-search-at-scale-feae31b04e5c">Part 1: Architecture &amp; Design Decisions</a></p><p><strong>Questions about ElasticSearch optimization?</strong><br> Drop a comment below-I’m happy to discuss specific challenges you’re facing with vector search or hybrid queries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9083ba9c95a" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/elasticsearch-vector-search-a9083ba9c95a">ElasticSearch &amp; Vector Search</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Production-Grade Multi-Modal Search at Scale]]></title>
            <link>https://blog.gopenai.com/building-production-grade-multi-modal-search-at-scale-feae31b04e5c?source=rss-803008333c2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/feae31b04e5c</guid>
            <dc:creator><![CDATA[Saurav Paul]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 04:21:51 GMT</pubDate>
            <atom:updated>2025-11-26T07:49:24.726Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: Architecture &amp; Design Decisions for 50M Daily Users</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MGvPf1xBQ7u1rLN7.png" /></figure><h4>Series Navigation</h4><p>- <a href="https://medium.com/@SauravEvan/feae31b04e5c">Part 1: Architecture &amp; Design Decisions</a><br>- <a href="https://medium.com/@SauravEvan/elasticsearch-vector-search-a9083ba9c95a">Part 2: ElasticSearch &amp; Vector Search</a><br>- Part 3: RAG &amp; Multi-Modal Search<br>- Part 4: Latency &amp; Cost Optimization<br>- Part 5: Production Operations &amp; Lessons Learned</p><p>Modern e-commerce search is fundamentally broken. Users type <em>“</em><strong><em>confident interview outfit</em></strong><em>”</em> and get keyword-matched results for products containing those exact words. They upload a screenshot from Instagram hoping to find similar styles and hit a dead end. They describe a vibe or feeling and receive algorithmically irrelevant products ranked by last season’s click-through rates.</p><p>In my previous role what I learned is, this isn’t just a user experience problem-it’s a revenue problem. When lifestyle retailers-scale, fashion retailers lose 62% of potential customers in the search-to-purchase funnel, <strong>that’s millions in lost revenue</strong>. Traditional keyword-based search systems simply cannot understand the semantic richness of fashion queries, the visual similarity between products, or the contextual nuances of how people actually shop.</p><p>During my tenure, We have built and scaled a next-generation search system serving <strong>30–50 million daily active users</strong> during peak seasons, processing <strong>15 million visual searches monthly</strong>, and handling <strong>10,000 concurrent requests</strong> with sub-200ms p95 latency. The system delivers personalized, multi-modal search across a 500K+ product catalog with real-time inventory updates, resulting in <strong>$18.5M in annual revenue impact</strong> and a <strong>47% conversion improvement</strong>.</p><p>But here’s what you won’t read in most blog posts: our initial implementation was a disaster. P95 latency sat at <strong>780ms-completely</strong> unacceptable for production. Our <strong>cost per query was $0.12</strong>, which would have bankrupted the project at scale. Our first RAG implementation hallucinated product details <strong>23% of the time</strong>.</p><p>This series chronicles the journey from that broken initial system to a production-grade platform that handles massive scale. In this first post, I’ll cover the core architectural decisions that shaped everything else: why we chose certain technologies, how we structured the system, and what tradeoffs we made.</p><p>I needed to design a system that simultaneously handles:</p><ol><li><strong>Multi-modal inputs</strong> — Text queries, Instagram/TikTok images, voice search</li><li><strong>Semantic understanding</strong> — Intent-based matching beyond keywords</li><li><strong>Personalized recommendations</strong> — User preferences, style DNA, context</li><li><strong>RAG-powered responses</strong> — Grounded, factual, no hallucinations</li><li><strong>Sub-200ms latency</strong> at 10K concurrent requests</li><li><strong>Reasonable cost</strong> — Target of $0.03/query</li><li><strong>Real-time updates</strong> across 500K+ products</li><li><strong>GDPR/CCPA compliance</strong> with full data lineage</li></ol><p>This isn’t a theoretical exercise-this is battle-tested production infrastructure serving tens of millions of real users making real purchasing decisions.</p><h3>Architecture Overview</h3><h4>The Mental Model</h4><p>Before diving into specific technologies, let me explain the mental model. Our system is fundamentally a <strong>hybrid search engine</strong> augmented with <strong>retrieval-augmented generation (RAG)</strong>, wrapped in a <strong>multi-modal processing layer</strong>, optimized for extreme scale.</p><p>Think of it as three interconnected layers:</p><p><strong>Layer 1: Multi-Modal Input Processing</strong><br> Accepts and normalizes text queries, images from social media, and voice inputs into a unified representation that preserves semantic meaning across modalities.</p><p><strong>Layer 2: Hybrid Search Engine</strong><br> Combines semantic vector similarity search with traditional keyword matching, providing the best of both worlds: understanding intent while respecting exact matches.</p><p><strong>Layer 3: RAG-Powered Responses</strong><br> Takes search results and generates intelligent, grounded responses using large language models, ensuring factual accuracy while providing natural, conversational product recommendations.</p><h3>System Architecture Diagram</h3><pre>┌─────────────────────────────────────────────────────────────────┐<br>│                        Client Layer                             │<br>│  (Mobile Apps, Web, Voice Assistants, Social Media Integration) │<br>└────────────────────────────┬────────────────────────────────────┘<br>                             │<br>                    ┌────────▼─────────┐<br>                    │   Cloud CDN      │<br>                    │  (Edge Caching)  │<br>                    └────────┬─────────┘<br>                             │<br>                    ┌────────▼─────────┐<br>                    │  Cloud Load      │<br>                    │   Balancer       │<br>                    └────────┬─────────┘<br>                             │<br>        ┌────────────────────┼────────────────────┐<br>        │                    │                    │<br>   ┌────▼─────┐      ┌──────▼──────┐     ┌──────▼──────┐<br>   │  Cloud   │      │   Cloud     │     │   Cloud     │<br>   │   Run    │      │    Run      │     │    Run      │<br>   │ (Search  │      │ (Vision AI) │     │   (RAG)     │<br>   │ Service) │      │             │     │             │<br>   └────┬─────┘      └──────┬──────┘     └──────┬──────┘<br>        │                   │                   │<br>        │         ┌─────────┴───────────────────┤<br>        │         │                             │<br>   ┌────▼─────────▼───┐                  ┌──────▼──────────┐<br>   │  Memorystore     │                  │   Vertex AI     │<br>   │  Redis (5GB)     │                  │   (PaLM 2)      │<br>   │  Response Cache  │                  │                 │<br>   └──────────────────┘                  └─────────────────┘<br>        │<br>   ┌────▼──────────────────────────────────────────────────┐<br>   │              Elasticsearch Cluster                    │<br>   │  Node 1 (n2-highmem-4)  Node 2  Node 3                │<br>   │  - Dense Vectors (768-dim)                            │<br>   │  - Sparse Vectors (BM25)                              │<br>   │  - 5 Primary Shards, 1 Replica                        │<br>   │  - 500GB SSD each                                     │<br>   └──────────────────────┬────────────────────────────────┘<br>                          │<br>        ┌─────────────────┼─────────────────┐<br>        │                 │                 │<br>   ┌────▼─────┐    ┌──────▼──────┐    ┌─────▼──────┐<br>   │  Cloud   │    │  BigQuery   │    │  Vertex AI │<br>   │   SQL    │    │ (Analytics) │    │   Feature  │<br>   │(Postgres)│    │             │    │   Store    │<br>   └──────────┘    └─────────────┘    └────────────┘</pre><p>Let’s trace an actual user query through the system. When a user searches for <strong><em>“confident interview outfit size 8,”</em></strong> here’s what happens:</p><p><strong>Data Flow: From Query to Response in Under 200ms</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oP_SaJnApnmOJJLRynGi4Q.png" /></figure><p><strong>Step 1: Request Reception (0–5ms)</strong></p><ul><li>Cloud Load Balancer receives request</li><li>Routes to nearest available Cloud Run instance</li><li>CDN edge cache check-if cached, return immediately (10% of queries)</li></ul><p><strong>Step 2: Cache Check (5–15ms)</strong></p><ul><li>Query Redis for cached response (73% hit rate)</li><li>Cache key: hash(query_text + user_segment + filters)</li><li>Cache TTL: 5 minutes for products, 1 hour for embeddings</li><li>If cache hit, skip to Step 7</li></ul><p><strong>Step 3: Query Parsing &amp; Embedding (15–45ms)</strong></p><ul><li>Parse query for filters (size: 8, occasion: interview)</li><li>Generate 768-dim embedding using fine-tuned sentence transformer</li><li>Extract semantic intent (“confident” → professional, polished aesthetic)</li><li>Parallel process: keyword extraction for BM25 component</li></ul><p><strong>Step 4: Feature Store Lookup (45–55ms)</strong></p><ul><li>Fetch user features from Vertex AI Feature Store (&lt;10ms p99)</li><li>Features: style_vector (512-dim), recent_interactions, price_affinity</li><li>Fallback to segment-level features if user features unavailable</li></ul><p><strong>Step 5: ElasticSearch Query (55–110ms)</strong></p><ul><li>Execute hybrid search query (0.7 × semantic + 0.3 × keyword)</li><li>Filter by: in_stock=true, size=8, category=formal_wear</li><li>Retrieve top-100 candidates from 500K products</li><li>Re-rank using personalization features</li><li>Return top-20 results with metadata</li></ul><p><strong>Step 6: RAG Enhancement (Optional, 110–180ms)</strong></p><ul><li>For complex queries requiring explanation, invoke Vertex AI Search</li><li>Ground LLM response in top-10 search results</li><li>Generate natural language recommendations</li><li>Validate factual accuracy (price, availability, attributes)</li></ul><p><strong>Step 7: Response Assembly (180–195ms)</strong></p><ul><li>Format results with product details, images, pricing</li><li>Add personalization signals</li><li>Cache response in Redis with 5-minute TTL</li><li>Return to client with 200 OK</li></ul><p><strong>Step 8: Async Post-Processing (background)</strong></p><ul><li>Log interaction event to Pub/Sub → BigQuery</li><li>Update user features in Feature Store</li><li>Trigger embedding refresh if product catalog updated</li><li>Feed interaction data to ML training pipeline</li></ul><p><strong>Total latency: 195ms p95</strong> (within our 200ms budget)</p><h3>Key Architectural Decisions</h3><h4>Decision 1: Cloud Run for Micro-services</h4><p>Why Cloud Run over GKE?</p><p>We chose Cloud Run over Google Kubernetes Engine (GKE) for its operational simplicity at scale. With traffic varying 10x between peak and off-peak hours (Black Friday: 150K concurrent users vs typical: 15K), auto-scaling from 0 to 1000 instances without managing Kubernetes was crucial.</p><p><strong>Benefits:</strong></p><ul><li>Auto-scaling from 0 to 1000 instances based on traffic</li><li>Per-request billing (only pay for actual usage)</li><li>No infrastructure management overhead</li><li>Faster deployment cycles (no cluster upgrades)</li></ul><p><strong>Cost Impact:</strong><br> Cloud Run’s per-request billing saved us<strong>$47K/month</strong> compared to always-on GKE clusters sized for peak traffic.</p><p><strong>Configuration:</strong></p><pre>apiVersion: serving.knative.dev/v1<br>kind: Service<br>metadata:<br>  name: search-service<br>spec:<br>  template:<br>    spec:<br>      autoscaling.knative.dev/minScale: 5<br>      autoscaling.knative.dev/maxScale: 1000<br>      autoscaling.knative.dev/target: 80<br>    spec:<br>      containers:<br>      - image: gcr.io/project/search-service<br>        resources:<br>          limits:<br>            cpu: 2000m<br>            memory: 4Gi</pre><h4>Decision 2: ElasticSearch Over Specialized Vector Databases</h4><p><strong>The Evaluation:</strong><br> We evaluated Pinecone, Weaviate, and Milvus but chose ElasticSearch for three critical reasons:</p><ol><li><strong>Hybrid search support</strong> — Combining dense vectors with BM25 in a single query</li><li><strong>Operational maturity</strong> — Our team already ran ElasticSearch at scale</li><li><strong>Cost</strong> — Self-hosted ElasticSearch on GCP was <strong>4x cheaper</strong> than managed vector DB services at our scale</li></ol><p><strong>Why not a pure vector database?</strong></p><p>Pure vector databases excel at similarity search but struggle with exact keyword matching. When users search for “<strong>Nike Air Max 90</strong>,” they want exactly that product, not semantically similar Adidas shoes. ElasticSearch let us combine both approaches seamlessly.</p><p><strong>Configuration:</strong></p><pre>Cluster: 3 nodes<br>Instance Type: n2-highmem-4 (4 vCPU, 32GB RAM)<br>Storage: 500GB SSD per node<br>JVM Heap: 16GB per node<br>Shards: 5 primary, 1 replica<br>Total Index Size: 180GB (500K products)</pre><h4>Decision 3: Redis for Multi-Layer Caching</h4><p>With a <strong>73% cache hit rate</strong> on search queries, Redis paid for itself within two weeks. At $0.03/query cost, caching saved <strong>$2.1M annually</strong>.</p><p><strong>Cache Strategy:</strong></p><ul><li><strong>Tier 1:</strong> CDN edge cache (10% hit rate, 0ms latency)</li><li><strong>Tier 2:</strong> Redis cache (63% hit rate, 1–2ms latency)</li><li><strong>Tier 3:</strong> ElasticSearch query cache (18% hit rate, 15ms latency)</li></ul><p><strong>Combined cache hit rate: 73%</strong></p><p>We sized Redis at <strong>5GB (enough for 2M cached query responses at avg 2.5KB each) with LRU eviction</strong>. The instance costs <strong>$580/month</strong> but saves us <strong>$175K/month</strong> in compute costs.</p><h4>Decision 4: Vertex AI for Model Serving</h4><p><strong>Why managed ML platform over self-hosted?</strong></p><p>Managing model serving infrastructure for PaLM 2 would have required a dedicated ML platform team of 3 engineers.</p><p><strong>Vertex AI provided:</strong></p><ul><li>Model versioning and A/B testing out of the box</li><li>Auto-scaling inference endpoints (0–100 instances)</li><li>Integrated monitoring and drift detection</li><li>Security and compliance certifications (SOC2, HIPAA)</li></ul><p><strong>Cost Comparison:</strong></p><ul><li>Vertex AI: $89K/year (managed service)</li><li>Self-hosted: $340K/year (3 FTE + infrastructure)</li></ul><p>The premium was worth it-we gained 18 months of engineering time to focus on core product features instead of infrastructure.</p><h4>Decision 5: Hybrid Search Strategy (0.7 × Semantic + 0.3 × Keyword)</h4><p>This was our <strong>most critical decision</strong> for search quality.</p><p><strong>Why hybrid?</strong></p><p>Pure semantic search failed catastrophically on exact matches. When users searched for “<strong>Nike Air Max 90</strong>,” semantically similar Adidas products ranked higher because they matched the “athletic shoe” intent. Pure keyword search couldn’t understand queries like “athleisure meeting outfit.”</p><p><strong>A/B Test Results:</strong></p><pre>| Strategy           | hit@10   | User Satisfaction | Conversion Rate |<br>|--------------------|--------  |-------------------|-----------------|<br>| Pure Keyword(BM25) | 0.61     | 68%               | 11.2%           |<br>| Pure Semantic      | 0.79     | 81%               | 14.8%           |<br>| Hybrid (0.5/0.5)   | 0.84     | 86%               | 15.9%           |<br>| Hybrid (0.7/0.3)   | 0.87     | 90%               | 16.4%           |<br>| Hybrid (0.9/0.1)   | 0.83     | 88%               | 15.7%           |</pre><p>The <strong>0.7/0.3</strong> split maximized all three metrics. We give semantic understanding primary weight (0.7) while preserving keyword precision (0.3).</p><h4>Infrastructure Scaling Characteristics</h4><p>At our scale, here’s how resources scale with load:</p><p><strong>ElasticSearch:</strong></p><ul><li>Linear scaling up to 50K QPS per node</li><li>3 nodes handle 150K QPS comfortably</li><li>Index size: 180GB (500K products × 360KB avg)</li><li>Memory: 64GB per node (32GB heap, 32GB filesystem cache)</li><li>CPU: Averages 40% utilization, spikes to 75% during catalog updates</li></ul><p><strong>Cloud Run:</strong></p><ul><li>Search Service: 0–1000 instances, avg 250 during business hours</li><li>Each instance: 2 vCPU, 4GB RAM, handles 20 concurrent requests</li><li>Vision AI Service: 0–200 instances</li><li>RAG Service: 0–100 instances (only ~15% of queries)</li></ul><p><strong>Redis:</strong></p><ul><li>5GB memory, single instance with replication for HA</li><li>Stores 2M cached responses (avg 2.5KB each)</li><li>100K ops/sec capacity, avg 40K ops/sec</li><li>73% hit rate on search queries</li></ul><p><strong>Cost Breakdown at 50M DAU (1.5B queries/month):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5CxrFO6_vLae7UC1g6WftA.png" /></figure><pre>Elasticsearch:  $4,800/month (3 × n2-highmem-4 + storage)<br>Cloud Run:     $12,300/month (avg 250 search instances)<br>Vertex AI:      $7,400/month (PaLM 2 API + AutoML endpoints)<br>Redis:            $580/month (5GB Memorystore)<br>BigQuery:       $2,100/month (analytics queries)<br>Cloud SQL:        $450/month (metadata storage)<br>────────────────────────────────────────────────────<br>TOTAL:         $27,630/month = $0.018/query<br></pre><p>With ML training costs: <strong>$0.03/query</strong> (within budget)</p><h4>Why This Architecture Works at Scale</h4><p>This architecture balances three critical dimensions:</p><p>1. <strong>Performance</strong><br>Multi-layer caching (CDN, Redis, ElasticSearch) + parallel processing + colocation in single GCP region achieves sub-200ms latency even at 10K QPS.</p><p><strong>2. Cost</strong><br>Intelligent caching (73% hit rate) + auto-scaling (Cloud Run) + model quantization keeps costs at $0.03/query vs initial $0.12/query.</p><p><strong>3. Flexibility</strong><br>Micro-services architecture + managed services (Vertex AI, Cloud Run) enables rapid iteration without infrastructure overhead.</p><p>The key insight: <strong>Don’t build what you can buy, don’t manage what you can abstract</strong>. We focused engineering effort on the unique value proposition (hybrid search, multi-modal processing) and leveraged managed services for undifferentiated heavy lifting.</p><h3>What’s Next</h3><p>This post covered the high-level architecture and key design decisions.</p><p><strong>In Part 2</strong>, we’ll dive deep into the ElasticSearch implementation — cluster configuration, hybrid search queries, vector similarity algorithms, and the specific optimizations that let us serve 500K products with sub-50ms search latency.</p><ul><li>ElasticSearch cluster setup for <strong>30–50M DAU</strong></li><li><strong>Dense vs sparse</strong> vector implementation</li><li><strong>HNSW algorithm</strong> for approximate nearest neighbors</li><li>Index design and shard strategy</li><li>Bulk indexing at 12K documents/second</li><li>Production metrics and monitoring</li></ul><p><strong>Continue the series:</strong><br><a href="https://medium.com/@SauravEvan/elasticsearch-vector-search-a9083ba9c95a">Part 2: ElasticSearch &amp; Vector Search — Serving 500K Products with Sub-50ms Latency</a></p><p><strong>Stay updated:</strong><br> Follow me on <a href="https://www.linkedin.com/in/paulsaurav/">LinkedIn</a> for the next post in this series.</p><p><strong>About this series:</strong><br> This is a detailed chronicle of building production search infrastructure at massive scale. Each post is based on real production experience serving 30–50M daily active users, with actual metrics, code examples, and lessons learned. No fluff, just practical engineering insights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feae31b04e5c" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/building-production-grade-multi-modal-search-at-scale-feae31b04e5c">Building Production-Grade Multi-Modal Search at Scale</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Medical RAG System with Google’s Agent Technologies: A Complete Implementation Guide]]></title>
            <link>https://blog.gopenai.com/building-a-medical-rag-system-with-googles-agent-technologies-a-complete-implementation-guide-5337b715f875?source=rss-803008333c2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5337b715f875</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Saurav Paul]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 17:33:51 GMT</pubDate>
            <atom:updated>2025-11-26T07:48:57.130Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7ixKmwefyXwzgO4EaRUxA.png" /></figure><h3><strong>Introduction</strong></h3><p>In this comprehensive article, I’ll walk through the implementation of an advanced Retrieval-Augmented Generation (RAG) system for medical customer support using Google Cloud Platform’s agent technologies. This system leverages the latest advancements in AI agent orchestration, vector search, and compliance frameworks to deliver accurate, contextual, and compliant medical information.</p><p>The implementation follows an enhanced MLOps framework that addresses the unique challenges of medical RAG systems, including:</p><ol><li>Strict compliance requirements for handling medical information</li><li>High accuracy demands when providing medical guidance</li><li>Seamless agent coordination for complex medical queries</li><li>Comprehensive evaluation of responses for medical correctness</li><li>Cost optimization while maintaining high-quality responses</li></ol><p>By the end of this article, you’ll have a complete, production-ready medical RAG system that can be deployed locally using Docker or to Google Cloud Platform for production use.</p><h3>Architecture Overview</h3><p>The system architecture follows a micro services approach with eight core components that work together to provide a robust medical RAG workflow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*tR3rWK1qE-jPv4-6vRGwwQ.png" /></figure><p>Each component has a specific role:</p><ol><li>Web Interface: React-based UI for interacting with the system</li><li>API Gateway: Central entry point for all requests</li><li>Agent Orchestrator: Coordinates multiple specialized agents using Google’s Agent Development Kit (ADK)</li><li>Document Processor: Handles ingestion and processing of medical documents</li><li>Vector Store: Stores and retrieves vector embeddings using Vertex AI Matching Engine</li><li>Compliance Service: Ensures HIPAA and GDPR compliance</li><li>Evaluation Service: Evaluates response quality and medical correctness</li><li>Monitoring Service: Tracks system performance and usage metrics</li></ol><h3>Implementation Details</h3><p>Let’s dive into the implementation of each component, starting with the core configuration that defines our medical RAG workflow.</p><h4>Core Configuration</h4><p>The system uses a comprehensive configuration approach that defines all aspects of the medical RAG workflow:</p><pre><br>class MedicalRAGConfig:<br>    &quot;&quot;&quot;Configuration for Medical RAG Workflow.&quot;&quot;&quot;<br>    <br>    def __init__(self, config_path: Optional[str] = None):<br>        &quot;&quot;&quot;Initialize the configuration.&quot;&quot;&quot;<br>        # Default configuration<br>        self.config = {<br>            # Core settings<br>            &quot;project&quot;: {<br>                &quot;name&quot;: &quot;medical-rag-support&quot;,<br>                &quot;description&quot;: &quot;Medical Customer Support RAG Workflow&quot;,<br>                &quot;version&quot;: &quot;1.0.0&quot;<br>            },<br>            <br>            # GCP settings<br>            &quot;gcp&quot;: {<br>                &quot;project_id&quot;: os.environ.get(&quot;GCP_PROJECT_ID&quot;, &quot;medical-rag-project&quot;),<br>                &quot;location&quot;: os.environ.get(&quot;GCP_LOCATION&quot;, &quot;us-central1&quot;),<br>                &quot;service_account&quot;: os.environ.get(&quot;GCP_SERVICE_ACCOUNT&quot;, &quot;&quot;),<br>                &quot;enable_apis&quot;: [<br>                    &quot;aiplatform.googleapis.com&quot;,<br>                    &quot;documentai.googleapis.com&quot;,<br>                    &quot;storage.googleapis.com&quot;,<br>                    &quot;logging.googleapis.com&quot;,<br>                    &quot;monitoring.googleapis.com&quot;<br>                ]<br>            },<br>            <br>            # Agent settings<br>            &quot;agent&quot;: {<br>                &quot;type&quot;: &quot;medical_assistant&quot;,<br>                &quot;model&quot;: &quot;gemini-pro&quot;,<br>                &quot;temperature&quot;: 0.2,<br>                &quot;max_output_tokens&quot;: 1024,<br>                &quot;safety_settings&quot;: {<br>                    &quot;harmful_categories&quot;: &quot;block_medium_and_above&quot;,<br>                    &quot;harassment&quot;: &quot;block_medium_and_above&quot;,<br>                    &quot;hate_speech&quot;: &quot;block_medium_and_above&quot;,<br>                    &quot;sexually_explicit&quot;: &quot;block_medium_and_above&quot;,<br>                    &quot;dangerous_content&quot;: &quot;block_medium_and_above&quot;<br>                }<br>            },<br>            <br>            # Vector database settings<br>            &quot;vector_db&quot;: {<br>                &quot;type&quot;: &quot;vertex_matching_engine&quot;,<br>                &quot;dimensions&quot;: 768,<br>                &quot;distance_measure&quot;: &quot;cosine&quot;,<br>                &quot;index_update_schedule&quot;: &quot;hourly&quot;,<br>                &quot;embedding_model&quot;: &quot;textembedding-gecko@latest&quot;<br>            },<br>            <br>            # Document processing settings<br>            &quot;document_processing&quot;: {<br>                &quot;chunk_size&quot;: 512,<br>                &quot;chunk_overlap&quot;: 128,<br>                &quot;processors&quot;: [<br>                    {<br>                        &quot;type&quot;: &quot;text_splitter&quot;,<br>                        &quot;config&quot;: {<br>                            &quot;separator&quot;: &quot;\n\n&quot;,<br>                            &quot;keep_separator&quot;: False<br>                        }<br>                    },<br>                    {<br>                        &quot;type&quot;: &quot;metadata_extractor&quot;,<br>                        &quot;config&quot;: {<br>                            &quot;extract_title&quot;: True,<br>                            &quot;extract_date&quot;: True,<br>                            &quot;extract_authors&quot;: True,<br>                            &quot;extract_medical_entities&quot;: True<br>                        }<br>                    },<br>                    {<br>                        &quot;type&quot;: &quot;medical_entity_extractor&quot;,<br>                        &quot;config&quot;: {<br>                            &quot;entity_types&quot;: [&quot;condition&quot;, &quot;medication&quot;, &quot;procedure&quot;, &quot;anatomy&quot;]<br>                        }<br>                    }<br>                ],<br>                &quot;supported_formats&quot;: [&quot;pdf&quot;, &quot;docx&quot;, &quot;txt&quot;, &quot;html&quot;, &quot;csv&quot;, &quot;xlsx&quot;]<br>            },<br>            <br>            # Compliance settings<br>            &quot;compliance&quot;: {<br>                &quot;enabled&quot;: True,<br>                &quot;frameworks&quot;: [&quot;hipaa&quot;, &quot;gdpr&quot;],<br>                &quot;pii_detection&quot;: {<br>                    &quot;enabled&quot;: True,<br>                    &quot;info_types&quot;: [<br>                        &quot;PERSON_NAME&quot;,<br>                        &quot;US_SOCIAL_SECURITY_NUMBER&quot;,<br>                        &quot;PHONE_NUMBER&quot;,<br>                        &quot;EMAIL_ADDRESS&quot;,<br>                        &quot;MEDICAL_RECORD_NUMBER&quot;,<br>                        &quot;HEALTH_INSURANCE_ID_NUMBER&quot;<br>                    ]<br>                },<br>                &quot;content_safety&quot;: {<br>                    &quot;enabled&quot;: True,<br>                    &quot;block_unsafe_content&quot;: True,<br>                    &quot;log_safety_issues&quot;: True<br>                },<br>                &quot;audit_logging&quot;: {<br>                    &quot;enabled&quot;: True,<br>                    &quot;log_queries&quot;: True,<br>                    &quot;log_responses&quot;: True,<br>                    &quot;log_pii_detections&quot;: True<br>                }<br>            },<br>            <br>            # Additional settings for evaluation, serving, monitoring, and cost optimization<br>            # ...<br>        }<br>        <br>        # Load configuration from file if provided<br>        if config_path and os.path.exists(config_path):<br>            self._load_from_file(config_path)<br></pre><p>This configuration approach allows for flexible customization while providing sensible defaults for medical RAG workflows.</p><h3>Agent Orchestration with Google ADK</h3><p>The heart of our system is the Agent Orchestrator, which leverages Google’s Agent Development Kit (ADK) to coordinate multiple specialized agents</p><pre>class ADKIntegration:<br>    &quot;&quot;&quot;Integration with Google&#39;s Agent Development Kit (ADK).&quot;&quot;&quot;<br>    <br>    def __init__(self, config: Config):<br>        &quot;&quot;&quot;Initialize the ADK integration.&quot;&quot;&quot;<br>        self.config = config<br>        self.project_id = config.get(&quot;gcp.project_id&quot;)<br>        self.location = config.get(&quot;gcp.location&quot;, &quot;us-central1&quot;)<br>        self.agent_service_client = None<br>        self.initialized = False<br>        <br>        # Initialize ADK if available<br>        if &quot;google.cloud.aiplatform&quot; in globals():<br>            try:<br>                aiplatform.init(project=self.project_id, location=self.location)<br>                self.agent_service_client = AgentServiceClient()<br>                self.initialized = True<br>                logging.info(f&quot;ADK integration initialized for project {self.project_id}&quot;)<br>            except Exception as e:<br>                logging.error(f&quot;Failed to initialize ADK: {str(e)}&quot;)<br>    <br>    def create_agent(self, <br>                    name: str, <br>                    description: str, <br>                    display_name: str = None,<br>                    model: str = &quot;gemini-pro&quot;,<br>                    tools: List[Dict[str, Any]] = None) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;Create a new agent using ADK.&quot;&quot;&quot;<br>        if not self.initialized:<br>            raise RuntimeError(&quot;ADK integration not initialized&quot;)<br>        <br>        display_name = display_name or name<br>        <br>        # Convert tool configurations to ADK Tool objects<br>        adk_tools = []<br>        if tools:<br>            for tool_config in tools:<br>                tool = Tool(<br>                    name=tool_config.get(&quot;name&quot;),<br>                    description=tool_config.get(&quot;description&quot;, &quot;&quot;),<br>                    function_declarations=tool_config.get(&quot;function_declarations&quot;, [])<br>                )<br>                adk_tools.append(tool)<br>        <br>        try:<br>            # Create the agent<br>            agent = Agent.create(<br>                display_name=display_name,<br>                description=description,<br>                tools=adk_tools if adk_tools else None,<br>                model=model<br>            )<br>            <br>            # Return agent details<br>            agent_details = {<br>                &quot;id&quot;: agent.name.split(&quot;/&quot;)[-1],<br>                &quot;name&quot;: name,<br>                &quot;display_name&quot;: display_name,<br>                &quot;description&quot;: description,<br>                &quot;model&quot;: model,<br>                &quot;tools&quot;: tools or [],<br>                &quot;created_at&quot;: agent.create_time.isoformat() if hasattr(agent, &#39;create_time&#39;) else None,<br>                &quot;updated_at&quot;: agent.update_time.isoformat() if hasattr(agent, &#39;update_time&#39;) else None,<br>                &quot;status&quot;: &quot;created&quot;<br>            }<br>            <br>            logging.info(f&quot;Created agent: {agent_details[&#39;id&#39;]}&quot;)<br>            return agent_details<br>            <br>        except Exception as e:<br>            logging.error(f&quot;Failed to create agent: {str(e)}&quot;)<br>            raise</pre><p>The Agent Orchestrator coordinates multiple specialized agents, each with specific capabilities:</p><ol><li>Medical Knowledge Agent: Answers general medical questions</li><li>Medication Agent: Provides information about medications and interactions</li><li>Procedure Agent: Explains medical procedures and protocols</li><li>Triage Agent: Helps determine urgency and appropriate care level</li></ol><p>These agents work together through the orchestration layer to provide comprehensive medical support.</p><h3>Document Processing and Vector Search</h3><p>The Document Processor handles the ingestion and processing of medical documents</p><pre>class DocumentProcessor:<br>    &quot;&quot;&quot;Processes documents for the medical RAG workflow.&quot;&quot;&quot;<br>    <br>    def __init__(self, config: Config):<br>        &quot;&quot;&quot;Initialize the document processor.&quot;&quot;&quot;<br>        self.config = config<br>        self.chunk_size = config.get(&quot;document_processing.chunk_size&quot;, 512)<br>        self.chunk_overlap = config.get(&quot;document_processing.chunk_overlap&quot;, 128)<br>        self.processors = self._initialize_processors(config.get(&quot;document_processing.processors&quot;, []))<br>        self.vector_db_client = VectorDBClient(config)<br>        self.embedding_model = config.get(&quot;vector_db.embedding_model&quot;, &quot;textembedding-gecko@latest&quot;)<br>        <br>        # Initialize embedding model<br>        self.embedding_client = None<br>        try:<br>            self.embedding_client = aiplatform.TextEmbeddingModel.from_pretrained(self.embedding_model)<br>            logging.info(f&quot;Initialized embedding model: {self.embedding_model}&quot;)<br>        except Exception as e:<br>            logging.error(f&quot;Failed to initialize embedding model: {str(e)}&quot;)<br>    <br>    def process_document(self, <br>                        document_path: str, <br>                        metadata: Dict[str, Any] = None) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;Process a document and store in vector database.&quot;&quot;&quot;<br>        # Extract text and metadata<br>        document_text, extracted_metadata = self._extract_text_and_metadata(document_path)<br>        <br>        # Merge with provided metadata<br>        if metadata:<br>            extracted_metadata.update(metadata)<br>        <br>        # Split into chunks<br>        chunks = self._split_text(document_text)<br>        <br>        # Process chunks with all processors<br>        processed_chunks = []<br>        for chunk in chunks:<br>            processed_chunk = self._process_chunk(chunk, extracted_metadata)<br>            processed_chunks.append(processed_chunk)<br>        <br>        # Generate embeddings and store in vector database<br>        embeddings = self._generate_embeddings([chunk[&quot;text&quot;] for chunk in processed_chunks])<br>        <br>        # Store in vector database<br>        document_id = str(uuid.uuid4())<br>        self.vector_db_client.store_embeddings(document_id, processed_chunks, embeddings)<br>        <br>        return {<br>            &quot;document_id&quot;: document_id,<br>            &quot;chunk_count&quot;: len(processed_chunks),<br>            &quot;metadata&quot;: extracted_metadata<br>        }</pre><p>The Vector DB Client interfaces with Vertex AI Matching Engine for efficient vector search</p><pre>class VectorDBClient:<br>    &quot;&quot;&quot;Client for interacting with vector database.&quot;&quot;&quot;<br>    <br>    def __init__(self, config: Config):<br>        &quot;&quot;&quot;Initialize the vector database client.&quot;&quot;&quot;<br>        self.config = config<br>        self.project_id = config.get(&quot;gcp.project_id&quot;)<br>        self.location = config.get(&quot;gcp.location&quot;, &quot;us-central1&quot;)<br>        self.index_id = None<br>        self.index_endpoint = None<br>        <br>        # Initialize Matching Engine<br>        try:<br>            aiplatform.init(project=self.project_id, location=self.location)<br>            self._initialize_matching_engine()<br>        except Exception as e:<br>            logging.error(f&quot;Failed to initialize Matching Engine: {str(e)}&quot;)<br>    <br>    def _initialize_matching_engine(self):<br>        &quot;&quot;&quot;Initialize or get existing Matching Engine index.&quot;&quot;&quot;<br>        try:<br>            # Check for existing index<br>            indexes = aiplatform.MatchingEngineIndex.list()<br>            for index in indexes:<br>                if index.display_name == &quot;medical-rag-index&quot;:<br>                    self.index_id = index.name<br>                    break<br>            <br>            # Create new index if needed<br>            if not self.index_id:<br>                index = aiplatform.MatchingEngineIndex.create(<br>                    display_name=&quot;medical-rag-index&quot;,<br>                    dimensions=self.config.get(&quot;vector_db.dimensions&quot;, 768),<br>                    approximate_neighbors_count=20,<br>                    distance_measure_type=self.config.get(&quot;vector_db.distance_measure&quot;, &quot;COSINE&quot;)<br>                )<br>                self.index_id = index.name<br>            <br>            # Get or create index endpoint<br>            endpoints = aiplatform.MatchingEngineIndexEndpoint.list()<br>            for endpoint in endpoints:<br>                if endpoint.display_name == &quot;medical-rag-endpoint&quot;:<br>                    self.index_endpoint = endpoint<br>                    break<br>            <br>            if not self.index_endpoint:<br>                self.index_endpoint = aiplatform.MatchingEngineIndexEndpoint.create(<br>                    display_name=&quot;medical-rag-endpoint&quot;,<br>                    network=&quot;projects/{}/global/networks/default&quot;.format(self.project_id)<br>                )<br>            <br>            # Deploy index to endpoint if not already deployed<br>            deployed = False<br>            for deployed_index in self.index_endpoint.deployed_indexes:<br>                if deployed_index.index == self.index_id:<br>                    deployed = True<br>                    break<br>            <br>            if not deployed:<br>                self.index_endpoint.deploy_index(<br>                    index=self.index_id,<br>                    deployed_index_id=&quot;medical-rag-deployed-index&quot;<br>                )<br>            <br>            logging.info(f&quot;Matching Engine initialized with index {self.index_id}&quot;)<br>            <br>        except Exception as e:<br>            logging.error(f&quot;Error initializing Matching Engine: {str(e)}&quot;)<br>            raise</pre><h3>Compliance and Governance</h3><pre>class ComplianceService:<br>    &quot;&quot;&quot;Ensures compliance with medical data regulations.&quot;&quot;&quot;<br>    <br>    def __init__(self, config: Config):<br>        &quot;&quot;&quot;Initialize the compliance service.&quot;&quot;&quot;<br>        self.config = config<br>        self.enabled = config.get(&quot;compliance.enabled&quot;, True)<br>        self.frameworks = config.get(&quot;compliance.frameworks&quot;, [&quot;hipaa&quot;, &quot;gdpr&quot;])<br>        self.pii_detection_enabled = config.get(&quot;compliance.pii_detection.enabled&quot;, True)<br>        self.info_types = config.get(&quot;compliance.pii_detection.info_types&quot;, [])<br>        self.content_safety_enabled = config.get(&quot;compliance.content_safety.enabled&quot;, True)<br>        self.block_unsafe_content = config.get(&quot;compliance.content_safety.block_unsafe_content&quot;, True)<br>        <br>        # Initialize DLP client for PII detection<br>        self.dlp_client = None<br>        if self.pii_detection_enabled:<br>            try:<br>                from google.cloud import dlp_v2<br>                self.dlp_client = dlp_v2.DlpServiceClient()<br>                logging.info(&quot;DLP client initialized for PII detection&quot;)<br>            except Exception as e:<br>                logging.error(f&quot;Failed to initialize DLP client: {str(e)}&quot;)<br>        <br>        # Initialize Content Safety client<br>        self.safety_client = None<br>        if self.content_safety_enabled:<br>            try:<br>                from google.cloud import contentwarehouse_v1<br>                self.safety_client = contentwarehouse_v1.ContentWarehouseClient()<br>                logging.info(&quot;Content Safety client initialized&quot;)<br>            except Exception as e:<br>                logging.error(f&quot;Failed to initialize Content Safety client: {str(e)}&quot;)<br>    <br>    def check_query_compliance(self, query: str) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;Check if a user query complies with regulations.&quot;&quot;&quot;<br>        if not self.enabled:<br>            return {&quot;compliant&quot;: True, &quot;reason&quot;: &quot;Compliance checks disabled&quot;}<br>        <br>        results = {<br>            &quot;compliant&quot;: True,<br>            &quot;pii_detected&quot;: False,<br>            &quot;unsafe_content&quot;: False,<br>            &quot;pii_findings&quot;: [],<br>            &quot;safety_findings&quot;: []<br>        }<br>        <br>        # Check for PII<br>        if self.pii_detection_enabled and self.dlp_client:<br>            pii_results = self._detect_pii(query)<br>            results[&quot;pii_detected&quot;] = pii_results[&quot;pii_detected&quot;]<br>            results[&quot;pii_findings&quot;] = pii_results[&quot;findings&quot;]<br>            <br>            if pii_results[&quot;pii_detected&quot;]:<br>                results[&quot;compliant&quot;] = False<br>                results[&quot;reason&quot;] = &quot;PII detected in query&quot;<br>        <br>        # Check for unsafe content<br>        if self.content_safety_enabled and self.safety_client:<br>            safety_results = self._check_content_safety(query)<br>            results[&quot;unsafe_content&quot;] = safety_results[&quot;unsafe&quot;]<br>            results[&quot;safety_findings&quot;] = safety_results[&quot;findings&quot;]<br>            <br>            if safety_results[&quot;unsafe&quot;] and self.block_unsafe_content:<br>                results[&quot;compliant&quot;] = False<br>                results[&quot;reason&quot;] = &quot;Unsafe content detected in query&quot;<br>        <br>        return results<br>    <br>    def check_response_compliance(self, response: str) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;Check if a response complies with regulations.&quot;&quot;&quot;<br>        # Similar to query compliance but with different thresholds<br>        # ...</pre><h3>User Interface</h3><p>The React-based UI provides a clean, intuitive interface for medical support interactions</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br>import { <br>  Container, Box, Typography, TextField, Button, <br>  Paper, CircularProgress, Divider, Chip, Grid <br>} from &#39;@mui/material&#39;;<br>import { ThemeProvider, createTheme } from &#39;@mui/material/styles&#39;;<br>import ChatInterface from &#39;./components/ChatInterface&#39;;<br>import DocumentManager from &#39;./components/DocumentManager&#39;;<br>import Dashboard from &#39;./components/Dashboard&#39;;<br>import Monitoring from &#39;./components/Monitoring&#39;;<br>import Governance from &#39;./components/Governance&#39;;<br><br>const theme = createTheme({<br>  palette: {<br>    primary: {<br>      main: &#39;#1976d2&#39;,<br>    },<br>    secondary: {<br>      main: &#39;#388e3c&#39;,<br>    },<br>  },<br>});<br><br>function App() {<br>  const [activeTab, setActiveTab] = useState(&#39;chat&#39;);<br>  const [isAuthenticated, setIsAuthenticated] = useState(false);<br>  const [user, setUser] = useState(null);<br>  const [loading, setLoading] = useState(false);<br>  <br>  useEffect(() =&gt; {<br>    // Check authentication status<br>    const checkAuth = async () =&gt; {<br>      setLoading(true);<br>      try {<br>        const response = await fetch(&#39;/api/auth/status&#39;);<br>        const data = await response.json();<br>        <br>        if (data.authenticated) {<br>          setIsAuthenticated(true);<br>          setUser(data.user);<br>        }<br>      } catch (error) {<br>        console.error(&#39;Authentication check failed:&#39;, error);<br>      } finally {<br>        setLoading(false);<br>      }<br>    };<br>    <br>    checkAuth();<br>  }, []);<br>  <br>  const handleLogin = async (credentials) =&gt; {<br>    setLoading(true);<br>    try {<br>      const response = await fetch(&#39;/api/auth/login&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        },<br>        body: JSON.stringify(credentials),<br>      });<br>      <br>      const data = await response.json();<br>      <br>      if (data.success) {<br>        setIsAuthenticated(true);<br>        setUser(data.user);<br>      } else {<br>        // Handle login failure<br>      }<br>    } catch (error) {<br>      console.error(&#39;Login failed:&#39;, error);<br>    } finally {<br>      setLoading(false);<br>    }<br>  };<br>  <br>  return (<br>    &lt;ThemeProvider theme={theme}&gt;<br>      &lt;Container maxWidth=&quot;lg&quot;&gt;<br>        &lt;Box sx={{ my: 4 }}&gt;<br>          &lt;Typography variant=&quot;h4&quot; component=&quot;h1&quot; gutterBottom&gt;<br>            Medical Support Assistant<br>          &lt;/Typography&gt;<br>          <br>          {loading ? (<br>            &lt;CircularProgress /&gt;<br>          ) : isAuthenticated ? (<br>            &lt;&gt;<br>              &lt;Box sx={{ borderBottom: 1, borderColor: &#39;divider&#39;, mb: 2 }}&gt;<br>                &lt;Grid container spacing={2}&gt;<br>                  &lt;Grid item&gt;<br>                    &lt;Button <br>                      variant={activeTab === &#39;chat&#39; ? &#39;contained&#39; : &#39;outlined&#39;} <br>                      onClick={() =&gt; setActiveTab(&#39;chat&#39;)}<br>                    &gt;<br>                      Chat<br>                    &lt;/Button&gt;<br>                  &lt;/Grid&gt;<br>                  &lt;Grid item&gt;<br>                    &lt;Button <br>                      variant={activeTab === &#39;documents&#39; ? &#39;contained&#39; : &#39;outlined&#39;} <br>                      onClick={() =&gt; setActiveTab(&#39;documents&#39;)}<br>                    &gt;<br>                      Documents<br>                    &lt;/Button&gt;<br>                  &lt;/Grid&gt;<br>                  &lt;Grid item&gt;<br>                    &lt;Button <br>                      variant={activeTab === &#39;dashboard&#39; ? &#39;contained&#39; : &#39;outlined&#39;} <br>                      onClick={() =&gt; setActiveTab(&#39;dashboard&#39;)}<br>                    &gt;<br>                      Dashboard<br>                    &lt;/Button&gt;<br>                  &lt;/Grid&gt;<br>                  &lt;Grid item&gt;<br>                    &lt;Button <br>                      variant={activeTab === &#39;monitoring&#39; ? &#39;contained&#39; : &#39;outlined&#39;} <br>                      onClick={() =&gt; setActiveTab(&#39;monitoring&#39;)}<br>                    &gt;<br>                      Monitoring<br>                    &lt;/Button&gt;<br>                  &lt;/Grid&gt;<br>                  &lt;Grid item&gt;<br>                    &lt;Button <br>                      variant={activeTab === &#39;governance&#39; ? &#39;contained&#39; : &#39;outlined&#39;} <br>                      onClick={() =&gt; setActiveTab(&#39;governance&#39;)}<br>                    &gt;<br>                      Governance<br>                    &lt;/Button&gt;<br>                  &lt;/Grid&gt;<br>                &lt;/Grid&gt;<br>              &lt;/Box&gt;<br>              <br>              &lt;Box sx={{ mt: 2 }}&gt;<br>                {activeTab === &#39;chat&#39; &amp;&amp; &lt;ChatInterface user={user} /&gt;}<br>                {activeTab === &#39;documents&#39; &amp;&amp; &lt;DocumentManager user={user} /&gt;}<br>                {activeTab === &#39;dashboard&#39; &amp;&amp; &lt;Dashboard user={user} /&gt;}<br>                {activeTab === &#39;monitoring&#39; &amp;&amp; &lt;Monitoring user={user} /&gt;}<br>                {activeTab === &#39;governance&#39; &amp;&amp; &lt;Governance user={user} /&gt;}<br>              &lt;/Box&gt;<br>            &lt;/&gt;<br>          ) : (<br>            &lt;LoginForm onLogin={handleLogin} /&gt;<br>          )}<br>        &lt;/Box&gt;<br>      &lt;/Container&gt;<br>    &lt;/ThemeProvider&gt;<br>  );<br>}<br><br>export default App;</pre><p>The ChatInterface component provides the main interaction point for users</p><pre>import React, { useState, useEffect, useRef } from &#39;react&#39;;<br>import { <br>  Box, Paper, Typography, TextField, Button, <br>  CircularProgress, Avatar, Divider, Chip <br>} from &#39;@mui/material&#39;;<br>import SendIcon from &#39;@mui/icons-material/Send&#39;;<br>import AttachFileIcon from &#39;@mui/icons-material/AttachFile&#39;;<br>import HealthAndSafetyIcon from &#39;@mui/icons-material/HealthAndSafety&#39;;<br>import ReactMarkdown from &#39;react-markdown&#39;;<br><br>const ChatInterface = ({ user }) =&gt; {<br>  const [messages, setMessages] = useState([]);<br>  const [input, setInput] = useState(&#39;&#39;);<br>  const [loading, setLoading] = useState(false);<br>  const [sessionId, setSessionId] = useState(null);<br>  const messagesEndRef = useRef(null);<br>  <br>  useEffect(() =&gt; {<br>    // Initialize chat session<br>    const initSession = async () =&gt; {<br>      try {<br>        const response = await fetch(&#39;/api/chat/session&#39;, {<br>          method: &#39;POST&#39;,<br>          headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>          },<br>          body: JSON.stringify({ user_id: user.id }),<br>        });<br>        <br>        const data = await response.json();<br>        setSessionId(data.session_id);<br>        <br>        // Add welcome message<br>        setMessages([<br>          {<br>            role: &#39;assistant&#39;,<br>            content: &#39;Hello! I\&#39;m your medical support assistant. How can I help you today?&#39;,<br>            timestamp: new Date().toISOString()<br>          }<br>        ]);<br>      } catch (error) {<br>        console.error(&#39;Failed to initialize chat session:&#39;, error);<br>      }<br>    };<br>    <br>    initSession();<br>  }, [user]);<br>  <br>  useEffect(() =&gt; {<br>    // Scroll to bottom when messages change<br>    messagesEndRef.current?.scrollIntoView({ behavior: &#39;smooth&#39; });<br>  }, [messages]);<br>  <br>  const handleSendMessage = async () =&gt; {<br>    if (!input.trim() || !sessionId) return;<br>    <br>    const userMessage = {<br>      role: &#39;user&#39;,<br>      content: input,<br>      timestamp: new Date().toISOString()<br>    };<br>    <br>    setMessages(prev =&gt; [...prev, userMessage]);<br>    setInput(&#39;&#39;);<br>    setLoading(true);<br>    <br>    try {<br>      const response = await fetch(&#39;/api/chat/message&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        },<br>        body: JSON.stringify({<br>          session_id: sessionId,<br>          query: input,<br>          user_id: user.id<br>        }),<br>      });<br>      <br>      const data = await response.json();<br>      <br>      if (data.error) {<br>        // Handle error<br>        setMessages(prev =&gt; [...prev, {<br>          role: &#39;system&#39;,<br>          content: `Error: ${data.message}`,<br>          timestamp: new Date().toISOString()<br>        }]);<br>      } else {<br>        // Add assistant response<br>        setMessages(prev =&gt; [...prev, {<br>          role: &#39;assistant&#39;,<br>          content: data.response,<br>          timestamp: data.timestamp,<br>          metadata: data.metadata<br>        }]);<br>      }<br>    } catch (error) {<br>      console.error(&#39;Failed to send message:&#39;, error);<br>      setMessages(prev =&gt; [...prev, {<br>        role: &#39;system&#39;,<br>        content: &#39;Sorry, there was an error processing your request. Please try again.&#39;,<br>        timestamp: new Date().toISOString()<br>      }]);<br>    } finally {<br>      setLoading(false);<br>    }<br>  };<br>  <br>  return (<br>    &lt;Box sx={{ display: &#39;flex&#39;, flexDirection: &#39;column&#39;, height: &#39;70vh&#39; }}&gt;<br>      &lt;Paper <br>        elevation={3} <br>        sx={{ <br>          flex: 1, <br>          mb: 2, <br>          p: 2, <br>          overflowY: &#39;auto&#39;,<br>          display: &#39;flex&#39;,<br>          flexDirection: &#39;column&#39;<br>        }}<br>      &gt;<br>        {messages.map((msg, index) =&gt; (<br>          &lt;Box <br>            key={index}<br>            sx={{<br>              display: &#39;flex&#39;,<br>              justifyContent: msg.role === &#39;user&#39; ? &#39;flex-end&#39; : &#39;flex-start&#39;,<br>              mb: 2<br>            }}<br>          &gt;<br>            &lt;Box<br>              sx={{<br>                display: &#39;flex&#39;,<br>                maxWidth: &#39;70%&#39;,<br>                flexDirection: msg.role === &#39;user&#39; ? &#39;row-reverse&#39; : &#39;row&#39;,<br>                alignItems: &#39;flex-start&#39;<br>              }}<br>            &gt;<br>              &lt;Avatar <br>                sx={{ <br>                  bgcolor: msg.role === &#39;assistant&#39; ? &#39;primary.main&#39; : &#39;secondary.main&#39;,<br>                  mr: msg.role === &#39;user&#39; ? 0 : 1,<br>                  ml: msg.role === &#39;user&#39; ? 1 : 0<br>                }}<br>              &gt;<br>                {msg.role === &#39;assistant&#39; ? &lt;HealthAndSafetyIcon /&gt; : user.name.charAt(0)}<br>              &lt;/Avatar&gt;<br>              &lt;Paper<br>                elevation={1}<br>                sx={{<br>                  p: 2,<br>                  bgcolor: msg.role === &#39;assistant&#39; ? &#39;grey.100&#39; : &#39;primary.light&#39;,<br>                  color: msg.role === &#39;assistant&#39; ? &#39;text.primary&#39; : &#39;white&#39;,<br>                  borderRadius: 2<br>                }}<br>              &gt;<br>                &lt;ReactMarkdown&gt;{msg.content}&lt;/ReactMarkdown&gt;<br>                <br>                {msg.metadata &amp;&amp; msg.metadata.citations &amp;&amp; msg.metadata.citations.length &gt; 0 &amp;&amp; (<br>                  &lt;Box sx={{ mt: 1 }}&gt;<br>                    &lt;Typography variant=&quot;caption&quot; sx={{ fontWeight: &#39;bold&#39; }}&gt;<br>                      Sources:<br>                    &lt;/Typography&gt;<br>                    &lt;Box sx={{ display: &#39;flex&#39;, flexWrap: &#39;wrap&#39;, gap: 0.5, mt: 0.5 }}&gt;<br>                      {msg.metadata.citations.map((citation, idx) =&gt; (<br>                        &lt;Chip <br>                          key={idx}<br>                          label={citation.title || citation.url}<br>                          size=&quot;small&quot;<br>                          color=&quot;primary&quot;<br>                          variant=&quot;outlined&quot;<br>                          component=&quot;a&quot;<br>                          href={citation.url}<br>                          target=&quot;_blank&quot;<br>                          clickable<br>                        /&gt;<br>                      ))}<br>                    &lt;/Box&gt;<br>                  &lt;/Box&gt;<br>                )}<br>                <br>                &lt;Typography variant=&quot;caption&quot; sx={{ display: &#39;block&#39;, mt: 1, opacity: 0.7 }}&gt;<br>                  {new Date(msg.timestamp).toLocaleTimeString()}<br>                &lt;/Typography&gt;<br>              &lt;/Paper&gt;<br>            &lt;/Box&gt;<br>          &lt;/Box&gt;<br>        ))}<br>        &lt;div ref={messagesEndRef} /&gt;<br>      &lt;/Paper&gt;<br>      <br>      &lt;Box sx={{ display: &#39;flex&#39;, alignItems: &#39;center&#39; }}&gt;<br>        &lt;Button<br>          variant=&quot;outlined&quot;<br>          startIcon={&lt;AttachFileIcon /&gt;}<br>          sx={{ mr: 1 }}<br>        &gt;<br>          Attach<br>        &lt;/Button&gt;<br>        &lt;TextField<br>          fullWidth<br>          variant=&quot;outlined&quot;<br>          placeholder=&quot;Type your medical question...&quot;<br>          value={input}<br>          onChange={(e) =&gt; setInput(e.target.value)}<br>          onKeyPress={(e) =&gt; e.key === &#39;Enter&#39; &amp;&amp; handleSendMessage()}<br>          disabled={loading}<br>        /&gt;<br>        &lt;Button<br>          variant=&quot;contained&quot;<br>          endIcon={loading ? &lt;CircularProgress size={20} /&gt; : &lt;SendIcon /&gt;}<br>          sx={{ ml: 1 }}<br>          onClick={handleSendMessage}<br>          disabled={loading || !input.trim()}<br>        &gt;<br>          Send<br>        &lt;/Button&gt;<br>      &lt;/Box&gt;<br>    &lt;/Box&gt;<br>  );<br>};<br><br>export default ChatInterface;</pre><h3>Deployment</h3><p>The system can be deployed locally using Docker Compose or to GCP for production use</p><h4>Local Deployment with Docker</h4><p>The `docker-compose.yml` file defines all services required to run the complete framework locally</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  # API Gateway - Entry point for all requests<br>  api-gateway:<br>    build:<br>      context: .<br>      dockerfile: docker/api-gateway/Dockerfile<br>    ports:<br>      - &quot;8000:8000&quot;<br>    environment:<br>      - CONFIG_PATH=/app/config/medical_rag_config.yaml<br>      - LOG_LEVEL=INFO<br>      - VECTOR_DB_HOST=vector-db<br>      - AGENT_ORCHESTRATOR_HOST=agent-orchestrator<br>      - DOCUMENT_PROCESSOR_HOST=document-processor<br>    volumes:<br>      - ./config:/app/config<br>    depends_on:<br>      - agent-orchestrator<br>      - document-processor<br>      - vector-db<br>    networks:<br>      - rag-network<br><br>  # Agent Orchestrator - Manages and coordinates agents<br>  agent-orchestrator:<br>    build:<br>      context: .<br>      dockerfile: docker/agent-orchestrator/Dockerfile<br>    ports:<br>      - &quot;8001:8001&quot;<br>    environment:<br>      - CONFIG_PATH=/app/config/medical_rag_config.yaml<br>      - LOG_LEVEL=INFO<br>      - VECTOR_DB_HOST=vector-db<br>      - GOOGLE_APPLICATION_CREDENTIALS=/app/config/gcp-credentials.json<br>    volumes:<br>      - ./config:/app/config<br>    depends_on:<br>      - vector-db<br>    networks:<br>      - rag-network<br><br>  # Additional services defined...<br><br>networks:<br>  rag-network:<br>    driver: bridge<br><br>volumes:<br>  vector-db-data:<br>  monitoring-data:</pre><p>To run the system locally</p><pre># Clone the repository<br>git clone https://github.com/yourusername/medical-rag-framework.git<br>cd medical-rag-framework<br><br># Set up GCP credentials (required for ADK and Agentspace)<br>export GOOGLE_APPLICATION_CREDENTIALS=path/to/your/credentials.json<br><br># Start the system<br>docker-compose up -d<br><br># Access the UI<br>open http://localhost:3000</pre><h3>GCP Production Deployment</h3><pre>def deploy_to_gcp(project_id, region, config_path):<br>    &quot;&quot;&quot;Deploy the complete system to GCP.&quot;&quot;&quot;<br>    # Load configuration<br>    config = load_config(config_path)<br>    <br>    # Enable required APIs<br>    enable_apis(project_id, config.get(&#39;gcp&#39;, {}).get(&#39;enable_apis&#39;, []))<br>    <br>    # Setup service account<br>    sa_email = setup_service_account(<br>        project_id, <br>        &quot;medical-rag-sa&quot;,<br>        [<br>            &#39;roles/aiplatform.user&#39;,<br>            &#39;roles/storage.admin&#39;,<br>            &#39;roles/logging.admin&#39;,<br>            &#39;roles/monitoring.admin&#39;,<br>            &#39;roles/run.admin&#39;<br>        ]<br>    )<br>    <br>    # Deploy services<br>    api_gateway_url = deploy_api_gateway(project_id, region, sa_email, config)<br>    agent_orchestrator_url = deploy_agent_orchestrator(project_id, region, sa_email, config)<br>    document_processor_url = deploy_document_processor(project_id, region, sa_email, config)<br>    # Deploy additional services...<br>    <br>    # Deploy web UI<br>    web_ui_url = deploy_web_ui(<br>        project_id, <br>        region, <br>        sa_email, <br>        api_gateway_url, <br>        monitoring_url<br>    )<br>    <br>    return {<br>        &quot;web_ui_url&quot;: web_ui_url,<br>        &quot;api_gateway_url&quot;: api_gateway_url<br>    }</pre><h3>Deploy to GCP</h3><pre># Clone the repository<br>git clone https://github.com/yourusername/medical-rag-framework.git<br>cd medical-rag-framework<br><br># Install dependencies<br>pip install -r requirements.txt<br><br># Deploy to GCP<br>python scripts/deploy_to_gcp.py \<br>  --project-id your-gcp-project \<br>  --region us-central1 \<br>  --config config/medical_rag_config.yaml \<br>  --deploy-all</pre><h3>Conclusion</h3><p>This implementation provides a comprehensive, production-ready medical RAG system that leverages Google’s latest agent technologies. The system addresses the unique challenges of medical information retrieval and generation, including strict compliance requirements, high accuracy demands, and seamless agent coordination.</p><p>Key advantages of this approach include:</p><ol><li>Modular architecture that allows for easy extension and customization</li><li>Robust compliance framework for handling sensitive medical information</li><li>Multi-agent coordination using Google’s Agent Development Kit</li><li>Comprehensive evaluation of response quality and medical correctness</li><li>Cost optimization while maintaining high-quality responses</li></ol><p>By following this implementation guide, you can build a medical RAG system that provides accurate, contextual, and compliant medical information to users.</p><h3>Next Steps</h3><p>To further enhance the system, consider:</p><ol><li>Adding specialized medical agents for specific domains (cardiology, oncology, etc.)</li><li>Implementing human-in-the-loop workflows for critical medical advice</li><li>Expanding the evaluation framework with domain-specific metrics</li><li>Integrating with electronic health record systems for personalized support</li><li>Developing mobile applications for on-the-go medical support</li></ol><p>The complete source code for this implementation is available on [GitHub](<a href="https://github.com/sauravGit/medical-rag-framework">https://github.com/sauravGit/medical-rag-framework</a>)</p><p><strong>Disclaimer</strong>: This system is designed to provide informational support only and should not be used as a substitute for professional medical advice, diagnosis, or treatment. Always seek the advice of qualified healthcare providers with any questions you may have regarding medical conditions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5337b715f875" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/building-a-medical-rag-system-with-googles-agent-technologies-a-complete-implementation-guide-5337b715f875">Building a Medical RAG System with Google’s Agent Technologies: A Complete Implementation Guide</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Multimodal Mastery: Configuring Gemma 3 for Diverse Inputs]]></title>
            <link>https://medium.com/@SauravEvan/%EF%B8%8F-multimodal-mastery-configuring-gemma-3-for-diverse-inputs-3febc34998d4?source=rss-803008333c2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3febc34998d4</guid>
            <dc:creator><![CDATA[Saurav Paul]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 03:48:05 GMT</pubDate>
            <atom:updated>2025-04-17T04:03:13.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*9qL3KLfB1f1PPRgJ.png" /></figure><h3>Introduction: The Future Is Multimodal</h3><p>AI models are no longer confined to just text. Today’s most powerful systems handle <strong>text, images, and even more modalities</strong> — together. Google’s <strong>Gemma 3</strong> rises to the challenge with a multimodal variant designed for developers and researchers building rich, multi-format AI applications.</p><p>In this guide, we’ll walk through <strong>how to configure Gemma 3 for multimodal input</strong>, from choosing the right model to setting up vLLM and handling image + text requests through the API.</p><h3>1. 🧠 Choosing the Right Gemma 3 Variant</h3><p>Not all Gemma 3 models are created equal—especially when it comes to handling multiple input types.</p><h3>🔍 Look for Multimodal-Specific Models</h3><p>For text + image tasks, select a variant explicitly built for multimodal processing.</p><pre>env_vars = {<br>    &quot;MODEL_ID&quot;: &quot;google/gemma-3-4b-multimodal&quot;,<br>    &quot;HF_TOKEN&quot;: &quot;your-hf-token&quot;<br>}</pre><h3>✅ Why This Matters</h3><ul><li>Multimodal variants are <strong>optimized with specialized layers</strong> for image embeddings. These models typically include <strong>visual preprocessing capabilities</strong> such as CLIP or similar encoders. Ensures you won’t run into compatibility issues when feeding image data alongside text.</li></ul><h3>2. ⚙️ Setting Up vLLM for Multimodal Serving</h3><p>The serving layer needs to support both text and image flows. Let’s customize vLLM with the right flags:</p><h3>🛠️ Sample Configuration</h3><pre>vllm_args = [<br>    &quot;--model=gs://vertex-model-garden-.../gemma-3-4b-multimodal&quot;,<br>    &quot;--max-model-len=32768&quot;,<br>    &quot;--enable-chunked-prefill&quot;,<br>    &quot;--enable-prefix-caching&quot;,<br>    &quot;--image-input-preprocessor=clip&quot;<br>]</pre><h3>Key Settings Explained:</h3><p>--max-model-len=32768: Gives enough room for both <strong>text tokens and image embeddings</strong>.</p><p>--image-input-preprocessor=clip: Performs necessary <strong>image transformations</strong> before they hit the model.</p><h3>3. 🗨️ Sending Text + Image Inputs via the API</h3><p>Gemma 3’s <strong>ChatCompletion API</strong> now supports multimodal messages. Here’s how to structure a basic request:</p><h3>🧩 Example Request</h3><pre>response = client.chat.completions.create(<br>    model=&quot;google/gemma-3-4b-multimodal&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Describe this image:&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: {&quot;type&quot;: &quot;image&quot;, &quot;data&quot;: &quot;base64_encoded_image&quot;}}<br>    ],<br>    temperature=0.7<br>)</pre><h3>📸 Tips for Image Inputs</h3><p>Use <strong>base64 encoding</strong> for image data.Resize or <strong>preprocess images</strong> to match Gemma’s expected schema (check model documentation).Batch multiple images if needed, ensuring <strong>format compatibility</strong> across payloads.</p><h3>4. 🚀 Deployment Best Practices</h3><p>Multimodal inference demands <strong>more horsepower</strong> — especially GPU power.</p><h3>⚡ Optimize for Performance:</h3><ul><li>Use GPU-heavy instances like a3-highgpu-2g (or better).</li><li>Monitor <strong>VRAM utilization</strong>, especially during high-throughput serving.</li><li>Tune batch_size, precision_mode, and other <strong>performance toggles</strong> as per Gemma’s model card.</li></ul><h3>Conclusion: Building Multimodal Magic</h3><p>Gemma 3 gives you the <strong>freedom to build with words and visuals</strong>, opening the door to richer AI experiences — from image captioning to hybrid chat interfaces.</p><h3>✅ Key Takeaways:</h3><p>Use <strong>multimodal variants</strong> of Gemma 3 for text + image processing.Configure vLLM with appropriate model length and preprocessors.Structure API requests correctly using <strong>base64 image encoding</strong>.Deploy with GPU-backed infrastructure for optimal results.</p><p>Whether you’re fine-tuning applications, experimenting with visual tasks, or optimizing cloud deployments, Gemma 3 on Vertex AI is <strong>your gateway to cutting-edge multimodal development</strong>.</p><p>🧪 Have you tried building a multimodal app with Gemma 3? Share your experience or questions in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3febc34998d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>