<?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 Sarthak Vijay on Medium]]></title>
        <description><![CDATA[Stories by Sarthak Vijay on Medium]]></description>
        <link>https://medium.com/@sarthakvj?source=rss-a6a690c3b8cf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qU0zxWgED0ElcG99kGbq6Q.jpeg</url>
            <title>Stories by Sarthak Vijay on Medium</title>
            <link>https://medium.com/@sarthakvj?source=rss-a6a690c3b8cf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:10:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sarthakvj/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[How Structured Outputs Actually Work on Amazon Bedrock (and What Happens Inside the Decoder)]]></title>
            <link>https://sarthakvj.medium.com/how-structured-outputs-actually-work-on-amazon-bedrock-and-what-happens-inside-the-decoder-507f672063a1?source=rss-a6a690c3b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/507f672063a1</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Sarthak Vijay]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 08:52:19 GMT</pubDate>
            <atom:updated>2026-11-06T08:52:19.015Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why the model can no longer give you broken JSON, why it costs almost nothing per token, and the cases where you still need to check the result.</em></p><p>If you have put an LLM behind a production API, you have probably written a parser like this:</p><pre>text = text.strip().removeprefix(&quot;`&quot; * 3 + &quot;json&quot;).removesuffix(&quot;`&quot; * 3)<br>data = json.loads(text)<br>if data[&quot;category&quot;] not in CATEGORIES:<br>    raise InvalidResponse(text)   # ...and retry</pre><p>It mostly works. Then the model wraps the JSON in a friendly sentence, leaves out a required field, or invents a category that is not on your list, and the retry loop starts burning money.</p><p>Structured outputs on Amazon Bedrock fix this at the source. You hand Bedrock a JSON Schema, and the response is guaranteed to match it. This article explains how to use the feature and, more interestingly, what the inference server does on every token to make that guarantee hold.</p><h3>1. Three things people call “structured output”</h3><p>They are often mixed up, so it helps to separate them first.</p><ol><li><strong>Prompt-only JSON.</strong> You describe the format in the prompt and hope. Nothing enforces it.</li><li><strong>JSON mode.</strong> The output is guaranteed to be syntactically valid JSON, but it can still miss required fields, add extra ones or use the wrong types.</li><li><strong>Schema-constrained generation.</strong> You pass a JSON Schema and the output is guaranteed to match it: required fields present, types correct, enum values legal. This is what Bedrock’s structured outputs feature does.</li></ol><p>The rest of this article is about the third one.</p><h3>2. Using it on Bedrock</h3><p>Bedrock offers two mechanisms, and you can use them together in one request (<a href="https://docs.aws.amazon.com/bedrock/latest/userguide/structured-output.html">Bedrock user guide</a>):</p><p>MechanismWhat it constrainsConverse APIInvokeModel (Claude)JSON Schema output formatThe model’s final answeroutputConfig.textFormat (schema passed as a JSON <strong>string</strong>)output_config.format (schema passed as a JSON <strong>object</strong>)Strict tool useTool names and tool inputstoolSpec.strict: truetools[].strict: true</p><p>A small example: routing customer-support tickets with the Converse API.</p><pre>import json<br>import boto3</pre><pre>brt = boto3.client(&quot;bedrock-runtime&quot;)</pre><pre>schema = {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>        &quot;reasoning&quot;:  {&quot;type&quot;: &quot;string&quot;},<br>        &quot;category&quot;: {&quot;type&quot;: &quot;string&quot;,<br>                     &quot;enum&quot;: [&quot;Billing&quot;, &quot;Technical Issue&quot;, &quot;Account Access&quot;, &quot;Other&quot;]},<br>        &quot;priority&quot;: {&quot;type&quot;: &quot;string&quot;,<br>                     &quot;enum&quot;: [&quot;Low&quot;, &quot;Medium&quot;, &quot;High&quot;, &quot;Urgent&quot;]},<br>    },<br>    &quot;required&quot;: [&quot;reasoning&quot;, &quot;category&quot;, &quot;priority&quot;],<br>    &quot;additionalProperties&quot;: False,<br>}</pre><pre>resp = brt.converse(<br>    modelId=&quot;&lt;your Claude inference profile&gt;&quot;,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: &quot;Route this support ticket: ...&quot;}]}],<br>    inferenceConfig={&quot;maxTokens&quot;: 1024},<br>    outputConfig={<br>        &quot;textFormat&quot;: {<br>            &quot;type&quot;: &quot;json_schema&quot;,<br>            &quot;structure&quot;: {&quot;jsonSchema&quot;: {&quot;name&quot;: &quot;ticket_routing&quot;,<br>                                         &quot;schema&quot;: json.dumps(schema)}},<br>        }<br>    },<br>)</pre><pre>if resp[&quot;stopReason&quot;] != &quot;end_turn&quot;:          # check this before parsing<br>    raise RuntimeError(f&quot;stopped early: {resp[&#39;stopReason&#39;]}&quot;)</pre><pre>result = json.loads(resp[&quot;output&quot;][&quot;message&quot;][&quot;content&quot;][0][&quot;text&quot;])</pre><p>On the Anthropic API the feature launched in public beta in November 2025 (<a href="https://platform.claude.com/docs/en/build-with-claude/structured-outputs">Anthropic docs</a>). Bedrock made it generally available for Claude 4.5 models and several open-weight models in February 2026, and extended it to all Claude models in October 2026.</p><h3>3. What Bedrock does with your schema</h3><p>The user guide describes the request pipeline:</p><ol><li><strong>Validate.</strong> The schema is checked against a supported subset of JSON Schema Draft 2020–12. Unsupported features return a 400 error straight away.</li><li><strong>Compile.</strong> The first time Bedrock sees a schema, it compiles it into a grammar. This can take up to about 90 seconds.</li><li><strong>Cache.</strong> The compiled grammar is cached for 24 hours per account. Changing only a name or description keeps the cache; changing the structure does not.</li><li><strong>Generate.</strong> Later requests with the same schema run at close to normal latency, with the grammar enforced during decoding.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8ZapA4eKcvJPbSZsg4JtQ.png" /></figure><p>The rules that catch people out:</p><ul><li>Every object must set additionalProperties: false.</li><li>Not supported: recursive schemas, external $ref, minimum/maximum, minLength/maxLength.</li><li>At most 12 optional properties and at most 16 union-typed properties (anyOf or [&quot;string&quot;, &quot;null&quot;]).</li><li>default is a hint to the model, not something the decoder fills in.</li><li>Set the client read timeout to at least 120 seconds, so the first request does not time out while the grammar compiles.</li></ul><h3>4. What happens inside: token masking</h3><p>A common first guess is that the model generates several answers and the server throws away the invalid ones. That is not what happens. The model generates a single answer, one token at a time, and at each step it is only <em>allowed</em> to pick tokens that keep the output valid.</p><h3>4.1 One decoding step</h3><p>At every step the model produces a score (a logit) for each token in its vocabulary, which for modern models is 100K tokens or more. Normally the next token is sampled from those scores.</p><p>With structured outputs, one step is added between scoring and sampling:</p><pre>logits = [ 2.1,  0.4,  3.7, -1.2, ... ]   one score per vocabulary token<br>mask   = [  ok, block,   ok, block, ... ]  from the grammar&#39;s current state<br>result = [ 2.1,  -inf,  3.7,  -inf, ... ]  softmax turns -inf into probability 0</pre><p>Blocked tokens get a score of minus infinity, so their probability becomes zero. The model then samples from what is left. That is token masking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0l825dX3apiqRcjABaNSbg.png" /></figure><h3>4.2 A worked example</h3><p>Say the output so far is:</p><pre>{&quot;reasoning&quot;: &quot;The customer was charged twice for one order...&quot;, &quot;category&quot;: &quot;</pre><p>The model’s top candidates for the next token might be:</p><p>CandidateModel probabilityAllowed by the grammar?Refund0.55No, it does not start any enum valueBill0.30Yes, it is a prefix of BillingOther0.10Yes, it is the enum value Other</p><p>Refund is masked. The remaining probabilities are renormalised and the model picks Bill. The grammar now only allows ing&quot; next.</p><p>Later, when the closing } of the root object has been written, the grammar allows exactly one token: end-of-sequence. The model may &quot;want&quot; to add <em>&quot;Let me know if you need anything else!&quot;</em>, but it cannot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zOCFRFrTtb0dYfTgRupvg.png" /></figure><h3>4.3 The grammar is not in the prompt</h3><p>Anthropic does add a short system prompt describing the format. That helps the model write sensible content, but it is not what enforces the format. The grammar lives in the inference server’s sampling step, outside the model. The model weights do not change.</p><h3>5. Why the per-token check adds almost no latency</h3><p>If every token is checked against a grammar, why doesn’t generation slow down? Three reasons.</p><p><strong>1. Most of the work is done before generation.</strong> The hard question is “which of these 100K+ tokens are legal from this grammar state?” A token such as egory&quot;: spans several grammar symbols, so the answer is not obvious. Compilation works it out ahead of time and stores a ready mask for each state. Willard &amp; Louf introduced this index over the vocabulary in the paper behind the Outlines library. This precomputation is the 90-second first-request cost on Bedrock.</p><p><strong>2. The per-token work is tiny.</strong> A forward pass through a large model takes tens of milliseconds. Looking up a mask and applying it to the logits is one vector operation, measured in microseconds. The llguidance library reports about 50 µs of CPU time per token for a 128K-token vocabulary.</p><p><strong>3. The work runs in parallel.</strong> XGrammar computes the next mask on the CPU while the GPU is running the forward pass, so the mask is ready by the time the logits arrive.</p><p>JSON adds one complication. A finite-state machine cannot count nesting depth, so nested objects and arrays need a pushdown automaton (a state machine plus a stack). Some tokens then depend on the stack and cannot be fully precomputed. XGrammar splits the vocabulary into <em>context-independent</em> tokens, which are prechecked at compile time, and a much smaller set of <em>context-dependent</em> tokens that are checked at runtime. That is how it keeps the runtime check small; the paper reports up to 100× speedups over earlier engines and near-zero end-to-end overhead.</p><p>Structured generation can even be <em>faster</em> than free generation. Much of a JSON response is fully determined by the schema: key names, quotes, colons and braces. Engines can insert those without asking the model to choose them. SGLang calls this jump-forward decoding, and the .txt team (the authors of Outlines) describe the same idea as “coalescence”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpSonmiw2GtDjME1DWS7IA.png" /></figure><p><strong>Where latency does show up</strong></p><ul><li><strong>The first request for a new schema</strong>, while the grammar compiles. Complex schemas take longer and can fail to compile.</li><li><strong>A cache miss in a different region.</strong> The cache is per region. Cross-region inference profiles can send a request to a region that has never seen your schema, and that request pays the compile cost again. If you route across regions, warm each region, keep schemas small and set generous timeouts.</li></ul><p>Bedrock and Anthropic do not publish their decoder internals. What I describe in this section is how the open-source engines work. It is consistent with what Bedrock does document: compile once, cache, then run at near-normal latency.</p><h3>6. What is still not guaranteed</h3><p>A guaranteed schema is not a guaranteed answer. Four gaps remain.</p><ol><li><strong>Truncation.</strong> If the response hits the token limit, you get cut-off JSON with HTTP 200 and stop reason max_tokens. Always check the stop reason before parsing.</li><li><strong>Refusals.</strong> If the model refuses, the output may ignore the schema, again with HTTP 200 (<a href="https://platform.claude.com/docs/en/build-with-claude/structured-outputs">Anthropic docs</a>). On InvokeModel the stop reason is refusal. For Converse, the safest rule is to parse only when the stop reason is end_turn.</li><li><strong>Valid but wrong.</strong> In the example above, the model preferred “Refund” and was pushed into “Billing”. Here that happens to be the right queue, but a forced choice is not always a good one. You still need evaluations on a labelled dataset.</li><li><strong>Rules a schema cannot express.</strong> “Account Access tickets must be at least High priority” ties two fields together, which is awkward to write within the supported subset. Keep a validation layer after the call.</li></ol><p>A Pydantic model can cover both sides: it generates the schema you send and validates the business rules afterwards.</p><pre>from enum import Enum<br>from pydantic import BaseModel, ConfigDict, model_validator</pre><pre>class Category(str, Enum):<br>    BILLING = &quot;Billing&quot;; TECHNICAL = &quot;Technical Issue&quot;<br>    ACCOUNT = &quot;Account Access&quot;; OTHER = &quot;Other&quot;</pre><pre>class Priority(str, Enum):<br>    LOW = &quot;Low&quot;; MEDIUM = &quot;Medium&quot;; HIGH = &quot;High&quot;; URGENT = &quot;Urgent&quot;</pre><pre>class TicketRouting(BaseModel):<br>    model_config = ConfigDict(extra=&quot;forbid&quot;)      # additionalProperties: false<br>    reasoning: str                                  # first, so the model reasons before it commits<br>    category: Category<br>    priority: Priority</pre><pre>    @model_validator(mode=&quot;after&quot;)<br>    def account_access_is_high_priority(self):<br>        if self.category is Category.ACCOUNT and self.priority in (Priority.LOW, Priority.MEDIUM):<br>            raise ValueError(&quot;Account Access tickets must be High or Urgent&quot;)<br>        return self</pre><pre>schema = TicketRouting.model_json_schema()   # check it against Bedrock&#39;s supported subset before sending</pre><h3>7. Does constraining the format hurt answer quality?</h3><p>This is still being debated, and it is worth knowing both sides.</p><ul><li><strong>Tam et al., </strong><a href="https://arxiv.org/abs/2408.02442"><strong>“Let Me Speak Freely?”</strong></a><strong> (EMNLP 2024 Industry Track)</strong> found that format restrictions lowered reasoning performance, and that stricter formats lowered it more.</li><li><strong>The .txt team’s </strong><a href="https://blog.dottxt.co/say-what-you-mean.html"><strong>“Say What You Mean”</strong></a> argued that the study mostly measured JSON mode and weak prompts rather than proper schema-constrained generation. With a well-designed schema and prompt, they report structured generation matching or beating free generation.</li><li><a href="https://arxiv.org/abs/2604.03616"><strong>“The Format Tax”</strong></a><strong> (2026)</strong> reports that requiring structured formats still lowers reasoning and writing quality on open-weight models.</li><li><strong>Beurer-Kellner et al., </strong><a href="https://arxiv.org/abs/2403.06988"><strong>“Guiding LLMs the Right Way”</strong></a><strong> (DOMINO)</strong> showed that engines which misalign grammar rules with the model’s sub-word tokens can hurt accuracy, and that proper alignment avoids most of the damage.</li></ul><p>The practical advice is the same from all sides:</p><ul><li>Put a free-text reasoning field <strong>before</strong> the answer fields. The model writes fields in schema order, so it reasons first and commits second. (Anthropic notes that a field asking for the model&#39;s internal thinking can trigger a refusal, so test this with your model.)</li><li>Keep enums short and descriptive. Field names and descriptions act as part of the prompt.</li><li>Measure accuracy on your own labelled data before and after you switch. Constraining also stops the model from correcting itself partway through a response, so check that accuracy holds.</li></ul><h3>8. Summary</h3><ul><li>Bedrock compiles your JSON Schema into a grammar once and caches it for 24 hours.</li><li>During decoding, at every token, the inference server masks out tokens that would break the schema. The model samples only from the tokens that are left, so you get a valid response in a single pass, with no reject-and-retry.</li><li>The per-token cost is a precomputed mask lookup plus one vector operation, run in parallel with the GPU. The real latency cost is the first compile, and repeated compiles when traffic lands in a region whose cache is cold.</li><li>You still need to check the stop reason, run evaluations, and keep a validator for cross-field rules.</li></ul><h3>References</h3><h3><strong>Official documentation</strong></h3><ul><li>AWS, <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/structured-output.html">Get validated JSON results from models (Bedrock structured outputs)</a></li><li>AWS, <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/claude-messages-structured-outputs.html">Structured outputs for Anthropic Claude models on Bedrock</a></li><li>AWS, <a href="https://docs.aws.amazon.com/nova/latest/userguide/concept-chapter-servicename.html">Generating structured output with Amazon Nova</a></li><li>Anthropic, <a href="https://platform.claude.com/docs/en/build-with-claude/structured-outputs">Structured outputs</a></li></ul><p><strong>Research papers</strong></p><ul><li>B. T. Willard, R. Louf. <a href="https://arxiv.org/abs/2307.09702">Efficient Guided Generation for Large Language Models</a>. arXiv:2307.09702, 2023. <em>(FSM index over the vocabulary; basis of Outlines.)</em></li><li>Y. Dong et al. <a href="https://arxiv.org/abs/2411.15100">XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models</a>. arXiv:2411.15100, 2024. <em>(Context-independent vs context-dependent tokens, persistent stack, CPU/GPU overlap.)</em></li><li><a href="https://arxiv.org/abs/2601.04426">XGrammar-2: Dynamic and Efficient Structured Generation Engine for Agentic LLMs</a>. arXiv:2601.04426, 2026. <em>(Faster compilation and cross-grammar caching for tool calling.)</em></li><li>S. Geng et al. <a href="https://arxiv.org/abs/2501.10868">JSONSchemaBench: A Rigorous Benchmark of Structured Outputs for Language Models</a>. arXiv:2501.10868, 2025. <em>(Compares constrained-decoding engines on real-world schemas.)</em></li><li>L. Beurer-Kellner, M. Fischer, M. Vechev. <a href="https://arxiv.org/abs/2403.06988">Guiding LLMs The Right Way: Fast, Non-Invasive Constrained Generation</a>. arXiv:2403.06988, 2024. <em>(Token alignment and the DOMINO algorithm.)</em></li><li>Z. R. Tam et al. <a href="https://arxiv.org/abs/2408.02442">Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language Models</a>. EMNLP 2024 Industry Track.</li><li><a href="https://arxiv.org/abs/2604.03616">The Format Tax</a>. arXiv:2604.03616, 2026.</li></ul><p><strong>Engineering write-ups and libraries</strong></p><ul><li>MLC, <a href="https://blog.mlc.ai/2024/11/22/achieving-efficient-flexible-portable-structured-generation-with-xgrammar">Achieving Efficient, Flexible, and Portable Structured Generation with XGrammar</a></li><li>MLC, <a href="https://blog.mlc.ai/2026/05/04/xgrammar-2-fast-customizable-structured-generation">XGrammar-2: Fast and Customizable Structured Generation for Tool Calling and Agents</a></li><li>LMSYS, <a href="https://lmsys.org/blog/2024-02-05-compressed-fsm/">Fast JSON Decoding for Local LLMs with Compressed Finite State Machine</a> <em>(jump-forward decoding in SGLang)</em></li><li>.txt, <a href="https://blog.dottxt.co/coalescence.html">Coalescence: making LLM inference 5x faster</a></li><li>.txt, <a href="https://blog.dottxt.co/say-what-you-mean.html">Say What You Mean: A Response to “Let Me Speak Freely”</a></li><li><a href="https://github.com/guidance-ai/llguidance">llguidance</a>, <a href="https://github.com/dottxt-ai/outlines">Outlines</a>, <a href="https://github.com/mlc-ai/xgrammar">XGrammar</a></li><li>H. Konishi, <a href="https://hidekazu-konishi.com/entry/claude_structured_outputs_on_amazon_bedrock.html">Claude Structured Outputs on Amazon Bedrock: where the schema goes, what the grammar cache keeps, and why stop_reason comes first</a></li><li>fourTheorem, <a href="https://fourtheorem.com/amazon-bedrock-structured-outputs/">Understanding Amazon Bedrock Structured Outputs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=507f672063a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When One Agent Isn’t Enough: Multi-Agent Patterns That Actually Work (Hands-On)]]></title>
            <link>https://awstip.com/when-one-agent-isnt-enough-multi-agent-patterns-that-actually-work-hands-on-24db4cdb358e?source=rss-a6a690c3b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/24db4cdb358e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[amazon-bedrock-agentcore]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Sarthak Vijay]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 20:45:46 GMT</pubDate>
            <atom:updated>2026-06-15T07:24:56.414Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 7 of the AgentCore Series — A Complete Guide to Building Production AI Agents on AWS</em></p><p><em>Catching up? </em><a href="https://medium.com/p/8602c09efcf9"><em>Part 1</em></a><em> covers the platform. Parts </em><a href="https://sarthakvj.medium.com/deploy-first-agent-on-aws-agentcore-9e965736f854"><em>2</em></a><em>–</em><a href="https://sarthakvj.medium.com/stop-guessing-what-your-ai-agent-did-trace-it-hands-on-73563825ee6d"><em>6</em></a><em> build, connect, remember, authenticate, and observe a single agent. This part is about when to stop and split.</em></p><h3>What You’ll Build</h3><p>The summarizer from Parts 2–6 has been one agent doing one thing. We’re going to evolve it into a <strong>research team</strong>: a researcher that gathers material, an analyst that finds patterns, a fact-checker that flags weak claims, and a report writer that ties it all together.</p><p>By the end you’ll know:</p><ol><li>The three multi-agent patterns Strands gives you, and which to pick when</li><li>How to wire any of them into AgentCore Runtime (same deploy story as Part 2 — that’s the whole point)</li><li>The honest tradeoffs nobody mentions until you’ve debugged a 6-agent loop at 2am</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*ufKz7Z0s7ZLVNF2LqF4ghg.png" /></figure><h3>Stop. Should You Even Split?</h3><p>Before any of this: <strong>most agents that “need” to be multi-agent don’t.</strong> A single Strands agent with 8 well-described tools beats 4 specialized agents handing off to each other for almost every task under medium complexity.</p><p>Split when one of these is true:</p><ul><li><strong>Different system prompts genuinely conflict.</strong> A “be terse and factual” researcher and a “be expansive and narrative” writer can’t coexist in one prompt without one mode dominating.</li><li><strong>Different toolsets need different security boundaries.</strong> Researcher gets web access; report writer doesn’t. Splitting agents = splitting IAM roles.</li><li><strong>You need parallel execution.</strong> One agent is sequential by nature. Three agents on independent subtasks finish in a third the wall-clock time.</li><li><strong>The context window is the bottleneck.</strong> Long-running tasks where one agent’s history would crowd out reasoning room.</li></ul><p>If none of those apply, stay single-agent. You’ll thank yourself.</p><h3>The Three Patterns Strands Gives You</h3><p>PatternShapeUse when<strong>Agents-as-Tools</strong>Hierarchy. One orchestrator delegates to specialists wrapped as tools.The orchestrator decides which specialist to call, mid-conversation. Deterministic routing logic in the orchestrator’s prompt.<strong>Swarm</strong>Peer-to-peer. Agents hand off control to each other autonomously.The path through agents is dynamic and emergent — you can’t predict who calls whom from the task alone.<strong>Graph</strong>DAG. Fixed topology, dependencies between nodes, parallel branches.The workflow is structurally fixed: research feeds both analyst and fact-checker, both feed the writer.</p><p>Pick by asking: <strong>who decides the next agent?</strong></p><ul><li>Orchestrator decides → Agents-as-Tools</li><li>Each agent decides for itself → Swarm</li><li>The graph topology decides → Graph</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*faUGt6H9N09LXV8VpTkFwQ.jpeg" /></figure><h3>Pattern 1: Agents-as-Tools (Start Here)</h3><p>This is the simplest pattern and the one most teams actually need. You wrap each specialist agent in a @tool function and give them to an orchestrator.</p><pre>from strands import Agent, tool<br><br>RESEARCH_PROMPT = &quot;You are a research specialist. Gather factual, well-sourced information. Always cite sources.&quot;<br>@tool<br>def research_assistant(query: str) -&gt; str:<br>    &quot;&quot;&quot;Process research-related queries. Returns a detailed answer with citations.&quot;&quot;&quot;<br>    research_agent = Agent(<br>        system_prompt=RESEARCH_PROMPT,<br>        tools=[],  # Add web/search tools here<br>    )<br>    return str(research_agent(query))<br><br>@tool<br>def fact_checker(claim: str) -&gt; str:<br>    &quot;&quot;&quot;Verify a specific claim. Returns a confidence assessment with evidence.&quot;&quot;&quot;<br>    fact_check_agent = Agent(<br>        system_prompt=&quot;You are a fact-checking specialist. Be conservative; flag anything you can&#39;t verify.&quot;,<br>        tools=[],<br>    )<br>    return str(fact_check_agent(claim))<br><br># Orchestrator picks the right specialist based on the query<br>ORCHESTRATOR_PROMPT = &quot;&quot;&quot;You route queries to specialized assistants:<br>- Research questions needing factual gathering → use research_assistant<br>- Claims needing verification → use fact_checker<br>- Direct simple questions → answer yourself<br>Pick the most appropriate tool. Don&#39;t use a tool when you don&#39;t need to.&quot;&quot;&quot;<br>orchestrator = Agent(<br>    system_prompt=ORCHESTRATOR_PROMPT,<br>    tools=[research_assistant, fact_checker],<br>)</pre><p>That’s it. Drop orchestrator into your main.py entrypoint from Part 2 in place of the single agent. Deploy unchanged. AgentCore Runtime doesn&#39;t care that the agent has agents inside it; it&#39;s all just one Python entrypoint.</p><p><strong>Watch out for:</strong> the orchestrator’s prompt is doing the routing. Vague prompts → wrong specialist gets called → cascading badness. Be explicit, with examples if needed.</p><h3>Pattern 2: Swarm (When Routing Is Emergent)</h3><p>Use Swarm when <em>any</em> agent might decide to hand off to <em>any other</em> — and you want them to figure it out from context, not from a hard-coded orchestrator.</p><pre>from strands import Agent<br>from strands.multiagent import Swarm<br><br>researcher = Agent(name=&quot;researcher&quot;, system_prompt=&quot;Research specialist. Gather sources. When the task needs analysis, hand off to the analyst.&quot;)<br>analyst = Agent(name=&quot;analyst&quot;, system_prompt=&quot;Data analyst. Find patterns. Hand off to fact_checker for verification, or back to researcher if more data is needed.&quot;)<br>fact_checker = Agent(name=&quot;fact_checker&quot;, system_prompt=&quot;Verify claims. Hand off to writer when verification is complete.&quot;)<br>writer = Agent(name=&quot;writer&quot;, system_prompt=&quot;Synthesize findings into a final report.&quot;)<br>swarm = Swarm(<br>    [researcher, analyst, fact_checker, writer],<br>    entry_point=researcher,<br>    max_handoffs=20,<br>    max_iterations=20,<br>    execution_timeout=900.0,   # 15 min total<br>    node_timeout=300.0,        # 5 min per agent<br>    repetitive_handoff_detection_window=8,<br>    repetitive_handoff_min_unique_agents=3,<br>)<br>result = swarm(&quot;Research the impact of LLM agents on developer productivity and produce a fact-checked report.&quot;)<br>print(f&quot;Status: {result.status}&quot;)<br>print(f&quot;Path: {[node.node_id for node in result.node_history]}&quot;)</pre><p>Strands automatically injects a handoff_to_agent tool into every agent. The agents call it themselves when they decide they&#39;re done with their part:</p><pre>handoff_to_agent(agent_name=&quot;analyst&quot;, message=&quot;Sources gathered. Need pattern analysis.&quot;, context={...})</pre><p><strong>The two timeout knobs aren’t optional</strong>, they’re survival. repetitive_handoff_detection_window=8 + repetitive_handoff_min_unique_agents=3 means: &quot;if the last 8 handoffs cycled through fewer than 3 unique agents, stop — they&#39;re stuck in a loop.&quot; Without this you will, eventually, watch a swarm ping-pong between two agents until your timeout fires.</p><p><strong>Watch out for:</strong> swarms are powerful and unpredictable. If you’re shipping production behavior, prefer Graph. Swarm shines for exploratory or open-ended tasks where the <em>shape</em> of the work isn’t known up front.</p><h3>Pattern 3: Graph (When the Workflow Is Fixed)</h3><p>Graph is the most boring pattern, which is why it’s the one I’d ship to production first. You declare the topology; Strands runs it.</p><pre>from strands import Agent<br>from strands.multiagent import GraphBuilder<br><br>researcher = Agent(name=&quot;researcher&quot;, system_prompt=&quot;Research specialist...&quot;)<br>analyst = Agent(name=&quot;analyst&quot;, system_prompt=&quot;Data analysis specialist...&quot;)<br><br>fact_checker = Agent(name=&quot;fact_checker&quot;, system_prompt=&quot;Fact checking specialist...&quot;)<br>report_writer = Agent(name=&quot;report_writer&quot;, system_prompt=&quot;Report writing specialist...&quot;)<br><br>builder = GraphBuilder()<br>builder.add_node(researcher, &quot;research&quot;)<br>builder.add_node(analyst, &quot;analysis&quot;)<br>builder.add_node(fact_checker, &quot;fact_check&quot;)<br>builder.add_node(report_writer, &quot;report&quot;)<br><br># research feeds both analysis and fact_check (parallel branches)<br>builder.add_edge(&quot;research&quot;, &quot;analysis&quot;)<br>builder.add_edge(&quot;research&quot;, &quot;fact_check&quot;)<br><br># both branches converge into report<br>builder.add_edge(&quot;analysis&quot;, &quot;report&quot;)<br>builder.add_edge(&quot;fact_check&quot;, &quot;report&quot;)<br>builder.set_entry_point(&quot;research&quot;)<br>builder.set_execution_timeout(600)<br><br>graph = builder.build()<br>result = graph(&quot;Research the impact of AI on healthcare and produce a fact-checked report.&quot;)<br><br>print(f&quot;Status: {result.status}&quot;)<br>print(f&quot;Order: {[node.node_id for node in result.execution_order]}&quot;)</pre><p>The shape:</p><pre>              ┌──→ analysis ──┐<br>research ─────┤               ├──→ report<br>              └──→ fact_check ┘</pre><p>analysis and fact_check run <strong>in parallel</strong> because both are unblocked when research finishes. That&#39;s the headline win over Agents-as-Tools — when branches are independent, you don&#39;t pay for them sequentially.</p><p>You can also add <strong>conditional edges</strong> for cases where a downstream branch shouldn’t always fire:</p><pre>def only_if_research_succeeded(state):<br>    research_node = state.results.get(&quot;research&quot;)<br>    if not research_node:<br>        return False<br>    return &quot;successful&quot; in str(research_node.result).lower()</pre><pre>builder.add_edge(&quot;research&quot;, &quot;analysis&quot;, condition=only_if_research_succeeded)</pre><p><strong>Watch out for:</strong> Python Graphs default to OR-semantics (a node fires on <em>any</em> incoming edge completing). If you want a node to wait for <em>all</em> its dependencies, that’s typically what you want for fan-in nodes like report — verify the behavior matches your expectations on a small example before scaling.</p><h3>Wiring Any of These into AgentCore Runtime</h3><p>This is the punchline of the whole series: <strong>none of the patterns change how you deploy.</strong> Your main.py entrypoint stays:</p><pre>from bedrock_agentcore.runtime import BedrockAgentCoreApp<br><br>app = BedrockAgentCoreApp()<br># Define orchestrator / swarm / graph here using one of the patterns above<br>multi_agent = ...  # whichever you picked<br>@app.entrypoint<br>async def invoke(payload, context):<br>    return {&quot;result&quot;: str(multi_agent(payload.get(&quot;prompt&quot;, &quot;&quot;)))}</pre><p>agentcore deploy ships it. The runtime sees one entrypoint; everything inside is your problem. Identity (Part 5), Memory (Part 4), Gateway (Part 3), and Observability (Part 6) all keep working — including the trace tree, which now nests every sub-agent invocation as its own span.</p><p>That last point is more important than it sounds. <strong>Multi-agent without observability is unmaintainable.</strong> A 4-agent swarm that gives the wrong answer is a black box unless you can replay the path. Part 6 is what makes Part 7 viable.</p><h3>Picking a Pattern in Practice</h3><p>A decision tree that holds up:</p><ol><li>Can the task be done by one agent with more tools? → <strong>Yes, do that.</strong></li><li>Is the workflow shape known and fixed? → <strong>Graph.</strong></li><li>Does an orchestrator have enough info to route? → <strong>Agents-as-Tools.</strong></li><li>Otherwise → <strong>Swarm</strong>, but set conservative limits and budget time to debug loops.</li></ol><p>Real systems often combine these. An orchestrator (Agents-as-Tools) might delegate to a Graph for one branch and call a single specialist agent for another. Compose what fits.</p><h3>Two Errors You’ll Probably See</h3><p><strong>Swarm hits </strong><strong>max_iterations without finishing</strong> — your agents are too vague about when to hand off. Tighten each system prompt to specify <em>what condition triggers a handoff to whom</em>. Generic prompts → endless deliberation. Also check your detection window — if the swarm is genuinely stuck, you want it to stop, not keep burning tokens.</p><p><strong>Graph node never fires: </strong>almost always a missing or misnamed edge dependency. Print the graph topology before build(): list nodes, list edges, walk the dependency closure manually for one pass. Strands is precise about node IDs, and a typo in add_edge(&quot;research&quot;, &quot;analyis&quot;) silently leaves analysis orphaned.</p><h3>Where the Series Has Taken You</h3><p>Looking back across all seven parts:</p><ul><li><strong>Part 1</strong> — the platform: 7 services, what each one solves</li><li><strong>Part 2</strong> — runtime: get an agent deployed</li><li><strong>Part 3</strong> — gateway: tools without giving the agent the keys</li><li><strong>Part 4</strong> — memory: real persistence per user</li><li><strong>Part 5</strong> — identity: real authentication on every call</li><li><strong>Part 6</strong> — observability: replay every decision</li><li><strong>Part 7</strong> — composition: when one agent isn’t enough</li></ul><p>If you started in Part 1 with no AgentCore experience and built along, you’ve now shipped a system that does roughly what production-grade agent platforms charge $$$ for. The same platform, the same primitives, the same code path from local dev to production.</p><p>Two things to do next:</p><ol><li><strong>Build something you actually need.</strong> All the example agents in this series are toys. The skill is in picking a real workflow with real failure modes.</li><li><strong>Watch the AgentCore samples repo.</strong> Patterns evolve fast; the <a href="https://github.com/awslabs/amazon-bedrock-agentcore-samples">agentcore-samples</a> repo is where new examples land first.</li></ol><p><em>Tags: #AI #AgenticAI #AWS #AgentCore #AIEngineering #LLM #AmazonBedrock #Strands #MultiAgent</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24db4cdb358e" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/when-one-agent-isnt-enough-multi-agent-patterns-that-actually-work-hands-on-24db4cdb358e">When One Agent Isn’t Enough: Multi-Agent Patterns That Actually Work (Hands-On)</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Guessing What Your AI Agent Did: Trace It (Hands-On)]]></title>
            <link>https://sarthakvj.medium.com/stop-guessing-what-your-ai-agent-did-trace-it-hands-on-73563825ee6d?source=rss-a6a690c3b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/73563825ee6d</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sarthak Vijay]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 20:34:22 GMT</pubDate>
            <atom:updated>2026-06-10T20:34:22.658Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 6 of the AgentCore Series: A Complete Guide to Building Production AI Agents on AWS</em></p><p><em>Catching up? </em><a href="https://medium.com/p/8602c09efcf9"><em>Part 1</em></a><em> covers the platform. Parts </em><a href="https://sarthakvj.medium.com/deploy-first-agent-on-aws-agentcore-9e965736f854"><em>2</em></a><em>–</em><a href="https://sarthakvj.medium.com/lock-your-ai-agent-behind-real-user-authentication-hands-on-acb7e14536ec"><em>5</em></a><em> build, connect, remember, and authenticate the agent. Now we make all of that visible.</em></p><h3>What You’ll Build</h3><p>Right now if your agent gives a bad answer, you have one debugging tool: re-prompt it and hope. We’re going to fix that.</p><p>By the end of this article, every invocation of the summarizer will produce:</p><ol><li>A <strong>structured trace</strong> showing every LLM call, tool call, and intermediate decision</li><li><strong>Built-in metrics</strong> (latency, token usage, error rate) on a CloudWatch dashboard</li><li><strong>Logs</strong> correlated to the trace by ID — so when you find a slow span, you can jump to the exact log lines</li></ol><p>Total work: one account-level toggle, three lines added to requirements.txt, and one change to how the agent is launched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Lwo7CKGulab_-CwJcZMR3A.png" /></figure><h3>The Mental Model: Three Layers</h3><p>AgentCore Observability has three independent layers. Confusing them is the most common cause of “I enabled observability but I see nothing”:</p><ol><li><strong>Service-emitted metrics</strong> (latency, errors, etc.) — automatic the moment your runtime exists. No setup.</li><li><strong>Service-emitted spans/traces</strong> (every agent invocation, every tool call, the LLM hops between them) — requires <em>Transaction Search</em> turned on at the account level. One-time toggle.</li><li><strong>Your own spans/attributes/metrics</strong> (custom business logic, e.g. “URL was already in saved articles”) — requires the ADOT (AWS Distro for OpenTelemetry) SDK to be loaded by your agent.</li></ol><p>Skip any of these and you’ll have partial visibility. Set them up in this order; each unlocks the next.</p><h3>Step 1: Turn On Transaction Search (One Time, Per Account)</h3><p>Without this, traces don’t get persisted to CloudWatch and the GenAI Observability dashboard will be empty.</p><p>Console path (60 seconds):</p><ol><li>Open the CloudWatch console</li><li>Expand <strong>Application Signals (APM)</strong> → <strong>Transaction search</strong></li><li>Click <strong>Enable Transaction Search</strong></li><li>Check the box “ingest spans as structured logs”</li><li>Save</li></ol><p>CLI alternative (if you prefer):</p><pre>aws xray update-trace-segment-destination --destination CloudWatchLogs</pre><p>(You also need a one-time resource policy that lets X-Ray write to CloudWatch Logs — the AgentCore docs have the full JSON. The console toggle does this for you.)</p><p>This is per-account, per-region. Do it once, forget it.</p><h3>Step 2: Enable Tracing on the Runtime</h3><p>Service-emitted spans need to be turned on per-resource. Console:</p><ol><li>Open the <strong>Agent Runtime</strong> page</li><li>Select your Summarizer runtime</li><li>Open the <strong>Tracing</strong> pane → <strong>Edit</strong> → toggle <strong>Enable</strong> → Save</li></ol><p>Spans now flow to the aws/spans log group. After your next invocation, you&#39;ll see them in the GenAI Observability dashboard.</p><p>While you’re there, do the same on your <strong>Memory</strong> resource (the Tracing pane on the Memory page) and your <strong>Gateway</strong> from Part 3 — without these, the trace tree stops at the runtime boundary and you can’t see the gateway/memory hops.</p><h3>Step 3: Invoke and Read the Trace</h3><p>Open <a href="https://console.aws.amazon.com/cloudwatch/home#gen-ai-observability">https://console.aws.amazon.com/cloudwatch/home#gen-ai-observability</a> — this is the CloudWatch GenAI Observability page. It’s a tailored view of agent activity, separate from the regular CloudWatch dashboards.</p><p>Run an invocation:</p><pre>agentcore invoke &quot;Summarize https://strandsagents.com&quot; \<br>  --user-id &quot;alice&quot; --session-id &quot;ALongThirtyThreeCharacterSessionId123&quot;</pre><p>Within ~30 seconds, you should see in the dashboard:</p><ul><li>A new <strong>session</strong> for alice</li><li>A <strong>trace</strong> with nested spans:</li></ul><pre>agent.invoke (root)<br>├─ llm.completion (Claude — tool selection)<br>├─ tool.call: saved_articles_lookup<br>│   └─ gateway.invoke_target → lambda<br>├─ tool.call: fetch_url<br>└─ llm.completion (Claude — summary generation)</pre><p>The headline numbers — total latency, token usage, tool call count — are on the trace summary. The interesting work is <em>clicking into a span</em>: input, output, attributes, duration, and any errors are right there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jfDRj_Thk0iG2cdWNzakw.png" /></figure><h3>Step 4: Add ADOT to See What’s Inside Your Code</h3><p>Service-emitted spans show you what AgentCore sees: invocations, tool boundaries, LLM hops. They don’t show you what’s happening <em>inside</em> a tool function. For that you need ADOT.</p><p>Add the dep — back in your Part 2 project directory:</p><pre>cd app/Summarizer<br>uv add aws-opentelemetry-distro<br>cd ../..</pre><p>Then change how your agent launches. Instead of running main.py directly, you want opentelemetry-instrument python main.py. How you express that depends on your build type (the build field in agentcore/agentcore.json):</p><p><strong>CodeZip (the default):</strong> ADOT auto-instrumentation kicks in once aws-opentelemetry-distro is in the project&#39;s dependencies and OTEL_PYTHON_DISTRO=aws_distro is set. Add the env var in agentcore.json under your runtime block:</p><pre>&quot;environmentVariables&quot;: {<br>  &quot;OTEL_PYTHON_DISTRO&quot;: &quot;aws_distro&quot;,<br>  &quot;OTEL_PYTHON_CONFIGURATOR&quot;: &quot;aws_configurator&quot;<br>}</pre><p><strong>Container build:</strong> edit your Dockerfile&#39;s CMD directly:</p><pre>CMD [&quot;opentelemetry-instrument&quot;, &quot;python&quot;, &quot;main.py&quot;]</pre><p>Either way, redeploy:</p><pre>agentcore deploy</pre><p>That’s it. Auto-instrumentation hooks into Strands, boto3, requests — every framework call gets a span automatically. Now your trace tree gets richer: HTTP calls inside fetch_url, the actual Bedrock InvokeModel API call, even the boto3 retries if there are any.</p><h3>Step 5: Add Your Own Spans (When It’s Worth It)</h3><p>Most of the time, auto-instrumentation is enough. The places it’s worth adding manual spans:</p><ul><li><strong>Business logic that the LLM doesn’t see</strong> — e.g. “we filtered the response through a safety checker”</li><li><strong>Branches</strong> — “summarizer fell back to cached response because fetch_url failed”</li><li><strong>Rare, slow paths</strong> — anything you’d want to count occurrences of</li></ul><p>Pattern:</p><pre>from opentelemetry import trace</pre><pre>tracer = trace.get_tracer(__name__)</pre><pre>def safety_check(text: str) -&gt; str:<br>    with tracer.start_as_current_span(&quot;safety_check&quot;) as span:<br>        span.set_attribute(&quot;text.length&quot;, len(text))<br>        result = run_safety_filter(text)<br>        span.set_attribute(&quot;safety.passed&quot;, result.passed)<br>        if not result.passed:<br>            span.set_attribute(&quot;safety.violation_type&quot;, result.violation_type)<br>        return result.cleaned_text</pre><p>Two attributes, scoped to one span. Now when you see safety.passed=false in a trace, you know exactly which invocation, which input length, which violation. <strong>That&#39;s worth more than another print statement in CloudWatch logs.</strong></p><p>A rule worth following: <strong>don’t add a custom span unless you’d act on the data.</strong> A span you’ll never look at is just expense.</p><h3>Step 6: Wire Identity Through (Carry-over From Part 5)</h3><p>The user’s identity from the JWT (Part 5) shows up on every trace automatically — that’s the --user-id you passed at invoke time. But for richer filtering (&quot;show me all traces from users in the enterprise group&quot;), you can put extra context in OTEL baggage:</p><pre>from opentelemetry import baggage, context</pre><pre>ctx = baggage.set_baggage(&quot;user.tier&quot;, &quot;enterprise&quot;)<br>context.attach(ctx)</pre><p>Now every span in this invocation carries user.tier=enterprise, and the dashboard can filter on it. Useful when you want per-segment latency dashboards without rebuilding your agent.</p><h3>Step 7: Logs, Correlated</h3><p>Standard print() and logging.info() calls land in CloudWatch under:</p><pre>/aws/bedrock-agentcore/runtimes/&lt;agent-id&gt;-&lt;endpoint&gt;/[runtime-logs]</pre><p>OTEL structured logs (auto-generated by ADOT) land in:</p><pre>/aws/bedrock-agentcore/runtimes/&lt;agent-id&gt;-&lt;endpoint&gt;/otel-rt-logs</pre><p>The OTEL log group includes the trace ID on every line. So the workflow is:</p><ol><li>Find a slow/failing trace in the GenAI dashboard → copy trace ID</li><li>Open otel-rt-logs → filter by that trace ID</li><li>See every log line that ran during that exact invocation</li></ol><p>This replaces “scroll through logs and guess” with “I know exactly which 12 log lines correspond to this bad answer.” It’s the workflow you actually want.</p><h3>What “Done” Looks Like</h3><p>After Steps 1–4, your Summarizer should produce a trace that, on a single invocation, tells you:</p><ul><li>How long the whole thing took, end-to-end</li><li>How many tokens went into and came out of the model</li><li>Which tools the model picked and why (input/output of each)</li><li>Where the time went (LLM call vs tool call vs network)</li><li>Any errors, with the exact span they happened in</li></ul><p>If a coworker asks “why was Alice’s last summary slow?” — you can answer in 90 seconds with a trace, not with “let me re-run it and add prints.”</p><h3>Two Errors You’ll Probably See</h3><p><strong>The GenAI Observability dashboard is empty even after invoking</strong> — almost always one of: (a) Transaction Search isn’t enabled on the account, or (b) tracing isn’t toggled on for that specific runtime resource. Both are required and both are independent. Confirm in the console.</p><p><strong>Custom spans don’t appear in traces</strong> — your agent isn’t being launched via opentelemetry-instrument. On Container builds, check the Dockerfile&#39;s CMD. On CodeZip, check that OTEL_PYTHON_DISTRO=aws_distro is set in agentcore.json <em>and</em> that aws-opentelemetry-distro is actually in the deployed project&#39;s dependency lock (uv add writes both pyproject.toml and uv.lock). Auto-instrumentation only loads if the distro is on the path before your code imports anything else.</p><h3>Best Practices Worth Stealing</h3><p>From the AgentCore docs (and a few hard-won extras):</p><ul><li><strong>Reuse session IDs across related requests.</strong> A 5-turn conversation should be one session, not five. Otherwise the dashboard treats each turn as an isolated user, which makes funnels meaningless.</li><li><strong>Set CloudWatch alarms on built-in metrics before launch.</strong> error_rate &gt; 5%, p95_latency &gt; 30s. You&#39;ll find issues users would have hit before they do.</li><li><strong>Resist instrumenting everything.</strong> If a span has no attributes that help you act, delete it. Cardinality is a real cost in CloudWatch.</li></ul><h3>What’s Next in the Series</h3><ul><li><strong>Part 7:</strong> Multi-agent orchestration: wiring the summarizer into a larger system of cooperating agents</li></ul><p><em>Tags: #AI #AgenticAI #AWS #AgentCore #AIEngineering #LLM #AmazonBedrock #Observability #OpenTelemetry</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73563825ee6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lock Your AI Agent Behind Real User Authentication (Hands-On)]]></title>
            <link>https://sarthakvj.medium.com/lock-your-ai-agent-behind-real-user-authentication-hands-on-acb7e14536ec?source=rss-a6a690c3b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb7e14536ec</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sarthak Vijay]]></dc:creator>
            <pubDate>Thu, 28 May 2026 09:35:19 GMT</pubDate>
            <atom:updated>2026-05-28T09:35:19.481Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Part 5 of the AgentCore Series: A Complete Guide to Building Production AI Agents on AWS</em></strong></p><p><em>Catching up? </em><a href="https://medium.com/p/8602c09efcf9"><em>Part 1</em></a><em> covers the platform. </em><a href="https://sarthakvj.medium.com/deploy-first-agent-on-aws-agentcore-9e965736f854"><em>Part 2</em></a><em> deploys the agent. </em><a href="https://sarthakvj.medium.com/connect-your-ai-agent-to-a-lambda-b6cf38d829af"><em>Part 3</em></a><em> wires it to a Lambda via Gateway. </em><a href="https://medium.com/@sarthakvj/give-your-ai-agent-a-memory-that-actually-remembers-hands-on-9c50e6f534fd"><em>Part 4</em></a><em> gives it memory. This part finally answers: who’s calling?</em></p><h3>What You’ll Build</h3><p>Right now, anyone with AWS credentials in your account can invoke the summarizer. That’s fine for a demo. It’s not how production agents work.</p><p>We’re going to put a JWT in front of the runtime. Every invocation has to carry an authenticated user’s token. The agent will know <em>which user</em> is calling and can act accordingly — different memory, different permissions, different downstream calls.</p><p><strong>Concretely</strong>:</p><ol><li><strong>The runtime rejects requests without a valid JWT</strong></li><li><strong>The agent code can see the user’s identity (sub, email, groups)</strong></li><li><strong>The Part 4 memory now segments per real user, not “default-user”</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*654zsrk4NGbQWa0g1XSV9A.png" /></figure><h3>Two Auth Directions, Don’t Confuse Them</h3><p>AgentCore Identity covers two flows. People mix them up constantly:</p><ul><li><strong>Inbound auth</strong> — “who’s allowed to invoke my agent?” Configured as a JWT authorizer on the runtime or gateway. <em>This is what we’re doing.</em></li><li><strong>Outbound auth</strong> — “the agent needs to call Google Drive on the user’s behalf — how does it get a token?” Configured as a credential provider. We’ll touch this at the end.</li></ul><p>The two are independent. You can have inbound without outbound (most agents) or both (agents that act on third-party services). Don’t try to set up both on day one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXhBk0Hah0vN_qyKs7GzCA.png" /></figure><h3>Step 1: Stand Up an OIDC Issuer</h3><p>The JWT authorizer is identity-provider-agnostic, anything OIDC-compliant works (Auth0, Okta, your corporate IdP). For testing, Cognito is the path of least resistance because it’s in your AWS account.</p><p>Save this as setup_cognito.sh and run it. It creates a user pool, a client, and a test user, and prints everything you&#39;ll need:</p><pre>#!/bin/bash<br>REGION=$(aws configure get region)<br><br>USER_POOL_ID=$(aws cognito-idp create-user-pool \<br>  --pool-name AgentCoreSummarizerPool \<br>  --query &#39;UserPool.Id&#39; --output text)<br><br>CLIENT_RESPONSE=$(aws cognito-idp create-user-pool-client \<br>  --user-pool-id $USER_POOL_ID \<br>  --client-name SummarizerClient \<br>  --generate-secret \<br>  --explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_REFRESH_TOKEN_AUTH \<br>  --query &#39;UserPoolClient.{ClientId:ClientId,ClientSecret:ClientSecret}&#39; \<br>  --output json)<br><br>CLIENT_ID=$(echo $CLIENT_RESPONSE | jq -r &#39;.ClientId&#39;)<br>USERNAME=&quot;testuser$RANDOM&quot;<br>PASSWORD=&quot;TestPass!$RANDOM&quot;<br><br>aws cognito-idp admin-create-user --user-pool-id $USER_POOL_ID \<br>  --username $USERNAME --output text &gt; /dev/null<br>aws cognito-idp admin-set-user-password --user-pool-id $USER_POOL_ID \<br>  --username $USERNAME --password $PASSWORD --permanent --output text &gt; /dev/null<br>ISSUER_URL=&quot;https://cognito-idp.$REGION.amazonaws.com/$USER_POOL_ID&quot;<br>DISCOVERY_URL=&quot;$ISSUER_URL/.well-known/openid-configuration&quot;<br><br>echo &quot;export USER_POOL_ID=&#39;$USER_POOL_ID&#39;&quot;<br>echo &quot;export CLIENT_ID=&#39;$CLIENT_ID&#39;&quot;<br>echo &quot;export DISCOVERY_URL=&#39;$DISCOVERY_URL&#39;&quot;<br>echo &quot;export USERNAME=&#39;$USERNAME&#39;&quot;<br>echo &quot;export PASSWORD=&#39;$PASSWORD&#39;&quot;</pre><p>Run it, copy the export lines into your shell. You now have an OIDC issuer.</p><h3>Step 2: Attach the JWT Authorizer to the Runtime</h3><p>This is the actual thing we’re learning. The control-plane configures the runtime to require a JWT on every invocation. One subtlety up front: update_agent_runtime is a <strong>full update</strong> API, not a PATCH, you have to pass the runtime&#39;s existing config back in alongside the new authorizer. So it&#39;s a two-step call: read, then write.</p><pre># attach_authorizer.py<br>import boto3, os</pre><pre>ctrl = boto3.client(&quot;bedrock-agentcore-control&quot;, region_name=&quot;us-west-2&quot;)</pre><pre>current = ctrl.get_agent_runtime(<br>    agentRuntimeId=&quot;&lt;your-runtime-id&gt;&quot;,   # from `agentcore status`<br>)</pre><pre>ctrl.update_agent_runtime(<br>    agentRuntimeId=current[&quot;agentRuntimeId&quot;],<br>    agentRuntimeArtifact=current[&quot;agentRuntimeArtifact&quot;],<br>    roleArn=current[&quot;roleArn&quot;],<br>    networkConfiguration=current[&quot;networkConfiguration&quot;],<br>    authorizerConfiguration={<br>        &quot;customJWTAuthorizer&quot;: {<br>            &quot;discoveryUrl&quot;: os.environ[&quot;DISCOVERY_URL&quot;],<br>            &quot;allowedClients&quot;: [os.environ[&quot;CLIENT_ID&quot;]],<br>        }<br>    },<br>)<br>print(&quot;Authorizer attached.&quot;)</pre><p>The first call hands you the existing artifact, role, and network config; the second writes them back along with the new authorizerConfiguration. Skip the read and you&#39;ll get MissingParameter on agentRuntimeArtifact.</p><p>Three things matter:</p><ul><li><strong>discoveryUrl</strong> must end in /.well-known/openid-configuration. AgentCore fetches the public keys from there and rotates them automatically — you never deal with key management.</li><li><strong>allowedClients</strong> — the JWT&#39;s client_id claim must be one of these. This is the gate that prevents tokens issued for <em>other</em> apps in the same Cognito pool from being accepted.</li><li>You need <em>at least one</em> of: allowedClients, allowedAudience, allowedScopes, or requiredCustomClaims. They AND together — every constraint you set must pass.</li></ul><p>Same config shape works on Gateway from Part 3 (update_gateway instead of update_agent_runtime). Same JWT, different door.</p><h3>Step 3: Read the User’s Identity Inside the Agent</h3><p>Here’s the part that surprises people: <strong>the runtime validates the JWT but doesn’t decode the claims for you.</strong> It rejects bad tokens at the door, then forwards the raw Authorization header through to your code. If you want the user&#39;s identity (sub, email, groups), you decode the JWT yourself in the entrypoint.</p><p>That’s actually the right design; your agent decides which claims matter. Update main.py:</p><pre>import jwt  # PyJWT<br>from bedrock_agentcore.runtime import BedrockAgentCoreApp<br>from strands import Agent<br>from memory.session import get_session_manager<br><br>app = BedrockAgentCoreApp()<br><br>def claims_from_context(context):<br>    &quot;&quot;&quot;Pull the JWT off the request and decode it. Signature already validated by the runtime.&quot;&quot;&quot;<br>    headers = context.request_headers or {}<br>    auth = headers.get(&quot;Authorization&quot;, &quot;&quot;)<br>    if not auth.startswith(&quot;Bearer &quot;):<br>        return None<br>    token = auth.removeprefix(&quot;Bearer &quot;)<br>    # verify_signature=False is safe here - the runtime validated it before this code ran<br>    return jwt.decode(token, options={&quot;verify_signature&quot;: False})<br><br>@app.entrypoint<br>async def invoke(payload, context):<br>    claims = claims_from_context(context)<br>    if not claims:<br>        return {&quot;error&quot;: &quot;unauthenticated&quot;}<br>    actor_id = claims[&quot;sub&quot;]                 # stable user identifier from Cognito<br>    session_id = context.session_id or &quot;default-session&quot;<br>    agent = Agent(<br>        model=&quot;us.anthropic.claude-haiku-4-5-20251001-v1:0&quot;,<br>        session_manager=get_session_manager(session_id, actor_id),<br>        system_prompt=(<br>            &quot;You are a research assistant. Summarize URLs the user gives you. &quot;<br>            &quot;If you have notes on the user&#39;s preferences, respect them.&quot;<br>        ),<br>    )<br>    return {&quot;result&quot;: str(agent(payload.get(&quot;prompt&quot;, &quot;&quot;)))}</pre><p>Add pyjwt to requirements.txt if it&#39;s not already there.</p><p>Notice what changed from Part 4: actor_id is no longer &quot;default-user&quot;. It&#39;s the real sub claim from the JWT; a stable user identifier from Cognito. <strong>The Part 4 memory now naturally segments per user.</strong> No code change to memory; it just works once actor_id becomes real.</p><p>Redeploy:</p><pre>agentcore deploy</pre><h3>Step 4: Test the Auth Flow</h3><p>First, get a real JWT from Cognito:</p><pre>JWT=$(aws cognito-idp admin-initiate-auth \<br>  --user-pool-id $USER_POOL_ID \<br>  --client-id $CLIENT_ID \<br>  --auth-flow ADMIN_NO_SRP_AUTH \<br>  --auth-parameters USERNAME=$USERNAME,PASSWORD=$PASSWORD \<br>  --query &#39;AuthenticationResult.AccessToken&#39; --output text)<br>echo $JWT | head -c 60; echo &quot;...&quot;</pre><p>Now invoke without it (this should fail) and with it (this should work):</p><pre># Should fail — no token<br>curl -s -X POST &lt;runtime-invoke-url&gt; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;prompt&quot;: &quot;Summarize https://strandsagents.com&quot;}&#39;<br># → 401 Unauthorized<br><br># Should succeed<br>curl -s -X POST &lt;runtime-invoke-url&gt; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;Authorization: Bearer $JWT&quot; \<br>  -d &#39;{&quot;prompt&quot;: &quot;Summarize https://strandsagents.com&quot;}&#39;<br># → 200, with the summary</pre><p>The runtime’s invoke URL is in agentcore status. The 401 vs 200 split is the whole point: invocation now demands an authenticated user, and the agent code can trust the identity it receives.</p><h3>Step 5: What the Agent Sees</h3><p>The context object is intentionally thin, it gives you session_id, request_headers, and the raw request. The JWT is in request_headers[&quot;Authorization&quot;]. Once you decode it (as we did in Step 3), you have the full claim set to work with:</p><ul><li><strong>Memory</strong> automatically segments by user (we already saw this — actor_id = claims[&quot;sub&quot;])</li><li><strong>Authorization decisions</strong> can be made in the agent code — if &quot;admin&quot; in claims.get(&quot;cognito:groups&quot;, []): ...</li><li><strong>Audit</strong> — pass claims[&quot;sub&quot;] into your custom spans (Part 6) so every trace carries user identity</li></ul><p>Don’t overbuild the authorization layer in agent code. The JWT authorizer already gate-keeps invocation. <em>Inside</em> the agent, you’re checking finer-grained things: which tools to expose, which memories to retrieve, which records to mutate.</p><h3>A Note on Outbound (For Later)</h3><p>If your agent needs to call Google Drive or Slack <em>on the user’s behalf</em>, that’s outbound auth. The pattern is:</p><pre>from bedrock_agentcore.identity import requires_access_token<br><br>@requires_access_token(<br>    provider_name=&quot;GoogleDriveProvider&quot;,<br>    scopes=[&quot;https://www.googleapis.com/auth/drive.readonly&quot;],<br>    auth_flow=&quot;USER_FEDERATION&quot;,<br>)<br>async def list_files(*, access_token: str):<br>    # access_token is injected - call Google Drive with it<br>    ...</pre><p>This requires creating a credential provider (agentcore add credential --type oauth ...) and the user goes through a one-time OAuth consent flow on first use. Tokens are stored encrypted in AgentCore&#39;s token vault, never in your agent code. Skipping the full walkthrough here; the AgentCore docs have a clean Cognito-and-Google example.</p><p><strong>The mental model: inbound proves <em>who&#39;s calling</em>, outbound delegates <em>acting on their behalf</em>.</strong></p><h3>Two Errors You’ll Probably See</h3><p><strong>401 Unauthorized even with a valid token</strong> — almost always one of: (a) the token expired (Cognito access tokens default to 60 min), (b) allowedClients doesn&#39;t include the client that minted the token, or (c) the discovery URL is wrong (must include /.well-known/openid-configuration). Decode the JWT at jwt.io and check the client_id claim against your allowedClients.</p><p><strong>claims_from_context returns </strong><strong>None even with a valid token</strong> — the Authorization header isn&#39;t reaching your code. The runtime only forwards specific headers; confirm Authorization is in context.request_headers. If not, you&#39;re hitting agentcore dev (local dev server doesn&#39;t enforce JWTs by default) — test against the deployed runtime instead.</p><h3>Cleanup</h3><pre>agentcore remove all &amp;&amp; agentcore deploy   # tears down the runtime<br>aws cognito-idp delete-user-pool --user-pool-id $USER_POOL_ID</pre><h3>What’s Next in the Series</h3><ul><li><strong>Part 6:</strong> Observability deep dive; trace structure, evaluation metrics, replaying decisions (now with user identity in every trace, courtesy of this part)</li><li><strong>Part 7:</strong> Multi-agent orchestration</li></ul><p><em>Tags: #AI #AgenticAI #AWS #AgentCore #AIEngineering #LLM #AmazonBedrock #Strands #Identity #OAuth</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb7e14536ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Give Your AI Agent a Memory That Actually Remembers (Hands-On)]]></title>
            <link>https://sarthakvj.medium.com/give-your-ai-agent-a-memory-that-actually-remembers-hands-on-9c50e6f534fd?source=rss-a6a690c3b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c50e6f534fd</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sarthak Vijay]]></dc:creator>
            <pubDate>Wed, 27 May 2026 21:43:29 GMT</pubDate>
            <atom:updated>2026-05-27T21:43:29.875Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 4 of the AgentCore Series: A Complete Guide to Building Production AI Agents on AWS</em></p><p><em>Catching up? </em><a href="https://medium.com/p/8602c09efcf9"><em>Part 1</em></a><em> covers the platform. </em><a href="https://sarthakvj.medium.com/deploy-first-agent-on-aws-agentcore-9e965736f854"><em>Part 2</em></a><em> deploys a Strands agent in 5 minutes. </em><a href="https://sarthakvj.medium.com/connect-your-ai-agent-to-a-lambda-b6cf38d829af"><em>Part 3</em></a><em> wires it to a Lambda via Gateway. This part adds the brain: memory.</em></p><h3>What You’ll Build</h3><p>The summarizer from Parts 2 and 3 forgets everything the moment a session ends. We’re going to fix that.</p><h4>By the end of this article, the agent will:</h4><ol><li>Remember turn-by-turn context within a session (short-term memory)</li><li>Extract user preferences across sessions and apply them on the next visit (long-term memory)</li></ol><p>You’ll add this with about 10 lines of agent-side code. The infrastructure is one CLI command.</p><h3>Two Kinds of Memory, Picked for You</h3><p>AgentCore Memory makes one distinction up front:</p><ul><li><strong>Short-term memory: </strong>turn-by-turn history within a single session. Free, automatic, always on once the memory resource is attached.</li><li><strong>Long-term memory: </strong>insights extracted from conversations and persisted across sessions. Requires picking a <em>strategy</em>.</li></ul><p>Short-term is obvious. The interesting choice is long-term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WReeOMJE8DGeJpq-zop64Q.png" /></figure><p><strong>There are four built-in long-term strategies.</strong> Each runs in the background after every conversation, reads the events, and writes structured records you can query later:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YY7R8OnNxDeyNIetVjL0dQ.png" /></figure><p>You can attach more than one to a single memory resource. Don’t, at least not yet. <strong>Start with one, ship, then add.</strong> Each strategy costs an extraction pass per event; stacking three on day one means you’re paying for retrievals you’re not querying.</p><p>For the summarizer, we want the agent to remember the user’s reading preferences (language, depth). That’s userPreferenceMemoryStrategy.</p><blockquote><strong><em>Naming gotcha:</em></strong><em> The control-plane API uses </em><em>userPreferenceMemoryStrategy, </em><em>semanticMemoryStrategy, </em><em>summaryMemoryStrategy, </em><em>episodicMemoryStrategy (camelCase). The </em><em>agentcore CLI uses ALL-CAPS aliases: </em><em>USER_PREFERENCE, </em><em>SEMANTIC, </em><em>SUMMARIZATION, </em><em>EPISODIC. Same strategies, different names depending on which surface you&#39;re calling.</em></blockquote><h3>Step 1: Add the Memory Resource</h3><p>From your Part 2/3 project directory:</p><pre>agentcore add memory --name ReaderMemory --strategies USER_PREFERENCE<br>agentcore deploy</pre><p>Two minutes. That’s it for infrastructure.</p><p>After deploy, AgentCore automatically exposes an environment variable to your agent runtime:</p><pre>MEMORY_READERMEMORY_ID=mem_abc123...</pre><p>Verify:</p><pre>agentcore status</pre><h3>Step 2: Wire the Session Manager</h3><p>Strands has a first-party integration with AgentCore Memory. The session manager handles short-term memory automatically and lets you query long-term records.</p><p>Create app/Summarizer/memory/session.py:</p><pre>import os<br>from typing import Optional<br>from bedrock_agentcore.memory.integrations.strands.config import (<br>    AgentCoreMemoryConfig,<br>    RetrievalConfig,<br>)<br>from bedrock_agentcore.memory.integrations.strands.session_manager import (<br>    AgentCoreMemorySessionManager,<br>)<br><br>MEMORY_ID = os.getenv(&quot;MEMORY_READERMEMORY_ID&quot;)<br>REGION = os.getenv(&quot;AWS_REGION&quot;, &quot;us-west-2&quot;)<br><br>def get_session_manager(session_id: str, actor_id: str) -&gt; Optional[AgentCoreMemorySessionManager]:<br>    if not MEMORY_ID:<br>        return None  # Local dev without memory: degrade gracefully<br>    # Pull up to 3 preference records relevant to the current prompt<br>    retrieval_config = {<br>        f&quot;/users/{actor_id}/preferences/&quot;: RetrievalConfig(top_k=3, relevance_score=0.5),<br>    }<br>    return AgentCoreMemorySessionManager(<br>        AgentCoreMemoryConfig(<br>            memory_id=MEMORY_ID,<br>            session_id=session_id,<br>            actor_id=actor_id,<br>            retrieval_config=retrieval_config,<br>        ),<br>        REGION,<br>    )</pre><p>A couple of details that trip people up:</p><ul><li><strong>namespace</strong> — the path string is <em>not</em> arbitrary. It must match the strategy&#39;s namespaceTemplates. The default for userPreferenceMemoryStrategy is /users/{actorId}/preferences/. Use the same path on read.</li><li><strong>relevance_score=0.5</strong> — a floor. Scores below this are filtered out. Start at 0.5; tune from traces.</li><li><strong>top_k=3</strong> — how many records to inject as context. More is not better; the LLM gets noisier.</li></ul><h3>Step 3: Use the Session Manager in main.py</h3><p>Update the entrypoint from Part 3 to thread session_id and actor_id through:</p><pre>from bedrock_agentcore.runtime import BedrockAgentCoreApp<br>from strands import Agent<br>from memory.session import get_session_manager<br><br>app = BedrockAgentCoreApp()<br><br>@app.entrypoint<br>async def invoke(payload, context):<br>    session_id = context.session_id or &quot;default-session&quot;<br>    # actor_id from payload for now; Part 5 wires it from the authenticated JWT<br>    actor_id = payload.get(&quot;actor_id&quot;, &quot;default-user&quot;)<br>    agent = Agent(<br>        model=&quot;us.anthropic.claude-haiku-4-5-20251001-v1:0&quot;,<br>        session_manager=get_session_manager(session_id, actor_id),<br>        system_prompt=(<br>            &quot;You are a research assistant. Summarize URLs the user gives you. &quot;<br>            &quot;If you have notes on the user&#39;s preferences (language, depth, format), &quot;<br>            &quot;respect them without restating them.&quot;<br>        ),<br>    )<br>    return {&quot;result&quot;: str(agent(payload.get(&quot;prompt&quot;, &quot;&quot;)))}</pre><p>Notice the prompt: <em>“respect them without restating them.”</em> Without that, the agent will narrate “Based on your preference for short summaries…” every single turn, which is annoying. Tell it to act on memory, not announce it.</p><p>Redeploy:</p><pre>agentcore deploy</pre><h3>Step 4: Teach It Something, Then Test the Memory</h3><p>Two invocations, separate sessions, same actor_id.</p><p><strong>Session 1: establish a preference:</strong></p><pre>agentcore invoke &quot;Summarize https://strandsagents.com — and from now on keep summaries to 2 lines, no preamble.&quot;</pre><p>Behind the scenes: the assistant responds, the conversation is written as events, and the user-preference extractor (running async, ~30s later) writes a record like:</p><pre>namespace: /users/default-user/preferences/<br>content:   &quot;User prefers 2-line summaries with no preamble.&quot;</pre><p><strong>Session 2: different session, same user:</strong></p><pre>agentcore invoke &quot;Summarize https://anthropic.com&quot;</pre><p>The session manager queries /users/default-user/preferences/ before the model runs, finds the record, and prepends it as context. The agent gives you a 2-line summary without you asking.</p><p>That’s the loop. Once it works, every preference the user expresses anywhere in the agent compounds.</p><h3>Step 5: Inspect What’s Actually Stored</h3><p>You’ll want this on day one — both for debugging and to build trust that the extraction is working.</p><pre>import boto3<br>from bedrock_agentcore.memory import MemorySessionManager<br><br>mgr = MemorySessionManager(<br>    memory_id=&quot;mem_abc123...&quot;,  # from agentcore status<br>    region_name=&quot;us-west-2&quot;,<br>)<br>session = mgr.create_memory_session(<br>    actor_id=&quot;default-user&quot;,<br>    session_id=&quot;any-session&quot;,  # required, but list_long_term... is session-agnostic<br>)<br>records = session.list_long_term_memory_records(namespace_path=&quot;/users/default-user/preferences/&quot;)<br>for r in records:<br>    print(r)</pre><p>If the list is empty after 60 seconds: the extractor either didn’t fire (check agentcore status) or extracted nothing useful (the conversation didn&#39;t actually contain a preference). Both are fine — extractors are deliberately conservative. They&#39;d rather miss a record than fabricate one.</p><h3>When to Use Which Strategy (The Honest Version)</h3><p>The four strategies sound similar in the docs. They’re not. A practical decoder:</p><ul><li><strong>Use </strong><strong>userPreferenceMemoryStrategy</strong> when the value is the <em>user</em>. Settings, styles, choices. The summarizer&#39;s reading preferences. Don&#39;t use it for facts about <em>things</em>.</li><li><strong>Use </strong><strong>semanticMemoryStrategy</strong> when the value is the <em>world</em>. Ticket numbers, account IDs, project state. Don&#39;t use it for personalization — it&#39;ll record &quot;user mentioned order #123&quot; instead of &quot;user prefers fast shipping.&quot;</li><li><strong>Use </strong><strong>summaryMemoryStrategy</strong> when sessions are long and you can&#39;t afford to replay history. A 90-minute coding session compressed into a paragraph the next session loads instead. Doesn&#39;t compete with the other two — it&#39;s about session length, not insight type.</li><li><strong>Use </strong><strong>episodicMemoryStrategy</strong> when you want the agent to <em>learn</em>. Which approaches worked, which didn&#39;t, what to try next time. The expensive one — most early-stage agents don&#39;t need it. Reach for it after the agent is in production and you have a reason to optimize over time.</li></ul><p>If you can’t pick: start with the one that matches the value the user gets. Personalization → user preference. Persistence of state → semantic. The other two are optimizations.</p><h3>Two Errors You’ll Probably See</h3><ol><li><strong>Memory records list is empty after a clearly-preference-laden conversation</strong> — extractors run async (30s–2min) and only fire if the strategy thinks there’s something to extract. Wait, then re-check. If still empty, look at the actual events with session.get_last_k_turns(k=20) — if the events are there, the extractor saw nothing it considered a stable preference. That&#39;s by design.</li><li><strong>AccessDeniedException on </strong><strong>create_memory_session</strong> — your runtime role needs the relevant memory actions: bedrock-agentcore:CreateEvent, GetEvent, ListEvents, plus the memory-record actions (GetMemoryRecord, ListMemoryRecords, BatchCreateMemoryRecords). The CLI scaffolds these on first deploy; if you&#39;re running locally with bare aws configure, attach them yourself. The full action list is in the <a href="https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrockagentcore.html">bedrock-agentcore IAM reference</a>.</li></ol><h3>Cleanup</h3><pre>agentcore remove memory --name ReaderMemory<br>agentcore deploy</pre><p>Memory resources cost money while they exist (storage + extraction). Clean up dev memories or you’ll see them on the bill.</p><h3>What’s Next in the Series</h3><ul><li><strong>Part 5:</strong> <strong>Identity</strong>: picking up the JWT/end-user auth thread we deferred in Part 3</li><li><strong>Part 6:</strong> Observability deep dive: trace structure, evaluation metrics, replaying decisions</li><li><strong>Part 7:</strong> Multi-agent orchestration</li></ul><h3>Series Navigation</h3><ul><li><strong>Part 1:</strong> <a href="https://medium.com/p/8602c09efcf9">Understanding Amazon Bedrock AgentCore</a></li><li><strong>Part 2:</strong> Deploy your first agent in 5 minutes</li><li><strong>Part 3:</strong> Connect your agent to a Lambda — without giving it Lambda access</li><li><strong>Part 4:</strong> <em>(this article)</em> — Give your agent a memory that actually remembers</li><li><strong>Part 5:</strong> Coming soon</li></ul><p><strong><em>Tags: #AI #AgenticAI #AWS #AgentCore #AIEngineering #LLM #AmazonBedrock #Strands</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c50e6f534fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connect Your AI Agent to a Lambda]]></title>
            <link>https://sarthakvj.medium.com/connect-your-ai-agent-to-a-lambda-b6cf38d829af?source=rss-a6a690c3b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6cf38d829af</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[amazon-bedrock-agentcore]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sarthak Vijay]]></dc:creator>
            <pubDate>Mon, 25 May 2026 20:51:07 GMT</pubDate>
            <atom:updated>2026-05-27T21:20:27.105Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3 of the AgentCore Series: A Complete Guide to Building Production AI Agents on AWS</em></p><p><em>Catching up? </em><a href="https://medium.com/p/8602c09efcf9"><em>Part 1</em></a><em> covers the platform. </em><a href="https://medium.com/@sarthakvj/deploy-first-agent-on-aws-agentcore-9e965736f854"><em>Part 2</em></a><em> gets a Strands agent running on Runtime in 5 minutes. This part adds tools properly.</em></p><h3>What You’ll Build</h3><p>The Part 2 summarizer worked, but every URL was new to it. We’re going to give it memory of what you’ve already read.</p><p><strong>Concretely</strong>: a tiny Lambda called <strong>saved_articles_lookup</strong> that returns whether a URL has been read before. The agent calls it via <strong>AgentCore Gateway, </strong>not directly. That distinction is the point of this article.</p><p>When you’re done, the trace will show the agent picking the tool, Gateway invoking the Lambda, and the response flowing back, with the Lambda’s IAM role separate from the agent’s. That separation is the <em>privilege boundary</em>, and it’s the reason Gateway exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*VceyOYpjP_kotMkW0g5QKA.jpeg" /></figure><h3>Why Not Just Call the Lambda Directly?</h3><p>You could. Pass the agent a tool that does boto3.client(&quot;lambda&quot;).invoke(...) and ship it. It works.</p><p>What you’d lose:</p><ol><li><strong>The agent’s IAM role gets </strong><strong>lambda:InvokeFunction on every backend you wire up.</strong> That role is now a master key and the LLM is holding it.</li><li><strong>No central place to add auth, rate limits, or audit.</strong> Every agent reinvents these.</li><li><strong>Adding a tool means redeploying agent code.</strong> Tools become code, not config.</li></ol><p>Gateway flips that: the <strong><em>gateway</em></strong> holds the IAM role to invoke backends. The agent only knows “there’s an MCP server at this URL.” Adding a tool is a config change no redeploy of the agent.</p><h3>Step 1: Write the Lambda</h3><pre># saved_articles_lookup/handler.py<br>def lambda_handler(event, _):<br>    url = event.get(&quot;url&quot;, &quot;&quot;)<br>    SAVED = {&quot;https://strandsagents.com&quot;, &quot;https://anthropic.com&quot;}<br>    return {&quot;url&quot;: url, &quot;previously_read&quot;: url in SAVED}</pre><p>Deploy however you like. From the shell:</p><pre>zip handler.zip handler.py<br>aws lambda create-function \<br>  --function-name saved_articles_lookup \<br>  --runtime python3.12 \<br>  --role arn:aws:iam::ACCT:role/lambda-basic-execution \<br>  --handler handler.lambda_handler \<br>  --zip-file fileb://handler.zip \<br>  --region us-west-2</pre><p>Copy the function ARN. Gateway needs it.</p><h3>Step 2: Create the Gateway and Target</h3><p>Two API calls against the <strong>bedrock-agentcore-control</strong> client. The gateway takes a few seconds to provision, so we poll until it&#39;s ready.</p><pre># setup_gateway.py<br>import boto3, time<br>ctrl = boto3.client(&quot;bedrock-agentcore-control&quot;, region_name=&quot;us-west-2&quot;)<br><br># 1. Create the gateway<br>gw = ctrl.create_gateway(<br>    name=&quot;summarizer-gateway&quot;,<br>    roleArn=&quot;arn:aws:iam::ACCT:role/AgentCoreGatewayRole&quot;,  # invokes targets<br>    protocolType=&quot;MCP&quot;,<br>    authorizerType=&quot;AWS_IAM&quot;,  # agent runtime authenticates via SigV4<br>)<br>gateway_id = gw[&quot;gatewayId&quot;]<br><br># 2. Wait for READY (usually 10-30s)<br>while True:<br>    status = ctrl.get_gateway(gatewayIdentifier=gateway_id)[&quot;status&quot;]<br>    if status == &quot;READY&quot;:<br>        break<br>    print(f&quot;Gateway status: {status} - waiting...&quot;)<br>    time.sleep(5)<br>gateway_url = ctrl.get_gateway(gatewayIdentifier=gateway_id)[&quot;gatewayUrl&quot;]<br><br># 3. Add the Lambda target<br>ctrl.create_gateway_target(<br>    gatewayIdentifier=gateway_id,<br>    name=&quot;saved_articles&quot;,<br>    targetConfiguration={<br>        &quot;mcp&quot;: {<br>            &quot;lambda&quot;: {<br>                &quot;lambdaArn&quot;: &quot;arn:aws:lambda:us-west-2:ACCT:function:saved_articles_lookup&quot;,<br>                &quot;toolSchema&quot;: {<br>                    &quot;inlinePayload&quot;: [{<br>                        &quot;name&quot;: &quot;saved_articles_lookup&quot;,<br>                        &quot;description&quot;: &quot;Check whether a URL has been read before. Returns previously_read boolean.&quot;,<br>                        &quot;inputSchema&quot;: {<br>                            &quot;type&quot;: &quot;object&quot;,<br>                            &quot;properties&quot;: {&quot;url&quot;: {&quot;type&quot;: &quot;string&quot;}},<br>                            &quot;required&quot;: [&quot;url&quot;],<br>                        },<br>                    }]<br>                },<br>            }<br>        }<br>    },<br>    credentialProviderConfigurations=[<br>        {&quot;credentialProviderType&quot;: &quot;GATEWAY_IAM_ROLE&quot;}<br>    ],<br>)<br>print(f&quot;Gateway ready: {gateway_url}&quot;)</pre><p>Three things worth noticing:</p><ul><li><strong>authorizerType=&quot;AWS_IAM&quot;</strong> means the agent authenticates to the gateway using SigV4. No OAuth setup needed for agent-to-gateway calls.</li><li><strong>credentialProviderConfigurations</strong> tells the gateway to use its own IAM role when invoking the Lambda. That&#39;s the privilege separation — the gateway&#39;s role holds lambda:InvokeFunction, not the agent&#39;s.</li><li><strong>toolSchema</strong> is what the agent actually sees when it lists tools. Treat its description like a public API contract — the LLM picks tools by reading it.</li></ul><p>Run it. Save the gateway URL (it looks like https://&lt;id&gt;.gateway.bedrock-agentcore.us-west-2.amazonaws.com).</p><h3>Step 3: Step 3: Write a SigV4 Helper</h3><p>We picked authorizerType=”AWS_IAM”, so the agent needs to sign every request to the gateway with SigV4. The MCP client library doesn’t sign for you — there’s no streamablehttp_client_with_sigv4 in any pip package. It’s ~25 lines you write once.</p><p><em>Save this as app/Summarizer/streamable_http_sigv4.py:</em></p><pre><br><br>import httpx<br>  from botocore.auth import SigV4Auth<br>  from botocore.awsrequest import AWSRequest<br>  from mcp.client.streamable_http import streamablehttp_client<br><br><br>  class SigV4HttpxAuth(httpx.Auth):<br>      &quot;&quot;&quot;httpx.Auth that signs each request with SigV4 before it leaves the client.&quot;&quot;&quot;<br><br>      requires_request_body = True<br><br>      def __init__(self, credentials, service: str, region: str):<br>          self._signer = SigV4Auth(credentials, service, region)<br><br>      def auth_flow(self, request):<br>          body = request.read() or b&quot;&quot;<br>          aws_req = AWSRequest(<br>              method=request.method,<br>              url=str(request.url),<br>              data=body,<br>              headers=dict(request.headers),<br>          )<br>          self._signer.add_auth(aws_req)<br>          for k, v in aws_req.headers.items():<br>              request.headers[k] = v<br>          yield request<br><br><br>  def streamablehttp_client_with_sigv4(url, credentials, service, region):<br>      return streamablehttp_client(<br>          url,<br>          auth=SigV4HttpxAuth(credentials, service, region),<br>      )<br><br>## streamablehttp_client already accepts an httpx.Auth - <br>## we plug SigV4 signing into that hook. That&#39;s it.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YUITD2QsZygDvo_2gcILFg.jpeg" /></figure><h3><strong>Step 4: Connect the Agent</strong></h3><p>Strands speaks MCP natively. Replace the local @tool from Part 2 with the gateway as a tool source in your main.py:</p><pre>from bedrock_agentcore.runtime import BedrockAgentCoreApp<br>from strands import Agent<br>from strands.tools.mcp import MCPClient<br>from streamable_http_sigv4 import streamablehttp_client_with_sigv4<br>import boto3<br><br># Append /mcp - this is the MCP protocol endpoint on the gateway<br>GATEWAY_URL = &quot;https://&lt;your-gateway-id&gt;.gateway.bedrock-agentcore.us-west-2.amazonaws.com/mcp&quot;<br>app = BedrockAgentCoreApp()<br><br>@app.entrypoint<br>def invoke(payload):<br>    # Fresh credentials each invocation (STS tokens rotate)<br>    session = boto3.Session()<br>    credentials = session.get_credentials().get_frozen_credentials()<br>    # MCPClient signs requests to the gateway with the agent&#39;s runtime role<br>    mcp_client = MCPClient(<br>        lambda: streamablehttp_client_with_sigv4(<br>            url=GATEWAY_URL,<br>            credentials=credentials,<br>            service=&quot;bedrock-agentcore&quot;,<br>            region=&quot;us-west-2&quot;,<br>        )<br>    )<br>    with mcp_client:<br>        agent = Agent(<br>            model=&quot;us.anthropic.claude-haiku-4-5-20251001-v1:0&quot;,<br>            tools=mcp_client.list_tools_sync(),  # discovered, not hard-coded<br>            system_prompt=(<br>                &quot;You are a research assistant. For any URL the user gives you: &quot;<br>                &quot;(1) check saved_articles_lookup first, &quot;<br>                &quot;(2) if new, fetch and summarize, &quot;<br>                &quot;(3) always state which case it was.&quot;<br>            ),<br>        )<br>        return {&quot;result&quot;: str(agent(payload.get(&quot;prompt&quot;, &quot;&quot;)))}</pre><p>Notice what’s missing: <strong>no Lambda ARN, no </strong><strong>boto3.client(&quot;lambda&quot;), no IAM thinking in agent code.</strong> The agent doesn&#39;t know and doesn&#39;t need to know, what&#39;s behind the tool.</p><p>A few details:</p><ul><li><strong><em>SigV4HttpxAuth</em></strong><em> (from the helper you just wrote) signs each request to the gateway with the agent’s runtime IAM role. The gateway checks “is this agent allowed to call these tools?”</em></li><li><strong>with mcp_client:</strong> the MCP connection must be open while the agent runs. The context manager handles connect/disconnect.</li><li><strong>/mcp suffix</strong> on the URL, this is the MCP protocol endpoint. Without it, the handshake fails.</li></ul><p>Redeploy:</p><pre>agentcore deploy<br>agentcore invoke &quot;Have I read https://strandsagents.com yet?&quot;</pre><p><strong><em>Bearer token alternative:</em></strong><em> </em>If you’d rather use OAuth/JWT inbound auth (the pattern in the official AgentCore samples), set authorizerType=”CUSTOM_JWT” on the gateway and skip this helper, pass headers={“Authorization”: f”Bearer {token}”} straight to streamablehttp_client. We’ll wire JWT auth onto the runtime in Part 5; the gateway story is identical.</p><h3>Step 5: Read the Trace</h3><p>Open the trace view (agentcore traces, or CloudWatch Transaction Search). You&#39;ll see four hops:</p><pre>agent.invoke<br>  └─ tool_call: saved_articles___saved_articles_lookup<br>      └─ gateway.invoke_target<br>          └─ lambda: saved_articles_lookup<br>              ← {&quot;previously_read&quot;: true}</pre><blockquote><strong><em>Note:</em></strong><em> Gateway prefixes tool names with the target name (</em><em>saved_articles___). The agent sees this prefixed name when it lists tools — that&#39;s fine, the LLM matches on the description, not the exact name. If you want cleaner names, make your target name match your tool name.</em></blockquote><p>The interesting line is gateway.invoke_target. Its Caller is the agent runtime&#39;s role; its Invoked principal is the gateway&#39;s role. <strong>The agent never appears as the Lambda&#39;s invoker.</strong> That&#39;s the boundary, made real, in the audit log.</p><h3>The Auth Story (Read This Part)</h3><p>Every Gateway call has two identities:</p><pre>┌─────────┐  SigV4    ┌─────────┐  IAM     ┌─────────┐<br>│  Agent  │ ────────► │ Gateway │ ───────► │ Lambda  │<br>│ (role A)│           │ (role B)│          │         │<br>└─────────┘           └─────────┘          └─────────┘<br>  &quot;who is calling      &quot;what is the agent<br>   Gateway&quot;             allowed to do here?&quot;</pre><ul><li><strong>Agent → Gateway:</strong> the agent’s runtime role signs the request. Gateway checks <em>which tools this agent is allowed to invoke</em>.</li><li><strong>Gateway → Lambda:</strong> the gateway’s role invokes the Lambda. The agent’s role doesn’t need any Lambda permissions at all.</li></ul><p>This is the privilege boundary. The agent can’t escalate by asking the LLM for a clever Lambda invocation, because it never held lambda:InvokeFunction to begin with. The blast radius of a prompt-injected agent is bounded by what the <em>gateway</em> can do, not by what the agent role can do.</p><p>What we’re not setting up here: end-user identity propagation. If a real user triggered this call and the Lambda needs to know <em>which user</em>, you’d put a JWT issuer in front of the gateway and Gateway would forward the claims to the backend. That’s a deliberate skip for this part — the goal here is the boundary, not a full auth system. Part 5 picks the JWT thread up properly.</p><h3>Three Errors You’ll Probably See</h3><ol><li><strong>AccessDeniedException when the gateway invokes the Lambda</strong> — Two things must be true: (1) AgentCoreGatewayRole has lambda:InvokeFunction on the target ARN, and (2) the Lambda&#39;s resource policy trusts the gateway. Add the resource policy like this:</li></ol><pre>aws lambda add-permission \<br>  --function-name saved_articles_lookup \<br>  --statement-id AllowGatewayInvoke \<br>  --action lambda:InvokeFunction \<br>  --principal bedrock-agentcore.amazonaws.com \<br>  --source-arn &quot;arn:aws:bedrock-agentcore:us-west-2:ACCT:gateway/&lt;GATEWAY_ID&gt;&quot; \<br>  --region us-west-2<br></pre><p>2. <strong>Gateway status: FAILED:</strong>Check ctrl.get_gateway(gatewayIdentifier=gateway_id)[&quot;statusReasons&quot;]. Usually means the AgentCoreGatewayRole doesn&#39;t have a trust policy for bedrock-agentcore.amazonaws.com. The role&#39;s trust policy needs:</p><pre>{<br>  &quot;Effect&quot;: &quot;Allow&quot;,<br>  &quot;Principal&quot;: {&quot;Service&quot;: &quot;bedrock-agentcore.amazonaws.com&quot;},<br>  &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>}</pre><p><strong>3. Agent doesn’t call the tool even though it’s “available”</strong> — List the targets on the gateway side (ctrl.list_gateway_targets(...)) and re-read the description you gave the tool. A vague one (&quot;Look up an article&quot;) gets ignored by the model. Be explicit: <em>what does it return, when should the model use it.</em> The description is a prompt; treat it like one.</p><h3>What’s Next in the Series</h3><ul><li><strong>Part 4:</strong> Memory architectures: episodic vs. semantic, and when each actually earns its keep</li><li><strong>Part 5:</strong> Identity and end-user auth, picking up the JWT thread we deferred here</li><li><strong>Part 6:</strong> Observability deep dive: trace structure, evals, replaying decisions</li><li><strong>Part 7:</strong> Multi-agent orchestration</li></ul><h3>Series Navigation</h3><ul><li><strong>Part 1:</strong> <a href="https://medium.com/p/8602c09efcf9">Understanding Amazon Bedrock AgentCore</a></li><li><strong>Part 2:</strong> <a href="https://medium.com/@sarthakvj/deploy-first-agent-on-aws-agentcore-9e965736f854">Deploy First Agent on AgentCore</a></li></ul><p><em>Tags: #AI #AgenticAI #AWS #AgentCore #AIEngineering #LLM #AmazonBedrock #Strands #MCP</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6cf38d829af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy First Agent on AWS AgentCore]]></title>
            <link>https://sarthakvj.medium.com/deploy-first-agent-on-aws-agentcore-9e965736f854?source=rss-a6a690c3b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e965736f854</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[amazon-bedrock-agentcore]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Sarthak Vijay]]></dc:creator>
            <pubDate>Sat, 23 May 2026 16:24:29 GMT</pubDate>
            <atom:updated>2026-05-23T16:24:29.737Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploy First Agent on AgentCore</h3><h3>Deploy Your First Agent on AgentCore Runtime in 5 Minutes (Hands-On)</h3><p><em>Part 2 of the AgentCore Series: A Complete Guide to Building Production AI Agents on AWS</em></p><p><em>New here? Start with </em><a href="https://medium.com/p/8602c09efcf9"><em>Part 1: Understanding Amazon Bedrock AgentCore</em></a>; <em>the 7 services that make agents production-ready.</em></p><h3>What You’ll Build</h3><p>A research-summarizer agent: give it a URL, get back a one-line summary + three key points. Running on AgentCore Runtime, with real logs and traces, in about 5 minutes of actual work.</p><p>This is a copy-paste-along, not an essay. If you have an AWS account with Bedrock model access, open a terminal and follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-BX1NJ9R2tXWEysCsdnWLg.png" /></figure><h3>Prereqs (1 minute)</h3><pre># Node 20+ and Python 3.10+<br>node -v &amp;&amp; python3 --version</pre><pre># <strong>AgentCore CLI</strong><br>npm install -g @aws/agentcore<br>agentcore --help</pre><pre># <strong>uv — Astral&#39;s Python package manager. The CLI uses it to manage the project venv.</strong><br>brew install uv<br># (or: curl -LsSf <a href="https://astral.sh/uv/install.sh">https://astral.sh/uv/install.sh</a> | sh)<br>uv --version</pre><pre># Make sure a Claude model is enabled in your Bedrock console<br># (us-west-2 by default — Bedrock → Model access)</pre><p>That’s the whole toolchain. The CLI is @aws/agentcore on npm. No Docker required for the default CodeZip build.</p><h3>Step 1: Scaffold the Project</h3><pre>agentcore create --name Summarizer --defaults<br>cd Summarizer</pre><p>--defaults means: Python, Strands Agents, Bedrock, no memory. You get this layout:</p><pre>Summarizer/<br>  agentcore/<br>    agentcore.json        # project + agent config<br>    aws-targets.json      # account + region<br>  app/Summarizer/<br>    main.py               # your agent code<br>    pyproject.toml</pre><p>The whole agent is in app/Summarizer/main.py. Open it.</p><h3>Step 2: Modify the Scaffold (Don’t Replace It)</h3><p>The scaffolded main.py wires up an ASGI app object that exposes your agent over the runtime&#39;s HTTP protocol. <strong>Keep that scaffolding.</strong> Only swap the agent definition and the entrypoint body.</p><p>Yours should look like this when you’re done:</p><pre>from bedrock_agentcore.runtime import BedrockAgentCoreApp<br>from strands import Agent<br>from strands.tools import tool<br>import requests<br>from bs4 import BeautifulSoup</pre><pre>app = BedrockAgentCoreApp()   </pre><pre>@tool<br>def fetch_url(/service/url: str) -&gt; str:<br>    &quot;&quot;&quot;Fetch a URL and return its readable text (first 8k chars).&quot;&quot;&quot;<br>    html = requests.get(url, timeout=10).text<br>    return BeautifulSoup(html, &quot;html.parser&quot;).get_text(&quot; &quot;, strip=True)[:8000]</pre><pre>agent = Agent(<br>    model=&quot;us.anthropic.claude-haiku-4-5-20251001-v1:0&quot;,<br>    tools=[fetch_url],<br>    system_prompt=(<br>        &quot;You are a research assistant. Given a URL: &quot;<br>        &quot;(1) fetch it, (2) return a one-line summary, &quot;<br>        &quot;(3) three key points, (4) a 1-5 relevance score. Terse only.&quot;<br>    ),<br>)</pre><pre>@app.entrypoint<br>def invoke(payload):<br>    response = agent(payload.get(&quot;prompt&quot;, &quot;&quot;))<br>    return {&quot;result&quot;: str(response)}</pre><p>Install the two extra deps with uv (editing pyproject.toml by hand isn&#39;t enough, uv is declarative, you need to sync):</p><pre>cd app/Summarizer<br>uv add requests beautifulsoup4<br>cd ../..</pre><p>That updates pyproject.toml, resolves the lockfile, and installs into .venv in one step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TBxI-iRR-1aDP4tw7g8_7g.png" /></figure><h3>Step 3: Run It Locally First</h3><pre>agentcore dev</pre><p>This boots a local server (default port 8080, sometimes 8082) that mimics the runtime contract and opens a chat UI in your browser. Type a prompt:</p><blockquote><em>Summarize </em><a href="https://strandsagents.com/"><em>https://strandsagents.com</em></a></blockquote><p>You’ll see the model reason, the fetch_url tool fire, and the structured response come back. <strong>This is the same code path that will run in production.</strong> That&#39;s the whole point of the runtime contract.</p><h3>Step 4: Deploy to AgentCore Runtime</h3><pre>agentcore deploy</pre><p>The CLI synthesizes CDK, builds your code as a CodeZip (or container, your choice), and provisions the runtime + IAM role + observability hooks. First deploy takes a few minutes because of CDK bootstrap; subsequent deploys are quick.</p><p>When it finishes:</p><pre>agentcore invoke &quot;Summarize https://strandsagents.com&quot;</pre><p>Same prompt, now running on AgentCore Runtime in your AWS account. With session isolation, microVMs, the whole platform around it. You wrote 20 lines of meaningful code.</p><h3>Step 5: The Part That Matters — Logs &amp; Traces</h3><p>Here’s the unglamorous truth: <strong>the moment your agent leaves your laptop, your stdout intuition is gone.</strong> A deployed agent that “doesn’t work right” is opaque until you can replay the trace.</p><p>Wire up observability before you start iterating. Two commands:</p><pre>agentcore logs        # stream runtime logs (CloudWatch under the hood)<br>agentcore traces      # list and inspect agent decision traces</pre><p>Turn on CloudWatch Transaction Search in your account once (the Bedrock AgentCore docs walk through this). After that, every invocation shows you which tool was picked, what input it got, what came back, where the model’s reasoning went sideways. This replaces 90% of the “guess and re-prompt” loop.</p><p>Practical rule: <strong>don’t tune prompts in production without the trace view open.</strong> You’ll talk yourself into fixes that the trace would have told you weren’t the actual problem.</p><h3>Where to Go from Here</h3><p>The samples repo has end-to-end examples — real ones, not toys:</p><ul><li><strong>Quickstart samples:</strong> <a href="https://github.com/awslabs/agentcore-samples">github.com/awslabs/agentcore-samples</a> → 00-getting-started/ is where to land first</li><li><strong>Capability deep dives:</strong> same repo, 01-features/ (Runtime, Gateway, Identity, Memory, Tools, Observability)</li><li><strong>End-to-end use cases:</strong> 02-use-cases/ — full apps you can clone and reshape</li><li><strong>Strands SDK docs:</strong> <a href="https://strandsagents.com/">strandsagents.com</a></li><li><strong>AgentCore CLI source:</strong> <a href="https://github.com/aws/agentcore-cli">github.com/aws/agentcore-cli</a></li></ul><p>When you’re done playing, tear down with agentcore remove all &amp;&amp; agentcore deploy so you&#39;re not paying for an idle runtime.</p><h3>Two Errors You’ll Probably See</h3><p><strong>ExpiredTokenException: The security token... is expired</strong> — your AWS creds aged out. The dev server caches the boto3 client at startup, so refresh creds <em>and</em> restart agentcore dev (Ctrl+C, then re-run). Refreshing while it&#39;s running won&#39;t help.</p><p><strong>ValidationException: ...on-demand throughput isn&#39;t supported. Retry... with the ID or ARN of an inference profile...</strong> newer Claude models on Bedrock require a cross-region inference profile, not a raw model ID. Add the us. prefix:</p><pre># Wrong:  model=&quot;anthropic.claude-haiku-4-5-20251001-v1:0&quot;<br># Right:  model=&quot;us.anthropic.claude-haiku-4-5-20251001-v1:0&quot;</pre><h3>What’s Next in This Series</h3><ul><li><strong>Part 3:</strong> Wire the summarizer to a real internal API via Gateway — auth propagation and the privilege boundary</li><li><strong>Part 4:</strong> Memory — when episodic actually helps, when semantic is overkill</li><li><strong>Part 5:</strong> Identity and automated reasoning — what “mathematically verified” means in practice</li><li><strong>Part 6:</strong> Observability deep dive — trace structure, evaluation metrics, replaying decisions</li><li><strong>Part 7:</strong> Multi-agent orchestration patterns</li></ul><h3>Series Navigation</h3><ul><li><strong>Part 1:</strong> <a href="https://medium.com/p/8602c09efcf9">Understanding Amazon Bedrock AgentCore</a></li><li><strong>Part 2:</strong> <em>(this article)</em> — Deploy your first agent in 5 minutes</li><li><strong>Part 3:</strong> Coming soon</li></ul><p><em>Tags: #AI #AgenticAI #AWS #AgentCore #AIEngineering #LLM #AmazonBedrock #Strands</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e965736f854" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon Bedrock AgentCore]]></title>
            <link>https://sarthakvj.medium.com/amazon-bedrock-agentcore-8602c09efcf9?source=rss-a6a690c3b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/8602c09efcf9</guid>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[agentcore]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Sarthak Vijay]]></dc:creator>
            <pubDate>Fri, 22 May 2026 17:12:11 GMT</pubDate>
            <atom:updated>2026-05-22T17:12:11.264Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Understanding Amazon Bedrock AgentCore: The Platform Behind Production AI Agents</strong></p><p><em>Part 1 of the AgentCore Series: A Complete Guide to Building Production AI Agents on AWS</em></p><p><strong>What Is Amazon Bedrock AgentCore?</strong></p><p>If you’ve built an AI agent that works beautifully on your laptop but struggled to get it running in production, with proper security, scaling, memory, and monitoring — you’ve already felt the problem AgentCore solves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YUITD2QsZygDvo_2gcILFg.jpeg" /></figure><p><strong>Amazon Bedrock AgentCore</strong> is a managed platform for building, deploying, and operating AI agents at scale. It provides the infrastructure services that sit <em>beneath</em> your agent logic the runtime, the tool connections, the memory, the security, and the observability; so you can focus on what your agent actually does.</p><p>It’s framework-agnostic (works with LangGraph, CrewAI, Strands Agents, OpenAI Agents SDK, or your own code) and model-agnostic (use any LLM). You bring the brain; AgentCore provides the body.</p><h3>The Architecture: 7 Services That Make Agents Production-Ready</h3><p>AgentCore is not a single monolithic service. It’s a modular platform of seven distinct services, each solving a specific production challenge. You can use them independently or together.</p><p>Let’s walk through each one.</p><h4>1. Runtime: Where Your Agent Lives</h4><p><strong>The problem it solves:</strong> You have agent code. Where does it actually run? How does it scale? How do you isolate one user’s session from another?</p><p><strong>What it does:</strong></p><ul><li>Deploys your agent on serverless infrastructure with complete session isolation in microVMs</li><li>Supports workloads lasting up to 8 hours (long-running agents, not just quick chat responses)</li><li>Provides a persistent filesystem — agents can suspend mid-task and resume exactly where they left off</li><li>Scales automatically based on demand</li></ul><p><strong>Why it matters:</strong> The same code that runs on your laptop deploys to Runtime without modification. No Dockerfiles, no Kubernetes configs, no capacity planning.</p><p><strong>2. Gateway: How Your Agent Connects to Tools</strong></p><p><strong>The problem it solves:</strong> Your agent needs to call APIs, Lambda functions, MCP servers, and knowledge bases — and every connection needs authentication and access control.</p><p><strong>What it does:</strong></p><ul><li>Converts existing APIs and Lambda functions into agent-compatible tools with minimal code</li><li>Supports MCP (Model Context Protocol) servers natively</li><li>Handles authentication propagation — the agent acts on behalf of the user, not as a generic service account</li><li>Provides native VPC connectivity and AWS PrivateLink for reaching internal services</li></ul><p><strong>Why it matters:</strong> Your existing service mesh becomes agent-accessible without rebuilding anything. The Gateway handles the “plumbing” of connecting agents to your enterprise systems.</p><p><strong>3. Memory: How Your Agent Remembers</strong></p><p><strong>The problem it solves:</strong> Agents that forget everything between sessions are limited to simple, stateless interactions. Real-world agents need to maintain context.</p><p><strong>What it does:</strong></p><ul><li>Persistent memory that survives across sessions</li><li>Episodic memory — agents learn from past experiences and improve decision-making over time</li><li>Semantic memory — agents store and retrieve knowledge about users, domains, and tasks</li><li>Manages context windows intelligently so agents don’t lose important information</li></ul><p><strong>Why it matters:</strong> A support agent that remembers your previous tickets. A coding agent that knows your project’s conventions. A planning agent that builds on yesterday’s work. Memory transforms agents from stateless tools into persistent collaborators.</p><p><strong>4. Browser Tool: How Your Agent Navigates the Web</strong></p><p><strong>The problem it solves:</strong> Many workflows require interacting with web applications — filling forms, extracting data, navigating UIs; but giving an agent unrestricted browser access is a security nightmare.</p><p><strong>What it does:</strong></p><ul><li>Provides a managed, sandboxed browser runtime</li><li>Agents can browse, click, type, extract data, and take screenshots</li><li>Runs in isolation — one agent’s browser session can’t affect another</li><li>Secure by default — no risk to your host environment</li></ul><p><strong>Why it matters:</strong> Entire categories of automation (web scraping, form submission, UI testing, data extraction from web apps) become possible without building custom integrations for each website.</p><p><strong>5. Code Interpreter: How Your Agent Executes Code</strong></p><p><strong>The problem it solves:</strong> Agents often need to write and run code — data analysis, file processing, calculations — but executing arbitrary code is inherently risky.</p><ul><li>Provides a sandboxed execution environment for Python (and other languages)</li><li>Agents can generate code, run it, inspect results, and iterate</li><li>Complete isolation from your production environment</li><li>Supports file I/O within the sandbox for processing uploaded data</li></ul><p><strong>Why it matters:</strong> A data analysis agent can write pandas code, run it against your dataset, and return visualizations — all without any risk to your infrastructure. The sandbox is the safety net that makes code-generating agents viable in production.</p><p><strong>6. Identity: How Your Agent Stays Authorized</strong></p><p><strong>The problem it solves:</strong> When an agent calls a tool on behalf of a user, who verifies that the agent is allowed to make that call? How do you prevent privilege escalation? How do you audit what happened?</p><ul><li>End-to-end authentication and authorization for every tool call</li><li>User identity propagates through the entire agent execution chain</li><li>Access policies verified by <strong>automated reasoning</strong> — the same technology behind IAM and S3</li><li>Ensures agents can only access what the user they represent is allowed to access</li></ul><p><strong>Why it matters:</strong> This is the difference between a demo and an enterprise deployment. Without Identity, you’re trusting that your agent code never makes an unauthorized call. With Identity, the platform <em>enforces</em> it — mathematically verified, not just hoped for.</p><p><strong>7. Observability: How You Debug and Improve Your Agent</strong></p><p><strong>The problem it solves:</strong> An agent made a bad decision at 3am. What did it do? What tools did it call? Where did it go wrong? How do you prevent it next time?</p><ul><li>Full execution tracing — see every step, every tool call, every LLM invocation</li><li>Quality evaluation metrics: correctness, helpfulness, safety, goal success rates</li><li>Real-time CloudWatch dashboards</li><li>OpenTelemetry integration for teams using Datadog, Splunk, or other platforms</li><li>Audit trails for compliance</li></ul><p><strong>Why it matters:</strong> You can’t improve what you can’t measure. Observability transforms agent debugging from “read the logs and guess” into “replay the exact decision path and see where it diverged.”</p><p><strong>How It All Fits Together: </strong>You choose your orchestration framework. AgentCore provides everything else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5RU_GFNI1p4sJwtXjjsMw.png" /></figure><h3>Two Ways to Build</h3><p>AgentCore offers a spectrum from simple to fully custom:</p><p><strong>Managed Harness (Config-driven)</strong> — Declare your agent in 3 API calls: which model, which tools, what instructions. AgentCore assembles the runtime, memory, identity, and tooling automatically. Perfect for getting started or prototyping fast.</p><p><strong>Code-driven (Bring your framework)</strong> — Write your agent in LangGraph, CrewAI, Strands, or raw Python. Deploy it to AgentCore Runtime with full control over orchestration logic. Same platform, same security, same observability.</p><p>You can start with the managed harness and graduate to code-driven when your needs grow — no migration required.</p><p><strong>The Open Source Foundation: Strands Agents</strong></p><p>AgentCore’s managed harness is powered by <strong>Strands Agents</strong>, an open-source SDK from AWS. Strands takes a model-driven approach, three components define an agent:</p><ol><li>A Language Model</li><li>System Prompt</li><li>Set of tools</li></ol><pre>from strands import Agent<br>from strands.tools import tool<br>@tool<br>def lookup_order(order_id: str) -&gt; str:<br>&quot;&quot;&quot;Look up order status by ID.&quot;&quot;&quot;<br>return f&quot;Order {order_id}: Shipped, arriving Thursday&quot;<br>agent = Agent(<br>model=&quot;us.anthropic.claude-sonnet-4–20250514&quot;,<br>tools=[lookup_order],<br>system_prompt=&quot;You are a customer service agent.&quot;<br>)<br>response = agent(&quot;Where is my order #12345?&quot;)</pre><p>This same code runs locally during development and deploys to AgentCore in production unchanged.</p><h4>What’s Coming Next in This Series</h4><p>Now that you understand <em>what</em> AgentCore is and the seven services that compose it, the rest of this series goes hands-on:</p><ul><li><strong>Part 2:</strong> Building and deploying your first agent with Strands + AgentCore Runtime</li><li><strong>Part 3:</strong> Connecting agents to enterprise APIs with Gateway</li><li><strong>Part 4:</strong> Memory architectures — episodic vs. semantic and when to use each</li><li><strong>Part 5:</strong> Securing agents with Identity and automated reasoning</li><li><strong>Part 6:</strong> Debugging agents in production with Observability</li><li><strong>Part 7:</strong> Multi-agent systems and orchestration patterns at scale</li></ul><p><strong>Getting Started</strong></p><p>- <strong>AgentCore CLI:</strong> <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-get-started-cli.html">bedrock-agentcore/latest/devguide/runtime-get-started-cli.html</a>)</p><p>- <strong>Strands Agents SDK:</strong> <a href="http://github.com/strands-agents/sdk-python%20(https://github.com/strands-agents/sdk-python">github.com/strands-agents/sdk-python</a></p><p>- <strong>Sample code:</strong> <a href="https://github.com/awslabs/agentcore-samples">github.com/awslabs/agentcore-samples</a></p><p>- <strong>Availability:</strong> All AWS commercial regions (CLI, filesystem, skills); Managed harness in preview (US West, US East, Sydney, Frankfurt)</p><blockquote><strong><em>Follow along for Part 2, where we build and deploy a working agent from scratch.</em></strong></blockquote><p><em>#AI #AgenticAI #AWS #AgentCore #AIEngineering #LLM #AmazonBedrock</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8602c09efcf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS: Rise of Custom AI Chips]]></title>
            <link>https://sarthakvj.medium.com/aws-rise-of-custom-ai-chips-7959a9f1729e?source=rss-a6a690c3b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7959a9f1729e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sarthak Vijay]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 19:43:35 GMT</pubDate>
            <atom:updated>2026-01-10T19:43:35.890Z</atom:updated>
            <content:encoded><![CDATA[<p>The rise of custom AI chips marks a pivotal shift in the AI infrastructure landscape. For years, <strong>NVIDIA GPUs</strong> dominated machine learning workloads thanks to their flexibility and the maturity of the CUDA ecosystem. However, as AI models particularly large language models (LLMs) grew exponentially in size and deployment scale, the cost of training and inference surged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3VIW3jf2Xk4jBDAZp57QZw.png" /></figure><p>Hyperscalers such as <strong>AWS</strong> and <strong>Google</strong> realized that general-purpose GPUs, while powerful, were often inefficient for large-scale production workloads. This realization led to the development of <strong>specialized AI accelerators</strong> optimized for cost, efficiency, and the most common machine-learning patterns.</p><p>This article focuses primarily on <strong>AWS’s custom silicon strategy</strong> — <strong>Inferentia</strong> for inference and <strong>Trainium</strong> for training while also highlighting <strong>Google’s TPUs</strong>, which pioneered many of the ideas now shaping the industry.</p><h3>Why Move Beyond GPUs?</h3><p>By the late 2010s, three forces drove hyperscalers to rethink GPU-centric AI infrastructure:</p><h3>1. Exploding Costs at Scale</h3><p>Training frontier models and serving billions of inferences daily became prohibitively expensive. GPUs delivered flexibility but commanded premium pricing and were increasingly constrained by supply.</p><h3>2. Workload Mismatch</h3><p>Most production ML workloads — transformer inference, vision models, recommendation systems, and large but predictable training jobs do not require the full generality of GPUs. Paying for unused capabilities resulted in poor cost efficiency.</p><h3>3. Full-Stack Control</h3><p>Cloud providers already controlled compute, networking, storage, and data centers. Owning the silicon layer enabled better margins, predictable supply, and deep end-to-end optimization.</p><p>This philosophy of <strong>vertical integration for superior price-performance</strong> laid the foundation for custom AI chips.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*Nu3WSqCpDfcfCBkNRWF2XA.png" /></figure><h3>AWS’s Silicon Foundation: The Annapurna Labs Acquisition</h3><p>AWS’s silicon journey began in earnest with its <strong>2015 acquisition of Annapurna Labs</strong>, an Israeli company specializing in custom system-on-chips (SoCs).</p><p>Annapurna initially powered innovations such as:</p><ul><li><strong>Nitro cards</strong>, which offload networking, storage, and virtualization</li><li><strong>Graviton</strong>, AWS’s Arm-based CPU family</li></ul><p>This in-house expertise eventually expanded into machine-learning accelerators, giving AWS a production-ready silicon organization that few cloud providers possess.</p><h3>Inferentia: Starting with Inference (2019 →)</h3><p>AWS prioritized <strong>inference first</strong>, recognizing that inference typically dominates the total cost of ownership over a model’s lifecycle.</p><h3>Inferentia (2019)</h3><p>Announced at re:Invent 2019, Inferentia powered <strong>Inf1 instances</strong>, targeting high-throughput, low-latency inference using common precisions such as <strong>INT8</strong> and <strong>FP16</strong>. AWS positioned it as offering significantly better cost-performance than comparable GPU instances for supported workloads.</p><h3>Inferentia2 (2022)</h3><p>Inferentia2 brought major upgrades:</p><ul><li>Substantially higher compute and memory bandwidth</li><li><strong>32 GB of HBM2e per chip</strong></li><li>Improved transformer and attention support</li></ul><p><strong>Inf2 instances</strong> enable large-scale LLM and diffusion model inference, delivering multiple-fold improvements in throughput and latency compared to Inferentia1, depending on workload.</p><p>As of early 2026, <strong>Inferentia2 remains AWS’s primary inference accelerator</strong>. AWS has not publicly announced an Inferentia3, instead focusing on broader architectural improvements across its training platform.</p><h3>Trainium: Scaling Large-Model Training (2021 →)</h3><p>As LLMs grew into the hundreds of billions of parameters, <strong>training</strong> became the next major bottleneck.</p><h3>Trainium (2021)</h3><p>Trainium was AWS’s first training-focused AI chip, designed for large, distributed workloads. Key features included:</p><ul><li><strong>NeuronCores</strong> optimized for dense tensor operations</li><li><strong>NeuronLink</strong> for chip-to-chip communication</li><li>Integration with <strong>Elastic Fabric Adapter (EFA)</strong> for scalable, cloud-native clusters</li></ul><h3>Trainium2 (2024 GA)</h3><p>Trainium2 significantly expanded AWS’s training capabilities:</p><ul><li>Up to <strong>96 GB of HBM3 memory per chip</strong></li><li>Support for structured sparsity</li><li>Improved interconnect bandwidth and efficiency</li></ul><p><strong>Trn2 instances</strong> and <strong>Trn2 UltraServers</strong> enable tightly coupled clusters for large-scale training. AWS reports <strong>30–40% better price-performance</strong> compared to GPU-based instances for many real-world workloads.</p><p>Large deployments — such as AWS’s collaboration with <strong>Anthropic</strong> — demonstrate Trainium’s ability to scale to <strong>hundreds of thousands of chips</strong> for frontier-model training.</p><h3>The Software Differentiator: AWS Neuron SDK</h3><p>Custom silicon is only viable with strong software support. <strong>AWS Neuron</strong> provides the compiler, runtime, and tooling layer that makes Inferentia and Trainium usable at scale.</p><p>Key characteristics:</p><ul><li>Compiler-driven graph optimization and operator fusion</li><li>Integrations with <strong>PyTorch</strong>, <strong>TensorFlow</strong>, <strong>Hugging Face</strong>, and inference frameworks like <strong>vLLM</strong></li><li>Automatic partitioning across chips and instances</li></ul><p>Neuron trades some low-level flexibility for higher efficiency and operational simplicity, aligning well with production workloads rather than research experimentation.</p><h3>AWS Chips vs Traditional GPUs</h3><p>AWS’s accelerators are deliberately specialized:</p><p>AspectNVIDIA GPUsAWS Inferentia / TrainiumPrimary goalMaximum flexibilityCost-efficient production scaleTypical useResearch, prototypingHigh-volume inference &amp; trainingProgramming modelCUDA kernelsCompiler-driven graphs (Neuron)EconomicsPremium pricingStrong price-performance focus</p><p>GPUs remain indispensable for novel architectures and experimentation, but AWS chips optimize for the <em>median</em> cloud workload.</p><h3>Google’s TPUs: The Pioneering Path</h3><p><strong>Google</strong> was the first hyperscaler to commit to custom AI silicon, introducing the original <strong>TPU in 2015</strong> for internal workloads such as Search, Ads, and Translation.</p><p>Key characteristics of the TPU approach:</p><ul><li><strong>Systolic arrays</strong> optimized for matrix multiplication</li><li>Large, tightly coupled <strong>TPU Pods</strong> acting as AI supercomputers</li><li>Heavy reliance on the <strong>XLA compiler</strong> for graph-level optimization</li></ul><p>TPUs were built for Google’s internal products first and later productized on Google Cloud. Over multiple generations, Google expanded support beyond TensorFlow to JAX and PyTorch.</p><p>Philosophically:</p><ul><li><strong>TPUs reward clean, static graphs</strong></li><li><strong>AWS Neuron emphasizes cloud-native flexibility and operational realism</strong></li></ul><p>Both strategies validate the same conclusion: <strong>general-purpose GPUs are not always the most economical solution at hyperscale</strong>.</p><h3>Strategic Impact (Early 2026)</h3><p>AWS’s custom chips:</p><ul><li><strong>Reduce dependence on NVIDIA, especially for inference</strong></li><li><strong>Lower the barrier to training large models for cloud customers</strong></li><li><strong>Power internal Amazon services and platforms like Amazon Bedrock</strong></li><li><strong>Enable partners such as Anthropic to train frontier-scale models economically</strong></li></ul><p>Reference Doc:</p><p><a href="https://aws.amazon.com/ai/machine-learning/inferentia/">AWS Inferentia</a></p><p><a href="https://aws.amazon.com/blogs/machine-learning/how-to-run-qwen-2-5-on-aws-ai-chips-using-hugging-face-libraries/">https://aws.amazon.com/blogs/machine-learning/how-to-run-qwen-2-5-on-aws-ai-chips-using-hugging-face-libraries/</a></p><p><a href="https://www.reddit.com/r/aws/comments/1pc3wna/self_hosted_embedding_model_on_inf2_neuron_device/">https://www.reddit.com/r/aws/comments/1pc3wna/self_hosted_embedding_model_on_inf2_neuron_device/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7959a9f1729e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying DNS, IP Addresses, and Routing Under the Hood]]></title>
            <link>https://sarthakvj.medium.com/demystifying-dns-ip-addresses-and-routing-under-the-hood-ca08488ac147?source=rss-a6a690c3b8cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca08488ac147</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Sarthak Vijay]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 18:01:58 GMT</pubDate>
            <atom:updated>2026-01-03T18:01:58.781Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered what happens in those split seconds between typing google.com into your browser and seeing the search page load? It’s not magic, it’s a beautifully orchestrated dance involving DNS translation, IP routing, and layered protocols. Yet, most of us take it for granted.</p><p>In this article, we’ll peel back the layers of the internet’s “phonebook” (DNS) and explain why computers still rely on numeric IP addresses for the heavy lifting. We’ll walk through the entire process step-by-step, with clear examples and visuals. By the end, you’ll have a solid mental model of how the modern internet routes billions of packets every second.</p><p>Let’s dive in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4h5ZtYL8q58M8RIu-hXKg.jpeg" /></figure><p><strong>What Is DNS, Anyway?</strong> At its core, the Domain Name System (DNS) is the internet’s phonebook.</p><ul><li><strong>Humans love memorable names</strong>: google.com, example.org.</li><li>Computers and routers, however, deliver data packets using IP addresses like 142.250.184.78 (IPv4) or longer IPv6 ones.</li></ul><p><strong>DNS bridges this gap by translating human-friendly domain names into machine-friendly IP addresses.</strong> Without DNS, we’d all be memorizing strings of numbers to visit websites. (Imagine telling your friend: “Hey, check out 192.0.2.1!”). The Distributed Hierarchy of DNS</p><p>DNS isn’t stored on one giant server, it’s distributed across the globe for reliability and speed. No single point knows everything.Here’s the layered structure:</p><ol><li><strong>Root Servers</strong> (13 logical groups worldwide): They know where to find info for top-level domains (TLDs) like <strong>.com, .org, or .io</strong>.</li><li><strong>TLD Servers:</strong> Managed by registries (e.g., <strong>Verisign for .com</strong>), they point to the authoritative servers for specific domains.</li><li><strong>Authoritative Name Servers:</strong> Owned by the domain owner (or their registrar), these hold the actual records — like the IP address for <a href="http://www.example.com./">www.example.com.</a></li></ol><p>This hierarchy prevents overload and enables massive scale.</p><p><strong>Step-by-Step: How a DNS Lookup Actually WorksWhen you type </strong><a href="http://www.example.com/"><strong>www.example.com</strong></a><strong> into your browser:</strong></p><ol><li>Your device first checks local caches (browser cache, OS cache, /etc/hosts file).</li><li>If not found, it queries your configured DNS resolver (often your ISP’s, or public ones like Google’s 8.8.8.8 or Cloudflare’s 1.1.1.1).</li><li>The resolver (recursive resolver) does the legwork:</li></ol><ul><li>Asks a root server: “Where’s the .com TLD?”</li><li>Asks the .com TLD server: “Who handles example.com?”</li><li>Asks the authoritative server for example.com: “What’s the IP for <a href="http://www.example.com/">www.example.com</a>?&quot;</li></ul><p>4. The resolver gets the answer (e.g., an A record with the IPv4 address), caches it for the TTL period, and returns it to your device.</p><p>5. Your browser now connects to that IP — DNS’s job is done!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJ5G4lUfU_16WrgyVB1xHQ.png" /></figure><h4>Why Do We Still Need IP Addresses?</h4><p>Domain names are great for us, but routers as the traffic cops of the internet need something more efficient.<strong>IP addresses are</strong>:</p><ul><li>Fixed-length binary numbers (32 bits for IPv4, 128 for IPv6).</li><li>Perfect for fast mathematical operations like prefix matching.</li><li>Easy to aggregate into ranges for efficient routing.</li></ul><p>Hostnames, on the other hand:</p><ul><li>Are variable-length strings.</li><li>Can change frequently.</li><li>Would be slow and ambiguous to route at internet scale.</li></ul><p><strong>DNS exists purely to make life easier for humans while letting the network run on numbers.</strong> How Routers Think: CIDR and Longest Prefix Match Routers don’t store routes for every individual IP (there are billions!). Instead, they use CIDR (Classless Inter-Domain Routing) to group IPs into prefix ranges.Example: 142.250.184.0/24</p><ul><li>The /24 means the first 24 bits are fixed → covers 256 addresses (from .0 to .255).</li></ul><p>Routers build tables of these prefixes and use Longest Prefix Match (LPM) to decide where to forward packets:</p><ul><li>For destination IP 142.250.184.174, if the table has both 142.250.0.0/16 and 142.250.184.0/24, it picks the /24 — it’s more specific.</li></ul><blockquote><strong><em>This is super efficient because IPs are just big integers, allowing hardware-accelerated bitwise lookups.</em></strong></blockquote><h4>Caching, TTL, and Why DNS Changes Take Time</h4><p>Every DNS record comes with a Time To Live (TTL) value (e.g., 3600 seconds).</p><ul><li>Resolvers cache answers until the TTL expires.</li><li>This reduces load but means changes (like switching servers) aren’t instant “DNS propagation” is just caches expiring worldwide.</li></ul><blockquote><strong><em>Pro tip: Lower TTL before big migrations!</em></strong></blockquote><h4>Common DNS Record Types You Should Know</h4><ul><li>A: IPv4 address</li><li>AAAA: IPv6 address</li><li>CNAME: Alias (points one name to another)</li><li>MX: Mail servers</li><li>NS: Name servers for the domain</li><li>TXT: Arbitrary text (used for verification, SPF, etc.)</li></ul><p><strong>IPv4 vs. IPv6:</strong> The Address Space CrunchIPv4 offers ~4.3 billion addresses mostly exhausted. IPv6 provides an astronomically larger space (340 undecillion addresses) with better routing and security features.DNS happily returns either (or both).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*mEYqC7XrZ9kEbrXPmAMO5w.png" /></figure><p>The massive scale difference between IPv4 and IPv6. What Happens When an IP Changes?</p><ul><li>Existing connections stay on the old IP.</li><li>New requests gradually shift as caches expire.</li><li>Smart ops teams lower TTL first and drain traffic gracefully.</li></ul><p><strong>Tools to Explore DNS Yourse, lfTry these in your terminal:</strong></p><ul><li><strong><em>dig</em></strong> google.com (basic lookup)</li><li><strong><em>dig +trace</em></strong> google.com (see the full recursive path)</li><li><strong><em>nslookup</em></strong> (interactive mode)</li></ul><h4>The Big Picture: Layers Working Together</h4><p>The internet is built on clean separation:</p><blockquote>You type a name<br> ↓<br>DNS → IP address<br> ↓<br>IP routing (with CIDR &amp; LPM) moves packets<br> ↓<br>TCP/TLS establishes reliable connections<br> ↓<br>HTTP/HTTPS delivers content</blockquote><p>The TCP/IP stack: Each layer has one job.Understanding these fundamentals makes debugging networks, designing systems, or just appreciating the internet’s elegance so much more rewarding.</p><p><strong>Reference Docs:</strong></p><ul><li><a href="https://www.cloudflare.com/en-gb/learning/dns/what-is-dns/">https://www.cloudflare.com/en-gb/learning/dns/what-is-dns/</a></li><li><a href="https://www.cherryservers.com/blog/ipv4-vs-ipv6-key-differences">https://www.cherryservers.com/blog/ipv4-vs-ipv6-key-differences</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca08488ac147" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>