<?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 Guruprasad Seeryada on Medium]]></title>
        <description><![CDATA[Stories by Guruprasad Seeryada on Medium]]></description>
        <link>https://medium.com/@guruprasad.seeryada?source=rss-9704be97d188------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*D23ryXfH6uub5lYa</url>
            <title>Stories by Guruprasad Seeryada on Medium</title>
            <link>https://medium.com/@guruprasad.seeryada?source=rss-9704be97d188------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:34:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guruprasad.seeryada/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[Your voice AI demo won’t survive production. Here’s what actually ships.]]></title>
            <link>https://medium.com/@guruprasad.seeryada/your-voice-ai-demo-wont-survive-production-here-s-what-actually-ships-cc34be4737ea?source=rss-9704be97d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc34be4737ea</guid>
            <category><![CDATA[amazon-connect]]></category>
            <category><![CDATA[voice-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[contact-center]]></category>
            <dc:creator><![CDATA[Guruprasad Seeryada]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 02:24:08 GMT</pubDate>
            <atom:updated>2026-07-02T02:24:08.236Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Every enterprise has a voice AI demo. None of them handle 25,000 calls a day. The gap between demo and production is where projects die.</em></p><p>There are 500,000 customers you’ll never call. At $10 per human agent conversation, mass outbound dies on the spreadsheet. Renewals, cross-sell, win-back, lead qualification — the math doesn’t work beyond a few thousand contacts per day.</p><p>At $0.20 per AI conversation, it’s your highest-ROI channel.</p><p>I built an autonomous outbound voice agent that runs campaigns at scale on AWS. Real conversations, not robocalls. It failed spectacularly before it worked. Here’s what broke and how we fixed it.</p><p><strong>The architecture</strong></p><p>The traditional voice AI stack chains three models together: ASR (speech-to-text) → LLM (reasoning) → TTS (text-to-speech). Each hop adds latency. In production, the chain produces 3–5 second response times. Customers hang up after 2 seconds of silence.</p><p>The production architecture eliminates this chain entirely:</p><p><strong>Amazon Nova Sonic 2</strong> is a unified speech-to-speech model. It takes audio in and produces audio out in a single inference call. No ASR step. No TTS step. Sub-2-second response time.</p><p>The stack:</p><p>1. <strong>Amazon Connect Outbound Campaigns</strong> — TCPA-compliant dialing at scale. Handles pacing, time-of-day rules, answering machine detection, and regulatory compliance.</p><p>2. <strong>Amazon Connect Contact Flow</strong> — Routes the answered call to the AI agent. Manages conversation state and escalation to humans.</p><p>3. <strong>Amazon Nova Sonic 2</strong> — Bidirectional streaming audio. Understands tone, manages interruptions, fills silence with natural fillers (“let me check that for you…”).</p><p>4. <strong>Amazon Bedrock</strong> — Tool calling for enterprise data lookup (RAG against customer records, policy details, account status). Grounds every response in real data.</p><p>5. <strong>Amazon Bedrock Guardrails</strong> — Real-time PII redaction, off-topic blocking, compliance enforcement. Every utterance passes through guardrails before reaching the customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQWWFte0fgTIJ4VnjIfvIw.png" /></figure><p><strong>Why Nova Sonic changes the math</strong></p><p>The traditional multi-hop chain isn’t just slow. Each component is a failure point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uesQMc9EtIlELx2Bf1fVTg.png" /></figure><p>The latency difference is what separates “impressive demo” from “production system that generates revenue.” Humans tolerate 1.5 seconds of silence in natural conversation. At 3–5 seconds, they assume the line is dead.</p><p>Nova Sonic 2 fills the gap with voice fillers — natural pauses and acknowledgments that maintain conversational flow while the model reasons. The customer never hears silence.</p><p><strong>The five things that kill voice AI in production</strong></p><p>I learned these the hard way. Each one looks trivial in a demo and catastrophic at 25,000 calls per day.</p><p><strong>1. Latency causes hang-ups</strong></p><p>Demos run on warm endpoints with a single concurrent session. Production runs cold starts, thousands of concurrent sessions, and model throttling.</p><p><strong>Fix:</strong> Pre-warm Nova Sonic sessions. Start the bidirectional stream before the customer answers. When the dialer detects a human (not voicemail), the AI is already listening. First response comes in under a second.</p><p><strong>2. Hallucinations invent data</strong></p><p>An AI agent that tells a customer their policy costs $47/month when it actually costs $147/month is a compliance nightmare. In insurance, this is a regulatory violation.</p><p><strong>Fix:</strong> Bedrock Guardrails with custom denied topics + RAG-grounded responses. The agent can ONLY state facts retrieved from the customer’s actual record. If the data isn’t in the retrieval context, the agent says “let me transfer you to someone who can help with that” instead of guessing.</p><p><strong>3. PII leakage at scale</strong></p><p>The agent has access to customer records. At 25,000 calls per day, one misconfigured prompt and you’re reading someone’s SSN back to a wrong number.</p><p><strong>Fix:</strong> Bedrock Guardrails PII redaction on both input and output. SSN, credit card, date of birth — all masked before reaching the model and scrubbed from any response. Logged for audit. Zero PII in conversation transcripts.</p><p><strong>4. Compliance adds latency you didn’t budget for</strong></p><p>TCPA requires opt-in verification. State regulations vary. “Do not call” lists need real-time checking. These aren’t optional — they’re federal law.</p><p><strong>Fix:</strong> Amazon Connect Outbound Campaigns handles TCPA compliance natively. Time-of-day rules, DNC list checking, answering machine detection, and consent verification are handled by Connect before the AI ever speaks. You don’t build this. You configure it.</p><p><strong>5. “Let me speak to a human” must work instantly</strong></p><p>The AI is good but not perfect. When a customer escalates, the transfer to a human agent must be seamless. No re-authentication. No “please hold while I transfer you.” The human agent needs the full conversation context.</p><p><strong>Fix:</strong> Connect Contact Flow handles escalation natively. The conversation transcript (real-time) transfers with the call. The human agent sees everything the AI said and everything the customer said. Picks up mid-conversation.</p><p><strong>The revenue math</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AD6acHx6aHq5Fze7IA4zmw.png" /></figure><p>At $0.20 per conversation, you can call every customer in your renewal pipeline. Every lapsed policy. Every cross-sell candidate. The campaigns that were “not worth the cost” at $10/conversation become your highest-performing channel.</p><p><strong>What we measured in production</strong></p><p>After 30 days of production outbound campaigns:</p><p>- <strong>Connection rate:</strong> Same as human agents (dialer handles this, not the AI)</p><p>- <strong>Conversation completion:</strong> 73% of connected calls result in a complete conversation (vs 85% for human agents)</p><p>- <strong>Average conversation duration:</strong> 2.1 minutes (vs 4.5 minutes for human agents)</p><p>- <strong>Escalation to human:</strong> 18% of calls (target was &lt;25%)</p><p>- <strong>Customer satisfaction (post-call survey):</strong> 4.1/5 (vs 4.3/5 for human agents)</p><p>- <strong>Compliance violations:</strong> 0 (guardrails caught 47 potential PII exposures)</p><p>- <strong>Revenue per 1000 calls:</strong> Within 80% of human agent performance</p><p>The 73% completion rate was the surprise. Hang-ups happen in the first 3 seconds — before the AI even establishes rapport. Most hang-ups are people who don’t want any outbound call, human or AI. The ones who stay produce conversations nearly as effective as human agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIpRDHyQGDAIWvifNHWm8g.png" /></figure><p><strong>Guardrails in a voice context</strong></p><p>Bedrock Guardrails in a text chat is straightforward. In voice, you have additional challenges:</p><p><strong>Latency budget:</strong> Guardrails add inference time. In text, 200ms is invisible. In voice, 200ms adds to the silence gap. We run guardrails asynchronously on the generated response — the agent starts speaking while guardrails validate. If guardrails trigger mid-utterance, the agent smoothly redirects (“actually, let me rephrase that…”).</p><p><strong>False positives sound terrible.</strong> A guardrail that blocks a legitimate response creates dead air. Worse than a slightly imperfect response. Tune guardrails for precision over recall in voice contexts. Better to let a borderline response through than to create a 3-second silence.</p><p><strong>Denied topics need voice-friendly alternatives.</strong> In text, you can say “I can’t help with that.” In voice, you need a natural redirect: “That’s a great question — let me connect you with someone who specializes in that.”</p><p><strong>When to use this pattern</strong></p><p>This architecture works for:</p><p>- <strong>Outbound campaigns</strong> — renewals, cross-sell, win-back, appointment reminders, collections</p><p>- <strong>High volume</strong> — thousands of calls per day where human agents can’t scale</p><p>- <strong>Structured conversations</strong> — the AI follows a campaign script with bounded outcomes</p><p>- <strong>Compliance-heavy industries</strong> — insurance, banking, healthcare where guardrails are non-negotiable</p><p>It doesn’t work for:</p><p>- <strong>Complex advisory conversations</strong> — financial planning, claims negotiation, technical support</p><p>- <strong>Emotionally charged calls</strong> — bereavement, complaints, disputes</p><p>- <strong>Low volume, high value</strong> — if you’re making 50 calls a day, hire great people</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4gmhz8O_7YVTeOHJFPw-A.png" /></figure><p><strong>Conclusion</strong></p><p>Every enterprise has a voice AI demo. The demo uses one model, one concurrent session, and no compliance. It works perfectly in the conference room.</p><p>Production voice AI at 25,000 calls per day requires solving latency (Nova Sonic 2), compliance (Connect Outbound Campaigns), hallucination (Bedrock Guardrails + RAG), PII (guardrails redaction), and escalation (Connect Contact Flows). Each one is solvable. None of them are obvious from the demo.</p><p>The result: autonomous outbound agents that generate revenue at a fraction of human agent cost, run 24/7, and never have a bad day. Not perfect — 73% completion vs 85% for humans. But at 50x the volume and 1/50th the cost, the ROI isn’t close.</p><p><em>The views and opinions expressed in this article are my own and do not represent those of my employer. No customer-specific information is included. Metrics are generalized from production deployment patterns.</em></p><p><strong>Guruprasad Seeryada</strong> is a cloud architect with 20 years in enterprise technology. AWS Solutions Architect Professional, AWS AI Practitioner, AWS Security Specialty certified. Open source contributor to aws-samples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc34be4737ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Our multi-petabyte Iceberg table was costing $60K/month. We got it under $5K.]]></title>
            <link>https://medium.com/@guruprasad.seeryada/our-multi-petabyte-iceberg-table-was-costing-60k-month-we-got-it-under-5k-1390739d1b92?source=rss-9704be97d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/1390739d1b92</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[apache-iceberg]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Guruprasad Seeryada]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 13:50:23 GMT</pubDate>
            <atom:updated>2026-06-30T13:50:23.466Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The S3 Intelligent-Tiering clock reset problem, and the non-standard archival approach that solved it at scale.</em></p><p>A data engineering team runs a multi-petabyte Apache Iceberg table. Tens of trillions of rows. Several years of telemetry data partitioned by date. The table lives in Amazon S3 with Intelligent-Tiering enabled.</p><p>The storage bill was significant — hundreds of thousands per month across the account. The Iceberg table alone accounted for over $60K/month. Leadership asked the obvious question: can we keep this on AWS, or do we need to move it somewhere cheaper?</p><p>I found a way to get it under $5K/month. Here’s what was wrong and how we fixed it.</p><p><strong>The Intelligent-Tiering clock reset problem</strong></p><p>S3 Intelligent-Tiering is supposed to save money automatically. Objects that aren’t accessed for 30 days move to Infrequent Access. After 90 days, they move to Archive Instant Access. After 180 days, Deep Archive.</p><p>The problem: <strong>any read resets the clock.</strong> And when you query an Iceberg table, the engine reads metadata files to plan the query. Those metadata reads count as access. The tiering clock resets.</p><p>This team ran a nightly ETL job that scanned metadata across all partitions. Even though nobody had queried the 2019 data in months, the nightly job kept resetting the clock. Every object stayed in the frequent access tier. Intelligent-Tiering was active, billing was running, but nothing was actually tiering down.</p><p>Over $60K/month for data that nobody was reading. The tiering logic that should have saved them was being defeated by their own pipeline.</p><p><strong>Why standard approaches don’t work at this scale</strong></p><p>The obvious answer is “just move old partitions to Glacier.” But Iceberg tables don’t work like flat file sets.</p><p><strong>Problem 1: Iceberg metadata references every file. </strong>You can’t move data files to Glacier independently because Iceberg’s metadata catalog still points to them. If a query hits those partitions, it expects the files to be instantly readable. Glacier objects need restoration first. The query fails.</p><p><strong>Problem 2: You can’t just delete old partitions.</strong> Regulatory requirements mandated 7-year retention. The data had to stay. It had to be queryable on demand (with acceptable delay). But it didn’t need to be queryable in milliseconds.</p><p><strong>Problem 3: Lifecycle rules don’t understand Iceberg partitions.</strong> S3 Lifecycle rules work on prefixes and object tags. They don’t understand Iceberg’s partition structure. You’d need to map every partition’s file paths to lifecycle rules — fragile and unmaintainable at 46 trillion rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKeHrkJFk0fYHTJ_nxMhAQ.png" /></figure><p><strong>The solution: partition-aware archival with Iceberg table properties</strong></p><p>The approach separates hot and cold data at the Iceberg partition level, not the S3 object level.</p><p><strong>Step 1: Identify cold partitions.</strong> Query the Iceberg metadata to find partitions with zero reads in the last 90 days. For this dataset, everything older than two years was cold. That’s roughly 80% of the data by volume.</p><p><strong>Step 2: Compact cold partitions.</strong> Run AWS Glue compaction on cold partitions to consolidate small files into large ones. Fewer files = fewer metadata entries = lower Glacier retrieval cost when needed. We went from millions of small Parquet files to thousands of large ones per partition.</p><p><strong>Step 3: Move cold data files to Glacier Deep Archive.</strong> Use S3 Batch Operations to transition the compacted files to Glacier Deep Archive. This is the big savings: Deep Archive costs $0.00099/GB vs $0.023/GB for Standard.</p><p><strong>Step 4: Update Iceberg metadata to mark cold partitions.</strong> Add a custom table property that flags archived partitions. Queries against these partitions return a clear error (“data archived, request restoration”) instead of a cryptic Glacier timeout.</p><p><strong>Step 5: Stop the clock-reset pipeline.</strong> Modify the nightly ETL to skip metadata scans on archived partitions. The job only touches hot partitions (2023–2024). No more clock resets on cold data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlubpJgo0GpQzydXXqCdQw.png" /></figure><p><strong>The compaction step matters more than you think</strong></p><p>Before archival, the cold partitions contained millions of small Parquet files (many under 10 MB). This is typical for streaming ingestion workloads that write frequently in small batches.</p><p>Small files in Glacier Deep Archive means expensive restoration. Each file requires a separate restore request. At $0.02 per request and millions of files, a restore could cost more than a year of storage.</p><p>Compaction consolidated files into 256 MB–1 GB chunks. Fewer files means:</p><p>- Cheaper restoration when needed</p><p>- Fewer Iceberg metadata entries (faster query planning on hot partitions)</p><p>- Lower S3 request costs during the transition</p><p>We used AWS Glue with Iceberg’s built-in compaction:</p><pre>spark.sql(&quot;&quot;&quot;<br>CALL system.rewrite_data_files(<br>table =&gt; &#39;telemetry_db.events&#39;,<br>strategy =&gt; &#39;sort&#39;,<br>sort_order =&gt; &#39;event_date&#39;,<br>where =&gt; &#39;event_date &lt; &quot;2023–01–01&quot;&#39;,<br>options =&gt; map(<br>&#39;target-file-size-bytes&#39;, &#39;268435456&#39;,<br>&#39;max-concurrent-file-group-rewrites&#39;, &#39;10&#39;<br>)<br>)<br>&quot;&quot;&quot;)</pre><p>This took about 72 hours on a Glue 4.0 job with 200 DPUs. At $0.44/DPU-hour, the compaction cost ~$6,300. That’s 3 days of the old monthly bill. Paid for itself before the next billing cycle.</p><p><strong>Results</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sFZ-TkPrm8I2ghdZHeSsBQ.png" /></figure><p>The freed budget drove reinvestment. Within three months the team adopted new ETL workloads, grew compute capacity, and started using AI/ML services they couldn’t justify before. They went from “should we leave AWS” to “what else can we build.”</p><p><strong>What I’d do differently</strong></p><p><strong>Start with compaction.</strong> I spent two weeks on the archival approach before realizing that compaction alone would have reduced metadata overhead and improved tiering behavior. Compact first, then archive.</p><p><strong>Use S3 Lifecycle rules with object tags instead of Batch Operations.</strong> We used Batch Operations for the initial transition, but ongoing management is easier with lifecycle rules. Tag objects at write time with `partition_year`. Set lifecycle rules per tag. New cold partitions auto-archive without intervention.</p><p><strong>Monitor the tiering clock explicitly.</strong> CloudWatch doesn’t expose per-object tier transitions. We built a Lambda that samples object storage classes weekly and publishes custom metrics. This catches clock-reset regressions immediately.</p><p><strong>Document the restoration procedure on day one. </strong>Someone will need that 2019 data for an audit. The restoration request, wait time, and cost should be documented before anyone needs it under pressure.</p><p><strong>When this pattern applies</strong></p><p>This approach works when:</p><p>- Your Iceberg table has a clear time-based partition key</p><p>- Older partitions are rarely or never queried</p><p>- Regulatory retention requires keeping the data (can’t delete)</p><p>- Acceptable to wait 12–48 hours for cold data access</p><p>- The table is large enough that storage cost matters ($10K+/mo)</p><p>It doesn’t work when:</p><p>- All partitions get regular query traffic (no cold data exists)</p><p>- Instant access to historical data is required (use Intelligent-Tiering with a different pipeline)</p><p>- The table is small enough that the engineering effort exceeds the savings</p><p><strong>Conclusion</strong></p><p>The S3 Intelligent-Tiering clock reset is a subtle problem. It looks like tiering is working. You’re paying for the feature. But if your pipeline touches metadata on every run, nothing actually tiers down. At multi-petabyte scale, that’s tens of thousands per month in wasted potential.</p><p>The fix is partition-aware archival: compact cold data, move it to Glacier Deep Archive, update Iceberg metadata, and stop touching what you’re not reading. Ninety-five percent cost reduction. Hundreds of thousands per year back in the budget.</p><p>The data still exists. It’s still queryable (with a restoration delay). It’s still on AWS. And the team that was evaluating alternatives is now building new workloads with the savings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5g0iN-WZrPZJw15McYBdQ.png" /></figure><p><em>The views and opinions expressed in this article are my own and do not represent those of my employer. No customer-specific information is included. Numbers are generalized from real implementation patterns.</em></p><p><strong>Guruprasad Seeryada</strong> is a cloud architect with 20 years in enterprise technology. AWS Solutions Architect Professional, AWS AI Practitioner, AWS Security Specialty certified. Open source contributor to aws-samples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1390739d1b92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimize Amazon Bedrock Guardrails for high-throughput workloads]]></title>
            <link>https://medium.com/@guruprasad.seeryada/optimize-amazon-bedrock-guardrails-for-high-throughput-workloads-776efb7ade45?source=rss-9704be97d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/776efb7ade45</guid>
            <category><![CDATA[high-throughput]]></category>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[agent-guardrails]]></category>
            <category><![CDATA[optimize]]></category>
            <category><![CDATA[amazon-bedrock]]></category>
            <dc:creator><![CDATA[Guruprasad Seeryada]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 13:49:32 GMT</pubDate>
            <atom:updated>2026-08-12T21:43:45.881Z</atom:updated>
            <content:encoded><![CDATA[<p>by Guruprasad Seeryada</p><p><strong>Introduction</strong></p><p>Amazon Bedrock Guardrails throughput has a way of becoming a bottleneck faster than teams expect, especially once you are chasing a high-throughput workload. Once your centralized AI gateway is serving thousands of users and you have chosen to route every request flowing through that gateway to the <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html">Amazon Bedrock Guardrails</a> API, the service quotas start to push back, and what felt like plenty of headroom during a proof of concept turns into throttling in production.</p><p>This post walks through three techniques that address that problem together: content block batching, intelligent caching, and selective application. Applied as a set, they can cut your API calls substantially while keeping full compliance coverage over your traffic. The reduction percentages quoted throughout are estimates rather than guarantees, because how much you save depends heavily on your own content mix of repeated versus unique text, so treat the numbers here as a starting point and measure your own with the companion test suite.</p><p>By the end you will have an architecture pattern to reason about, working code you can lift straight from the <a href="https://github.com/svguruprasad/guardrails-batch-test">companion GitHub repo</a>, where `guardrail_optimizer.py` implements all three techniques and `test_batch.py` validates the batching behavior against your own guardrail, and a monitoring strategy you can put in place the same day.</p><p><strong>Solution overview</strong></p><p>Enterprise AI platforms tend to route their LLM traffic through a centralized gateway. Once you decide to apply guardrails to the requests flowing through that gateway, two <a href="https://console.aws.amazon.com/servicequotas/home/services/bedrock/quotas">service quotas</a> start to matter.</p><p>The first is requests per second, or RPS, which is the number of `ApplyGuardrail` API calls you make each second. This quota is adjustable, so you can request an increase when you need one.</p><p>The second is text units per second, or TUPs, which measures the volume of text processed each second, where one text unit equals 1,000 characters. This quota has a hard limit per region, so you cannot raise your way out of it.</p><p>The important thing to understand is that these are independent limits with different error messages behind them. An RPS throttle returns a request-level throttle message, while a TUPs throttle returns a text-units-per-second limit message, and it is a common misconception that the two are the same throttle. They are not, and fixing one can quietly make the other worse. Chunking a large input into smaller pieces, for example, reduces the text units in any single call but increases the number of calls you make, so you need strategies that address both limits at the same time rather than trading one for the other.</p><p>Here is the optimized request flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*E7K_4fknupfi25mYf9sZ0A.png" /></figure><p>Every step in that flow reduces what actually reaches the API. The cache check eliminates repeated content such as system prompts you have already evaluated and RAG context you have seen before. The selective filter skips content that does not need evaluation at all, like tool output from trusted internal systems. Batching then combines whatever is left into a single API call. Each technique stacks on the ones before it, and the order matters, so you want to cache first because it is the cheapest check, then filter, and finally batch whatever remains.</p><p>Each technique stacks on the others. The order matters: cache first (cheapest check), then filter, then batch what remains.</p><p><strong>Content block batching</strong></p><p>Content block batching sends multiple text chunks in one API call instead of many separate calls, and it directly reduces your RPS consumption.</p><p>Consider a 10,000 character document that needs chunking. Without batching, that is ten chunks of 1,000 characters each, which means ten separate `ApplyGuardrail` calls. At 500 requests per second through your gateway you would need 5,000 RPS of quota, and most accounts start well below that. The good news is that the <a href="https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ApplyGuardrail.html">ApplyGuardrail</a> API accepts an array of content blocks in a single request, so those same ten chunks travel in one call and consume one request instead of ten. It is worth understanding what the response gives you back before you rely on it, because if any block violates a policy the guardrail intervenes on the whole call, and the verdict you receive is aggregated across the batch rather than broken out block by block. We will come back to that behavior in the Testing and results section, since it shapes how you design around it.</p><p>One limit is worth keeping in mind. A single `ApplyGuardrail` request is capped at 1,000 text units, roughly a million characters, of content-filter processing on the Standard tier, and its throughput is metered separately as text units per second. An oversized request is rejected outright with a `ValidationException` rather than throttled, which is itself another reason to chunk large inputs before you send them.</p><p>In practice this means you split your text into chunks aligned to text unit boundaries of 1,000 characters each, wrap each chunk as a content block, and send the whole array in one call. Keep in mind that the response comes back aggregated across the batch. You get a single top-level `action` and one combined assessment for the call, not a separate assessment for each block. If your workflow needs to know exactly which chunk tripped the guardrail, you will have to re-evaluate the flagged content in a follow up call, because the batched response does not attribute the violation to a specific block for you.</p><pre>def apply_guardrail_batched(text, guardrail_id, guardrail_version):<br>chunks = [text[i:i+1000] for i in range(0, len(text), 1000)]<br>content_blocks = [{&quot;text&quot;: {&quot;text&quot;: chunk}} for chunk in chunks]<br>response = bedrock_runtime.apply_guardrail(<br>guardrailIdentifier=guardrail_id,<br>guardrailVersion=guardrail_version,<br>source=&quot;INPUT&quot;,<br>content=content_blocks<br>)<br>return response</pre><p>See the full implementation with error handling in the <a href="https://github.com/svguruprasad/guardrails-batch-test">GitHub repo</a>.</p><p>The main win from batching lands on requests per second rather than text units per second, and it is worth being precise about why. You are still sending the same underlying text, so the bulk of your text-unit consumption does not disappear just because you batched. What does change is the rounding. Because text units round up on every individual call, sending five loosely sized chunks as five separate calls pays that rounding penalty five times over, whereas sending them together as one batched call pays it only once, so batching often shaves a little off your text-unit total as a bonus. If text units per second is the quota that is actually squeezing you, treat that saving as a pleasant side effect and lean on caching or selective application to genuinely cut the volume of text you evaluate. Batching earns its keep when you chunk large inputs, up to the per-request ceiling of 1,000 text units, so a 20,000 character document collapses from twenty API calls into one, and anything larger spreads across as many requests as the cap requires.</p><p>One caution is worth flagging before you turn this on for untrusted input. Fixed-width chunking can cut a phrase in half at a block boundary, so a banned term or a prompt-injection string that straddles two chunks may slip past detection that a single-block evaluation would have caught. When the content is untrusted, use overlapping windows or chunk on semantic boundaries rather than cutting blindly every 1,000 characters.</p><p><strong>Intelligent caching</strong></p><p>Intelligent caching stores guardrail results for repeated content so that you only pay to evaluate what is actually new, and because it removes text from the request entirely, it reduces both RPS and TUPs.</p><p>The key insight is that most of the text in an enterprise AI request is not unique. System prompts repeat identically across every call. RAG context pulled from knowledge bases recurs constantly, in the form of the same product documentation and the same policy excerpts, and really only the user’s input changes every time. Picture a gateway handling 500 requests per second. Each request carries a 2,000 character system prompt, 3,000 characters of RAG context, and 500 characters of user input. Without caching you consume 5.5 text units per request. Across the fleet that adds up to 2,750 text units per second. With caching, only the 500 characters of genuinely new user input reach the API. For a request shaped like this one, that is about a 91% cut in text volume, which is just the arithmetic of the example rather than a measured benchmark.</p><p>You implement this by hashing each content block and storing the guardrail result with a time-to-live that depends on the type of content. System prompts get a long TTL of around 24 hours because they rarely change, RAG context gets a shorter TTL of about an hour to match your knowledge base refresh cycle, and user input never gets cached at all, since it is unique and untrusted.</p><pre>SYSTEM_PROMPT_TTL = 86400 # 24 hours<br>RAG_CONTEXT_TTL = 3600 # 1 hour<br>def apply_with_cache(text, content_type, guardrail_id, version):<br>if content_type == &quot;user_input&quot;:<br>return call_guardrail(text, guardrail_id, version)<br>cached = cache.get(text)<br>if cached:<br>return cached<br>result = call_guardrail(text, guardrail_id, version)<br>ttl = SYSTEM_PROMPT_TTL if content_type == &quot;system_prompt&quot; else RAG_CONTEXT_TTL<br>cache.put(text, result, ttl=ttl)<br>return result</pre><p>See the full `GuardrailCache` class, which handles TTLs, version-keyed invalidation, and hit-rate tracking, in `<a href="https://github.com/svguruprasad/guardrails-batch-test/blob/main/guardrail_optimizer.py">guardrail_optimizer.py</a>`.</p><p>The trade-off with caching is that it demands an invalidation strategy. Whenever you update your guardrail configuration by adding a new denied topic or changing a content filter threshold, any cached results from the old version become stale, so you should include the guardrail version in your cache key and let configuration updates invalidate old entries automatically. You also need to size the cache sensibly. A gateway handling 500 unique RAG contexts an hour with a one-hour TTL only ever holds about 500 entries, which is small, but if your RAG corpus is large and diverse then your hit rate falls and the benefit shrinks with it. Caching pays off most when your workload repeats itself. Because it removes repeated text from the request entirely, your RPS and TUPs savings track your cache hit rate closely, so the more your system prompts and RAG context recur, the more you save. Measure your own hit rate with the companion suite rather than assuming a figure. If every request is entirely unique, caching will not help you.</p><p><strong>Selective application</strong></p><p>Selective application reduces the total volume of text reaching the API by skipping content that does not need evaluation in the first place, on the premise that not all content carries the same risk.</p><p>Your own team authored the system prompt, and your own internal tools generated the tool output, so spending quota to evaluate that trusted content is spending it on text that will never trigger a violation. The approach is to classify content into risk tiers and apply guardrails accordingly. High-risk content, which means user input and any model output shown to end users, always gets evaluated, while low-risk content such as system prompts you validated at deployment and tool output from trusted systems gets skipped at request time.</p><p>In practice you tag each content block by type within a request and only send the ones that genuinely need fresh evaluation. System prompts are evaluated once when you deploy them and cached from then on, tool output from trusted internal systems is skipped entirely, and user input always goes through.</p><pre>def apply_selective(request, guardrail_id, version):<br>blocks = [{&quot;text&quot;: {&quot;text&quot;: request[&quot;user_input&quot;]}}]<br>for ctx in request.get(&quot;rag_contexts&quot;, []):<br>if cache.get(ctx) is None:<br>blocks.append({&quot;text&quot;: {&quot;text&quot;: ctx}})<br># System prompts: evaluated once at deployment, cached<br># Tool outputs: trusted internal systems, skipped<br>if not blocks:<br>return {&quot;action&quot;: &quot;NONE&quot;}<br>return bedrock_runtime.apply_guardrail(<br>guardrailIdentifier=guardrail_id,<br>guardrailVersion=version,<br>source=&quot;INPUT&quot;,<br>content=blocks<br>)</pre><p>The trade-off here is that selective application reduces coverage by design, because you are deliberately choosing not to evaluate certain content. That is perfectly safe when the content comes from trusted sources you control, and it becomes risky only when a supposedly trusted source can be influenced by user input, such as a tool that echoes user text back in its output. The right discipline is to audit your selective filters regularly and confirm that the risk classification still holds as your system evolves. This technique works best when your requests mix trusted and untrusted content. A request that is mostly system prompt and RAG context with a small share of user input can skip most of its text volume, and the savings scale with the share of content you can safely treat as trusted. Measure that share for your own traffic before you count on it.</p><p>See the full `apply_selective` implementation in `<a href="https://github.com/svguruprasad/guardrails-batch-test/blob/main/guardrail_optimizer.py">guardrail_optimizer.py</a>`.</p><p>When you combine all three techniques the reductions compound on one another. Selective application reduces what enters the pipeline at all, caching eliminates the repeated content from whatever remains, and batching consolidates the rest into as few API calls as possible. Where each one lands for your workload depends on your own ratio of repeated to unique content, so lean on the companion test suite and CloudWatch to measure the combined effect before you commit to a capacity plan.</p><p><strong>Testing and results</strong></p><p>We validated these ideas with a structured experiment, and both the code and the results live in the <a href="https://github.com/svguruprasad/guardrails-batch-test">companion GitHub repository</a>. We began with the most basic check, which is whether batching actually reduces the number of API calls or whether the service quietly counts each content block as its own request. Sending five content blocks in a single `ApplyGuardrail` call and measuring the client-side call count settled it at one request rather than five. The test measures that real call count rather than asserting a hardcoded constant. You can confirm the service-side figure in Amazon CloudWatch, under the `AWS/Bedrock/Guardrails` namespace, using the `Invocations` metric.</p><p>Text-unit consumption is where the experiment surprised us. The `ApplyGuardrail` response reports consumption per policy type, in fields such as `contentPolicyUnits` and `topicPolicyUnits`, and there is no single catch-all `textUnits` field, so the test sums the per-policy fields to arrive at a comparable number. We expected batching to be neutral on text volume, on the reasoning that you are sending the same characters either way. What we actually observed was that batching consumed fewer text units rather than the same amount. The reason comes down to rounding. Text units round up on every individual call. Five 1,500 character blocks sent as five separate calls bill two units apiece, for a total of ten. Those same five blocks sent together in one batched call round once over the concatenated content and bill only eight. The per-call rounding penalty gets paid once instead of five times. The practical takeaway is that batching quietly helps with both quotas at once, cutting your request count outright and trimming a little off your text-unit total whenever your chunks do not fall on exact 1,000 character boundaries.</p><p>The detection test is the one that matters most for production use, and it is also the one that corrected an assumption we had walked in with. We embedded a policy violation in one block and left clean text in the other, sent both together in a single batched call, and confirmed that the guardrail intervened and told us which policy had fired. What it did not tell us was which block was responsible. The response came back as a single aggregated assessment for the whole call rather than one assessment per block. Batching couples the verdict together, so a single offending block is enough to flip the entire call to `GUARDRAIL_INTERVENED`, and you learn that the batch was flagged and which policy caught it without learning which chunk actually carried the problem. That is reassuring in one sense, because a bad block is never quietly hidden inside a batch, but it does mean that when you need to pinpoint the offending chunk you have to re-run the flagged batch as smaller calls and narrow it down yourself.</p><p>Batching also reduces latency by eliminating the per-call overhead of connection setup, request serialization, and round trips across what would otherwise be many separate requests. If you want to quote a speedup number, measure it in your own environment, and warm the client and average several runs first. A cold opening burst that includes SDK initialization, TLS setup, and credential resolution inflates the per-call time of the sequential path and will overstate the ratio. Commit the generated `batch-test-results-*.json` file alongside any figure you cite so that the number stays reproducible.</p><p>These are measurable numbers rather than theoretical ones, so run the suite yourself from the <a href="https://github.com/svguruprasad/guardrails-batch-test">GitHub repo</a> and validate the behavior against your own guardrail configuration.</p><p>After you deploy these techniques, track these <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html">Amazon CloudWatch</a> metrics for your guardrails in the `AWS/Bedrock` namespace via the <a href="https://console.aws.amazon.com/cloudwatch/home">CloudWatch console</a>:</p><p><strong>InvocationThrottles (Sum)</strong>, This should drop toward zero. If it doesn’t, your batching or caching isn’t catching enough traffic.</p><p><strong>TextUnitCount (Sum)</strong>, Should decrease proportionally to your caching and selective application hit rates.</p><p><strong>Invocations (Sum)</strong>, Should decrease proportionally to batching and caching combined.</p><p>Add client-side metrics too. Track your cache hit rate, target above 60% for enterprise workloads. Track requests skipped by selective application to measure how much low-risk content you’re filtering. Track average content blocks per batched call, higher means more RPS savings.</p><p><strong>Best practices</strong></p><p>Start with caching, because it delivers the highest impact for the lowest complexity.</p><p>Invalidate on guardrail changes by including the guardrail version number in your cache key, so that when you update your guardrail configuration the cached results from the old version fall out automatically instead of lingering as stale verdicts.</p><p>Never cache user input. It is unique and untrusted, so it should always be evaluated fresh.</p><p>Test with production traffic patterns, because the impact of these optimizations depends entirely on your content mix, and lean on <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-harmful-content-handling-options.html">guardrails detect model</a> so you can measure the effect without blocking real requests while you tune.</p><p>Audit your selective filters regularly. Review which content types you have chosen to exclude and confirm that the risk classification behind that choice still holds.</p><p>Consider multi-region distribution. Quotas are enforced per region, so distributing traffic across regions gives you close to linear scaling of both the RPS and TUPs limits. Check where the service is available on the <a href="https://docs.aws.amazon.com/general/latest/gr/bedrock.html">Amazon Bedrock endpoints page</a>.</p><p><strong>Clean up</strong></p><p>If you created a test guardrail while following this post, delete it to avoid unintended usage:</p><p>1. Open the <a href="https://console.aws.amazon.com/bedrock/home#/guardrails">Amazon Bedrock Guardrails console</a>.</p><p>2. Select the guardrail you created for testing.</p><p>3. Choose <strong>Delete</strong> and confirm.</p><p>No other resources need cleanup. The Python code runs locally and doesn’t create AWS resources.</p><p><strong>## Conclusion</strong></p><p>You do not have to choose between safety guardrails and high throughput. Content block batching, intelligent caching, and selective application together cut your `ApplyGuardrail` API calls substantially, with the exact amount depending on your content mix, and batching brings a latency benefit on top of that by removing per-call overhead.</p><p>These techniques do their best work inside centralized AI gateway architectures. In that setting, repeated content like system prompts and RAG context usually makes up a large share of the text volume, and caching alone eliminates most of it. Your starting point depends on which quota is binding, so reach for batching when RPS is the bottleneck, caching when TUPs is the constraint, and all three when both are under pressure. For most enterprise workloads the honest answer is all three together, introduced in the order that returns the most for the least effort. Start with caching for its high impact and low complexity, add batching next because it is straightforward, and finish with selective application, which asks you to do the risk classification work.</p><p>Getting started takes only an AWS account with [<a href="https://console.aws.amazon.com/bedrock/home">Amazon Bedrock</a>]() access and a few minutes with the <a href="https://github.com/svguruprasad/guardrails-batch-test">companion repo</a>. The code samples use Python and boto3.</p><pre>git clone https://github.com/svguruprasad/guardrails-batch-test<br>cd guardrails-batch-test<br>pip install -r requirements.txt<br>export AWS_PROFILE=your-profile # credentials with Bedrock access<br>python3 setup_guardrail.py # create a test guardrail, prints its ID<br>python3 test_batch.py - guardrail-id &lt;id&gt; # validate the batching behavior<br>python3 delete_guardrail.py - guardrail-id &lt;id&gt; # clean up when done</pre><p>The reusable implementations of all three techniques live in `guardrail_optimizer.py`, namely `apply_guardrail_batched`, the `GuardrailCache` class with its `apply_with_cache` helper, and `apply_selective`. From there, adopting them is a matter of working through a short sequence:</p><p>1. Add caching for system prompts and RAG context, since this single change delivers the largest immediate impact.</p><p>2. Layer in content block batching for large inputs.</p><p>3. Classify your use cases by risk tier and apply selective filtering.</p><p>4. Set up CloudWatch monitoring under `AWS/Bedrock/Guardrails` to track your RPS and TUPs reductions over time.</p><p>For quota adjustments, head to the <a href="https://console.aws.amazon.com/servicequotas/home/services/bedrock/quotas">AWS Service Quotas console</a> for Amazon Bedrock.</p><p><strong>Resources</strong></p><p>- <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html">Amazon Bedrock Guardrails documentation</a></p><p>- <a href="https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ApplyGuardrail.html">ApplyGuardrail API reference</a></p><p>- <a href="https://github.com/svguruprasad/guardrails-batch-test">Companion GitHub repository, guardrails-batch-test</a></p><p>- <a href="https://aws.amazon.com/blogs/machine-learning/build-safe-generative-ai-applications-like-a-pro-best-practices-with-amazon-bedrock-guardrails/">Build safe generative AI applications like a Pro: Best Practices with Amazon Bedrock Guardrails</a></p><p>- [Use the ApplyGuardrail API with long-context inputs and streaming outputs](https://aws.amazon.com/blogs/machine-learning/use-the-applyguardrail-api-with-long-context-inputs-and-streaming-outputs-in-amazon-bedrock/)</p><p>- <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-enforcements.html">Amazon Bedrock Guardrails cross-account safeguards</a></p><p>- <a href="https://console.aws.amazon.com/servicequotas/home/services/bedrock/quotas">Amazon Bedrock service quotas</a></p><p><em>The views and opinions expressed in this article are my own and do not represent those of my employer. This article uses only publicly available AWS documentation and open-source software. No confidential, proprietary, or customer information is included.</em></p><p><strong>About the author</strong></p><p>Guruprasad Seeryada is a cloud architect and AI practitioner with 20 years of experience in enterprise technology. He holds the AWS Solutions Architect Professional, AWS AI Practitioner, and AWS Security Specialty certifications. He is an open source contributor to AWS Samples. His work focuses on AI safety, multi-agent architectures, and cloud optimization for financial services and insurance enterprises.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=776efb7ade45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built cross-region DR for 500 virtual desktops on FSx ONTAP. Here’s what broke.]]></title>
            <link>https://medium.com/@guruprasad.seeryada/i-built-cross-region-dr-for-500-virtual-desktops-on-fsx-ontap-heres-what-broke-050c12600927?source=rss-9704be97d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/050c12600927</guid>
            <category><![CDATA[amazon-fsx]]></category>
            <category><![CDATA[virtual-desktop]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <category><![CDATA[disaster-recovery]]></category>
            <category><![CDATA[ontap]]></category>
            <dc:creator><![CDATA[Guruprasad Seeryada]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 23:34:30 GMT</pubDate>
            <atom:updated>2026-06-27T23:34:30.672Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>I built cross-region DR for 500 virtual desktops on FSx ONTAP. Here’s what broke.</strong></p><p><em>The architecture is simple. SnapMirror replicates. You break the relationship. Users reconnect. What nobody tells you is that storage failover is the easy part.</em></p><p>A team runs Citrix virtual desktops for 500 users. User profiles, home directories, and application data sit on Amazon FSx for NetApp ONTAP in us-east-1. The file system handles 1,500 MB/s at peak. Everyone’s happy.</p><p>Then someone asks: “What happens if us-east-1 goes down?”</p><p>The honest answer was “we lose everything.” No replication. No DR file system. No runbook. The only backup was nightly snapshots in the same region. A regional failure meant rebuilding 500 user environments from scratch.</p><p>I spent three weeks fixing this. Here’s what I built, what surprised me, and what I’d change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEke_B_DI0Dab23KkgPotg.png" /></figure><p><strong>The design</strong></p><p>Active-passive warm standby. One production file system in us-east-1. One DR file system in us-east-2. SnapMirror replicates between them every 15 minutes.</p><p><strong>Primary (us-east-1):</strong></p><p>- MULTI_AZ_2 deployment</p><p>- 15 TB SSD storage</p><p>- 1,536 MB/s throughput</p><p>- 81,000 IOPS (user-provisioned)</p><p>- Serves all production VDI traffic</p><p><strong>DR (us-east-2):</strong></p><p>- SINGLE_AZ_2 deployment</p><p>- 18 TB SSD storage</p><p>- 384 MB/s throughput</p><p>- Automatic IOPS</p><p>- Receives SnapMirror replication</p><p>- Read-only until activated</p><p>The DR file system sits idle. It receives block-level incremental updates from primary. It costs a fraction of running a full MULTI_AZ_2 standby. When disaster hits, you break the SnapMirror relationship and the DR volume becomes read-write.</p><p>RPO is your replication schedule. Fifteen minutes means you lose at most fifteen minutes of user data. RTO is 25–35 minutes depending on how fast you execute the failover steps (throughput scaling takes ~20 minutes).</p><p><strong>Why SINGLE_AZ_2 in DR</strong></p><p>This was the first real decision. MULTI_AZ_2 in both regions doubles your storage bill for capacity that does nothing 99.9% of the time.</p><p>SINGLE_AZ_2 cuts the standby cost significantly. The tradeoff is real: after failover, your DR file system has no AZ resilience. If you lose that single AZ during an already-active DR event, you’re out of options.</p><p>For VDI profiles, I accepted this. User profiles aren’t financial transactions. The probability of simultaneous region and AZ failure is vanishingly small. The cost savings paid for the entire DR automation effort.</p><p>If you’re storing databases or transaction logs, think twice. For user profiles and home directories, SINGLE_AZ_2 in DR is the pragmatic call.</p><p><strong>The throughput gap that nobody mentions</strong></p><p>This caught me off guard. Primary runs at 1,536 MB/s. DR was sized at 384 MB/s because it only needs enough bandwidth for SnapMirror replication during normal operation.</p><p>Then I simulated failover. 500 users logging in simultaneously. Profile loads. Application data. Home directory mounts. All hitting a file system designed for replication traffic, not production workload.</p><p>384 MB/s isn’t enough. Not even close.</p><p>Three ways to handle this:</p><p><strong>Option 1: Match throughput in DR.</strong> Safe but expensive. You’re paying for 1,536 MB/s that sits idle.</p><p><strong>Option 2: Accept degraded performance.</strong> Document it. Set expectations with leadership. “During DR, desktops will be slower.” Some organizations accept this.</p><p><strong>Option 3: Scale throughput at failover time. </strong>FSx ONTAP supports throughput modifications. Add a step to your runbook that increases DR throughput before activating user access. This adds approximately 20 minutes to your RTO but keeps standby cost low.</p><p>I went with option 3. Users can tolerate an extra 20 minutes of downtime in a genuine regional disaster. They can’t tolerate sluggish desktops for the duration of the DR event, which might be days.</p><p><strong>Active Directory: the thing that actually broke</strong></p><p>Storage replication worked perfectly. SnapMirror synced on schedule. Failover promoted the DR volume. DNS updated. Everything looked good.</p><p>Then nobody could access their files.</p><p>The problem: SMB authentication requires Active Directory. All my AD domain controllers were in us-east-1. The FSx ONTAP DR file system in us-east-2 couldn’t authenticate users because there was no AD in the DR region.</p><p>This seems obvious in retrospect. It wasn’t obvious during design.</p><p><strong>What you need in the DR region before failover works:</strong></p><p>- AD domain controllers deployed and replicating</p><p>- DNS resolution from the DR VPC to those domain controllers</p><p>- The DR file system’s Storage Virtual Machine (SVM) joined to the domain</p><p>- Security groups allowing SMB (TCP 445), LDAP (389), Kerberos (88), and DNS (53) from DR subnets</p><p>Test AD connectivity independently of storage. I spent two days debugging SnapMirror when the actual blocker was missing domain controllers in us-east-2.</p><p><strong>The DNS IP ordering bug</strong></p><p>While setting up FSx Windows File Server in the DR region (a separate workload, same pattern), I hit a provisioning failure that burned a full day.</p><p>FSx Windows uses the <strong>first</strong> DNS IP in the list to locate Active Directory. If that first IP is unreachable from the FSx subnet, creation fails with “Active Directory unreachable.” The second IP is never tried.</p><p>My Terraform template passed the DNS IPs in a different order than the console did. Console worked. Terraform failed. Same IPs, different order.</p><p>The fix was one line: reorder the DNS IP list so the reachable IP comes first. But finding this took longer than the entire SnapMirror setup.</p><p>Lesson: when provisioning FSx file systems with AD, verify that the first DNS IP in your list is reachable from the file system’s subnet. Don’t assume both IPs are equivalent.</p><p><strong>Failover procedure</strong></p><p>Failover is manual. There’s no auto-failover for FSx ONTAP SnapMirror. Here are the steps:</p><p><strong>Step 1: Scale DR throughput.</strong> Modify the file system’s throughput capacity to match production needs. Don’t skip this or your users will suffer.</p><p><strong>Step 2: Break the SnapMirror relationship.</strong> This promotes the DR volume from read-only to read-write. Data since the last successful sync is lost.</p><p><strong>Step 3: Update DNS.</strong> Point your file share records (or DFS namespace) to the DR file system endpoints. Users reconnect to us-east-2.</p><p><strong>Step 4: Validate AD auth.</strong> Confirm SMB shares are accessible. A single test mount saves you from discovering auth failures when 500 users log in simultaneously.</p><p><strong>Step 5: Open the gates.</strong> Users see a fresh desktop with profiles from the last replication point.</p><p>Estimated RTO: 25–35 minutes. Throughput scaling (~20 min) is the dominant factor.</p><p><strong>Failback: harder than failover</strong></p><p>Getting back to primary after the disaster is resolved requires reversing the replication:</p><p>1. Re-establish SnapMirror in reverse — DR becomes source, primary becomes destination</p><p>2. Wait for sync to complete — could be minutes or hours depending on how much changed during DR</p><p>3. Break the reverse relationship — primary is now current</p><p>4. Re-establish original direction — primary → DR, back to normal</p><p>5. Update DNS back to primary</p><p>6. Scale down DR throughput to idle state</p><p>Failback is complex enough to script. Manual failback under pressure leads to missed steps.</p><p><strong>Monitoring: don’t let RPO silently degrade</strong></p><p>SnapMirror can fall behind. Network congestion. Large write bursts. Storage throttling. When replication lags, your RPO increases without anyone noticing.</p><p>Set up CloudWatch alarms on SnapMirror lag time. If lag exceeds your stated RPO (say, 30 minutes for a 15-minute schedule), alert. This catches silent replication failures before they become a disaster during an actual disaster.</p><p><strong>FlexCache: the option I didn’t use</strong></p><p>If you want read-only access in the DR region without breaking SnapMirror (for secondary offices reading shared content, not for full DR), FlexCache is worth evaluating. It creates a sparse local cache of the origin volume. Reads are fast. Writes route to origin.</p><p>But FlexCache isn’t DR. When the origin region fails, FlexCache serves only what’s already cached. For disaster recovery, you need SnapMirror.</p><p><strong>What I’d do differently</strong></p><p><strong>Test AD before storage.</strong> I validated SnapMirror first because it felt like the hard part. It wasn’t. AD connectivity in the DR region was the actual gap. Test auth first, storage second.</p><p><strong>Same IaC tool for both regions.</strong> Primary was CloudFormation. DR was Terraform. Two tools for the same workload creates drift and operational confusion. Pick one. Stick with it.</p><p><strong>Document the throughput scaling step in the runbook.</strong> Make it step one, not an afterthought. An undersized DR file system passes every replication test and fails the moment real users hit it.</p><p><strong>Run a full failover and failback test monthly.</strong> Not just SnapMirror break. The whole thing: throughput scale, DNS update, AD auth, user login, then reverse it all. The first test took 45 minutes. By the third, it was under 10.</p><p><strong>Conclusion</strong></p><p>Cross-region DR for virtual desktops on FSx ONTAP is straightforward in concept. SnapMirror replicates. You break the relationship. Users reconnect.</p><p>The complexity lives in the details nobody warns you about: AD authentication in the DR region, throughput gaps between primary and standby, DNS IP ordering during provisioning, and failback sequencing under pressure.</p><p>Build it. Test it end-to-end. Test it again. A DR plan you haven’t tested is a DR plan that doesn’t work.</p><p><em>The views and opinions expressed in this article are my own and do not represent those of my employer. No customer-specific information is included. Architecture details are generalized from common VDI deployment patterns.</em></p><p><strong>Guruprasad Seeryada</strong> is a cloud architect with 20 years in enterprise technology. AWS Solutions Architect Professional, AWS AI Practitioner, AWS Security Specialty certified. Open source contributor to aws-samples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=050c12600927" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to know if swapping your RAG model broke anything]]></title>
            <link>https://medium.com/@guruprasad.seeryada/how-to-know-if-swapping-your-rag-model-broke-anything-c4eba7db3fa1?source=rss-9704be97d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4eba7db3fa1</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Guruprasad Seeryada]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 22:40:43 GMT</pubDate>
            <atom:updated>2026-06-27T22:40:43.725Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A quantitative framework that tells you whether a model migration is safe — before your customers find out it isn’t.</em></p><p>I’ve watched this play out three times in the past year. A team runs a RAG system on Claude Sonnet 3.5. Anthropic releases Sonnet 4. The team wants to upgrade for better reasoning and lower cost. Nobody can answer the question: will the new model produce equivalent responses?</p><p>The upgrade happens. Two weeks later, a compliance officer notices that policy explanations have changed. Not wrong, exactly. Different. The new model dropped a qualifier. The meaning shifted just enough to matter in insurance.</p><p>This is model migration drift. It’s silent. The system keeps running. It keeps responding. But the quality has moved and nobody measured it.</p><p>I built a framework to measure it. Three metrics, statistical testing, and a go/no-go decision. I ran it against real models on Amazon Bedrock. Here’s what I found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFlZzYwKq5F8iOREhDfC2w.png" /></figure><p><strong>The problem</strong></p><p>When you swap the foundation model in a RAG system, responses change. Some changes improve quality. Others degrade it. You can’t tell which is which by reading five examples. You need to measure across your full query set and separate real drift from the noise that every probabilistic system produces.</p><p>Manual review doesn’t scale. A production RAG system serves thousands of query patterns. You need an automated, quantitative signal.</p><p><strong>What I built</strong></p><p>A composite drift score from three independent measurements:</p><p><strong>Semantic similarity</strong> — Do the responses mean the same thing? I convert each response to a 1024-dimensional vector using Amazon Titan Text Embeddings V2 and compute cosine similarity. Two responses that convey the same meaning in different words score high. Two responses that say different things score low.</p><p><strong>Structural similarity </strong>— Do the responses use the same words? ROUGE-L computes the longest common subsequence between two responses, normalized by length. This catches cases where meaning is preserved but the format changed significantly.</p><p><strong>Factual consistency</strong> — Does the new response stay grounded in the source documents? An entailment scorer checks whether the retrieved documents support the new response. This catches hallucination that embedding similarity misses.</p><p>The three metrics combine into a weighted composite:</p><pre>D(q) = 0.40 × semantic + 0.10 × structural + 0.50 × factual</pre><p>The weights reflect insurance/finance domains where factual accuracy is paramount. For a general chatbot, you’d weight semantic similarity higher.</p><p><strong>Why three metrics instead of one</strong></p><p>Embeddings alone aren’t enough. I learned this the hard way.</p><p>Cosine similarity compresses all semantic information into a single number. Subtle factual differences — “the deductible is $500” versus “the deductible is $5,000” — can produce similar embeddings because the topic and structure are the same. The embedding model sees “deductible” + “number” + “dollars” and calls it close enough.</p><p>ROUGE-L alone penalizes legitimate paraphrasing. A model that says the same thing more concisely scores low.</p><p>Factual consistency alone misses semantic drift that doesn’t contradict the sources. A response can be factually grounded but miss the point of the question.</p><p>The composite score catches what any single metric misses.</p><p><strong>Statistical testing: separating signal from noise</strong></p><p>A single comparison isn’t enough. RAG responses are probabilistic. Run the same query twice and you get slightly different wording.</p><p>For each query, I generate multiple responses from both models (k = 5 or 10). I compute the composite score for each pair. Then I run a one-sample t-test against the threshold:</p><p>- <strong>H₀</strong>: The mean drift score meets the threshold (migration is safe)</p><p>- <strong>H₁</strong>: The mean drift score is below threshold (migration causes drift)</p><p>With Bonferroni correction for multiple queries, this keeps the false positive rate controlled across the entire test suite.</p><p>The result is a statistically rigorous answer: “This model swap is safe” or “This model swap causes measurable drift on these specific queries.”</p><p><strong>What the experiments showed</strong></p><p>I ran this against a live Amazon Bedrock Knowledge Base with insurance domain documents. Five queries, five repetitions each, threshold of 0.85.</p><p><strong>Same model against itself (baseline)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ip8RF_XspgJwF_wU3R9xMg.png" /></figure><p>All pass. No false positives. The framework correctly identifies that running the same model twice produces equivalent responses.</p><p><strong>Minor version upgrade (Sonnet 4.5 → Sonnet 4.6)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcMQgIskNIDliQDhIOsQQA.png" /></figure><p><strong>Tier: Green.</strong> All queries pass. Minor version upgrades within the same model line are safe.</p><p><strong>Same-provider tier change (Haiku 4.5 → Sonnet 4.5)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EKgzTa3g_0_1Xx8aUVm4g.png" /></figure><p><strong>Tier: Yellow.</strong> One query fails. The larger model generates more detailed procedural responses. “Filing a claim” drifted because Sonnet structures multi-step explanations differently than Haiku. Worth investigating, not worth blocking.</p><p><strong>Cross-family migration (Haiku 4.5 → Nova Lite)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gwcr34bfFzoE1KRr5XZ7TA.png" /></figure><p><strong>Tier: Red.</strong> Two queries fail significantly. Different model families structure responses differently. The t-test confirmed both failures are statistically significant (not noise). This migration needs work before it’s safe.</p><p><strong>Summary</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iDNJkCQS-BSKEEYwm3aXw.png" /></figure><p>The tiers align with intuition. Minor updates are safe. Cross-family swaps carry real risk. The framework quantifies what teams already suspect but can’t prove.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZmpkzqBVPPow_YnHuX0rA.png" /></figure><p>For regulated domains (insurance, healthcare, finance), use a threshold of 0.90 and require human review on Yellow. For general chatbots, use 0.80 and accept Yellow without review.</p><p><strong>How to set your threshold</strong></p><p>Don’t guess. Calibrate empirically:</p><p>1. Run the framework with the same model as both baseline and candidate. This measures your system’s natural variation.</p><p>2. Set threshold at the 5th percentile of the resulting scores. Natural variation won’t trigger false positives at this level.</p><p>3. Validate with a known-good migration (minor version update). Confirm it produces Green.</p><p><strong>Running it yourself</strong></p><p>The full implementation is open source:</p><p><strong>GitHub:</strong> <a href="https://github.com/aws-samples/sample-bedrock-knowledge-base-drift-detection">aws-samples/sample-bedrock-knowledge-base-drift-detection</a></p><p>The repository includes:</p><p>- Core framework: `evaluate.py`, `similarity.py`, `stats.py`, `monitor.py`</p><p>- Configuration: `config.yaml` for weights, thresholds, and model selection</p><p>- Experiments: Real results from all four migration scenarios above</p><p>- Tests: Unit tests validating the statistical methodology</p><p>Requirements: Python 3.11+, boto3, an Amazon Bedrock Knowledge Base, and access to Titan Embeddings V2.</p><p><strong>When to run this</strong></p><p>Three integration points:</p><p><strong>Before deploying a model change.</strong> Add the drift check to your CI/CD pipeline. If Red, the change doesn’t promote.</p><p><strong>On a schedule.</strong> Run weekly against production. This catches drift from knowledge base updates (new documents, revised content) even without a model change.</p><p><strong>After an incident.</strong> When someone reports incorrect responses, run the framework to quantify how far the system moved from its validated state.</p><p><strong>What this doesn’t do</strong></p><p>Embedding similarity measures distance, not correctness. Two responses can be semantically similar but one contains a factual error. Drift detection tells you something changed. It doesn’t tell you whether the change is an improvement.</p><p>For that, you still need evaluation. Amazon Bedrock Evaluations, RAGAS, or human review. The drift framework tells you <em>where</em> to look. Evaluation tells you <em>what you find</em>.</p><p><strong>Conclusion</strong></p><p>Model migration in RAG systems is a recurring operational challenge. New models offer better capabilities and lower cost. But swapping without measurement is gambling with production quality.</p><p>The composite drift score gives you a number. The statistical testing gives you confidence. The decision framework gives you a process. Run it before every model change. Catch the drift before your customers do.</p><p><em>Code: </em><a href="https://github.com/aws-samples/sample-bedrock-knowledge-base-drift-detection"><em>github.com/aws-samples/sample-bedrock-knowledge-base-drift-detection</em></a></p><p><em>The views and opinions expressed in this article are my own and do not represent those of my employer.</em></p><p><strong>Guruprasad Seeryada</strong> is a cloud architect and AI practitioner with 20 years in enterprise technology. AWS Solutions Architect Professional, AWS AI Practitioner, AWS Security Specialty certified. Open source contributor to aws-samples. His work focuses on AI reliability for financial services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4eba7db3fa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Registering custom evaluators in Amazon Bedrock AgentCore]]></title>
            <link>https://medium.com/@guruprasad.seeryada/registering-custom-evaluators-in-amazon-bedrock-agentcore-979ec021d520?source=rss-9704be97d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/979ec021d520</guid>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[production]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Guruprasad Seeryada]]></dc:creator>
            <pubDate>Thu, 28 May 2026 22:11:15 GMT</pubDate>
            <atom:updated>2026-05-28T22:11:15.355Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to extend the built-in evaluation stack with your own Lambda-based checks</em></p><p>In [<a href="https://medium.com/@guruprasad.seeryada/my-ai-agent-caused-a-sev2-in-five-days-997f8e2d6776">Part 1</a>] I covered the three-layer evaluation stack using AgentCore’s 16 built-in evaluators. In <a href="https://medium.com/@guruprasad.seeryada/building-custom-evaluators-for-ai-agents-with-aws-lambda-e9a62b6641bd">Part 2</a> I built a Lambda-based gate evaluator that runs in Step Functions.</p><p>This post connects the two. I registered that Lambda function as a custom evaluator in AgentCore’s evaluation service. It now sits alongside the 16 built-in evaluators and can be used in the same evaluation configs.</p><h4><strong>Why register a custom evaluator</strong></h4><p>Built-in evaluators handle general checks: faithfulness, tool selection accuracy, instruction following. They don’t know your business rules. “The recipient must be a contact from the active customer” or “dollar amounts must match the Cost Explorer response” are domain-specific checks that require custom logic.</p><p>You can run Lambda evaluators standalone in Step Functions (Part 2). Registering them in AgentCore gives you one additional capability: using them in online evaluation configs that score production traces automatically. Instead of gating actions synchronously, you monitor them asynchronously and alert when checks fail.</p><h4><strong>The setup</strong></h4><p>AgentCore’s evaluation service lives on the `bedrock-agentcore-control` client. The built-in evaluators are already there:</p><pre>import boto3<br>client = boto3.client(&quot;bedrock-agentcore-control&quot;, region_name=&quot;us-east-1&quot;)<br>response = client.list_evaluators()<br>evaluators = response.get(&quot;evaluatorSummaries&quot;, [])<br>print(f&quot;Total evaluators: {len(evaluators)}&quot;)</pre><p>Output from my account:</p><pre>Total evaluators: 17<br>Built-in:<br>Builtin.Correctness<br>Builtin.Faithfulness<br>Builtin.Helpfulness<br>Builtin.ResponseRelevance<br>Builtin.Conciseness<br>Builtin.Coherence<br>Builtin.InstructionFollowing<br>Builtin.Refusal<br>Builtin.GoalSuccessRate<br>Builtin.ToolSelectionAccuracy<br>Builtin.ToolParameterAccuracy<br>Builtin.Harmfulness<br>Builtin.Stereotyping<br>Builtin.TrajectoryExactOrderMatch<br>Builtin.TrajectoryInOrderMatch<br>Builtin.TrajectoryAnyOrderMatch<br>Custom:<br>GateEvaluator-cBL1AhD1DJ (status: ACTIVE)</pre><p>17 total: 16 built-in plus the custom one I registered.</p><h4><strong>Deploying the Lambda</strong></h4><p>The gate evaluator checks two things: did the user approve the action, and does the data in the output trace back to a tool call. The full code is in <a href="https://medium.com/@guruprasad.seeryada/building-custom-evaluators-for-ai-agents-with-aws-lambda-e9a62b6641bd">Part 2</a>. Here’s the Lambda handler:</p><pre>import re<br>def lambda_handler(event, context):<br>  action = event.get(&quot;action&quot;, &quot;&quot;)<br>  agent_output = event.get(&quot;agent_output&quot;, {})<br>  criteria = event.get(&quot;evaluation_criteria&quot;, [])<br>  conversation_history = event.get(&quot;conversation_history&quot;, [])<br>  tool_call_results = event.get(&quot;tool_call_results&quot;, [])<br>  results = {}<br>  all_passed = True<br>  if &quot;user_explicitly_approved_sending&quot; in criteria:<br>    approved = check_user_approval(conversation_history, action)<br>    results[&quot;user_approval&quot;] = approved<br>  if not approved:<br>    all_passed = False<br>  if &quot;no_fabricated_data_in_body&quot; in criteria:<br>    grounded = check_data_grounding(agent_output, tool_call_results)<br>    results[&quot;data_grounded&quot;] = grounded<br>  if not grounded:<br>    all_passed = False<br>  return {&quot;passed&quot;: all_passed, &quot;results&quot;: results, &quot;action&quot;: action}</pre><p>Deploy it as a standard Lambda function with Python 3.12 runtime and the <em>AWSLambdaBasicExecutionRole </em>policy.</p><h4><strong>Registering the evaluator</strong></h4><p>The <em>create_evaluator </em>API takes three required parameters:</p><p>- <em>evaluatorName</em>: a display name</p><p>- <em>level</em> : when the evaluator runs. Options are <em>SESSION</em>, <em>TRACE</em>, or <em>TOOL_CALL</em></p><ul><li><em>evaluatorConfig</em>: either <em>codeBased</em> (Lambda) or <em>llmAsAJudge</em> (model-based)</li></ul><pre>response = client.create_evaluator(<br>  evaluatorName=&quot;GateEvaluator&quot;,<br>  description=&quot;Checks user approval and data grounding before actions&quot;,<br>  level=&quot;SESSION&quot;,<br>  evaluatorConfig={<br>    &quot;codeBased&quot;: {<br>      &quot;lambdaConfig&quot;: {<br>        &quot;lambdaArn&quot;: &quot;arn:aws:lambda:us-east-1:123456789012:function:gate-evaluator&quot;<br>        }<br>      }<br>    }<br>  )</pre><p>Output:</p><pre>evaluatorArn: arn:aws:bedrock-agentcore:us-east-1:123456789012:evaluator/GateEvaluator-cBL1AhD1DJ<br>evaluatorId: GateEvaluator-cBL1AhD1DJ<br>status: ACTIVE</pre><p>The evaluator is now registered and ACTIVE. It appears in <em>list_evaluators </em>alongside the built-in ones.</p><h4><strong>Testing the Lambda directly</strong></h4><p>Before trusting the evaluator in production, invoke it directly to confirm pass and fail cases work:</p><p><strong>Pass case</strong> (user approved, data grounded):</p><pre>test_pass = {<br>  &quot;action&quot;: &quot;send_email&quot;,<br>  &quot;agent_output&quot;: {<br>  &quot;recipient&quot;: &quot;customer@example.com&quot;,<br>  &quot;body&quot;: &quot;Meeting confirmed for 2026–05–26&quot;<br>    },<br>  &quot;evaluation_criteria&quot;: [<br>  &quot;user_explicitly_approved_sending&quot;,<br>  &quot;no_fabricated_data_in_body&quot;<br>    ],<br>  &quot;conversation_history&quot;: [<br>    {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;Shall I send the email?&quot;},<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Yes, send it&quot;}<br>    ],<br>  &quot;tool_call_results&quot;: [<br>    {&quot;tool&quot;: &quot;calendar&quot;, &quot;result&quot;: &quot;2026–05–26 10:00 confirmed&quot;}<br>    ]<br>  }</pre><p>Result:</p><pre>{<br>&quot;passed&quot;: true,<br>&quot;results&quot;: {<br>&quot;user_approval&quot;: true,<br>&quot;data_grounded&quot;: true<br>},<br>&quot;action&quot;: &quot;send_email&quot;<br>}</pre><p><strong>Fail case</strong> (fabricated dollar amount):</p><pre>test_fail = {<br>  &quot;action&quot;: &quot;send_email&quot;,<br>  &quot;agent_output&quot;: {<br>  &quot;recipient&quot;: &quot;customer@example.com&quot;,<br>  &quot;body&quot;: &quot;Your spend was $99,999.99&quot;<br>    },<br>  &quot;evaluation_criteria&quot;: [<br>    &quot;user_explicitly_approved_sending&quot;,<br>    &quot;no_fabricated_data_in_body&quot;<br>      ],<br>  &quot;conversation_history&quot;: [<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Go ahead and send&quot;}<br>      ],<br>  &quot;tool_call_results&quot;: [<br>    {&quot;tool&quot;: &quot;cost_explorer&quot;, &quot;result&quot;: &quot;Monthly spend: $47,231.84&quot;}<br>    ]<br>  }</pre><p>Result:</p><pre>{<br>&quot;passed&quot;: false,<br>&quot;results&quot;: {<br>&quot;user_approval&quot;: true,<br>&quot;data_grounded&quot;: false<br>},<br>&quot;action&quot;: &quot;send_email&quot;<br>}</pre><p>The evaluator correctly identifies that $99,999.99 doesn’t appear in any tool result. The user approved sending, but the data is fabricated. Gate fails.</p><h4><strong>The evaluation levels</strong></h4><p>The <em>level</em> parameter determines when your evaluator runs:</p><p>- <strong>SESSION</strong>: evaluates the full conversation session after it completes</p><p>- <strong>TRACE</strong>: evaluates each agent reasoning trace (one turn of thought + action)</p><p>- <strong>TOOL_CALL</strong>: evaluates individual tool call inputs and outputs</p><p>I chose SESSION for the gate evaluator because it needs the full conversation history to check user approval. A TOOL_CALL level evaluator would only see the tool input/output, not the preceding conversation.</p><p>What’s next</p><p>The registered evaluator can now be referenced in <em>create_online_evaluation_config</em> to monitor production agent sessions automatically. That requires agent runtime traces in CloudWatch Logs, which I’ll cover once I have a runtime generating production traffic.</p><p>For now, the complete evaluation stack is:</p><p>- <strong>16 built-in evaluators</strong> for general quality checks</p><p>- <strong>1 custom Lambda evaluator</strong> for domain-specific business rules</p><p>- <strong>Synchronous gating </strong>via Step Functions (Part 2)</p><p>- <strong>Progressive trust</strong> for promoting actions from gated to autonomous (<a href="https://medium.com/p/ec062c8b50dd">approval paradox post</a>)</p><h4><strong>The code</strong></h4><p>Full implementation: <a href="https://github.com/svguruprasad/agents-that-work">github.com/svguruprasad/agents-that-work</a></p><p><em>The views and opinions expressed in this article are my own and do not represent those of my employer. This article uses only publicly available AWS documentation and open-source software. No confidential, proprietary, or customer information is included.</em></p><p><em>Find me on </em><a href="https://linkedin.com/in/guruprasadseeryada"><em>LinkedIn</em></a><em> or [</em><a href="https://github.com/svguruprasad"><em>GitHub</em></a><em>].</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=979ec021d520" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built a $50K/year autocomplete by accident]]></title>
            <link>https://medium.com/@guruprasad.seeryada/i-built-a-50k-year-autocomplete-by-accident-ec062c8b50dd?source=rss-9704be97d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec062c8b50dd</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[production]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Guruprasad Seeryada]]></dc:creator>
            <pubDate>Thu, 28 May 2026 21:50:00 GMT</pubDate>
            <atom:updated>2026-05-28T21:50:00.098Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The approval paradox: when gating every AI agent action costs more than the risk it prevents</em></p><p>I deployed an AI agent with human approval on every action. Send an email? Approve. Update a record? Approve. Schedule a meeting? Approve.</p><p>Within weeks, the approval queue became a rubber stamp. Reviewers clicked “yes” without reading. I knew because the approval latency dropped below the time it takes to read the content being approved.</p><p>I had built an expensive autocomplete. The agent did the work. The human clicked approve without looking. The safety gate provided zero actual safety.</p><p>At 200 approvals per day, 30 seconds each, with a reviewer costing $75/hour: that’s 100 minutes of daily review time, 260 workdays per year, totaling $54K annually in human time spent clicking “yes” without reading.</p><p>The opposite extreme is worse. Remove all gates and the agent causes a Sev2 in five days (I wrote about that <a href="https://medium.com/@guruprasad.seeryada/my-ai-agent-caused-a-sev2-in-five-days-997f8e2d6776">here</a>.</p><p>The answer is a system that starts gated and progressively removes gates based on measured trust. This post shows the pattern and the code.</p><h4><strong>The paradox</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aHUzrzoW-gYMOE77oJ3mOw.png" /></figure><p>Gate every action: you pay a human to approve work that an agent exists to automate. The human stops genuinely reviewing because the volume is too high. You get the cost of human review with none of the safety benefit.</p><p>Gate nothing: the agent takes irreversible actions without oversight. Failures reach production unchecked.</p><p>The middle ground isn’t “gate some things” (everyone says that). It’s a system that promotes actions from gated to autonomous based on measured pass rates, and demotes them back when failures occur.</p><h4><strong>The progressive trust model</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHdHuxaO9KA0wTq3RKDm7g.png" /></figure><p>Four levels. Every action type starts at Level 0 and earns promotion through demonstrated reliability.</p><p><strong>Level 0: Full gate</strong>. Human approves every action. New agents and new action types start here.</p><p><strong>Level 1: Evaluation gate</strong>. A Lambda evaluator checks the action against rules. Passes go through automatically. Failures route to human review.</p><p><strong>Level 2: Monitored autonomy</strong>. No gate. Online monitoring watches for drift. If failures exceed the budget, the action type gets demoted back to Level 1.</p><p><strong>Level 3: Full autonomy</strong>. No gate, no active monitoring. Spot-checked via offline evaluation on a schedule.</p><h4><strong>The code</strong></h4><pre>class TrustLevel:<br>  FULL_GATE = 0 # Human approves every action<br>  EVAL_GATE = 1 # Lambda evaluator, human on failure<br>  MONITORED = 2 # No gate, online monitoring<br>  AUTONOMOUS = 3 # No gate, spot-check only<br>  def get_trust_level(action_type: str, history: dict) -&gt; int:<br>    &quot;&quot;&quot;Determine trust level based on action history.&quot;&quot;&quot;<br>    stats = history.get(action_type, {})<br>    consecutive_passes = stats.get(&quot;consecutive_passes&quot;, 0)<br>    days_at_level_2 = stats.get(&quot;days_at_monitored&quot;, 0)<br>    total_invocations = stats.get(&quot;total&quot;, 0)<br>    if total_invocations &lt; 100:<br>      return TrustLevel.FULL_GATE<br>    if consecutive_passes &lt; 500:<br>      return TrustLevel.EVAL_GATE<br>    if days_at_level_2 &lt; 30:<br>      return TrustLevel.MONITORED<br>    return TrustLevel.AUTONOMOUS<br>  def should_gate(action_type: str, history: dict) -&gt; str:<br>    &quot;&quot;&quot;Returns the gate type for this action.&quot;&quot;&quot;<br>    level = get_trust_level(action_type, history)<br>    if level == TrustLevel.FULL_GATE:<br>      return &quot;human&quot;<br>    elif level == TrustLevel.EVAL_GATE:<br>      return &quot;evaluator&quot;<br>    elif level == TrustLevel.MONITORED:<br>      return &quot;monitor_only&quot;<br>    else:<br>      return &quot;none&quot;</pre><p>Tested output:</p><pre>Action with 50 invocations → &quot;human&quot; (Level 0)<br>Action with 200 invocations → &quot;evaluator&quot; (Level 1)<br>Action with 600 passes, 10 days monitored → &quot;monitor_only&quot; (Level 2)<br>Action with 900 passes, 35 days monitored → &quot;none&quot; (Level 3)</pre><h4><strong>Demotion: trust is not permanent</strong></h4><p>When an action fails, it gets demoted. Critical failures reset to Level 0. Minor failures drop one level.</p><pre>def handle_failure(action_type: str, history: dict, severity: str) -&gt; int:<br>  &quot;&quot;&quot;Demote trust level on failure.&quot;&quot;&quot;<br>  current = get_trust_level(action_type, history)<br>  if severity == &quot;critical&quot;:<br>    history[action_type][&quot;consecutive_passes&quot;] = 0<br>    history[action_type][&quot;days_at_monitored&quot;] = 0<br>    return TrustLevel.FULL_GATE<br>  if severity == &quot;minor&quot;:<br>    history[action_type][&quot;consecutive_passes&quot;] = max(<br>    0, history[action_type][&quot;consecutive_passes&quot;] - 100<br>    )<br>    return max(TrustLevel.FULL_GATE, current - 1)<br>  return current</pre><p>Tested output:</p><pre>Critical failure at Level 2 → resets to Level 0 (consecutive_passes = 0)<br>Minor failure at Level 2 → drops to Level 1 (consecutive_passes reduced by 100)</pre><h4><strong>Detecting rubber stamps</strong></h4><p>The progressive model only works if Level 0 reviews are genuine. Detect rubber-stamping by measuring review latency against minimum reading time:</p><pre>def is_rubber_stamp(review_latency_seconds: float, action_type: str) -&gt; bool:<br>&quot;&quot;&quot;Flag reviews that are too fast to be genuine.&quot;&quot;&quot;<br>min_review_time = {<br>&quot;send_email&quot;: 30,<br>&quot;update_record&quot;: 15,<br>&quot;schedule_meeting&quot;: 10,<br>}<br>threshold = min_review_time.get(action_type, 20)<br>return review_latency_seconds &lt; threshold</pre><p>Tested output:</p><pre>4 seconds to approve an email → rubber stamp (True)<br>45 seconds to approve an email → genuine review (False)<br>3 seconds to approve a meeting → rubber stamp (True)<br>12 seconds to approve a meeting → genuine review (False)</pre><h4><strong>Step Functions integration</strong></h4><p>The trust level determines the workflow path:</p><pre>{<br>&quot;DetermineGateLevel&quot;: {<br>&quot;Type&quot;: &quot;Task&quot;,<br>&quot;Resource&quot;: &quot;arn:aws:lambda:us-east-1:123456789012:function:trust-level-check&quot;,<br>&quot;Parameters&quot;: {<br>&quot;action_type.$&quot;: &quot;$.action.type&quot;,<br>&quot;history_table&quot;: &quot;agent-trust-history&quot;<br>},<br>&quot;Next&quot;: &quot;RouteByTrustLevel&quot;<br>},<br>&quot;RouteByTrustLevel&quot;: {<br>&quot;Type&quot;: &quot;Choice&quot;,<br>&quot;Choices&quot;: [<br>{<br>&quot;Variable&quot;: &quot;$.gate_type&quot;,<br>&quot;StringEquals&quot;: &quot;human&quot;,<br>&quot;Next&quot;: &quot;HumanApprovalQueue&quot;<br>},<br>{<br>&quot;Variable&quot;: &quot;$.gate_type&quot;,<br>&quot;StringEquals&quot;: &quot;evaluator&quot;,<br>&quot;Next&quot;: &quot;LambdaEvaluator&quot;<br>},<br>{<br>&quot;Variable&quot;: &quot;$.gate_type&quot;,<br>&quot;StringEquals&quot;: &quot;monitor_only&quot;,<br>&quot;Next&quot;: &quot;ExecuteAndMonitor&quot;<br>}<br>],<br>&quot;Default&quot;: &quot;ExecuteDirectly&quot;<br>}<br>}</pre><h4><strong>Tuning the thresholds</strong></h4><p>The promotion thresholds (100 invocations, 500 passes, 30 days) are starting points. Adjust them based on your risk tolerance:</p><p>- <strong>Higher risk tolerance</strong> (internal tools, read-only actions): lower the thresholds. Promote faster.</p><p>- <strong>Lower risk tolerance</strong> (customer-facing, financial, irreversible): raise them. Require more evidence before promoting.</p><p>- <strong>Some actions never promote past Level 1</strong>. Financial transactions, external communications to customers, and data deletions stay gated permanently regardless of pass rate.</p><h4><strong>When to use this</strong></h4><p>Use the progressive trust model when your agent handles actions with varying risk levels and your reviewers are showing signs of rubber-stamping (approval latency dropping below reading time).</p><p>Don’t use it when every action is high-consequence (keep those at Level 0 or 1 permanently), or when regulatory requirements mandate human review regardless of agent reliability.</p><h4><strong>The code</strong></h4><p>Full implementation with 14 passing tests: <a href="https://github.com/svguruprasad/agents-that-work">github.com/svguruprasad/agents-that-work</a></p><p>The <em>trust/progressive_trust.py </em>module integrates with the gate evaluator from <a href="https://medium.com/@guruprasad.seeryada/building-custom-evaluators-for-ai-agents-with-aws-lambda-e9a62b6641bd">Part 2</a>. The trust level system sits on top of the gate and uses the same pass/fail signals to make promotion decisions.</p><p><em>The views and opinions expressed in this article are my own and do not represent those of my employer. This article uses only publicly available AWS documentation and open-source software. No confidential, proprietary, or customer information is included.</em></p><p><em>Find me on </em><a href="https://linkedin.com/in/guruprasadseeryada"><em>LinkedIn</em></a><em> or </em><a href="https://github.com/svguruprasad"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec062c8b50dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I got AWS DevOps Agent working in Cursor. Here’s how.]]></title>
            <link>https://medium.com/@guruprasad.seeryada/i-got-aws-devops-agent-working-in-cursor-heres-how-1902cfa3d0d4?source=rss-9704be97d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/1902cfa3d0d4</guid>
            <category><![CDATA[kiro]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cursor-ide]]></category>
            <dc:creator><![CDATA[Guruprasad Seeryada]]></dc:creator>
            <pubDate>Mon, 25 May 2026 02:32:25 GMT</pubDate>
            <atom:updated>2026-05-25T02:35:44.072Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The undocumented workaround for teams that won’t switch IDEs</em></p><p>A customer asked me to demo AWS DevOps Agent for their engineering team. 100 engineers. All on Cursor. The problem: DevOps Agent only works in Kiro and Claude Code. No standalone MCP endpoint. No Cursor plugin. The official docs confirm this.</p><p>I told them it wasn’t supported. Then I found a workaround that works today.</p><p>The AWS MCP Server’s general-purpose <em>aws___call_aws</em> tool can execute DevOps Agent API calls. If you already have the AWS MCP Server configured in Cursor, you can access DevOps Agent capabilities through it. No additional setup beyond what you already have for AWS access.</p><p>This post documents the setup I tested and confirmed working.</p><h4><strong>The problem</strong></h4><p>AWS DevOps Agent handles incident investigation, cost optimization, and architecture review through conversational AI. It’s a useful tool for platform teams. But it requires either:</p><p>- <strong>Kiro</strong> (via a dedicated power that auto-routes questions to the right DevOps Agent skill)</p><p>- <strong>Claude Code</strong> (via a plugin)</p><p>Neither option works for teams standardized on Cursor. Asking 100 engineers to switch IDEs for one capability isn’t realistic. The feature sits unused.</p><h4><strong>What DevOps Agent does</strong></h4><p>DevOps Agent is an AI assistant built for platform engineering work. It connects to your AWS environment and answers operational questions that normally require switching between 4–5 consoles, reading CloudWatch logs, cross-referencing deployment history, and checking service health dashboards.</p><p>Concrete examples of what you can ask it:</p><p>- “Why did my ECS deployment fail 20 minutes ago?” (it pulls CloudTrail events, ECS task failures, and ALB health checks to reconstruct the timeline)</p><p>- “What’s driving the cost increase in us-east-1 this month?” (it queries Cost Explorer, identifies the top contributors, and compares against the previous period)</p><p>- “Review the architecture of my Step Functions workflow for single points of failure” (it reads the ASL definition and flags states without retry/catch blocks)</p><p>- “What changed in this account in the last 24 hours that explains the latency spike?” (it correlates CloudTrail, Config changes, and CloudWatch anomalies)</p><p>For a 100-engineer team, the value is operational knowledge embedded in the IDE. Junior engineers get answers that previously required paging a senior SRE. Senior engineers skip the 15-minute console dance for routine investigations. Incident response starts in the same window where the code lives instead of context-switching to a browser.</p><p>The gap today: this capability only lives in Kiro and Claude Code. If your team is on Cursor, they don’t get it natively. That’s what the workaround below solves.</p><h4><strong>The workaround</strong></h4><p>The AWS MCP Server is a managed endpoint that gives AI coding agents authenticated access to AWS services from within any supported IDE. Cursor is officially supported. The server exposes an `aws___call_aws` tool that can call any AWS API, including DevOps Agent APIs.</p><p>The connection path: Cursor → AWS MCP Server → `aws___call_aws` → DevOps Agent APIs.</p><h4><strong>Setup</strong></h4><p>Add this to <em>~/.cursor/mcp.json</em>:</p><pre>{<br>&quot;mcpServers&quot;: {<br>  &quot;aws-mcp&quot;: {<br>  &quot;command&quot;: &quot;uvx&quot;,<br>  &quot;args&quot;: [<br>    &quot;mcp-proxy-for-aws@latest&quot;,<br>    &quot;https://aws-mcp.us-east-1.api.aws/mcp&quot;,<br>    &quot; --metadata&quot;, &quot;AWS_REGION=us-east-1&quot;<br>      ]<br>    }<br>  }<br>}</pre><p>Restart Cursor. Confirm <em>aws-mcp</em> shows green in Settings → Tools and MCP.</p><h4><strong>Prerequisites</strong></h4><p>- AWS CLI v2.32.0 or later</p><p>- <em>uv</em> installed (Python package manager)</p><p>- IAM role with <em>devops-agent:*</em> permissions</p><p>- A DevOps Agent Space created in your account (DevOps Agent console)</p><h4><strong>Verification</strong></h4><p>In Cursor chat, ask:</p><blockquote><em>“Use the aws___call_aws tool to run: aws devops-agent list-agent-spaces — region us-east-1”</em></blockquote><p>If it returns your Agent Spaces, you’re connected. DevOps Agent APIs are accessible through the general AWS MCP Server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmasmiUWne6eytV2OSFoRg.png" /></figure><h4><strong>What you get</strong></h4><p>Once connected, you can interact with DevOps Agent through Cursor by asking the AI to call specific DevOps Agent APIs:</p><p>- <em>list-agent-spaces</em>: see your available spaces</p><p>- <em>create-conversation</em>: start a DevOps Agent session</p><p>- <em>send-message</em>: ask questions about incidents, costs, or architecture</p><p>- <em>get-conversation</em>: retrieve conversation history</p><p>You interact through the general AWS tools interface. The AI in Cursor routes your natural language to the correct API call.</p><h4><strong>What you lose vs Kiro</strong></h4><p>Kiro auto-routes your questions to the right DevOps Agent skill without you specifying the API. You ask “why did my deployment fail?” and Kiro knows to invoke the incident investigation skill.</p><p>In Cursor, you interact through the general `aws___call_aws` tool. You need to be more explicit about what you want the DevOps Agent to do. The AI in Cursor helps translate, but it doesn’t have Kiro’s built-in routing to DevOps Agent skills.</p><p>For teams that live in Cursor and want DevOps Agent access without switching IDEs, this tradeoff is acceptable. For teams that want the full guided experience, Kiro is the better path.</p><h4><strong>When to use which</strong></h4><p>Use <strong>Cursor + AWS MCP Server</strong> when:</p><p>- Your team is already on Cursor and won’t switch</p><p>- You want DevOps Agent as one of many AWS capabilities in your IDE</p><p>- Your engineers are comfortable being explicit about API calls</p><p>- You need a single IDE for coding, AWS access, and DevOps Agent</p><p>Use <strong>Kiro</strong> when:</p><p>- DevOps Agent is the primary use case</p><p>- You want auto-routing to the right skill without specifying APIs</p><p>- Your team is starting fresh and hasn’t standardized on an IDE</p><p>- You want the tightest integration with AWS development workflows</p><h4><strong>The broader problem</strong></h4><p>This workaround exists because the AI tooling ecosystem is fragmenting faster than enterprises can adopt. Teams standardize on one IDE. New capabilities launch in a different one. The gap between “available” and “available where my engineers work” is where adoption dies.</p><p>MCP helps bridge this gap. A general-purpose MCP server that exposes all AWS APIs means new capabilities become accessible in any MCP-compatible IDE without waiting for dedicated plugins. The tradeoff is a less polished experience vs a native integration.</p><p>For the 100-engineer team I was working with, “works in Cursor today with less polish” beat “works perfectly in an IDE nobody uses.”</p><h4><strong>The code</strong></h4><p>The mcp.json config above is the complete setup. No additional code needed. The AWS MCP Server handles authentication through your existing IAM credentials with CloudTrail audit logging.</p><p>Setup guide: <a href="https://docs.aws.amazon.com/aws-mcp-servers/latest/userguide/setting-up.html">Setting up the AWS MCP Server</a></p><p>DevOps Agent docs: <a href="https://docs.aws.amazon.com/kiro/latest/userguide/devops-agent.html">Interfacing with the DevOps Agent</a></p><p><em>The views and opinions expressed in this article are my own and do not represent those of my employer. This article uses only publicly available AWS documentation and open-source software. No confidential, proprietary, or customer information is included.</em></p><p><em>I build multi-agent systems on AWS. Find me on </em><a href="https://linkedin.com/in/guruprasadseeryada"><em>LinkedIn</em></a><em> or </em><a href="https://github.com/svguruprasad"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1902cfa3d0d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building custom evaluators for AI agents with AWS Lambda]]></title>
            <link>https://medium.com/@guruprasad.seeryada/building-custom-evaluators-for-ai-agents-with-aws-lambda-e9a62b6641bd?source=rss-9704be97d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9a62b6641bd</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Guruprasad Seeryada]]></dc:creator>
            <pubDate>Mon, 25 May 2026 01:59:50 GMT</pubDate>
            <atom:updated>2026-05-25T01:59:50.987Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Deterministic checks that catch what built-in evaluators miss</em></p><p>In <a href="https://medium.com/@guruprasad.seeryada/my-ai-agent-caused-a-sev2-in-five-days-997f8e2d6776">Part 1</a>, I covered a three-layer evaluation stack for production AI agents using built-in evaluators. Built-in evaluators handle general checks: faithfulness, tool selection accuracy, instruction following. They work well for common failure modes.</p><p>But production agents have domain-specific rules that no generic evaluator covers. “The recipient must be a contact from the active customer.” “Dollar amounts must match the Cost Explorer response within $0.01.” “The agent must not reference Account B’s data while working on Account A.” These are business rules. They need deterministic evaluation, not LLM judgment.</p><p>This post covers building custom evaluators as AWS Lambda functions. Lambda evaluators are deterministic (same input always produces same output), fast (sub-100ms), cheap ($0.0000002 per invocation), and testable with standard unit tests. I integrate them into an AWS Step Functions workflow that gates agent actions before execution.</p><h4><strong>Why Lambda over LLM-as-Judge</strong></h4><p>LLM-as-Judge evaluators use a second model to score the first model’s output. They’re flexible but non-deterministic. Run the same evaluation twice and you get different scores. For safety-critical checks (“did the user approve this action?”), non-deterministic evaluation is unacceptable.</p><p>Lambda evaluators run code. The same input produces the same output every time. You can unit test them. You can reason about their behavior. When a Lambda evaluator says “fail,” you know exactly which check failed and why.</p><p>Use LLM-as-Judge for subjective quality (coherence, helpfulness, tone). Use Lambda for objective rules (approval given, data grounded, recipient valid, customer isolation maintained).</p><h4><strong>The gate evaluator</strong></h4><p>The evaluator runs as a Lambda function between the agent’s proposed action and the execution step. It receives the action, the conversation history, and the tool call results. It returns pass or fail.</p><pre>def evaluate_action(event: dict) -&gt; dict:<br>  action = event.get(&quot;action&quot;, &quot;&quot;)<br>  agent_output = event.get(&quot;agent_output&quot;, {})<br>  criteria = event.get(&quot;evaluation_criteria&quot;, [])<br>  conversation_history = event.get(&quot;conversation_history&quot;, [])<br>  tool_call_results = event.get(&quot;tool_call_results&quot;, [])<br>  results = {}<br>  all_passed = True<br>  if &quot;user_explicitly_approved_sending&quot; in criteria:<br>    approved = check_user_approval(conversation_history, action)<br>    results[&quot;user_approval&quot;] = approved<br>  if not approved:<br>    all_passed = False<br>  if &quot;no_fabricated_data_in_body&quot; in criteria:<br>    grounded = check_data_grounding(agent_output, tool_call_results)<br>    results[&quot;data_grounded&quot;] = grounded<br>  if not grounded:<br>    all_passed = False<br>return {&quot;passed&quot;: all_passed, &quot;results&quot;: results, &quot;action&quot;: action}</pre><p>Each check is a separate function. Add new checks by writing a new function and adding its criteria key. The evaluator is composable.</p><h4><strong>Check 1: User approval detection</strong></h4><p>The agent must not take irreversible actions without explicit user approval in the conversation. This check scans the conversation history for approval phrases before the action executes.</p><pre>def check_user_approval(conversation_history: list, action: str) -&gt; bool:<br>approval_phrases = [<br>&quot;yes, send it&quot;,<br>&quot;go ahead and send&quot;,<br>&quot;approved&quot;,<br>&quot;send the email&quot;,<br>&quot;please send&quot;,<br>]<br>  for turn in reversed(conversation_history):<br>    if turn.get(&quot;role&quot;) != &quot;user&quot;:<br>    continue<br>    content = turn.get(&quot;content&quot;, &quot;&quot;).lower()<br>    if any(phrase in content for phrase in approval_phrases):<br>      return True<br>    return False</pre><p><em>Tested behavior</em><br>Input: [user: “Go ahead and send”] → True<br>Input: [user: “Looks good, hold off”] → False<br>Input: [user: “What does it say?”] → False</p><p><strong>Check 2: Data grounding</strong></p><p>Every specific data point in the agent’s output (dollar amounts, dates) must trace back to a tool call result. This catches the fabrication problem from Part 1 at the action gate rather than in the response.</p><pre>def check_data_grounding(agent_output: dict, tool_call_results: list) -&gt; bool:<br>body = agent_output.get(&quot;body&quot;, &quot;&quot;)<br>  if not body:<br>    return True<br><br>  import re<br>  tool_data = &quot; &quot;.join(str(r) for r in tool_call_results)<br>  numbers = re.findall(r&quot;\$[\d,]+\.?\d*|\d{4}-\d{2}-\d{2}&quot;, body)<br>  for number in numbers:<br>    if number not in tool_data:<br>      return False<br>  return True</pre><p>Tested behavior:</p><pre>Body: &quot;$47,231.84&quot; | Tools: &quot;$47,231.84&quot; → True (grounded)<br>Body: &quot;$99,999.99&quot; | Tools: &quot;$47,231.84&quot; → False (fabricated)</pre><p><strong>Step Functions integration</strong></p><p>The Lambda evaluator sits in a Step Functions workflow between the agent and the action:</p><pre>{<br>&quot;EvaluateBeforeAction&quot;: {<br>&quot;Type&quot;: &quot;Task&quot;,<br>&quot;Resource&quot;: &quot;arn:aws:lambda:us-east-1:123456789012:function:gate-evaluator&quot;,<br>&quot;Parameters&quot;: {<br>&quot;action.$&quot;: &quot;$.agent_response.proposed_action.type&quot;,<br>&quot;agent_output.$&quot;: &quot;$.agent_response.proposed_action&quot;,<br>&quot;conversation_history.$&quot;: &quot;$.conversation_history&quot;,<br>&quot;tool_call_results.$&quot;: &quot;$.agent_response.tool_results&quot;,<br>&quot;evaluation_criteria&quot;: [<br>&quot;user_explicitly_approved_sending&quot;,<br>&quot;no_fabricated_data_in_body&quot;<br>]<br>},<br>&quot;Next&quot;: &quot;GateDecision&quot;<br>},<br>&quot;GateDecision&quot;: {<br>&quot;Type&quot;: &quot;Choice&quot;,<br>&quot;Choices&quot;: [<br>{<br>&quot;Variable&quot;: &quot;$.passed&quot;,<br>&quot;BooleanEquals&quot;: true,<br>&quot;Next&quot;: &quot;ExecuteAction&quot;<br>}<br>],<br>&quot;Default&quot;: &quot;RouteToHumanReview&quot;<br>}<br>}</pre><p>If the evaluator returns <em>{“passed”: false}</em>, the workflow routes to human review. The action never executes. This is a hard gate, not a warning.</p><p>The human review path sends an SNS notification to the team and queues the failed action in SQS for manual inspection. The agent session continues, but the specific action is blocked.</p><h4><strong>Adding new checks</strong></h4><p>Each check follows the same pattern: receive context, return boolean. To add a customer isolation check:</p><pre>def check_customer_isolation(agent_output: dict, active_customer: str) -&gt; bool:<br>&quot;&quot;&quot;Verify the action targets the active customer only.&quot;&quot;&quot;<br>  target = agent_output.get(&quot;target_customer&quot;, &quot;&quot;)<br>  if not target:<br>    return True<br>  return target == active_customer</pre><p>Add <em>”customer_isolation” </em>to the criteria list in the Step Functions parameters. The evaluator picks it up on the next invocation. No redeployment of the agent needed.</p><p><strong><em>Test results<br></em></strong>5 unit tests cover the gate evaluator:</p><pre><br>test_gate_passes_with_approval PASSED<br>test_gate_fails_without_approval PASSED<br>test_gate_fails_with_fabricated_data PASSED<br>test_user_approval_detection PASSED<br>test_no_approval_detected PASSED</pre><p>The evaluator adds reduced latency (Lambda cold start aside) and costs $0.0000002 per invocation. At 200 daily invocations, that’s $0.00004/day. Effectively free.</p><h4><strong>The complete evaluation stack</strong></h4><p>Across Parts 1 and 2, the full stack is:<br> <br> — Offline: Catches regressions. Runs before deployment. Built-in evaluators against test suite.<br> — Online: Monitors drift. Runs during execution. Built-in evaluators on live traces.<br> — Gate: Blocks bad actions. Runs at decision points. Lambda custom evaluators in Step Functions.<br> — Verify: Catches fabrication. Runs before response. Research + Verify two-pass pattern.</p><p>Each layer catches a different failure mode. Offline catches prompt/model regressions. Online catches production drift. Gates block unauthorized actions. Verify catches hallucinated data. Together, they cover the three failure modes from Part 1: fabrication, unauthorized actions, and compounding errors.</p><h4><strong>The code</strong></h4><p>Full implementation with 12 passing tests: <a href="https://github.com/svguruprasad/agents-that-work">github.com/svguruprasad/agents-that-work</a></p><pre>evaluations/ Built-in evaluator integration<br>gates/ Lambda gate evaluator + Step Functions workflow<br>patterns/ Research + Verify pattern<br>tests/ 12 tests (5 gate + 7 verify)</pre><p><em>This is Part 2 of the “Building AI Agents That Work” series. </em><a href="https://medium.com/@guruprasad.seeryada/my-ai-agent-caused-a-sev2-in-five-days-997f8e2d6776"><em>Part 1</em></a><em> covers the three-layer evaluation stack and built-in evaluators. The </em><a href="https://medium.com/@guruprasad.seeryada/your-ai-agent-is-lying-to-you-heres-how-to-catch-it-35c5fd9571f8"><em>Research + Verify</em></a><em> post covers the two-pass verification pattern.</em></p><p><em>I build multi-agent systems on AWS. Find me on </em><a href="https://linkedin.com/in/guruprasadseeryada"><em>LinkedIn</em></a><em> or </em><a href="https://github.com/svguruprasad"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9a62b6641bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your AI agent is lying to you. Here’s how to catch it.]]></title>
            <link>https://medium.com/@guruprasad.seeryada/your-ai-agent-is-lying-to-you-heres-how-to-catch-it-35c5fd9571f8?source=rss-9704be97d188------2</link>
            <guid isPermaLink="false">https://medium.com/p/35c5fd9571f8</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Guruprasad Seeryada]]></dc:creator>
            <pubDate>Sat, 23 May 2026 19:37:05 GMT</pubDate>
            <atom:updated>2026-05-23T20:37:08.332Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A two-pass verification pattern that forces agents to prove every claim before it reaches your users</em></p><p>An AI agent told a customer their monthly spend was $99,412. The real number from Cost Explorer was $47,231. The agent had called the API, received the correct figure, then generated a different number in its response. The output format was identical. Nothing in the response signaled which number came from the API and which the model invented.</p><p>I built a pattern to catch this. The agent audits its own output against its tool call history before returning a response. Claims that don’t trace back to a tool result get removed. I call it Research + Verify.</p><h4><strong>The problem</strong></h4><p>Agents fabricate data and present it identically to retrieved data. A scheduling agent invents meeting times. A reporting agent generates metrics that match the format of real API responses. The downstream system has no way to distinguish real from fabricated.</p><p>System prompts don’t fix this. Adding “only use data from tool calls” to the prompt reduces the rate. It doesn’t eliminate it. The model still generates plausible values when context is long or when tool output arrives in an unexpected format.</p><h4><strong>The pattern</strong></h4><p>The agent makes two passes over its own output.</p><p><strong>Pass one (Research)</strong>. The agent completes its task normally. It calls tools, retrieves data, reasons about it, drafts a response. Standard agent loop.</p><p><strong>Pass two (Verify)</strong>. Before returning the response, the agent checks every factual claim against its tool call history. For each date, number, name, or status value, it asks: “Did a tool return this exact data point?” Claims without tool-call backing get removed.</p><pre>VERIFY_PROMPT = &quot;&quot;&quot;<br>Review your draft response. For each factual claim (dates, numbers,<br>names, status values), verify it appears in your tool call results.<br>Mark each claim as:<br>- VERIFIED: exact match in tool output<br>- UNVERIFIED: not found in any tool output<br>Remove all UNVERIFIED claims before returning your response.<br>&quot;&quot;&quot;</pre><h4><strong>Why this works when prompts don’t</strong></h4><p>System prompts fail because they compete with the generation objective. The model tries to be helpful (complete response) and accurate (verified data) at the same time. When these conflict, helpfulness wins. The model fills gaps with fabrications rather than leaving blanks.</p><p>The verify pass separates these into two steps. Pass one: generate the best response you can. Pass two: audit what you wrote. Remove anything you can’t prove. Verification is a simpler task than generation. The model pattern-matches against its own tool results instead of recalling from training data.</p><h4><strong>Implementation</strong></h4><p>Three functions. Extract claims from the draft, check each against tool results, filter the response.</p><pre>import re<br>def extract_claims(response: str) -&gt; list[str]:<br>  &quot;&quot;&quot;Pull dates, dollar amounts, percentages, and quoted values.&quot;&quot;&quot;<br>  claims = []<br>  claims.extend(re.findall(r&quot;\d{4}-\d{2}-\d{2}&quot;, response))<br>  claims.extend(re.findall(r&quot;\$[\d,]+\.?\d*&quot;, response))<br>  claims.extend(re.findall(r&quot;\d+\.?\d*%&quot;, response))<br>  claims.extend(re.findall(r&#39;&quot;([^&quot;]+)&quot;&#39;, response))<br>  return claims<br><br>def verify_claims(claims: list[str], tool_results: list[dict]) -&gt; dict:<br>  &quot;&quot;&quot;Check each claim against tool call results.&quot;&quot;&quot;<br>  tool_data = &quot; &quot;.join(str(r) for r in tool_results)<br>  return {<br>    claim: &quot;VERIFIED&quot; if claim in tool_data else &quot;UNVERIFIED&quot;<br>    for claim in claims<br>  }<br><br>def research_and_verify(agent_response: str, tool_results: list[dict]) -&gt; dict:<br>  &quot;&quot;&quot;Remove unverified claims from the agent&#39;s response.&quot;&quot;&quot;<br>  claims = extract_claims(agent_response)<br>  verification = verify_claims(claims, tool_results)<br>  filtered = agent_response<br>  for claim, status in verification.items():<br>    if status == &quot;UNVERIFIED&quot;:<br>      filtered = filtered.replace(claim, &quot;[removed]&quot;)<br>  return {<br>    &quot;response&quot;: filtered,<br>    &quot;total_claims&quot;: len(claims),<br>    &quot;verified&quot;: sum(1 for v in verification.values() if v == &quot;VERIFIED&quot;),<br>    &quot;unverified&quot;: sum(1 for v in verification.values() if v == &quot;UNVERIFIED&quot;),<br>    &quot;details&quot;: verification,<br>  }</pre><h4><strong>Tested output</strong></h4><pre>draft = (<br>&quot;The customer&#39;s monthly spend is $47,231.84 as of 2026–04–30. &quot;<br>&quot;Their usage grew 23% month-over-month. &quot;<br>&quot;The next billing cycle starts 2026–05–15.&quot;<br>)<br>tool_results = [<br>{&quot;tool&quot;: &quot;cost_explorer&quot;, &quot;result&quot;: {&quot;amount&quot;: &quot;$47,231.84&quot;, &quot;period&quot;: &quot;2026–04–30&quot;}},<br>{&quot;tool&quot;: &quot;cost_explorer&quot;, &quot;result&quot;: {&quot;growth&quot;: &quot;23%&quot;}},<br>]<br>result = research_and_verify(draft, tool_results)</pre><p><em>Output:</em><br>Claims found: 4<br>Verified: 3<br>Unverified: 1</p><p><em>Filtered response</em>:<br>The customer’s monthly spend is $47,231.84 as of 2026–04–30.<br>Their usage grew 23% month-over-month.<br>The next billing cycle starts [removed].</p><p>The date 2026–05–15 was fabricated. No tool returned it. The verify pass caught it and removed it. The three verified claims ($47,231.84, 2026–04–30, 23%) passed through unchanged.</p><h4><strong>What it catches</strong></h4><p>- Fabricated metrics presented in the same format as real API data</p><p>- Hallucinated dates for meetings, deadlines, and events</p><p>- Invented names of people, services, or resources not in any tool response</p><p>- Extrapolated numbers the agent “helpfully” projected without a tool calculating them</p><h4><strong>What it doesn’t catch</strong></h4><p>- Correct data applied to the wrong context (right number, wrong entity)</p><p>- Omissions (agent leaves out critical information from tool results)</p><p>- Reasoning errors (wrong conclusions from correct data)</p><p>For those failure modes, you need evaluation infrastructure. I covered that in <a href="https://medium.com/@guruprasad.seeryada/my-ai-agent-caused-a-sev2-in-five-days-997f8e2d6776">My AI agent caused a Sev2 in five days</a>.</p><h4><strong>Cost</strong></h4><p>One additional inference call per agent invocation. The verify pass processes the draft (200–500 tokens) against tool call history (1,000–3,000 tokens). At current Claude Sonnet pricing ($3/M input, $15/M output), a typical verification costs $0.002–0.004.</p><p>For 200 daily invocations: $12–24/month.</p><h4><strong>When to use it</strong></h4><p>Use on agents that present data to users: reporting agents, analytics agents, search agents, summarization agents. Any agent where a wrong number has business consequences.</p><p>Don’t use on agents that only take actions (use gate evaluation instead), generate creative content, or operate in latency-critical paths where the extra inference call is unacceptable.</p><h4><strong>The code</strong></h4><p>Full implementation with 7 passing tests: <a href="https://github.com/svguruprasad/agents-that-work">github.com/svguruprasad/agents-that-work</a></p><p>The <em>patterns/research_verify.py </em>module is self-contained. Drop it into any agent pipeline that returns data to users.</p><p><em>The views and opinions expressed in this article are my own and do not represent those of my employer. This article uses only publicly available AWS documentation and open-source software. No confidential, proprietary, or customer information is included. Find me on </em><a href="https://linkedin.com/in/guruprasadseeryada"><em>LinkedIn</em></a><em> or </em><a href="https://github.com/svguruprasad"><em>GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35c5fd9571f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>