<script data-pm-proxy="intercept"></script><?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:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:googleplay="http://www.google.com/schemas/play-podcasts/1.0"><channel><title><![CDATA[Hands On AI Agent Mastery Course ]]></title><description><![CDATA[Learning Outcomes

Built 15+ production-ready agents with proper error handling and monitoring
Implemented scalable architectures handling concurrent requests and resource management
Deployed agent systems with CI/CD pipeline]]></description><link>https://aiamastery.substack.com</link><image><url>https://substackcdn.com/image/fetch/$s_!k-B7!,w_256,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4d40ea52-b34e-4ede-9fd0-dbd14e27ac97_1280x1280.png</url><title>Hands On AI Agent Mastery Course </title><link>https://aiamastery.substack.com</link></image><generator>Substack</generator><lastBuildDate>Fri, 04 Sep 2026 13:14:38 GMT</lastBuildDate><atom:link href="/__u/aiamastery.substack.com/feed" rel="self" type="application/rss+xml"/><copyright><![CDATA[Systemdr, Inc.]]></copyright><language><![CDATA[en]]></language><webMaster><![CDATA[aiamastery@substack.com]]></webMaster><itunes:owner><itunes:email><![CDATA[aiamastery@substack.com]]></itunes:email><itunes:name><![CDATA[AI Roadmap]]></itunes:name></itunes:owner><itunes:author><![CDATA[AI Roadmap]]></itunes:author><googleplay:owner><![CDATA[aiamastery@substack.com]]></googleplay:owner><googleplay:email><![CDATA[aiamastery@substack.com]]></googleplay:email><googleplay:author><![CDATA[AI Roadmap]]></googleplay:author><itunes:block><![CDATA[Yes]]></itunes:block><item><title><![CDATA[Lesson 15 — Evaluation Framework]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-15-evaluation-framework</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-15-evaluation-framework</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Wed, 02 Sep 2026 02:00:23 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!03EU!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>Agent quality cannot be judged by reading a few replies. This lesson builds a scoring service that grades outputs against golden cases with exact-match, containment, token-F1, and an offline LLM-as-judge heuristic. Scores aggregate in a thread-safe store and appear on a live dashboard. One demo request exercises all four scorers, so operators read real numbers.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Four scorers: strict, soft, lexical, and judged.</p></li><li><p>Offline judge stub &#8212; no API key, deterministic in CI.</p></li><li><p>Thread-safe running means, pass rate, bounded event ring.</p></li><li><p>Dashboard polling <code>/metrics</code> every second.</p></li><li><p>Containerised on port 8094 with health check.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p><code>eval/</code> package: <code>cases.py</code>, <code>scorers.py</code>, <code>metrics.py</code>, <code>service.py</code>.</p></li><li><p>Routes <code>/evaluate</code>, <code>/score</code>, <code>/demo</code>, <code>/metrics</code>, <code>/cases</code>, <code>/health</code>, <code>/dashboard</code>.</p></li><li><p>A CLI demo printing per-case scores and suite averages.</p></li><li><p>Six golden cases: exact hits, soft matches, refusals, wrong answers.</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><blockquote><p>Day 14 bounded history with token budgets. Bounded prompts are the precondition for fair scoring: otherwise a metric drop cannot be separated from silent truncation.</p></blockquote><h2><strong>Enables Next Lesson</strong></h2><blockquote><p>Day 16 adds a vector store and RAG. Retrieval quality only matters if measurable, so this becomes the harness for retrieved-context answers.</p></blockquote><h2><strong>Architecture Context</strong></h2><ul><li><p><strong>Where it sits:</strong> after the model response, before any release gate.</p></li><li><p><strong>Why it exists:</strong> manual review does not scale and cannot be regression-tested.</p></li><li><p><strong>Problem solved:</strong> converts text quality into numeric, alertable signals.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!03EU!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!03EU!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png 424w, /__u/substackcdn.com/image/fetch/$s_!03EU!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png 848w, /__u/substackcdn.com/image/fetch/$s_!03EU!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png 1272w, /__u/substackcdn.com/image/fetch/$s_!03EU!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!03EU!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png" width="574" height="344.5576923076923" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/c9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:874,&quot;width&quot;:1456,&quot;resizeWidth&quot;:574,&quot;bytes&quot;:1022159,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/208421367?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!03EU!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png 424w, /__u/substackcdn.com/image/fetch/$s_!03EU!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png 848w, /__u/substackcdn.com/image/fetch/$s_!03EU!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png 1272w, /__u/substackcdn.com/image/fetch/$s_!03EU!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc9c72e37-af90-4c6c-b766-0251fbfab33b_5000x3000.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p></p><h2><strong>Integration</strong></h2><h3><strong>Integration Components</strong></h3><blockquote><p><code>EvalCase</code> is a Pydantic model holding <code>id</code>, <code>prompt</code>, <code>expected</code>, <code>actual</code>. Each metric is a pure function registered in <code>METRIC_FNS</code>. <code>EvalService.evaluate()</code> scores a suite and delegates aggregation to the shared <code>METRICS</code> store. Routes return results and a fresh snapshot together, so the dashboard needs no second request.</p></blockquote><h3><strong>Module Objectives Alignment</strong></h3><blockquote><p>The objective is provable, non-zero measurement. Dictionary registration means a new metric needs no change to the service, routes, or rendering loop.</p></blockquote><h2><strong>Core Concepts</strong></h2><p><strong>Strict versus soft correctness.</strong> <code>exact_match</code> scores 0.0 for a correct answer wrapped in a sentence; <code>contains</code> accepts the wrapping. Reporting both separates formatting failures from knowledge failures.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><p><strong>Token-F1.</strong> Precision is overlap over actual tokens, recall over expected tokens, F1 their harmonic mean. It grants partial credit for verbose-but-correct answers while penalising padding, since precision falls as unrelated tokens appear. Whitespace tokenisation avoids tokenizer churn.</p><p><strong>LLM-as-judge.</strong> Production judges call a stronger model; this graded heuristic returns 0.98 exact, 0.92 contained, 0.45 partial, 0.15 miss, 0.05 refusal &#8212; same interface, deterministic and offline.</p><p><strong>Aggregation as evidence.</strong> The store keeps cumulative sums, recomputes means on write, and retains 24 events: enough for a dashboard, bounded so memory cannot grow.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!wf72!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff5049b6a-d335-41fa-854e-bbb4bfd03a6b_5000x3400.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!wf72!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff5049b6a-d335-41fa-854e-bbb4bfd03a6b_5000x3400.png 424w, /__u/substackcdn.com/image/fetch/$s_!wf72!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff5049b6a-d335-41fa-854e-bbb4bfd03a6b_5000x3400.png 848w, /__u/substackcdn.com/image/fetch/$s_!wf72!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff5049b6a-d335-41fa-854e-bbb4bfd03a6b_5000x3400.png 1272w, /__u/substackcdn.com/image/fetch/$s_!wf72!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff5049b6a-d335-41fa-854e-bbb4bfd03a6b_5000x3400.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!wf72!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff5049b6a-d335-41fa-854e-bbb4bfd03a6b_5000x3400.png" width="672" height="456.9230769230769" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f5049b6a-d335-41fa-854e-bbb4bfd03a6b_5000x3400.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:990,&quot;width&quot;:1456,&quot;resizeWidth&quot;:672,&quot;bytes&quot;:762826,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/208421367?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff5049b6a-d335-41fa-854e-bbb4bfd03a6b_5000x3400.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!wf72!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff5049b6a-d335-41fa-854e-bbb4bfd03a6b_5000x3400.png 424w, /__u/substackcdn.com/image/fetch/$s_!wf72!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff5049b6a-d335-41fa-854e-bbb4bfd03a6b_5000x3400.png 848w, /__u/substackcdn.com/image/fetch/$s_!wf72!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff5049b6a-d335-41fa-854e-bbb4bfd03a6b_5000x3400.png 1272w, /__u/substackcdn.com/image/fetch/$s_!wf72!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff5049b6a-d335-41fa-854e-bbb4bfd03a6b_5000x3400.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Production AI System Design Relevance</strong></h2><blockquote><p>This is the gate between generation and release. Prompts change constantly upstream; users see results downstream. Scoring a fixed suite makes a model swap measurable rather than a guess.</p></blockquote><h2><strong>Workflow</strong></h2><ul><li><p><strong>Request flow:</strong> the dashboard polls <code>GET /metrics</code>; a demo click issues <code>POST /demo</code>.</p></li><li><p><strong>Execution flow:</strong> load the suite, score every case with every metric, mark pass or fail, record the batch.</p></li><li><p><strong>Data flow:</strong> scores become events; sums update cumulative and last-run means; the snapshot returns to caller and UI.</p></li><li><p><strong>State changes:</strong> <code>cases_scored</code>, <code>eval_runs</code>, <code>pass_count</code>, <code>fail_count</code>, <code>demo_runs</code>, and means advance per run.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!h5JL!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6a7dd35c-9b04-44d6-aeb9-e93a367e785a_5000x2600.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!h5JL!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6a7dd35c-9b04-44d6-aeb9-e93a367e785a_5000x2600.png 424w, /__u/substackcdn.com/image/fetch/$s_!h5JL!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6a7dd35c-9b04-44d6-aeb9-e93a367e785a_5000x2600.png 848w, /__u/substackcdn.com/image/fetch/$s_!h5JL!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6a7dd35c-9b04-44d6-aeb9-e93a367e785a_5000x2600.png 1272w, /__u/substackcdn.com/image/fetch/$s_!h5JL!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6a7dd35c-9b04-44d6-aeb9-e93a367e785a_5000x2600.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!h5JL!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6a7dd35c-9b04-44d6-aeb9-e93a367e785a_5000x2600.png" width="1456" height="757" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/6a7dd35c-9b04-44d6-aeb9-e93a367e785a_5000x2600.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:757,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:547742,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/208421367?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6a7dd35c-9b04-44d6-aeb9-e93a367e785a_5000x2600.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!h5JL!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6a7dd35c-9b04-44d6-aeb9-e93a367e785a_5000x2600.png 424w, /__u/substackcdn.com/image/fetch/$s_!h5JL!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6a7dd35c-9b04-44d6-aeb9-e93a367e785a_5000x2600.png 848w, /__u/substackcdn.com/image/fetch/$s_!h5JL!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6a7dd35c-9b04-44d6-aeb9-e93a367e785a_5000x2600.png 1272w, /__u/substackcdn.com/image/fetch/$s_!h5JL!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6a7dd35c-9b04-44d6-aeb9-e93a367e785a_5000x2600.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Production Integration</strong></h2><ul><li><p><strong>Architecture fit:</strong> one uvicorn worker, since counters live in process memory.</p></li><li><p><strong>Enterprise patterns:</strong> swap the judge stub for a model call behind a timeout and cache; version the dataset.</p></li><li><p><strong>Scalability:</strong> scoring is O(cases &#215; metrics) and CPU-bound; shard suites, externalise state before replicating.</p></li><li><p><strong>Observability:</strong> export means, pass rate, run counts; alert on drops between builds.</p></li><li><p><strong>Security:</strong> no credentials committed, <code>.env</code> ignored, event details truncated.</p></li></ul><h2><strong>Step-by-Step Implementation</strong></h2><h2><strong>GitHub Link</strong></h2><p><strong><a href="https://github.com/sysdr/production-ai-engineering-p/tree/main/lesson15/aiam-day15">https://github.com/sysdr/production-ai-engineering-p/tree/main/lesson15/aiam-day15</a></strong></p><blockquote><p><code>cases.py</code> defines the schema first, so malformed cases fail at construction rather than mid-run. <code>scorers.py</code> keeps metrics pure functions of one case, making units trivial. <code>metrics.py</code> guards mutation with a lock and recomputes means in the same critical section. <code>service.py</code> is the only place scoring and recording are sequenced, so API and CLI cannot drift. Pydantic rejects empty fields with HTTP 422; smoke checks assert no dashboard field stays zero. Failures surface as <code>FAIL</code> events.</p></blockquote><h2><strong>Coding Highlights</strong></h2><p>Registering scorers by name keeps the pipeline extensible:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;84fd8d5f-9ba3-4776-b321-0417c357d3cf&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">METRIC_FNS = {"exact": exact_match, "contains": contains,
              "token_f1": token_f1, "llm_judge": llm_judge}
scores = {name: fn(case) for name, fn in METRIC_FNS.items()}</code></pre></div><p>Sums and derived means update under one lock:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;5c966192-9a0f-4c53-8e0e-ad285137abdb&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">with self._lock:
    self._data["exact_sum"] += exact_sum
    self._data["exact_mean"] = round(self._data["exact_sum"] / total_cases, 3)</code></pre></div><blockquote><p>Splitting these would expose a new sum with a stale mean &#8212; a metric that never occurred.</p></blockquote><h3>Working Demo Link:</h3><div id="youtube2-KaJPZOSuALo" class="youtube-wrap" data-attrs="{&quot;videoId&quot;:&quot;KaJPZOSuALo&quot;,&quot;startTime&quot;:null,&quot;endTime&quot;:null}" data-component-name="Youtube2ToDOM"><div class="youtube-inner"><iframe src="https://www.youtube-nocookie.com/embed/KaJPZOSuALo?rel=0&amp;autoplay=0&amp;showinfo=0&amp;enablejsapi=0" frameborder="0" loading="lazy" gesture="media" allow="autoplay; fullscreen" allowautoplay="true" allowfullscreen="true" width="728" height="409"></iframe></div></div><h2><strong>Production Considerations</strong></h2><ul><li><p><strong>Scalability:</strong> one worker in-memory; Redis when replicated.</p></li><li><p><strong>Security:</strong> authenticate mutating routes; never log prompts.</p></li><li><p><strong>Monitoring:</strong> alert on pass-rate deltas and on a stalled suite.</p></li><li><p><strong>Logging:</strong> case ids and scores only.</p></li><li><p><strong>Testing:</strong> per-scorer units, aggregation, API contracts.</p></li><li><p><strong>Failure handling:</strong> bad cases rejected at validation; empty suites no-op rather than divide by zero.</p></li><li><p><strong>Edge cases:</strong> empty strings, refusal stubs, case-only differences.</p></li></ul><h2><strong>Validation</strong></h2><ul><li><p><strong>Verification:</strong> <code>/health</code> healthy, <code>/demo</code> non-zero, <code>/dashboard</code> serves HTML.</p></li><li><p><strong>Testing strategy:</strong> 16 pytest cases across scorers, aggregation, and routes, plus live smoke checks.</p></li><li><p><strong>Success criteria:</strong> tests pass; no dashboard field stays zero after a demo.</p></li><li><p><strong>Expected outputs:</strong> <code>exact&#8776;0.167</code>, <code>contains&#8776;0.667</code>, <code>token_f1&#8776;0.281</code>, <code>llm_judge&#8776;0.657</code>, pass rate <code>&#8776;66.7%</code>.</p></li><li><p><strong>Benchmarks:</strong> the six-case suite scores in single-digit milliseconds.</p></li><li><p><strong>Production checklist:</strong> versioned cases, pinned dependencies, health check, regression alert.</p></li></ul><h2><strong>Key Insights</strong></h2><blockquote><p>A suite where everything passes cannot detect regressions, which is why two cases fail deliberately. The common mistake is shipping exact-match alone: it fails correct answers and pushes teams to fix formatting instead of substance. Judge fidelity trades against cost &#8212; semantic judges catch paraphrase but add latency and flaky builds.</p></blockquote><h3><strong>Important Classes</strong></h3><ul><li><p><code>EvalCase</code> &#8212; validated case schema.</p></li><li><p><code>MetricsStore</code> &#8212; locked counters, means, event ring.</p></li><li><p><code>EvalService</code> &#8212; orchestrates scoring and recording.</p></li></ul><h3><strong>Key Methods</strong></h3><ul><li><p><code>score_case()</code> &#8212; all metrics for one case.</p></li><li><p><code>EvalService.evaluate()</code> &#8212; scores a suite, returns averages.</p></li><li><p><code>MetricsStore.record_eval()</code> &#8212; updates aggregates atomically.</p></li><li><p><code>MetricsStore.snapshot()</code> &#8212; consistent read with throughput.</p></li></ul><h2><strong>Success Criteria</strong></h2><blockquote><p>Every dashboard metric is non-zero after one demo, tests pass without warnings, and the container reports healthy on port 8094.</p></blockquote><h2><strong>Real-World Examples</strong></h2><ul><li><p><strong>Model upgrade gating:</strong> a support team scores golden tickets against a candidate model. Exact-match falls while containment and judge scores rise, exposing a formatting change, not quality loss.</p></li><li><p><strong>Prompt regression in CI:</strong> a docs assistant scores its suite per pull request. An edit meant to shorten answers cuts token-F1 recall by eleven points, failing the build before release.</p></li></ul><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Lesson 14 — Context Window Management]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-14-context-window-management</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-14-context-window-management</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Sun, 30 Aug 2026 02:00:40 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!GLKs!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fde08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>Parallel tool fan-out fills history faster than models can accept. This lesson bounds growth with token budgets, priority trimming, and sliding-window compaction. <code>ContextWindow</code> counts tokens, drops low-value turns, and keeps dialogue under <code>available = max_tokens - reserved</code>. <code>MetricsStore</code> records every fit; the dashboard polls <code>/metrics</code>. <code>POST /demo</code> runs both strategies so counters leave zero.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Stable chars//4 token estimates without deprecated tokenizer APIs.</p></li><li><p>Priority trim that preserves high-priority system and policy messages.</p></li><li><p>Sliding-window compaction that keeps the newest turns under budget.</p></li><li><p>Live dashboard for tokens, utilization, trim events, and demo runs.</p></li><li><p>Docker lifecycle on port 8093 via <code>start.sh</code>, <code>demo.sh</code>, and <code>run_tests.sh</code>.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p><code>context/</code> package: <code>tokens.py</code>, <code>window.py</code>, <code>metrics.py</code>, <code>service.py</code>.</p></li><li><p>FastAPI (<code>app.py</code>): <code>/fit</code>, <code>/sliding</code>, <code>/demo</code>, <code>/metrics</code>, <code>/health</code>, <code>/dashboard</code>.</p></li><li><p>CLI demo (<code>main.py</code>) comparing priority trim versus sliding window.</p></li><li><p>Default overfull conversation: one system message plus eight user/assistant turns.</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><p>Day 13 overlapped independent tool I/O with <code>asyncio.gather</code>. Gathered results inflate prompts; Day 14 keeps that context inside token budgets.</p><h2><strong>Enables Next Lesson</strong></h2><p>Bounded prompts enable fair evaluation. Day 15 scores agent outputs under controlled windows so metric drift is not caused by silent truncation.</p><h2><strong>Architecture Context</strong></h2><ul><li><p><strong>Where this component sits:</strong> between the conversation store and the model call site.</p></li><li><p><strong>Why it exists:</strong> unbounded history and tool payloads hit hard context limits or silently degrade quality.</p></li><li><p><strong>Problem solved:</strong> deterministic trim policies with operator-visible token and message counters.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!GLKs!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fde08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!GLKs!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fde08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png 424w, /__u/substackcdn.com/image/fetch/$s_!GLKs!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fde08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png 848w, /__u/substackcdn.com/image/fetch/$s_!GLKs!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fde08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png 1272w, /__u/substackcdn.com/image/fetch/$s_!GLKs!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fde08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!GLKs!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fde08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png" width="636" height="432.44505494505495" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/de08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:990,&quot;width&quot;:1456,&quot;resizeWidth&quot;:636,&quot;bytes&quot;:1006189,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/208292523?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fde08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!GLKs!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fde08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png 424w, /__u/substackcdn.com/image/fetch/$s_!GLKs!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fde08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png 848w, /__u/substackcdn.com/image/fetch/$s_!GLKs!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fde08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png 1272w, /__u/substackcdn.com/image/fetch/$s_!GLKs!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fde08a89c-71e4-4844-aa4f-9a71451fd4fb_5000x3400.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div>
      <p>
          <a href="/__u/aiamastery.substack.com/p/lesson-14-context-window-management">
              Read more
          </a>
      </p>
   ]]></content:encoded></item><item><title><![CDATA[Lesson 13 — Async Agent Pipeline]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-13-async-agent-pipeline</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-13-async-agent-pipeline</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Thu, 27 Aug 2026 02:01:08 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!MgW3!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F75333fad-ef7b-4d96-9452-f6685331e3c6_4250x3900.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>This lesson turns independent agent tool calls into an async execution pipeline. Sequential <code>await</code> is the latency baseline; <code>asyncio.gather</code> overlaps I/O so wall time tracks the slowest tool, not the sum. <code>MetricsStore</code> records sequential and parallel runs, gather calls, concurrency, and speedup while the FastAPI dashboard polls <code>/metrics</code>. <code>POST /demo</code> runs both modes so every counter leaves zero.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Simulated async tools via <code>asyncio.sleep</code> with structured results.</p></li><li><p>Sequential runner for baseline wall-clock latency.</p></li><li><p>Parallel runner using <code>asyncio.gather</code> for overlapped tool I/O.</p></li><li><p>Live dashboard for speedup, concurrency, and recent tool events.</p></li><li><p>Docker lifecycle on port 8092 via <code>start.sh</code>, <code>demo.sh</code>, and <code>run_tests.sh</code>.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p><code>pipeline/</code> package: <code>tools.py</code>, <code>runner.py</code>, <code>metrics.py</code>, <code>service.py</code>.</p></li><li><p>FastAPI (<code>app.py</code>): <code>/run/sequential</code>, <code>/run/parallel</code>, <code>/demo</code>, <code>/metrics</code>, <code>/health</code>, <code>/dashboard</code>.</p></li><li><p>CLI demo (<code>main.py</code>) printing sequential vs parallel timings and speedup.</p></li><li><p>Default five-tool workload: search, calculate, summarise, lookup, validate.</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><p>Day 12 made agent lifecycle edges explicit with an audited FSM. Day 13 keeps that control plane and overlaps tool I/O inside TOOL_CALL/PROCESSING.</p><h2><strong>Enables Next Lesson</strong></h2><p>Parallel tool fan-out grows context quickly. Day 14 manages context windows so gathered results stay inside token budgets.</p><h2><strong>Architecture Context</strong></h2><ul><li><p><strong>Where this component sits:</strong> between the agent planner and tool adapters.</p></li><li><p><strong>Why it exists:</strong> serial tool awaits waste wall time when tools have no data dependency.</p></li><li><p><strong>Problem solved:</strong> measurable speedup with operator-visible sequential vs parallel counters.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!6jHR!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F596bacdb-7f29-44c0-9b89-34295518c688_4500x3100.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!6jHR!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F596bacdb-7f29-44c0-9b89-34295518c688_4500x3100.png 424w, /__u/substackcdn.com/image/fetch/$s_!6jHR!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F596bacdb-7f29-44c0-9b89-34295518c688_4500x3100.png 848w, /__u/substackcdn.com/image/fetch/$s_!6jHR!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F596bacdb-7f29-44c0-9b89-34295518c688_4500x3100.png 1272w, /__u/substackcdn.com/image/fetch/$s_!6jHR!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F596bacdb-7f29-44c0-9b89-34295518c688_4500x3100.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!6jHR!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F596bacdb-7f29-44c0-9b89-34295518c688_4500x3100.png" width="512" height="352.7032967032967" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/596bacdb-7f29-44c0-9b89-34295518c688_4500x3100.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1003,&quot;width&quot;:1456,&quot;resizeWidth&quot;:512,&quot;bytes&quot;:834587,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/208289537?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F596bacdb-7f29-44c0-9b89-34295518c688_4500x3100.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!6jHR!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F596bacdb-7f29-44c0-9b89-34295518c688_4500x3100.png 424w, /__u/substackcdn.com/image/fetch/$s_!6jHR!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F596bacdb-7f29-44c0-9b89-34295518c688_4500x3100.png 848w, /__u/substackcdn.com/image/fetch/$s_!6jHR!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F596bacdb-7f29-44c0-9b89-34295518c688_4500x3100.png 1272w, /__u/substackcdn.com/image/fetch/$s_!6jHR!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F596bacdb-7f29-44c0-9b89-34295518c688_4500x3100.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div>
      <p>
          <a href="/__u/aiamastery.substack.com/p/lesson-13-async-agent-pipeline">
              Read more
          </a>
      </p>
   ]]></content:encoded></item><item><title><![CDATA[Lesson 12 — Agent State Machine]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-12-agent-state-machine</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-12-agent-state-machine</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Mon, 24 Aug 2026 02:00:46 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!eSR8!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>This lesson models an agent as an explicit finite-state machine with audited transitions. Legal edges move through IDLE, VALIDATING, PROCESSING, TOOL_CALL, RESPONDING, DONE, and ERROR. Illegal shortcuts raise errors and increment blocked counters. <code>MetricsStore</code> records transitions, recoveries, and history; the FastAPI dashboard polls <code>/metrics</code>. <code>POST /demo</code> runs happy path, error recovery, and an invalid edge so counters leave zero.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Explicit <code>TRANSITIONS</code> map encodes allowed agent lifecycle edges.</p></li><li><p>Error path recovers ERROR &#8594; IDLE with rising <code>error_count</code> and recovery metrics.</p></li><li><p>Invalid transitions are blocked and surfaced as BLOCKED events.</p></li><li><p>Live dashboard shows transitions, states visited, recoveries, and throughput.</p></li><li><p>Docker lifecycle on port 8091 via <code>start.sh</code>, <code>demo.sh</code>, and <code>run_tests.sh</code>.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p><code>fsm/</code> package: <code>states.py</code>, <code>machine.py</code>, <code>metrics.py</code>, <code>service.py</code>.</p></li><li><p>FastAPI (<code>app.py</code>): <code>/transition</code>, <code>/scenario</code>, <code>/demo</code>, <code>/metrics</code>, <code>/health</code>, <code>/dashboard</code>.</p></li><li><p>CLI demo (<code>main.py</code>) printing happy-path, error-recovery, and blocked edges.</p></li><li><p><code>DEMO_SCENARIOS</code> covering tool-call loops and injection-style failure recovery.</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><p>Day 11 produced typed answers and entities. Day 12 advances only when validation and tool outcomes are well-defined, not free-form strings.</p><h2><strong>Enables Next Lesson</strong></h2><p>A correct FSM becomes the skeleton for Day 13&#8217;s async pipeline: each state can await I/O without losing auditability or recovery semantics.</p><h2><strong>Architecture Context</strong></h2><ul><li><p><strong>Where this component sits:</strong> between validated structured output and tool/response handlers.</p></li><li><p><strong>Why it exists:</strong> agents without explicit states hide loops, retries, and failures in ad-hoc flags.</p></li><li><p><strong>Problem solved:</strong> deterministic lifecycle control with measurable transitions and operator-visible history.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!eSR8!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!eSR8!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png 424w, /__u/substackcdn.com/image/fetch/$s_!eSR8!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png 848w, /__u/substackcdn.com/image/fetch/$s_!eSR8!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png 1272w, /__u/substackcdn.com/image/fetch/$s_!eSR8!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!eSR8!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png" width="612" height="360.64285714285717" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:858,&quot;width&quot;:1456,&quot;resizeWidth&quot;:612,&quot;bytes&quot;:750350,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/208167847?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!eSR8!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png 424w, /__u/substackcdn.com/image/fetch/$s_!eSR8!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png 848w, /__u/substackcdn.com/image/fetch/$s_!eSR8!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png 1272w, /__u/substackcdn.com/image/fetch/$s_!eSR8!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F29eef8ef-7a85-4656-8c50-0e8e14a8cfe2_4750x2800.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div>
      <p>
          <a href="/__u/aiamastery.substack.com/p/lesson-12-agent-state-machine">
              Read more
          </a>
      </p>
   ]]></content:encoded></item><item><title><![CDATA[Lesson 11 — Structured Output]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-11-structured-output</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-11-structured-output</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Fri, 21 Aug 2026 02:00:17 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!wfse!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>This lesson turns raw model text into typed, validated objects with Pydantic v2 schemas. <code>Entity</code> and <code>StructuredResponse</code> enforce allowed entity types, confidence bounds, and optional follow-ups. <code>parse_structured()</code> uses <code>model_validate_json</code> so invalid JSON and schema violations fail loudly. <code>MetricsStore</code> tracks OK/FAIL parses, entities, follow-ups, and latency; the FastAPI dashboard polls <code>/metrics</code>. <code>POST /demo</code> runs five mixed payloads so every counter leaves zero after one click.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Pydantic v2 <code>field_validator</code> clamps confidence and rejects invalid entity types.</p></li><li><p><code>model_validate_json</code> replaces deprecated <code>parse_raw</code> paths.</p></li><li><p>Demo mixes three valid and two invalid payloads for full validation coverage.</p></li><li><p>Live dashboard shows parse OK/FAIL, entities, follow-ups, and throughput.</p></li><li><p>Docker lifecycle on port 8090 via <code>start.sh</code>, <code>demo.sh</code>, and <code>run_tests.sh</code>.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p><code>structured/</code> package: <code>models.py</code>, <code>parser.py</code>, <code>metrics.py</code>, <code>service.py</code>.</p></li><li><p>FastAPI (<code>app.py</code>): <code>/parse</code>, <code>/demo</code>, <code>/metrics</code>, <code>/health</code>, <code>/dashboard</code>.</p></li><li><p>CLI demo (<code>main.py</code>) printing OK/FAIL outcomes for each payload.</p></li><li><p><code>DEMO_RAW_PAYLOADS</code> covering location, org/date, follow-up, bad type, and non-JSON.</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><p>Day 10 assembled prompts and routed categories. Day 11 assumes that text may be JSON and proves it against a contract before any downstream agent trusts fields.</p><h2><strong>Enables Next Lesson</strong></h2><p>Validated structures become reliable inputs for Day 12&#8217;s agent state machine: transitions consume typed answers and entities, not free-form strings.</p><h2><strong>Architecture Context</strong></h2><ul><li><p><strong>Where this component sits:</strong> between raw LLM/text ingress and business handlers that need typed fields.</p></li><li><p><strong>Why it exists:</strong> production systems cannot treat model prose as trustworthy data.</p></li><li><p><strong>Problem solved:</strong> schema enforcement with measurable OK/FAIL rates and operator-visible events.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!wfse!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!wfse!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png 424w, /__u/substackcdn.com/image/fetch/$s_!wfse!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png 848w, /__u/substackcdn.com/image/fetch/$s_!wfse!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png 1272w, /__u/substackcdn.com/image/fetch/$s_!wfse!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!wfse!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png" width="592" height="382.1978021978022" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:940,&quot;width&quot;:1456,&quot;resizeWidth&quot;:592,&quot;bytes&quot;:976350,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/208155063?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!wfse!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png 424w, /__u/substackcdn.com/image/fetch/$s_!wfse!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png 848w, /__u/substackcdn.com/image/fetch/$s_!wfse!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png 1272w, /__u/substackcdn.com/image/fetch/$s_!wfse!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7a9a1311-57a1-4e61-b408-87dc1cde17ab_4800x3100.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div>
      <p>
          <a href="/__u/aiamastery.substack.com/p/lesson-11-structured-output">
              Read more
          </a>
      </p>
   ]]></content:encoded></item><item><title><![CDATA[Lesson 10 — Prompt Engineering]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-10-prompt-engineering</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-10-prompt-engineering</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Tue, 18 Aug 2026 02:00:38 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!20Pz!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>This lesson builds a support-message classifier using prompt templates, few-shot examples, and keyword routing &#8212; without calling an LLM. <code>PromptTemplate</code> renders <code>{{placeholders}}</code>; <code>FEW_SHOT_EXAMPLES</code> inject labeled pairs into every prompt; <code>classify()</code> routes messages to billing, technical, general, or urgent. <code>MetricsStore</code> records renders, categories, token estimates, and recent events; a FastAPI dashboard polls <code>/metrics</code>. <code>POST /demo</code> runs five messages so every counter moves from zero after the first click. </p><p>The project in <code>aiam-day10/</code> runs via <code>start.sh</code>, <code>demo.sh</code>, and <code>run_tests.sh</code>.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Mustache-style <code>{{key}}</code> template rendering with unresolved-variable detection.</p></li><li><p>Few-shot example formatting for consistent classifier prompts.</p></li><li><p>Deterministic keyword routing &#8212; fast, testable, no API cost.</p></li><li><p>Dashboard auto-refreshes; <code>/demo</code> exercises all four categories.</p></li><li><p>Docker lifecycle scripts on port 8089.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p><code>prompt/</code> package: <code>template.py</code>, <code>classify.py</code>, <code>metrics.py</code>, <code>service.py</code>.</p></li><li><p>FastAPI (<code>app.py</code>): <code>/classify</code>, <code>/demo</code>, <code>/metrics</code>, <code>/health</code>, <code>/dashboard</code>.</p></li><li><p>CLI demo (<code>main.py</code>) printing inputs, categories, and token estimates.</p></li><li><p><code>DEMO_MESSAGES</code> &#8212; billing, technical, general, urgent &#8212; so every dashboard counter updates.</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><p>Day 9 sequences tool calls with ReAct thoughts. Day 10 shapes the prompts that would drive that planner: templates structure instructions, few-shot pairs set behavior, routing picks the right handler path.</p><h2><strong>Enables Next Lesson</strong></h2><p>Prompt engineering prepares structured output. Production swaps <code>classify()</code> for an LLM call; the template, few-shot injection, and metrics contract stay the same.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Architecture Context</strong></h2><ul><li><p><strong>Where this component sits:</strong> between <code>app.py</code> (API) and <code>prompt/classify.py</code> (routing logic).</p></li><li><p><strong>Why it exists:</strong> consistent, auditable prompts before any model invocation.</p></li><li><p><strong>Problem solved:</strong> repeatable prompt assembly with measurable category distribution.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!20Pz!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!20Pz!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png 424w, /__u/substackcdn.com/image/fetch/$s_!20Pz!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png 848w, /__u/substackcdn.com/image/fetch/$s_!20Pz!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png 1272w, /__u/substackcdn.com/image/fetch/$s_!20Pz!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!20Pz!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png" width="574" height="355.99038461538464" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:903,&quot;width&quot;:1456,&quot;resizeWidth&quot;:574,&quot;bytes&quot;:1277418,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/208033255?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!20Pz!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png 424w, /__u/substackcdn.com/image/fetch/$s_!20Pz!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png 848w, /__u/substackcdn.com/image/fetch/$s_!20Pz!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png 1272w, /__u/substackcdn.com/image/fetch/$s_!20Pz!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2ae9b2cd-8009-44dc-a199-fef43f91fd08_5500x3410.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Integration</strong></h2><h3><strong>Integration Components</strong></h3><p><code>app.py</code> validates <code>ClassifyBody</code> and calls <code>PromptService.render_and_classify()</code>. The service formats few-shot examples, renders <code>SUPPORT_CLASSIFIER_TEMPLATE</code>, runs <code>classify()</code>, and records metrics. <code>/demo</code> loops <code>DEMO_MESSAGES</code> then marks <code>demo_runs</code>.</p><h3><strong>Module Objectives Alignment</strong></h3><p>Prove template correctness, isolate routing from rendering, and expose per-category counters so operators confirm all paths executed.</p><h2><strong>Core Concepts</strong></h2><p><strong>Templates</strong> separate prompt structure from runtime data. <code>PromptTemplate.render(**kwargs)</code> replaces <code>{{examples}}</code> and <code>{{message}}</code>; leftover placeholders raise <code>ValueError</code> &#8212; catching typos before production.</p><p><strong>Few-shot examples</strong> prime classification behavior. Four labeled pairs (<code>billing</code>, <code>technical</code>, <code>general</code>, <code>urgent</code>) format into the examples block; the model (or router) sees consistent <code>Message:</code> / <code>Category:</code> pairs.</p><p><strong>Keyword routing</strong> maps substrings to categories: <code>"charge"</code> &#8594; billing, <code>"500"</code> &#8594; technical, <code>"urgent"</code> &#8594; urgent. First match wins; default is <code>general</code>. Deterministic routing enables unit tests without API keys.</p><p><strong>Token estimation</strong> uses <code>len(prompt) // 4</code> &#8212; a rough budget check before sending to a paid endpoint.</p><h2><strong>Production AI System Design Relevance</strong></h2><p>Prompt engineering sits before every LLM call. Day 9&#8217;s ReAct planner will consume prompts built this way. Templates version in Git; few-shot sets A/B test in staging; routing pre-filters before expensive inference.</p><h2><strong>Workflow</strong></h2><ul><li><p><strong>Request flow:</strong> <code>POST /classify</code> (one message) or <code>/demo</code> (five messages); Pydantic validates length.</p></li><li><p><strong>Execution flow:</strong> format examples &#8594; render template &#8594; classify &#8594; record metrics.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!5ljt!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6ced8d6a-12ff-4618-ad0d-29b00503a7cc_900x850.svg" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!5ljt!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6ced8d6a-12ff-4618-ad0d-29b00503a7cc_900x850.svg 424w, /__u/substackcdn.com/image/fetch/$s_!5ljt!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6ced8d6a-12ff-4618-ad0d-29b00503a7cc_900x850.svg 848w, /__u/substackcdn.com/image/fetch/$s_!5ljt!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6ced8d6a-12ff-4618-ad0d-29b00503a7cc_900x850.svg 1272w, /__u/substackcdn.com/image/fetch/$s_!5ljt!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6ced8d6a-12ff-4618-ad0d-29b00503a7cc_900x850.svg 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!5ljt!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6ced8d6a-12ff-4618-ad0d-29b00503a7cc_900x850.svg" width="558" height="526.9574175824176" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/6ced8d6a-12ff-4618-ad0d-29b00503a7cc_900x850.svg&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1375,&quot;width&quot;:1456,&quot;resizeWidth&quot;:558,&quot;bytes&quot;:6657,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/svg+xml&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/208033255?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6ced8d6a-12ff-4618-ad0d-29b00503a7cc_900x850.svg&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!5ljt!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6ced8d6a-12ff-4618-ad0d-29b00503a7cc_900x850.svg 424w, /__u/substackcdn.com/image/fetch/$s_!5ljt!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6ced8d6a-12ff-4618-ad0d-29b00503a7cc_900x850.svg 848w, /__u/substackcdn.com/image/fetch/$s_!5ljt!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6ced8d6a-12ff-4618-ad0d-29b00503a7cc_900x850.svg 1272w, /__u/substackcdn.com/image/fetch/$s_!5ljt!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F6ced8d6a-12ff-4618-ad0d-29b00503a7cc_900x850.svg 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><ul><li><p><strong>Data flow:</strong> each classification becomes a <code>recent_events</code> entry (max 20); aggregates update category counts and timing.</p></li><li><p><strong>State changes:</strong> <code>prompts_rendered</code>, <code>classifications</code>, per-category counts, <code>demo_runs</code>, token averages advance.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!a-M3!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F34463beb-826d-453a-a1b9-8928044968ee_4750x2750.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!a-M3!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F34463beb-826d-453a-a1b9-8928044968ee_4750x2750.png 424w, /__u/substackcdn.com/image/fetch/$s_!a-M3!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F34463beb-826d-453a-a1b9-8928044968ee_4750x2750.png 848w, /__u/substackcdn.com/image/fetch/$s_!a-M3!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F34463beb-826d-453a-a1b9-8928044968ee_4750x2750.png 1272w, /__u/substackcdn.com/image/fetch/$s_!a-M3!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F34463beb-826d-453a-a1b9-8928044968ee_4750x2750.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!a-M3!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F34463beb-826d-453a-a1b9-8928044968ee_4750x2750.png" width="612" height="354.3379120879121" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/34463beb-826d-453a-a1b9-8928044968ee_4750x2750.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:843,&quot;width&quot;:1456,&quot;resizeWidth&quot;:612,&quot;bytes&quot;:615196,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/208033255?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F34463beb-826d-453a-a1b9-8928044968ee_4750x2750.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!a-M3!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F34463beb-826d-453a-a1b9-8928044968ee_4750x2750.png 424w, /__u/substackcdn.com/image/fetch/$s_!a-M3!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F34463beb-826d-453a-a1b9-8928044968ee_4750x2750.png 848w, /__u/substackcdn.com/image/fetch/$s_!a-M3!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F34463beb-826d-453a-a1b9-8928044968ee_4750x2750.png 1272w, /__u/substackcdn.com/image/fetch/$s_!a-M3!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F34463beb-826d-453a-a1b9-8928044968ee_4750x2750.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Production Integration</strong></h2><ul><li><p><strong>Architecture fit:</strong> stateless API; persist prompt versions externally.</p></li><li><p><strong>Enterprise patterns:</strong> template registry, few-shot versioning, category allowlists.</p></li><li><p><strong>Scalability:</strong> single uvicorn worker for in-memory metrics; externalize at scale.</p></li><li><p><strong>Observability:</strong> export category distribution, render latency, token estimates.</p></li><li><p><strong>Security:</strong> authenticate <code>/classify</code>; no secrets in templates; 500-char message cap.</p></li></ul><h2><strong>Step-by-Step Implementation</strong></h2><h2><strong>GitHub Link</strong></h2><p><strong><a href="https://github.com/sysdr/production-ai-engineering-p/tree/main/lesson10/aiam-day10">https://github.com/sysdr/production-ai-engineering-p/tree/main/lesson10/aiam-day10</a></strong></p><p><code>template.py</code> defines <code>PromptTemplate</code> and <code>format_few_shot_examples()</code>. <code>classify.py</code> holds <code>CLASSIFICATION_RULES</code> and <code>classify()</code>. <code>metrics.py</code> locks counters and returns deep-copy snapshots. <code>service.py</code> owns <code>DEMO_MESSAGES</code> and <code>run_demo()</code>. <code>app.py</code> serves the dashboard with auto-refresh.</p><h2><strong>Coding Highlights</strong></h2><p>Template rendering with validation:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;9bbb5a3e-9816-4c6d-85d8-1a6a93fe0b28&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">for key, value in kwargs.items():
    text = text.replace("{{" + key + "}}", str(value))
if "{{" in text:
    raise ValueError(f"unresolved template variables: {missing}")</code></pre></div><p>Few-shot formatting:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;7518c525-0f6b-4482-9c58-40b09ee2a7e8&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">return "\n".join(
    f"Message: {message}\nCategory: {category}\n"
    for message, category in examples
)</code></pre></div><p>Unresolved placeholders caught at render time prevent silent prompt corruption in production.</p><h3>Working Demo Link:</h3><div id="youtube2-DvizJERdkLU" class="youtube-wrap" data-attrs="{&quot;videoId&quot;:&quot;DvizJERdkLU&quot;,&quot;startTime&quot;:null,&quot;endTime&quot;:null}" data-component-name="Youtube2ToDOM"><div class="youtube-inner"><iframe src="https://www.youtube-nocookie.com/embed/DvizJERdkLU?rel=0&amp;autoplay=0&amp;showinfo=0&amp;enablejsapi=0" frameborder="0" loading="lazy" gesture="media" allow="autoplay; fullscreen" allowautoplay="true" allowfullscreen="true" width="728" height="409"></iframe></div></div><h2><strong>Production Considerations</strong></h2><ul><li><p><strong>Scalability:</strong> externalize metrics and prompt versions beyond one replica.</p></li><li><p><strong>Security:</strong> no API keys in repo; <code>.env</code> gitignored; message length capped.</p></li><li><p><strong>Monitoring:</strong> alert on skewed category distribution or zero <code>classifications</code>.</p></li><li><p><strong>Testing:</strong> <code>test_prompt.py</code> for template/routing; <code>test_api.py</code> for HTTP and metrics.</p></li><li><p><strong>Failure handling:</strong> unresolved template vars raise; unknown keywords default to <code>general</code>.</p></li></ul><h2><strong>Validation</strong></h2><ul><li><p><strong>Verification:</strong> <code>/health</code> green; <code>/demo</code> completes five classifications; dashboard serves.</p></li><li><p><strong>Testing strategy:</strong> 9 pytest cases across template, classify, service, and API.</p></li><li><p><strong>Success criteria:</strong> tests pass; after demo, all category counters and <code>demo_runs</code> are non-zero.</p></li><li><p><strong>Expected outputs:</strong> charge &#8594; billing; API 500 &#8594; technical; phone &#8594; general; URGENT down &#8594; urgent.</p></li><li><p><strong>Benchmarks:</strong> sub-second demo; ~73 tokens per rendered prompt.</p></li><li><p><strong>Production checklist:</strong> single replica, auth on <code>/classify</code>, alert on zero category coverage.</p></li></ul><h2><strong>Key Insights</strong></h2><p>Prompt quality depends on template structure and few-shot diversity, not length alone. Demo messages must hit every category &#8212; a zero counter signals a broken path. Common mistakes: missing placeholder validation, stale few-shot examples, routing rules that overlap.</p><h3><strong>Important Classes</strong></h3><ul><li><p><code>PromptTemplate</code> &#8212; renders and estimates tokens.</p></li><li><p><code>MetricsStore</code> &#8212; thread-safe counters and recent events.</p></li><li><p><code>PromptService</code> &#8212; API runs and demo orchestration.</p></li></ul><h3><strong>Key Methods</strong></h3><ul><li><p><code>PromptTemplate.render()</code> / <code>estimate_tokens()</code> &#8212; build and size prompts.</p></li><li><p><code>classify()</code> &#8212; keyword routing to category.</p></li><li><p><code>MetricsStore.record_classification()</code> / <code>snapshot()</code> &#8212; update and read dashboard state.</p></li></ul><h2><strong>Success Criteria</strong></h2><p><code>aiam-day10/</code> runs from <code>start.sh</code> and <code>demo.sh</code> alone. All tests pass. Dashboard metrics non-zero after demo. Cleanup removes containers and artifacts.</p><h2><strong>Real-World Examples</strong></h2><ul><li><p>A support triage system renders few-shot prompts per queue, routes billing keywords to a payment specialist agent, and logs category distribution for SLA dashboards.</p></li><li><p>A content moderation pipeline templates policy instructions, injects labeled violation examples, and pre-routes urgent keywords to human review before LLM scoring.</p></li></ul><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Week 2: Model Landscape & Prompting Basics]]></title><description><![CDATA[Inference Orchestration Platform]]></description><link>https://aiamastery.substack.com/p/week-2-model-landscape-and-prompting</link><guid isPermaLink="false">https://aiamastery.substack.com/p/week-2-model-landscape-and-prompting</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Sun, 16 Aug 2026 16:43:11 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!XD2D!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Inference Orchestration Platform</strong></h2><blockquote><p>Integrated production console for <strong>model landscape selection, secure LLM API access, structured output extraction, and autonomous agent deliberation</strong>. This project unifies four core engineering domains into a single deployable system with a unified dashboard, REST API, activity logging, and Docker packaging.</p></blockquote><h2><strong>What this project covers</strong></h2><blockquote><p>This platform is the capstone integration for the <strong>Model Landscape &amp; Prompting</strong> track. It combines concepts and patterns from four standalone reference implementations:</p></blockquote><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!VsRN!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F938eec5d-cdb6-41b0-9d79-7aaf56645cde_1115x287.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!VsRN!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F938eec5d-cdb6-41b0-9d79-7aaf56645cde_1115x287.png 424w, /__u/substackcdn.com/image/fetch/$s_!VsRN!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F938eec5d-cdb6-41b0-9d79-7aaf56645cde_1115x287.png 848w, /__u/substackcdn.com/image/fetch/$s_!VsRN!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F938eec5d-cdb6-41b0-9d79-7aaf56645cde_1115x287.png 1272w, /__u/substackcdn.com/image/fetch/$s_!VsRN!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F938eec5d-cdb6-41b0-9d79-7aaf56645cde_1115x287.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!VsRN!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F938eec5d-cdb6-41b0-9d79-7aaf56645cde_1115x287.png" width="1115" height="287" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/938eec5d-cdb6-41b0-9d79-7aaf56645cde_1115x287.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:287,&quot;width&quot;:1115,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:51088,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/204395570?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F938eec5d-cdb6-41b0-9d79-7aaf56645cde_1115x287.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!VsRN!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F938eec5d-cdb6-41b0-9d79-7aaf56645cde_1115x287.png 424w, /__u/substackcdn.com/image/fetch/$s_!VsRN!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F938eec5d-cdb6-41b0-9d79-7aaf56645cde_1115x287.png 848w, /__u/substackcdn.com/image/fetch/$s_!VsRN!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F938eec5d-cdb6-41b0-9d79-7aaf56645cde_1115x287.png 1272w, /__u/substackcdn.com/image/fetch/$s_!VsRN!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F938eec5d-cdb6-41b0-9d79-7aaf56645cde_1115x287.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h3><strong>Dashboard tabs</strong></h3><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!cL9f!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdf55d83e-83f8-45a1-84bf-7943a94c9352_807x282.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!cL9f!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdf55d83e-83f8-45a1-84bf-7943a94c9352_807x282.png 424w, /__u/substackcdn.com/image/fetch/$s_!cL9f!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdf55d83e-83f8-45a1-84bf-7943a94c9352_807x282.png 848w, /__u/substackcdn.com/image/fetch/$s_!cL9f!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdf55d83e-83f8-45a1-84bf-7943a94c9352_807x282.png 1272w, /__u/substackcdn.com/image/fetch/$s_!cL9f!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdf55d83e-83f8-45a1-84bf-7943a94c9352_807x282.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!cL9f!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdf55d83e-83f8-45a1-84bf-7943a94c9352_807x282.png" width="807" height="282" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/df55d83e-83f8-45a1-84bf-7943a94c9352_807x282.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:282,&quot;width&quot;:807,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:47205,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/204395570?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdf55d83e-83f8-45a1-84bf-7943a94c9352_807x282.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!cL9f!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdf55d83e-83f8-45a1-84bf-7943a94c9352_807x282.png 424w, /__u/substackcdn.com/image/fetch/$s_!cL9f!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdf55d83e-83f8-45a1-84bf-7943a94c9352_807x282.png 848w, /__u/substackcdn.com/image/fetch/$s_!cL9f!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdf55d83e-83f8-45a1-84bf-7943a94c9352_807x282.png 1272w, /__u/substackcdn.com/image/fetch/$s_!cL9f!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fdf55d83e-83f8-45a1-84bf-7943a94c9352_807x282.png 1456w" sizes="100vw"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Architecture</strong></h2><pre><code><code>&#9484;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;
&#9474;                    React Dashboard (:3300)                   &#9474;
&#9474;  Overview &#9474; Catalog &#9474; Gateway &#9474; Structured &#9474; Autonomy        &#9474;
&#9492;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9516;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9496;
                           &#9474; REST / WebSocket proxy
&#9484;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9660;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;
&#9474;                   FastAPI Backend (:8300)                    &#9474;
&#9474;  catalog/ &#9474; gateway/ &#9474; structured/ &#9474; autonomy/               &#9474;
&#9492;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9496;
</code></code></pre><p><strong>Stack:</strong> Python 3.12 &#183; FastAPI &#183; Pydantic v2 &#183; google-genai &#183; Vite &#183; React 19 &#183; Recharts &#183; Docker (nginx + slim images)</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!XD2D!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!XD2D!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png 424w, /__u/substackcdn.com/image/fetch/$s_!XD2D!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png 848w, /__u/substackcdn.com/image/fetch/$s_!XD2D!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png 1272w, /__u/substackcdn.com/image/fetch/$s_!XD2D!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!XD2D!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png" width="1456" height="1001" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1001,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:674858,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/204395570?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!XD2D!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png 424w, /__u/substackcdn.com/image/fetch/$s_!XD2D!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png 848w, /__u/substackcdn.com/image/fetch/$s_!XD2D!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png 1272w, /__u/substackcdn.com/image/fetch/$s_!XD2D!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F3f227bc1-7f06-4353-a1ad-af2229e9e6b7_4400x3025.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div>
      <p>
          <a href="/__u/aiamastery.substack.com/p/week-2-model-landscape-and-prompting">
              Read more
          </a>
      </p>
   ]]></content:encoded></item><item><title><![CDATA[Lesson 9 — ReAct Loop]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-9-react-loop</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-9-react-loop</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Thu, 13 Aug 2026 02:00:18 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!b49C!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>This lesson implements Reason+Act (ReAct): an agent alternates thoughts with tool calls until it answers or hits a step limit. Unlike one-shot prompting, every thought, action, and observation is visible for debugging. Three tools &#8212; search, calculate, lookup &#8212; sit behind a planner in <code>react/loop.py</code>; <code>MetricsStore</code> records each step; a FastAPI dashboard shows live counters. <code>POST /demo</code> runs three questions so metrics move from zero after the first click. </p><p>The project in <code>aiam-day09/</code> runs via <code>start.sh</code>, <code>demo.sh</code>, and <code>run_tests.sh</code>.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Thought &#8594; Action &#8594; Observation with stopping on <code>final_answer</code> or <code>max_steps</code>.</p></li><li><p>Tool dispatch via <code>Action: name[argument]</code> parsed by strict regex.</p></li><li><p>AST-safe calculator &#8212; no <code>eval()</code>.</p></li><li><p>Dashboard polls <code>/metrics</code>; <code>/demo</code> exercises all three tools.</p></li><li><p>Docker lifecycle scripts on port 8088.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p><code>react/</code> package: <code>tools.py</code>, <code>loop.py</code>, <code>metrics.py</code>, <code>service.py</code>.</p></li><li><p>FastAPI (<code>app.py</code>): <code>/run</code>, <code>/demo</code>, <code>/metrics</code>, <code>/health</code>, <code>/dashboard</code>.</p></li><li><p>CLI demo (<code>main.py</code>) printing steps, observations, and final answers.</p></li><li><p><code>DEMO_QUESTIONS</code> &#8212; search, calculate, lookup &#8212; so every dashboard counter updates.</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><p>Day 8 fanned typed work to workers in parallel. Day 9 sequences one tool per step: observe, then continue or stop with a Final Answer.</p><h2><strong>Enables Next Lesson</strong></h2><p>ReAct is the control loop prompt engineering will steer. Production swaps <code>_plan_thought()</code> for an LLM; the action/observation contract and metrics stay the same.</p><h2><strong>Architecture Context</strong></h2><ul><li><p><strong>Where this component sits:</strong> between <code>app.py</code> (API) and <code>react/tools.py</code> (tool backends).</p></li><li><p><strong>Why it exists:</strong> multi-step questions need grounded facts before a final answer.</p></li><li><p><strong>Problem solved:</strong> bounded, observable tool use with measurable loop health.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!b49C!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!b49C!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png 424w, /__u/substackcdn.com/image/fetch/$s_!b49C!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png 848w, /__u/substackcdn.com/image/fetch/$s_!b49C!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png 1272w, /__u/substackcdn.com/image/fetch/$s_!b49C!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!b49C!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png" width="552" height="398.83516483516485" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1052,&quot;width&quot;:1456,&quot;resizeWidth&quot;:552,&quot;bytes&quot;:1165349,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/208023391?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!b49C!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png 424w, /__u/substackcdn.com/image/fetch/$s_!b49C!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png 848w, /__u/substackcdn.com/image/fetch/$s_!b49C!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png 1272w, /__u/substackcdn.com/image/fetch/$s_!b49C!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9c7af2ef-eb16-4e37-a453-9739bf180aad_4950x3575.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div>
      <p>
          <a href="/__u/aiamastery.substack.com/p/lesson-9-react-loop">
              Read more
          </a>
      </p>
   ]]></content:encoded></item><item><title><![CDATA[Lesson 8 — Multi-Agent Orchestration]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-8-multi-agent-orchestration</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-8-multi-agent-orchestration</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Tue, 11 Aug 2026 02:00:48 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!I4cP!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffe869e93-251f-4927-865d-e61fba33df14_5225x3575.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>This lesson shows how a supervisor fans typed work to specialized workers in parallel. Single-agent pipelines waste wall time when research, writing, and summarization can overlap. A shared dispatch path records completions, timing, and speedup for operators. A FastAPI dashboard makes those signals visible after each demo.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Supervisor/worker fan-out with <code>ThreadPoolExecutor</code>.</p></li><li><p>Typed tasks: research, write, and summarise.</p></li><li><p>Parallel wall-clock vs serial estimate speedup metrics.</p></li><li><p>Live dashboard for dispatch, completion, and recent task events.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p>An <code>orchestration</code> package: workers, supervisor, metrics store, and service layer.</p></li><li><p>HTTP APIs for <code>/dispatch</code>, <code>/demo</code>, <code>/metrics</code>, <code>/health</code>, and <code>/dashboard</code>.</p></li><li><p>CLI demo that runs six parallel tasks across three worker specialties.</p></li><li><p>Docker image, compose file, and lifecycle scripts for run, test, and cleanup.</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><p>Day 7 sandboxed untrusted code so agents could execute snippets safely. Day 8 assumes that guardrail and focuses on coordinating multiple agents without serializing every step.</p><h2><strong>Enables Next Lesson</strong></h2><p>Parallel dispatch is the substrate for a ReAct loop: the planner chooses tools, workers execute in parallel where safe, and the loop merges results before the next thought step.</p><h2><strong>Architecture Context</strong></h2><ul><li><p><strong>Where this component sits:</strong> between the planner/API gateway and specialized worker agents.</p></li><li><p><strong>Why it exists:</strong> multi-step agent work stalls if every specialty runs one after another.</p></li><li><p><strong>Problem solved:</strong> concurrent typed dispatch with observable speedup and task outcomes.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!I4cP!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffe869e93-251f-4927-865d-e61fba33df14_5225x3575.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!I4cP!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffe869e93-251f-4927-865d-e61fba33df14_5225x3575.png 424w, /__u/substackcdn.com/image/fetch/$s_!I4cP!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffe869e93-251f-4927-865d-e61fba33df14_5225x3575.png 848w, /__u/substackcdn.com/image/fetch/$s_!I4cP!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffe869e93-251f-4927-865d-e61fba33df14_5225x3575.png 1272w, /__u/substackcdn.com/image/fetch/$s_!I4cP!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffe869e93-251f-4927-865d-e61fba33df14_5225x3575.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!I4cP!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffe869e93-251f-4927-865d-e61fba33df14_5225x3575.png" width="596" height="407.7032967032967" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/fe869e93-251f-4927-865d-e61fba33df14_5225x3575.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:996,&quot;width&quot;:1456,&quot;resizeWidth&quot;:596,&quot;bytes&quot;:1174639,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207530808?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffe869e93-251f-4927-865d-e61fba33df14_5225x3575.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!I4cP!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffe869e93-251f-4927-865d-e61fba33df14_5225x3575.png 424w, /__u/substackcdn.com/image/fetch/$s_!I4cP!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffe869e93-251f-4927-865d-e61fba33df14_5225x3575.png 848w, /__u/substackcdn.com/image/fetch/$s_!I4cP!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffe869e93-251f-4927-865d-e61fba33df14_5225x3575.png 1272w, /__u/substackcdn.com/image/fetch/$s_!I4cP!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffe869e93-251f-4927-865d-e61fba33df14_5225x3575.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div>
      <p>
          <a href="/__u/aiamastery.substack.com/p/lesson-8-multi-agent-orchestration">
              Read more
          </a>
      </p>
   ]]></content:encoded></item><item><title><![CDATA[Lesson 7 — Sandboxed Code Execution]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-7-sandboxed-code-execution</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-7-sandboxed-code-execution</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Mon, 10 Aug 2026 02:01:03 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!-cQ7!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>This lesson isolates untrusted Python before it can touch the host. AI agents often emit runnable snippets; executing them raw is unsafe. A child process, blocked imports, and timeouts form a minimal sandbox. Outcomes feed a live dashboard so operators see OK, blocked, timeout, and error rates. The demo proves every metric moves when real cases run.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Subprocess isolation for each submitted snippet.</p></li><li><p>Dangerous imports (<code>os</code>, <code>subprocess</code>, <code>socket</code>, and peers) denied at load time.</p></li><li><p>Hard timeouts that kill infinite loops without hanging the API worker.</p></li><li><p>FastAPI dashboard with demo-driven execution metrics.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p>A <code>sandbox</code> package: executor, metrics store, and service layer.</p></li><li><p>HTTP APIs for <code>/execute</code>, <code>/demo</code>, <code>/metrics</code>, <code>/health</code>, and <code>/dashboard</code>.</p></li><li><p>CLI demo covering safe, blocked, timeout, and syntax-error paths.</p></li><li><p>Docker image, compose file, and lifecycle scripts for runs and tests.</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><p>Day 6 made latency and errors visible. Those signals baseline sandbox pressure&#8212;timeouts and blocks should appear as operational events, not silent hangs.</p><h2><strong>Enables Next Lesson</strong></h2><p>Safe local execution is a prerequisite for multi-agent orchestration, where agents exchange code without sharing one privileged process.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Architecture Context</strong></h2><ul><li><p><strong>Where this component sits:</strong> between the agent/tool planner and the host OS, as an execution step or sidecar.</p></li><li><p><strong>Why it exists:</strong> model-generated code may probe files, spawn shells, or open sockets.</p></li><li><p><strong>Problem solved:</strong> untrusted snippets run under constraints while remaining measurable.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!-cQ7!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!-cQ7!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png 424w, /__u/substackcdn.com/image/fetch/$s_!-cQ7!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png 848w, /__u/substackcdn.com/image/fetch/$s_!-cQ7!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png 1272w, /__u/substackcdn.com/image/fetch/$s_!-cQ7!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!-cQ7!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png" width="520" height="375.7142857142857" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1052,&quot;width&quot;:1456,&quot;resizeWidth&quot;:520,&quot;bytes&quot;:1074812,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207520756?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!-cQ7!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png 424w, /__u/substackcdn.com/image/fetch/$s_!-cQ7!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png 848w, /__u/substackcdn.com/image/fetch/$s_!-cQ7!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png 1272w, /__u/substackcdn.com/image/fetch/$s_!-cQ7!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F88367af6-e119-44a1-a84f-41e03e17d575_4950x3575.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Integration</strong></h2><h3><strong>Integration Components</strong></h3><p>FastAPI validates payloads with Pydantic and calls <code>SandboxService</code>. The service runs <code>SandboxExecutor</code> in a child process, classifies the result, and records it in <code>MetricsStore</code>. The dashboard polls <code>/metrics</code>; <code>/demo</code> seeds every outcome class. Docker runs one uvicorn worker so in-memory metrics stay coherent.</p><h3><strong>Module Objectives Alignment</strong></h3><p>Contain blast radius, fail closed on dangerous imports and runaway loops, and expose counters for policy tuning.</p><h2><strong>Core Concepts</strong></h2><p>Subprocess isolation keeps faults out of the API process. A crash or busy loop in user code should not corrupt the gateway event loop. Temporary source is written, executed with a cleaned environment, then deleted.</p><p>Import policy uses a deny-list of dangerous roots. Strict allow-only lists break when CPython pulls helpers such as <code>keyword</code> for <code>collections</code>/<code>json</code>. Denying <code>os</code>, <code>subprocess</code>, and <code>socket</code> preserves useful stdlib while blocking common escapes.</p><p>Timeouts convert hangs into a deterministic <code>TIMEOUT</code> outcome. Metrics separate OK, blocked, timeout, and error so operators see whether policy or capacity is failing.</p><h2><strong>Production AI System Design Relevance</strong></h2><p>This is the execution guardrail of a production AI stack. It belongs next to tool runners and code-act agents, after planning and before durable side effects. Day 6 observability wraps it; Day 8 multi-agent workflows consume it as a shared capability.</p><h2><strong>Workflow</strong></h2><ul><li><p><strong>Request flow:</strong> client posts code to <code>/execute</code> or triggers <code>/demo</code>; FastAPI validates fields and timeout bounds.</p></li><li><p><strong>Execution flow:</strong> executor wraps code with the import guard, spawns <code>python</code>, waits up to the limit, and classifies output.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!mbo1!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bf70ccf-d25e-4866-8f1f-2cdeaea620b8_5225x3575.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!mbo1!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bf70ccf-d25e-4866-8f1f-2cdeaea620b8_5225x3575.png 424w, /__u/substackcdn.com/image/fetch/$s_!mbo1!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bf70ccf-d25e-4866-8f1f-2cdeaea620b8_5225x3575.png 848w, /__u/substackcdn.com/image/fetch/$s_!mbo1!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bf70ccf-d25e-4866-8f1f-2cdeaea620b8_5225x3575.png 1272w, /__u/substackcdn.com/image/fetch/$s_!mbo1!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bf70ccf-d25e-4866-8f1f-2cdeaea620b8_5225x3575.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!mbo1!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bf70ccf-d25e-4866-8f1f-2cdeaea620b8_5225x3575.png" width="522" height="357.0824175824176" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/5bf70ccf-d25e-4866-8f1f-2cdeaea620b8_5225x3575.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:996,&quot;width&quot;:1456,&quot;resizeWidth&quot;:522,&quot;bytes&quot;:878385,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207520756?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bf70ccf-d25e-4866-8f1f-2cdeaea620b8_5225x3575.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!mbo1!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bf70ccf-d25e-4866-8f1f-2cdeaea620b8_5225x3575.png 424w, /__u/substackcdn.com/image/fetch/$s_!mbo1!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bf70ccf-d25e-4866-8f1f-2cdeaea620b8_5225x3575.png 848w, /__u/substackcdn.com/image/fetch/$s_!mbo1!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bf70ccf-d25e-4866-8f1f-2cdeaea620b8_5225x3575.png 1272w, /__u/substackcdn.com/image/fetch/$s_!mbo1!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bf70ccf-d25e-4866-8f1f-2cdeaea620b8_5225x3575.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><ul><li><p><strong>Data flow:</strong> results update counters and a bounded recent-events list; <code>/metrics</code> returns a snapshot for the UI.</p></li><li><p><strong>State changes:</strong> totals increment, rates recalculate, <code>demo_runs</code> advances, and event history rotates.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!6fr0!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fba84ae9d-74f8-4a09-b0c1-7050caad8f76_4950x2475.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!6fr0!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fba84ae9d-74f8-4a09-b0c1-7050caad8f76_4950x2475.png 424w, /__u/substackcdn.com/image/fetch/$s_!6fr0!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fba84ae9d-74f8-4a09-b0c1-7050caad8f76_4950x2475.png 848w, /__u/substackcdn.com/image/fetch/$s_!6fr0!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fba84ae9d-74f8-4a09-b0c1-7050caad8f76_4950x2475.png 1272w, /__u/substackcdn.com/image/fetch/$s_!6fr0!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fba84ae9d-74f8-4a09-b0c1-7050caad8f76_4950x2475.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!6fr0!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fba84ae9d-74f8-4a09-b0c1-7050caad8f76_4950x2475.png" width="560" height="280" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/ba84ae9d-74f8-4a09-b0c1-7050caad8f76_4950x2475.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:728,&quot;width&quot;:1456,&quot;resizeWidth&quot;:560,&quot;bytes&quot;:649365,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207520756?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fba84ae9d-74f8-4a09-b0c1-7050caad8f76_4950x2475.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!6fr0!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fba84ae9d-74f8-4a09-b0c1-7050caad8f76_4950x2475.png 424w, /__u/substackcdn.com/image/fetch/$s_!6fr0!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fba84ae9d-74f8-4a09-b0c1-7050caad8f76_4950x2475.png 848w, /__u/substackcdn.com/image/fetch/$s_!6fr0!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fba84ae9d-74f8-4a09-b0c1-7050caad8f76_4950x2475.png 1272w, /__u/substackcdn.com/image/fetch/$s_!6fr0!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fba84ae9d-74f8-4a09-b0c1-7050caad8f76_4950x2475.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Production Integration</strong></h2><ul><li><p><strong>Architecture fit:</strong> prefer a dedicated executor with CPU/memory cgroups over the public API pod.</p></li><li><p><strong>Enterprise patterns:</strong> per-tenant policies, signed job envelopes, artifact-only returns.</p></li><li><p><strong>Scalability:</strong> queue across executor workers; centralize metrics when replicas exceed one.</p></li><li><p><strong>Observability:</strong> export outcome counters, timeout rate, and duration histograms.</p></li><li><p><strong>Security:</strong> drop capabilities, read-only rootfs, default-deny network, never mount Docker.sock.</p></li></ul><h2><strong>Step-by-Step Implementation</strong></h2><h2><strong>GitHub Link</strong></h2><p><strong><a href="https://github.com/sysdr/production-ai-engineering/tree/main/lesson7/aiam-day07">https://github.com/sysdr/production-ai-engineering/tree/main/lesson7/aiam-day07</a></strong></p><p>The executor owns isolation so the API stays thin. The service maps cases to executor calls and annotates import hits for the dashboard. Metrics stay behind a lock and return copied snapshots. Validation rejects empty or oversized payloads. Syntax failures record as <code>ERROR</code>, not timeouts. Production adds cgroups and network policy beyond this demo.</p><h2><strong>Coding Highlights</strong></h2><p>Deny dangerous roots while preserving normal stdlib loads:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;a066ca02-674c-48e2-b478-dd020a152d2c&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">if root in _blocked:
    raise ImportError("Blocked: " + name)</code></pre></div><p>This fails closed on escape modules without breaking transitive imports.</p><p>Timeouts become structured outcomes:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;1d3a45a0-2b27-4559-a3c4-6a3cec07c145&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">except subprocess.TimeoutExpired:
    return SandboxResult(ok=False, output="TIMED OUT", timeout=True, ...)</code></pre></div><p>Operators alert on <code>timeout=True</code> instead of guessing from missing responses.</p><h3>Working Demo Link:</h3><div id="youtube2-PwzB7-l0McQ" class="youtube-wrap" data-attrs="{&quot;videoId&quot;:&quot;PwzB7-l0McQ&quot;,&quot;startTime&quot;:null,&quot;endTime&quot;:null}" data-component-name="Youtube2ToDOM"><div class="youtube-inner"><iframe src="https://www.youtube-nocookie.com/embed/PwzB7-l0McQ?rel=0&amp;autoplay=0&amp;showinfo=0&amp;enablejsapi=0" frameborder="0" loading="lazy" gesture="media" allow="autoplay; fullscreen" allowautoplay="true" allowfullscreen="true" width="728" height="409"></iframe></div></div><h2><strong>Production Considerations</strong></h2><ul><li><p><strong>Scalability:</strong> queue jobs; bound concurrency per tenant; store histograms centrally.</p></li><li><p><strong>Security:</strong> pair import denial with OS isolation; a deny-list alone is not a jail.</p></li><li><p><strong>Monitoring / logging:</strong> log outcome, duration, and request id&#8212;not full untrusted source.</p></li><li><p><strong>Testing:</strong> unit-test OK/block/timeout/syntax; API-test that demo metrics are non-zero.</p></li><li><p><strong>Failure handling:</strong> always unlink temp files; surface executor crashes as errors.</p></li><li><p><strong>Edge cases:</strong> relative imports, empty output, nested blocked imports.</p></li></ul><h2><strong>Validation</strong></h2><ul><li><p><strong>Verification:</strong> health green; demo populates every counter; dashboard HTML serves.</p></li><li><p><strong>Testing strategy:</strong> executor unit tests plus FastAPI contract and metric-mutation tests.</p></li><li><p><strong>Success criteria:</strong> all tests pass; after demo, primary metrics are non-zero.</p></li><li><p><strong>Expected outputs:</strong> OK for arithmetic/math/json/collections; blocked OS/subprocess/socket; timeout on infinite loops; error on syntax.</p></li><li><p><strong>Benchmarks:</strong> blocked imports finish in tens of milliseconds; timeouts match configured limits.</p></li><li><p><strong>Production checklist:</strong> resource limits set, network default-deny, secrets absent from images, alerts on timeout rate.</p></li></ul><h2><strong>Key Insights</strong></h2><p>Isolation without measurement invites silent failure. Import denial needs OS controls. Common mistakes: brittle allow-lists, sharing one interpreter with the API, and averaging away timeout tails.</p><h3><strong>Important Classes</strong></h3><ul><li><p><code>SandboxExecutor</code> &#8212; child-process runner with import guard and timeout.</p></li><li><p><code>MetricsStore</code> &#8212; thread-safe counters and recent events.</p></li><li><p><code>SandboxService</code> &#8212; demo cases and API-facing execution.</p></li></ul><h3><strong>Key Methods</strong></h3><ul><li><p><code>SandboxExecutor.run()</code> &#8212; isolate, execute, classify.</p></li><li><p><code>MetricsStore.record()</code> / <code>snapshot()</code> &#8212; mutate and read dashboard state.</p></li><li><p><code>SandboxService.run_demo()</code> &#8212; deterministic coverage of all outcomes.</p></li></ul><h2><strong>Real-World Examples</strong></h2><ul><li><p>A coding agent executes proposed PR snippets in ephemeral executors; blocked <code>subprocess</code> calls increment policy metrics and never reach CI hosts.</p></li><li><p>An analytics copilot evaluates user formulas server-side; timeouts protect shared capacity when a customer submits an infinite loop, while other tenants keep being served.</p></li></ul><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Lesson 6 — Observability Stack]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-6-observability-stack</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-6-observability-stack</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Sun, 09 Aug 2026 02:01:19 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!tYg6!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>This lesson adds observability to an AI service. Requests emit JSON and contribute latency measurements. RED metrics turn runtime behavior into operational signals. A dashboard presents percentiles, throughput, failures, routes, and events. Demo traffic proves telemetry changes when work executes.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>JSON logs with route, status, latency, and request IDs.</p></li><li><p>Thread-safe RED metrics with p50, p95, and p99 latency.</p></li><li><p>FastAPI dashboard with route counters and recent events.</p></li><li><p>Docker execution, health checks, demo traffic, and tests.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p>An observability package containing logging, metrics, and service modules.</p></li><li><p>A latency histogram and synchronized in-memory metrics store.</p></li><li><p>Health, metrics, simulation, demo, and dashboard endpoints.</p></li><li><p>Docker lifecycle scripts and unit/API validation.</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><p>The previous lesson protected model output with scanning, redaction, and integrity checks. This lesson makes that service measurable and its reliability visible.</p><h2><strong>Enables Next Lesson</strong></h2><p>Error and latency signals establish the baseline for sandboxed code execution, making new resource pressure and failures visible.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Architecture Context</strong></h2><ul><li><p><strong>Where this component sits:</strong> at the HTTP request boundary, surrounding gateway and AI workload execution.</p></li><li><p><strong>Why it exists:</strong> production failures include gradual latency growth and intermittent upstream errors, not only crashes.</p></li><li><p><strong>Problem solved:</strong> opaque request handling becomes searchable events and quantitative service-health signals.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!tYg6!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!tYg6!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png 424w, /__u/substackcdn.com/image/fetch/$s_!tYg6!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png 848w, /__u/substackcdn.com/image/fetch/$s_!tYg6!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png 1272w, /__u/substackcdn.com/image/fetch/$s_!tYg6!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!tYg6!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png" width="504" height="315" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/fd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:910,&quot;width&quot;:1456,&quot;resizeWidth&quot;:504,&quot;bytes&quot;:786246,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207402534?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!tYg6!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png 424w, /__u/substackcdn.com/image/fetch/$s_!tYg6!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png 848w, /__u/substackcdn.com/image/fetch/$s_!tYg6!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png 1272w, /__u/substackcdn.com/image/fetch/$s_!tYg6!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffd8e83f8-3a88-4aa5-9b56-eaadf878f7d1_4400x2750.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Integration</strong></h2><h3><strong>Integration Components</strong></h3><p>FastAPI delegates workload generation to <code>ObservabilityService</code>, with Pydantic validating input. The service writes each outcome to stdout and <code>MetricsStore</code>. The dashboard polls <code>/metrics</code>; <code>/demo</code> produces healthy, slow, and failed samples. Docker packages one reproducible worker.</p><h3><strong>Module Objectives Alignment</strong></h3><p>The implementation measures behavior, latency distribution, and error rate. Tests verify JSON fields, percentile ordering, APIs, dashboard availability, and demo metrics.</p><h2><strong>Core Concepts</strong></h2><p>Structured logging produces one JSON document per event, allowing direct field indexing. Route, status, latency, and request ID support correlation. Payloads are excluded because they may contain private data.</p><p>Latency averages hide long-tail behavior. Nearest-rank calculation sorts observations and selects the requested percentage rank. Production systems use bounded histogram buckets to control memory.</p><p>RED means Rate, Errors, and Duration: demand, reliability, and user-visible performance. Increased throughput is unhealthy when error rate and p99 also rise.</p><p>The lock keeps counters, histograms, and events coherent. Snapshot copies prevent partial UI reads. Multiple workers require centralized aggregation.</p><h2><strong>Production AI System Design Relevance</strong></h2><p>Observability belongs beside gateway middleware, measuring AI stages consistently. Its signals support SLOs, capacity planning, incidents, and deployments.</p><h2><strong>Workflow</strong></h2><ul><li><p><strong>Request flow:</strong> a caller opens the dashboard or invokes <code>/simulate</code> or <code>/demo</code>; FastAPI validates input and calls the service.</p></li><li><p><strong>Execution flow:</strong> the service selects a route profile, derives latency and status, assigns severity, and creates a request ID.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!RMai!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F881f1aac-5726-44e0-ad8b-b37ad9c93504_4400x3410.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!RMai!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F881f1aac-5726-44e0-ad8b-b37ad9c93504_4400x3410.png 424w, /__u/substackcdn.com/image/fetch/$s_!RMai!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F881f1aac-5726-44e0-ad8b-b37ad9c93504_4400x3410.png 848w, /__u/substackcdn.com/image/fetch/$s_!RMai!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F881f1aac-5726-44e0-ad8b-b37ad9c93504_4400x3410.png 1272w, /__u/substackcdn.com/image/fetch/$s_!RMai!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F881f1aac-5726-44e0-ad8b-b37ad9c93504_4400x3410.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!RMai!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F881f1aac-5726-44e0-ad8b-b37ad9c93504_4400x3410.png" width="508" height="393.56043956043953" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/881f1aac-5726-44e0-ad8b-b37ad9c93504_4400x3410.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1128,&quot;width&quot;:1456,&quot;resizeWidth&quot;:508,&quot;bytes&quot;:733827,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207402534?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F881f1aac-5726-44e0-ad8b-b37ad9c93504_4400x3410.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!RMai!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F881f1aac-5726-44e0-ad8b-b37ad9c93504_4400x3410.png 424w, /__u/substackcdn.com/image/fetch/$s_!RMai!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F881f1aac-5726-44e0-ad8b-b37ad9c93504_4400x3410.png 848w, /__u/substackcdn.com/image/fetch/$s_!RMai!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F881f1aac-5726-44e0-ad8b-b37ad9c93504_4400x3410.png 1272w, /__u/substackcdn.com/image/fetch/$s_!RMai!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F881f1aac-5726-44e0-ad8b-b37ad9c93504_4400x3410.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><ul><li><p><strong>Data flow:</strong> metadata goes to stdout and the metrics store; <code>/metrics</code> returns snapshots rendered by the browser.</p></li><li><p><strong>State changes:</strong> counters increment, latency enters the histogram, percentiles recalculate, and recent events rotate.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!33Pd!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd3412558-5b53-4e60-b927-62b0d35f860b_4400x2640.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!33Pd!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd3412558-5b53-4e60-b927-62b0d35f860b_4400x2640.png 424w, /__u/substackcdn.com/image/fetch/$s_!33Pd!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd3412558-5b53-4e60-b927-62b0d35f860b_4400x2640.png 848w, /__u/substackcdn.com/image/fetch/$s_!33Pd!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd3412558-5b53-4e60-b927-62b0d35f860b_4400x2640.png 1272w, /__u/substackcdn.com/image/fetch/$s_!33Pd!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd3412558-5b53-4e60-b927-62b0d35f860b_4400x2640.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!33Pd!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd3412558-5b53-4e60-b927-62b0d35f860b_4400x2640.png" width="506" height="303.739010989011" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/d3412558-5b53-4e60-b927-62b0d35f860b_4400x2640.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:874,&quot;width&quot;:1456,&quot;resizeWidth&quot;:506,&quot;bytes&quot;:649411,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207402534?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd3412558-5b53-4e60-b927-62b0d35f860b_4400x2640.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!33Pd!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd3412558-5b53-4e60-b927-62b0d35f860b_4400x2640.png 424w, /__u/substackcdn.com/image/fetch/$s_!33Pd!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd3412558-5b53-4e60-b927-62b0d35f860b_4400x2640.png 848w, /__u/substackcdn.com/image/fetch/$s_!33Pd!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd3412558-5b53-4e60-b927-62b0d35f860b_4400x2640.png 1272w, /__u/substackcdn.com/image/fetch/$s_!33Pd!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd3412558-5b53-4e60-b927-62b0d35f860b_4400x2640.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Production Integration</strong></h2><ul><li><p><strong>Architecture fit:</strong> move timing and classification into gateway middleware.</p></li><li><p><strong>Enterprise deployment:</strong> export through OpenTelemetry or Prometheus and ship stdout logs centrally.</p></li><li><p><strong>Scalability:</strong> aggregate bounded histograms across replicas; never average computed percentiles.</p></li><li><p><strong>Observability:</strong> alert on SLO burn rate, sustained errors, and tail latency.</p></li><li><p><strong>Security:</strong> never log prompts, completions, authorization headers, or tenant secrets.</p></li></ul><h3><strong>Step-by-Step Implementation</strong></h3><h2><strong>GitHub Link</strong></h2><p><strong><a href="https://github.com/sysdr/production-ai-engineering/tree/main/lesson6/aiam-day06https://github.com/sysdr/production-ai-engineering/tree/main/lesson6/aiam-day06">https://github.com/sysdr/production-ai-engineering/tree/main/lesson6/aiam-day06</a></strong></p><p><code>JSONFormatter</code> converts records into stable fields. Logger setup removes prior handlers to prevent duplicates. <code>Histogram</code> owns percentile math; <code>MetricsStore</code> owns synchronization and history. <code>ObservabilityService</code> sends identical classifications to logs and metrics.</p><p>FastAPI exposes health, telemetry, simulation, demo, and dashboard routes. The browser consumes snapshots. Demo traffic includes known slow and failed samples, then healthy events. Pydantic rejects malformed input; tests cover histograms, formatting, APIs, and mutation.</p><h2><strong>Coding Highlights</strong></h2><p>Nearest-rank percentiles are deterministic:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;d63aa812-5dfb-4018-9002-7e57be8371ad&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">rank = max(1, math.ceil((p / 100) * len(values)))
return sorted(values)[rank - 1]</code></pre></div><p>Severity reflects both failure and slowness:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;3909173d-e60d-4960-8362-42e16ac174a5&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">level = "ERROR" if status &gt;= 400 else "WARNING" if latency &gt;= 500 else "INFO"</code></pre></div><p>This separates slow success from outright failure, preserving operational meaning.</p><h3>Working Demo Link:</h3><div id="youtube2-anV2Wr7iRSA" class="youtube-wrap" data-attrs="{&quot;videoId&quot;:&quot;anV2Wr7iRSA&quot;,&quot;startTime&quot;:null,&quot;endTime&quot;:null}" data-component-name="Youtube2ToDOM"><div class="youtube-inner"><iframe src="https://www.youtube-nocookie.com/embed/anV2Wr7iRSA?rel=0&amp;autoplay=0&amp;showinfo=0&amp;enablejsapi=0" frameborder="0" loading="lazy" gesture="media" allow="autoplay; fullscreen" allowautoplay="true" allowfullscreen="true" width="728" height="409"></iframe></div></div><h2><strong>Production Considerations</strong></h2><ul><li><p><strong>Scalability:</strong> bound histogram memory and label cardinality.</p></li><li><p><strong>Security:</strong> redact sensitive fields and protect dashboard access.</p></li><li><p><strong>Monitoring/logging:</strong> retain correlation IDs and alert on sustained SLO violations.</p></li><li><p><strong>Testing:</strong> verify boundaries, formatter output, APIs, and demo metrics.</p></li><li><p><strong>Failure handling:</strong> telemetry failure must not break user requests.</p></li><li><p><strong>Edge cases:</strong> handle empty samples, concurrency, malformed labels, and downstream timeouts.</p></li></ul><h2><strong>Validation</strong></h2><ul><li><p><strong>Verification:</strong> inspect JSON, call health and metrics endpoints, and compare pre/post-demo snapshots.</p></li><li><p><strong>Testing strategy:</strong> unit tests cover math and formatting; API tests cover contracts and state.</p></li><li><p><strong>Success criteria:</strong> all tests pass and dashboard values refresh after execution.</p></li><li><p><strong>Expected outputs:</strong> ordered percentiles, non-zero RED metrics, and per-route totals.</p></li><li><p><strong>Benchmarks:</strong> metric recording should remain sub-millisecond locally.</p></li><li><p><strong>Production checklist:</strong> health green, labels bounded, secrets absent, retention defined, SLO load test passed.</p></li></ul><h2><strong>Key Insights</strong></h2><p>Averages conceal tail pain; percentiles expose it. Structured fields improve investigations but increase cardinality. Common mistakes include logging payloads, unbounded labels, averaging percentiles, and letting telemetry failures affect users.</p><h3><strong>Important Classes</strong></h3><ul><li><p><code>JSONFormatter</code> renders machine-readable events.</p></li><li><p><code>Histogram</code> calculates latency percentiles.</p></li><li><p><code>MetricsStore</code> synchronizes RED metrics.</p></li><li><p><code>ObservabilityService</code> coordinates execution and telemetry.</p></li></ul><h3><strong>Key Methods</strong></h3><ul><li><p><code>percentile()</code> computes p50, p95, and p99.</p></li><li><p><code>record_request()</code> updates counters, latency, and events.</p></li><li><p><code>run_demo()</code> generates deterministic observable traffic.</p></li></ul><h2><strong>Real-World Examples</strong></h2><ul><li><p>A model gateway compares provider p95 latency and error rate, shifting traffic away from degradation before exhausting its SLO.</p></li><li><p>A retrieval pipeline correlates request IDs across search, reranking, and generation to isolate latency regressions.</p></li></ul><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Lesson 5 — Security Hardening]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-5-security-hardening</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-5-security-hardening</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Sat, 08 Aug 2026 02:00:22 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!XRVT!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>This lesson adds an output-side security layer to the AI service. It scans generated text for leaked secrets and PII before responses leave the system, and signs payloads with HMAC so integrity can be verified downstream. Findings are redacted, counted, and exposed through a live dashboard. The result is a self-contained service that enforces rather than observes.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Regex-based detection of secrets (API keys, tokens) and PII (email, phone, card).</p></li><li><p>Deterministic redaction with per-category counters.</p></li><li><p>HMAC-SHA256 signing and constant-time verification.</p></li><li><p>FastAPI dashboard with non-zero, demo-driven metrics.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p>A security domain package (<code>hardening</code>, <code>metrics</code>, <code>service</code>).</p></li><li><p>An <code>OutputGuard</code> that scans and redacts text.</p></li><li><p>A <code>SignatureVerifier</code> for HMAC signing and tamper detection.</p></li><li><p>API surface (<code>/scan</code>, <code>/sign</code>, <code>/verify</code>, <code>/metrics</code>, <code>/demo</code>, <code>/dashboard</code>, <code>/health</code>).</p></li><li><p>Unit and API tests plus Docker lifecycle scripts.</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><p>The previous lesson enforced throughput and cost limits before model execution. This lesson extends enforcement to the output boundary, guarding what the system emits rather than what it accepts.</p><h2><strong>Enables Next Lesson</strong></h2><p>Clean, signed, redacted output is a precondition for trustworthy telemetry, enabling the observability stack in the next lesson to reason over safe data.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Architecture Context</strong></h2><ul><li><p><strong>Where it sits:</strong> at the response egress, between model output and the caller.</p></li><li><p><strong>Why it exists:</strong> models can echo secrets or personal data present in prompts, context, or tool results.</p></li><li><p><strong>Problem solved:</strong> prevents data exfiltration and provides integrity guarantees on payloads crossing trust boundaries.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!XRVT!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!XRVT!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png 424w, /__u/substackcdn.com/image/fetch/$s_!XRVT!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png 848w, /__u/substackcdn.com/image/fetch/$s_!XRVT!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png 1272w, /__u/substackcdn.com/image/fetch/$s_!XRVT!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!XRVT!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png" width="500" height="324.8626373626374" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:946,&quot;width&quot;:1456,&quot;resizeWidth&quot;:500,&quot;bytes&quot;:763659,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207390044?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!XRVT!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png 424w, /__u/substackcdn.com/image/fetch/$s_!XRVT!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png 848w, /__u/substackcdn.com/image/fetch/$s_!XRVT!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png 1272w, /__u/substackcdn.com/image/fetch/$s_!XRVT!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F31a87e17-9bc0-4dd3-a96b-9f5676d82cc4_4400x2860.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Integration</strong></h2><h3><strong>Integration Components</strong></h3><blockquote><p>FastAPI validates payloads with Pydantic and delegates to <code>SecurityService</code>. The service runs the guard and signer, records outcomes in a shared in-memory metrics store, and returns a decision. The dashboard polls <code>/metrics</code> and triggers <code>/demo</code>.</p></blockquote><h3><strong>Module Objectives Alignment</strong></h3><p>The module targets three production objectives: prevent sensitive-data leakage, guarantee payload integrity, and make both measurable for operators.</p><h2><strong>Core Concepts</strong></h2><p>Output scanning is pattern-driven because secrets and PII share stable syntactic shapes. Compiling patterns once and applying them per request keeps latency low while covering multiple categories in a single pass. Detection and redaction are separated conceptually but computed together: detection drives metrics and block decisions, redaction produces a safe-to-emit string.</p><p>HMAC signing solves a different problem &#8212; integrity, not confidentiality. A shared secret produces a signature that a holder can verify but an attacker cannot forge without the key. Verification uses constant-time comparison to avoid timing side channels.</p><p>A deliberate design choice treats an expected rejection (a tampered payload correctly failing verification) as a <em>success</em> signal, while an unexpected accept is the true failure. This aligns metrics with security intent rather than raw booleans. State is kept in-process to keep scope small while preserving interfaces that can move to shared stores later.</p><h2><strong>Production AI System Design Relevance</strong></h2><p>This lesson is the egress guardrail of an AI platform. It belongs next to response serialization and gateway middleware, where every model output can be inspected, redacted, and attested before delivery.</p><h2><strong>Workflow</strong></h2><ul><li><p><strong>Request flow:</strong> caller submits text to scan or a payload to sign/verify.</p></li><li><p><strong>Execution flow:</strong> the service runs guard or signer, then records an event.</p></li><li><p><strong>Data flow:</strong> validated input enters the service, mutates in-memory metrics, and returns a decision; the dashboard reads snapshots via <code>/metrics</code>.</p></li><li><p><strong>State changes:</strong> scan/block counters increment, secret/PII tallies grow, HMAC counters update, and a bounded recent-events list is refreshed.</p></li></ul><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!bbOd!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8340cdb6-7271-479a-8b77-5f29c0f9fa3d_4400x3300.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!bbOd!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8340cdb6-7271-479a-8b77-5f29c0f9fa3d_4400x3300.png 424w, /__u/substackcdn.com/image/fetch/$s_!bbOd!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8340cdb6-7271-479a-8b77-5f29c0f9fa3d_4400x3300.png 848w, /__u/substackcdn.com/image/fetch/$s_!bbOd!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8340cdb6-7271-479a-8b77-5f29c0f9fa3d_4400x3300.png 1272w, /__u/substackcdn.com/image/fetch/$s_!bbOd!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8340cdb6-7271-479a-8b77-5f29c0f9fa3d_4400x3300.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!bbOd!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8340cdb6-7271-479a-8b77-5f29c0f9fa3d_4400x3300.png" width="494" height="370.5" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/8340cdb6-7271-479a-8b77-5f29c0f9fa3d_4400x3300.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1092,&quot;width&quot;:1456,&quot;resizeWidth&quot;:494,&quot;bytes&quot;:896258,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207390044?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8340cdb6-7271-479a-8b77-5f29c0f9fa3d_4400x3300.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!bbOd!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8340cdb6-7271-479a-8b77-5f29c0f9fa3d_4400x3300.png 424w, /__u/substackcdn.com/image/fetch/$s_!bbOd!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8340cdb6-7271-479a-8b77-5f29c0f9fa3d_4400x3300.png 848w, /__u/substackcdn.com/image/fetch/$s_!bbOd!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8340cdb6-7271-479a-8b77-5f29c0f9fa3d_4400x3300.png 1272w, /__u/substackcdn.com/image/fetch/$s_!bbOd!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8340cdb6-7271-479a-8b77-5f29c0f9fa3d_4400x3300.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Production Integration</strong></h2><ul><li><p><strong>Architecture fit:</strong> embed as egress middleware in API workers.</p></li><li><p><strong>Enterprise patterns:</strong> centralize pattern sets and signing keys per tenant or environment.</p></li><li><p><strong>Scalability:</strong> stateless scanning scales horizontally; shared counters move to Redis when multi-worker.</p></li><li><p><strong>Observability:</strong> counters, rates, and an event timeline feed dashboards and alerts.</p></li><li><p><strong>Security:</strong> secrets come from environment variables; comparisons are constant-time.</p></li></ul><h3><strong>Step-by-Step Implementation</strong></h3><h2><strong>GitHub Link</strong></h2><p><strong><a href="https://github.com/sysdr/production-ai-engineering/tree/main/lesson5/aiam-day05">https://github.com/sysdr/production-ai-engineering/tree/main/lesson5/aiam-day05</a></strong></p><p>The guard compiles patterns at construction. Each scan collects findings, computes category counts, and builds a redacted copy. The service wraps guard and signer, timing each call and writing an event to the metrics store. The API layer validates inputs, exposes endpoints, and serves the dashboard. Errors surface as validation failures at the edge. The demo exercises clean text, every detector, and both HMAC paths so no metric stays zero.</p><h2><strong>Coding Highlights</strong></h2><p>Constant-time verification prevents timing attacks:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;88544a74-e997-4613-86e8-bda26ad011a6&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">def verify(self, payload: str, signature: str) -&gt; bool:
    return hmac.compare_digest(self.sign(payload), signature)</code></pre></div><p>Intent-aware status keeps metrics meaningful &#8212; a caught tamper is a win, not a failure:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;af9f1ce1-1089-4fca-ab9d-9da2c61a8864&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">status = "tamper_caught" if expect_reject else "hmac_fail"</code></pre></div><p>This matters because naive boolean logging flags correct security behavior as an error.</p><h3>Working Demo Link:</h3><div id="youtube2-EPnhsoDd6tU" class="youtube-wrap" data-attrs="{&quot;videoId&quot;:&quot;EPnhsoDd6tU&quot;,&quot;startTime&quot;:null,&quot;endTime&quot;:null}" data-component-name="Youtube2ToDOM"><div class="youtube-inner"><iframe src="https://www.youtube-nocookie.com/embed/EPnhsoDd6tU?rel=0&amp;autoplay=0&amp;showinfo=0&amp;enablejsapi=0" frameborder="0" loading="lazy" gesture="media" allow="autoplay; fullscreen" allowautoplay="true" allowfullscreen="true" width="728" height="409"></iframe></div></div><h2><strong>Production Considerations</strong></h2><ul><li><p><strong>Scalability:</strong> externalize counters for multi-worker deployments.</p></li><li><p><strong>Security:</strong> never log raw findings; store only categories.</p></li><li><p><strong>Monitoring/logging:</strong> track block rate and HMAC failure rate.</p></li><li><p><strong>Testing:</strong> cover each detector and both verification paths.</p></li><li><p><strong>Failure handling:</strong> fail closed on scan errors.</p></li><li><p><strong>Edge cases:</strong> overlapping patterns and unicode payloads.</p></li></ul><h2><strong>Validation</strong></h2><ul><li><p><strong>Verification:</strong> unit tests assert detection, redaction, and HMAC correctness.</p></li><li><p><strong>Testing strategy:</strong> API tests confirm endpoints and non-zero demo metrics.</p></li><li><p><strong>Success criteria:</strong> all tests pass; dashboard values update on demo.</p></li><li><p><strong>Expected outputs:</strong> blocked secrets/PII, valid/tampered HMAC results.</p></li><li><p><strong>Benchmarks:</strong> sub-millisecond scans on short text.</p></li><li><p><strong>Checklist:</strong> secrets from env, redaction on, tests green, health OK.</p></li></ul><h2><strong>Key Insights</strong></h2><p>Redaction and detection must ship together; detection without safe output is incomplete. A common mistake is scanning too late or logging the secrets being caught. The tradeoff is coverage versus false positives.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!lhwM!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F398e46b7-53b3-4f92-b72e-8155df52a37b_4400x2750.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!lhwM!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F398e46b7-53b3-4f92-b72e-8155df52a37b_4400x2750.png 424w, /__u/substackcdn.com/image/fetch/$s_!lhwM!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F398e46b7-53b3-4f92-b72e-8155df52a37b_4400x2750.png 848w, /__u/substackcdn.com/image/fetch/$s_!lhwM!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F398e46b7-53b3-4f92-b72e-8155df52a37b_4400x2750.png 1272w, /__u/substackcdn.com/image/fetch/$s_!lhwM!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F398e46b7-53b3-4f92-b72e-8155df52a37b_4400x2750.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!lhwM!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F398e46b7-53b3-4f92-b72e-8155df52a37b_4400x2750.png" width="510" height="318.75" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/398e46b7-53b3-4f92-b72e-8155df52a37b_4400x2750.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:910,&quot;width&quot;:1456,&quot;resizeWidth&quot;:510,&quot;bytes&quot;:663147,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207390044?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F398e46b7-53b3-4f92-b72e-8155df52a37b_4400x2750.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!lhwM!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F398e46b7-53b3-4f92-b72e-8155df52a37b_4400x2750.png 424w, /__u/substackcdn.com/image/fetch/$s_!lhwM!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F398e46b7-53b3-4f92-b72e-8155df52a37b_4400x2750.png 848w, /__u/substackcdn.com/image/fetch/$s_!lhwM!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F398e46b7-53b3-4f92-b72e-8155df52a37b_4400x2750.png 1272w, /__u/substackcdn.com/image/fetch/$s_!lhwM!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F398e46b7-53b3-4f92-b72e-8155df52a37b_4400x2750.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h3><strong>Important Classes</strong></h3><ul><li><p><code>OutputGuard</code> &#8212; scanning and redaction.</p></li><li><p><code>SignatureVerifier</code> &#8212; HMAC signing and verification.</p></li><li><p><code>SecurityService</code> &#8212; orchestration and metrics.</p></li></ul><h3><strong>Key Methods</strong></h3><ul><li><p><code>scan()</code> &#8212; findings, counts, redacted text.</p></li><li><p><code>sign()</code> / <code>verify()</code> &#8212; integrity operations.</p></li><li><p><code>run_demo()</code> &#8212; deterministic metric population.</p></li></ul><h2><strong>Real-World Examples</strong></h2><ul><li><p><strong>Chatbot egress filter:</strong> a support assistant redacts customer emails and card numbers from replies before display.</p></li><li><p><strong>Webhook integrity:</strong> a deploy service signs payloads with HMAC so receivers reject forged requests.</p></li></ul><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Lesson 4 — Rate Limiting and Cost Control]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-4-rate-limiting-and-cost-control</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-4-rate-limiting-and-cost-control</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Fri, 07 Aug 2026 02:00:38 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!GsDt!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>This lesson adds production controls for AI request throughput and token spend.<br>You implement tier-aware throttling before expensive model execution happens.<br>You also track per-user cost in real time so usage aligns with budget policies.<br>A live dashboard exposes request, throttle, latency, and budget metrics.<br>The child project remains self-contained and runnable with local scripts.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Token-bucket throttling with <code>standard</code>, <code>premium</code>, and <code>admin</code> tiers</p></li><li><p>Per-request input/output token accounting converted to USD spend</p></li><li><p>Budget-alert counters and event timeline for operational visibility</p></li><li><p>FastAPI endpoints for health, checks, metrics, dashboard, and demo</p></li><li><p>Dockerized runtime with script-driven lifecycle management</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p>Rate-control domain package (<code>bucket</code>, <code>cost_tracker</code>, <code>metrics</code>, <code>service</code>)</p></li><li><p>API and dashboard surface (<code>/check</code>, <code>/metrics</code>, <code>/demo</code>, <code>/dashboard</code>, <code>/health</code>)</p></li><li><p>Deterministic demo scenario for non-zero metric updates</p></li><li><p>Unit and API tests covering behavior and contracts</p></li><li><p>Operational scripts for start, stop, test, and cleanup</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><blockquote><p>The previous lesson centered on memory behavior and metric observability.<br>This lesson shifts from observation to enforcement by adding policy controls.<br>Now the system does not just report usage; it actively regulates it.</p></blockquote><h2><strong>Enables Next Lesson</strong></h2><p>These controls reduce blast radius and cost drift, enabling stronger policy and security hardening in the next lesson.</p><h2><strong>Architecture Context</strong></h2><ul><li><p>Where this component sits</p></li><li><p>Why it exists</p></li><li><p>Problem solved</p></li></ul><p>This component sits between request intake and model execution, enforcing throughput and spend constraints before model work begins.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!GsDt!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!GsDt!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png 424w, /__u/substackcdn.com/image/fetch/$s_!GsDt!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png 848w, /__u/substackcdn.com/image/fetch/$s_!GsDt!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png 1272w, /__u/substackcdn.com/image/fetch/$s_!GsDt!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!GsDt!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png" width="508" height="349.25" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1001,&quot;width&quot;:1456,&quot;resizeWidth&quot;:508,&quot;bytes&quot;:578932,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207259655?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!GsDt!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png 424w, /__u/substackcdn.com/image/fetch/$s_!GsDt!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png 848w, /__u/substackcdn.com/image/fetch/$s_!GsDt!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png 1272w, /__u/substackcdn.com/image/fetch/$s_!GsDt!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F8baa0130-182e-4b1f-87a6-78d2fcfffabc_4400x3025.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Integration</strong></h2><h3><strong>Integration Components</strong></h3><p>FastAPI validates request payloads and forwards policy work to the service layer. The service coordinates bucket checks, spend recording, and metric updates. The dashboard polls <code>/metrics</code> and triggers <code>/demo</code> for validation.</p><h3><strong>Module Objectives Alignment</strong></h3><p>The module aligns with production goals: stable throughput, controlled cost growth, and measurable system behavior.</p><h2><strong>Core Concepts</strong></h2><p>Token bucket is chosen because it allows controlled bursts while limiting sustained traffic. That fits real AI workloads better than fixed-window throttling, which can create boundary spikes.</p><p>Tier configuration maps product plans to infrastructure policy. Higher tiers get larger capacity and refill rates without requiring separate code paths.</p><p>Cost tracking is done per request to avoid delayed budget surprises. Real-time accounting enables early alerts and tighter operational response.</p><p>Metrics are modeled as counters, gauges, and event entries. This supports both dashboard rendering and automated smoke verification.</p><p>In-memory state keeps scope simple while preserving interfaces that can move to shared stores later.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!WOIW!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcfd361ad-066e-4f87-a4a7-55200943be4b_4400x2750.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!WOIW!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcfd361ad-066e-4f87-a4a7-55200943be4b_4400x2750.png 424w, /__u/substackcdn.com/image/fetch/$s_!WOIW!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcfd361ad-066e-4f87-a4a7-55200943be4b_4400x2750.png 848w, /__u/substackcdn.com/image/fetch/$s_!WOIW!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcfd361ad-066e-4f87-a4a7-55200943be4b_4400x2750.png 1272w, /__u/substackcdn.com/image/fetch/$s_!WOIW!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcfd361ad-066e-4f87-a4a7-55200943be4b_4400x2750.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!WOIW!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcfd361ad-066e-4f87-a4a7-55200943be4b_4400x2750.png" width="494" height="308.75" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/cfd361ad-066e-4f87-a4a7-55200943be4b_4400x2750.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:910,&quot;width&quot;:1456,&quot;resizeWidth&quot;:494,&quot;bytes&quot;:485115,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207259655?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcfd361ad-066e-4f87-a4a7-55200943be4b_4400x2750.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!WOIW!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcfd361ad-066e-4f87-a4a7-55200943be4b_4400x2750.png 424w, /__u/substackcdn.com/image/fetch/$s_!WOIW!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcfd361ad-066e-4f87-a4a7-55200943be4b_4400x2750.png 848w, /__u/substackcdn.com/image/fetch/$s_!WOIW!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcfd361ad-066e-4f87-a4a7-55200943be4b_4400x2750.png 1272w, /__u/substackcdn.com/image/fetch/$s_!WOIW!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcfd361ad-066e-4f87-a4a7-55200943be4b_4400x2750.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Key Insights</strong></h2><p>Throughput control and cost control must ship together. Request count alone cannot represent AI cost risk, and spend-only controls cannot protect latency under burst load.</p><p>A common mistake is applying checks too late in the pipeline. Guardrails should run before model invocation.</p><p>Another mistake is demos that do not force state transitions. If metrics stay flat, defects can hide in integration paths.</p><h2><strong>Production AI System Design Relevance</strong></h2><p>This lesson acts as the governance layer of an AI system. It protects model-serving capacity, reduces tenant contention, and keeps economics visible to platform teams.</p><p>In the broader architecture, it belongs near API ingress, gateway middleware, or request orchestration boundaries.</p><h2><strong>Workflow</strong></h2><p>Explain:</p><ul><li><p>request flow</p></li><li><p>execution flow</p></li><li><p>data flow</p></li><li><p>state changes</p></li></ul><p>Request flow: client submits user, tier, and token metadata.<br>Execution flow: service checks tokens, records spend for allowed requests, updates metrics/events, returns policy decision.<br>Data flow: validated payload enters service, state mutates in-memory, dashboard fetches snapshots via <code>/metrics</code>.<br>State changes: bucket tokens deplete/refill, spend accumulates, remaining budget drops, alert counters increment.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!h-WQ!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07350376-f80d-4695-b5dd-23e3ad6255ed_4675x3300.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!h-WQ!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07350376-f80d-4695-b5dd-23e3ad6255ed_4675x3300.png 424w, /__u/substackcdn.com/image/fetch/$s_!h-WQ!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07350376-f80d-4695-b5dd-23e3ad6255ed_4675x3300.png 848w, /__u/substackcdn.com/image/fetch/$s_!h-WQ!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07350376-f80d-4695-b5dd-23e3ad6255ed_4675x3300.png 1272w, /__u/substackcdn.com/image/fetch/$s_!h-WQ!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07350376-f80d-4695-b5dd-23e3ad6255ed_4675x3300.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!h-WQ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07350376-f80d-4695-b5dd-23e3ad6255ed_4675x3300.png" width="510" height="360.0824175824176" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/07350376-f80d-4695-b5dd-23e3ad6255ed_4675x3300.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1028,&quot;width&quot;:1456,&quot;resizeWidth&quot;:510,&quot;bytes&quot;:588400,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207259655?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07350376-f80d-4695-b5dd-23e3ad6255ed_4675x3300.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!h-WQ!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07350376-f80d-4695-b5dd-23e3ad6255ed_4675x3300.png 424w, /__u/substackcdn.com/image/fetch/$s_!h-WQ!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07350376-f80d-4695-b5dd-23e3ad6255ed_4675x3300.png 848w, /__u/substackcdn.com/image/fetch/$s_!h-WQ!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07350376-f80d-4695-b5dd-23e3ad6255ed_4675x3300.png 1272w, /__u/substackcdn.com/image/fetch/$s_!h-WQ!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07350376-f80d-4695-b5dd-23e3ad6255ed_4675x3300.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Production Integration</strong></h2><p>Explain:</p><ul><li><p>production architecture fit</p></li><li><p>enterprise deployment patterns</p></li><li><p>scalability</p></li><li><p>observability</p></li><li><p>security considerations</p></li></ul><p>Architecture fit: reusable middleware or embedded policy module in API workers.<br>Enterprise pattern: central tier/budget policy config per tenant or environment.<br>Scalability: externalize counters and budgets to Redis or durable stores for multi-replica consistency.<br>Observability: export metrics/events to Prometheus or OpenTelemetry and alert on burn-rate and throttle spikes.<br>Security: strict schema validation, bounded token values, and controlled admin policy updates.</p><h3><strong>Important Classes</strong></h3><ul><li><p><code>TokenBucket</code></p></li><li><p><code>RateLimiter</code></p></li><li><p><code>CostTracker</code></p></li><li><p><code>MetricsStore</code></p></li><li><p><code>RateLimitService</code></p></li></ul><h3><strong>Key Methods</strong></h3><ul><li><p><code>TokenBucket.consume()</code></p></li><li><p><code>RateLimiter.check()</code></p></li><li><p><code>CostTracker.record()</code></p></li><li><p><code>MetricsStore.record()</code></p></li><li><p><code>RateLimitService.check_request()</code></p></li><li><p><code>RateLimitService.run_demo()</code></p></li></ul><h3><strong>Step-by-Step Implementation</strong></h3><h2><strong>GitHub Link:</strong></h2><p><strong><a href="https://github.com/sysdr/production-ai-engineering/tree/main/lesson4/aiam-day04">https://github.com/sysdr/production-ai-engineering/tree/main/lesson4/aiam-day04</a></strong></p><p>First, implement throttling primitives with deterministic behavior (<code>TokenBucket</code>, <code>RateLimiter</code>). This isolates rate math and makes tests precise.</p><p>Next, add <code>CostTracker</code> to convert token usage into spend at request time. This creates immediate economics visibility.</p><p>Then, centralize observability with <code>MetricsStore</code>. One write path prevents metric drift and simplifies debugging.</p><p>After that, compose all controls in <code>RateLimitService</code>, which executes the canonical transaction: throttle, account, emit metrics, return decision.</p><p>Expose FastAPI endpoints with explicit schema constraints for tier and token bounds. Validation prevents malformed policy inputs from corrupting state.</p><p>Add deterministic demo operations that guarantee non-zero metric movement. This is critical for dashboard checks and CI smoke tests.</p><p>Finally, wire scripts and Docker so runtime is fully independent and operational without external scaffolding.</p><h2><strong>Coding Highlights</strong></h2><p>Service-layer orchestration keeps endpoint handlers thin and testable. Policy maps avoid hard-coded branches, and event emission adds incident context beyond raw counters.</p><h3>Working Demo Link:</h3><div id="youtube2-FLiCq4LJeuU" class="youtube-wrap" data-attrs="{&quot;videoId&quot;:&quot;FLiCq4LJeuU&quot;,&quot;startTime&quot;:null,&quot;endTime&quot;:null}" data-component-name="Youtube2ToDOM"><div class="youtube-inner"><iframe src="https://www.youtube-nocookie.com/embed/FLiCq4LJeuU?rel=0&amp;autoplay=0&amp;showinfo=0&amp;enablejsapi=0" frameborder="0" loading="lazy" gesture="media" allow="autoplay; fullscreen" allowautoplay="true" allowfullscreen="true" width="728" height="409"></iframe></div></div><h2><strong>Production Considerations</strong></h2><ul><li><p>Scalability: move shared state to distributed storage</p></li><li><p>Security: lock down policy mutation and validate all inputs</p></li><li><p>Monitoring: alert on throttle ratio, burn rate, and latency drift</p></li><li><p>Logging: structured decision logs for audit and triage</p></li><li><p>Testing: unit + API + script-level smoke coverage</p></li><li><p>Failure handling: safe degradation when telemetry dependencies fail</p></li><li><p>Edge cases: refill timing drift, burst storms, mis-tiered traffic</p></li></ul><h2><strong>Validation</strong></h2><p>Verification uses burst-limit tests, refill timing assertions, and cost-math checks. Success means healthy endpoints, deterministic throttling, accurate spend, and non-zero metrics after demo. Expected outputs are rising counters, populated events, latency values, and budget alerts under stress. Production checklist: self-contained child scripts and reproducible startup/cleanup.</p><h2><strong>Real-World Examples</strong></h2><ol><li><p>Enterprise support copilot: premium tenants get higher refill rates, while budget alerts prevent monthly overrun.</p></li><li><p>Internal developer assistant: build bots are rate-limited and token-accounted to protect shared model capacity.</p></li></ol><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Lesson 3 — Memory Systems]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-3-memory-systems</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-3-memory-systems</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Thu, 06 Aug 2026 02:00:25 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!LaPW!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><blockquote><p>This lesson adds production conversational memory: sliding-window short-term storage, a TTL semantic cache, and optional Redis. Agents that forget waste tokens; agents that remember forever raise cost and serve stale answers. You implement bounded session history, cache hit/miss paths, TTL eviction, and a FastAPI dashboard for retained, reused, and discarded state.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Sliding-window short-term memory with turn and token budgets.</p></li><li><p>Exact-match semantic cache with LRU and TTL eviction.</p></li><li><p>Redis persistence with in-memory fallback.</p></li><li><p>Live dashboard for hits, misses, evictions, Redis ops, and latency.</p></li><li><p>Docker Compose using official Python and Redis images.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p><code>ShortTermMemory</code> and <code>SemanticCache</code> core stores.</p></li><li><p><code>RedisStore</code> and <code>MemoryService</code> coordinating persistence and metrics.</p></li><li><p>FastAPI: <code>/health</code>, <code>/metrics</code>, <code>/memory/*</code>, <code>/cache/*</code>, <code>/demo</code>, <code>/dashboard</code>.</p></li><li><p>CLI demo and pytest coverage for memory and API behavior.</p></li><li><p>Scripts: start, demo, test, stop, cleanup.</p></li></ul><h2><strong>Connection to Previous Lesson</strong></h2><p>Lesson 2 delivered a permission-gated tool boundary. Lesson 3 sits above it: memory decides what context survives and which answers can be reused without another model call.</p><h2><strong>Enables Next Lesson</strong></h2><p>Bounded memory enables rate limiting and cost control. Hit rates and token estimates feed Day 4 spend throttling.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><h2><strong>Architecture Context</strong></h2><ul><li><p>Where this component sits &#8212; Between the agent turn loop and durable storage; after tool/model results, before next prompt assembly.</p></li><li><p>Why it exists &#8212; Context and reuse must be explicit policies, not unbounded lists.</p></li><li><p>Problem solved &#8212; Prevents context overflow, duplicate LLM calls, and lost session state across restarts when Redis is available.</p></li></ul><h3><strong>Component Architecture</strong></h3><p><code>ShortTermMemory</code> and <code>SemanticCache</code> own local state; <code>RedisStore</code> wraps persistence; <code>MemoryService</code> orchestrates both and feeds <code>METRICS</code>; <code>app.py</code> exposes HTTP and the UI.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!Ra4Q!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7727b3df-5da0-412f-9100-29d83860d765_5500x3850.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!Ra4Q!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7727b3df-5da0-412f-9100-29d83860d765_5500x3850.png 424w, /__u/substackcdn.com/image/fetch/$s_!Ra4Q!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7727b3df-5da0-412f-9100-29d83860d765_5500x3850.png 848w, /__u/substackcdn.com/image/fetch/$s_!Ra4Q!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7727b3df-5da0-412f-9100-29d83860d765_5500x3850.png 1272w, /__u/substackcdn.com/image/fetch/$s_!Ra4Q!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7727b3df-5da0-412f-9100-29d83860d765_5500x3850.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!Ra4Q!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7727b3df-5da0-412f-9100-29d83860d765_5500x3850.png" width="494" height="345.73214285714283" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/7727b3df-5da0-412f-9100-29d83860d765_5500x3850.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1019,&quot;width&quot;:1456,&quot;resizeWidth&quot;:494,&quot;bytes&quot;:1057572,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207250599?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7727b3df-5da0-412f-9100-29d83860d765_5500x3850.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!Ra4Q!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7727b3df-5da0-412f-9100-29d83860d765_5500x3850.png 424w, /__u/substackcdn.com/image/fetch/$s_!Ra4Q!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7727b3df-5da0-412f-9100-29d83860d765_5500x3850.png 848w, /__u/substackcdn.com/image/fetch/$s_!Ra4Q!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7727b3df-5da0-412f-9100-29d83860d765_5500x3850.png 1272w, /__u/substackcdn.com/image/fetch/$s_!Ra4Q!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7727b3df-5da0-412f-9100-29d83860d765_5500x3850.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Integration</strong></h2><h3><strong>Integration Components</strong></h3><ul><li><p><code>memory/short_term.py</code>, <code>semantic_cache.py</code>, <code>redis_store.py</code>, <code>service.py</code>, <code>metrics.py</code></p></li><li><p><code>app.py</code> API/dashboard; <code>main.py</code> CLI; Compose and lifecycle scripts</p></li></ul><h3><strong>Module Objectives Alignment</strong></h3><ul><li><p>Context discipline, cache economics, persistence, observability, deployability.</p></li></ul><h2><strong>Core Concepts</strong></h2><blockquote><p>Short-term memory keeps a per-session deque capped by turns and estimated tokens, dropping oldest pairs when budgets break&#8212;the tradeoff between recall and prompt cost. Semantic cache keys normalized queries; hits avoid recomputation, but TTL keeps answers from outliving truth. Redis is the shared durable layer for multi-instance deployments; when unreachable, the service degrades to in-memory so demos and tests still run. Metrics treat store, lookup, eviction, and Redis ops as first-class events because memory bugs rarely crash&#8212;they quietly raise cost or serve stale data.</p></blockquote><h2><strong>Key Insights</strong></h2><ul><li><p>Memory is a cost and correctness control, not a convenience buffer.</p></li><li><p>Unbounded history becomes a production incident.</p></li><li><p>Cache without TTL creates silent staleness; TTL without metrics hides thrash.</p></li><li><p>In-process metrics suit single-worker lessons; replicas need shared stores.</p></li><li><p>Fail open on Redis for availability; surface connection state on <code>/health</code>.</p></li></ul><h2><strong>Production AI System Design Relevance</strong></h2><blockquote><p>Production agents need a memory plane that bounds context, caches expensive answers, and survives restarts. This lesson is that plane for later rate limiters and multi-agent workflows.</p></blockquote><h2><strong>Workflow</strong></h2><ul><li><p>request flow &#8212; API/CLI calls <code>MemoryService</code> for store, history, cache lookup/set, or demo.</p></li><li><p>execution flow &#8212; Update local structures, optionally mirror to Redis, record latency and outcomes.</p></li><li><p>data flow &#8212; Turns and cache values move through service methods; dashboard polls <code>/metrics</code>.</p></li><li><p>state changes &#8212; Deques grow/trim; cache entries expire; Redis keys set with TTL; counters update.</p></li></ul><h3><strong>Control Flow</strong></h3><p>Request &#8594; service method &#8594; local update &#8594; optional Redis &#8594; metrics &#8594; response.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!LaPW!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!LaPW!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png 424w, /__u/substackcdn.com/image/fetch/$s_!LaPW!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png 848w, /__u/substackcdn.com/image/fetch/$s_!LaPW!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png 1272w, /__u/substackcdn.com/image/fetch/$s_!LaPW!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!LaPW!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png" width="484" height="251.6401098901099" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:757,&quot;width&quot;:1456,&quot;resizeWidth&quot;:484,&quot;bytes&quot;:663751,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207250599?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!LaPW!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png 424w, /__u/substackcdn.com/image/fetch/$s_!LaPW!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png 848w, /__u/substackcdn.com/image/fetch/$s_!LaPW!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png 1272w, /__u/substackcdn.com/image/fetch/$s_!LaPW!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F32621e14-1ea3-49d9-88b8-18c672f4e7f5_5500x2860.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Production Integration</strong></h2><ul><li><p>production architecture fit &#8212; Shared library beside the agent runtime; Redis as multi-pod fabric.</p></li><li><p>enterprise deployment patterns &#8212; Compose/K8s, official images, env <code>REDIS_URL</code>, health probes.</p></li><li><p>scalability &#8212; App replicas require Redis for shared sessions/cache.</p></li><li><p>observability &#8212; Hit rate, evictions, Redis ops, latency, event timelines.</p></li><li><p>security considerations &#8212; No secrets in repo; private Redis; sanitize session IDs and payloads.</p></li></ul><h3><strong>Data Flow</strong></h3><p>Store/lookup APIs accept turns and cache values; metrics snapshots drive the dashboard; demo exercises window trim, hit/miss, and TTL eviction.</p><div class="captioned-image-container"><figure><a class="image-link image2" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!t2bd!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F64c6b69b-26bc-41c0-be77-51025685f057_5500x2475.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!t2bd!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F64c6b69b-26bc-41c0-be77-51025685f057_5500x2475.png 424w, /__u/substackcdn.com/image/fetch/$s_!t2bd!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F64c6b69b-26bc-41c0-be77-51025685f057_5500x2475.png 848w, /__u/substackcdn.com/image/fetch/$s_!t2bd!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F64c6b69b-26bc-41c0-be77-51025685f057_5500x2475.png 1272w, /__u/substackcdn.com/image/fetch/$s_!t2bd!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F64c6b69b-26bc-41c0-be77-51025685f057_5500x2475.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!t2bd!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F64c6b69b-26bc-41c0-be77-51025685f057_5500x2475.png" width="528" height="237.52747252747253" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/64c6b69b-26bc-41c0-be77-51025685f057_5500x2475.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:655,&quot;width&quot;:1456,&quot;resizeWidth&quot;:528,&quot;bytes&quot;:605770,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207250599?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F64c6b69b-26bc-41c0-be77-51025685f057_5500x2475.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!t2bd!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F64c6b69b-26bc-41c0-be77-51025685f057_5500x2475.png 424w, /__u/substackcdn.com/image/fetch/$s_!t2bd!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F64c6b69b-26bc-41c0-be77-51025685f057_5500x2475.png 848w, /__u/substackcdn.com/image/fetch/$s_!t2bd!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F64c6b69b-26bc-41c0-be77-51025685f057_5500x2475.png 1272w, /__u/substackcdn.com/image/fetch/$s_!t2bd!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F64c6b69b-26bc-41c0-be77-51025685f057_5500x2475.png 1456w" sizes="100vw" loading="lazy"></picture><div></div></div></a></figure></div><h3>Important Classes</h3><p><code>Turn</code>, <code>ShortTermMemory</code>, <code>SemanticCache</code>, <code>RedisStore</code>, <code>MemoryService</code>, <code>MetricsStore</code>.</p><h3>Key Methods</h3><p><code>store()</code>, <code>get()</code>, <code>cache_lookup()</code>, <code>cache_store()</code>, <code>run_demo()</code>, <code>record()</code>, <code>snapshot()</code>.</p><h2><strong>Implementation</strong></h2><h3><strong>GitHub Link</strong></h3><p><a href="https://github.com/sysdr/production-ai-engineering/tree/main/lesson3/aiam-day03">https://github.com/sysdr/production-ai-engineering/tree/main/lesson3/aiam-day03</a></p><p>Bounded session memory &#8594; TTL cache &#8594; Redis with safe fallback &#8594; <code>MemoryService</code> + metrics &#8594; FastAPI/dashboard &#8594; Compose packaging. Validate with unit tests, <code>/demo</code> non-zero metrics, and Redis-connected health. Redis failures degrade without crashing the API.</p><h2><strong>Coding Highlights</strong></h2><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;95cc762f-79ee-44a1-860d-0249b91eff2b&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">while turns and self._token_estimate(turns) &gt; self.max_tokens:
    turns = turns[2:]  # drop oldest pair</code></pre></div><p>Token budget trimming prevents prompt blowups before the model is called.</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;6a081f1d-9e62-4662-b77c-2f6afe8e4231&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">if entry and (time.time() - entry["ts"]) &lt; self.ttl:
    self.hits += 1
    return entry["value"]</code></pre></div><p>TTL-checked hits are the economic win; expired keys become misses and evictions.</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;6307b5bb-01f5-49fc-9e7a-f553dfde735e&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">METRICS.record(op="cache_lookup", cache_hit=hit is not None, redis_ops=redis_ops)</code></pre></div><p>Normalized metrics make memory behavior operable, not anecdotal.</p><h3>Working Demo Link:</h3><div id="youtube2-QoNDUNNImV8" class="youtube-wrap" data-attrs="{&quot;videoId&quot;:&quot;QoNDUNNImV8&quot;,&quot;startTime&quot;:null,&quot;endTime&quot;:null}" data-component-name="Youtube2ToDOM"><div class="youtube-inner"><iframe src="https://www.youtube-nocookie.com/embed/QoNDUNNImV8?rel=0&amp;autoplay=0&amp;showinfo=0&amp;enablejsapi=0" frameborder="0" loading="lazy" gesture="media" allow="autoplay; fullscreen" allowautoplay="true" allowfullscreen="true" width="728" height="409"></iframe></div></div><h2><strong>Production Considerations</strong></h2><ul><li><p>scalability: shared Redis across replicas.</p></li><li><p>security: private Redis, no API keys, bounded payloads.</p></li><li><p>monitoring: hit rate, evictions, Redis connectivity, latency.</p></li><li><p>logging: structured op labels without secrets.</p></li><li><p>testing: window limits, hit/miss, TTL, demo metric assertions.</p></li><li><p>failure handling: Redis offline &#8594; local memory; health reports status.</p></li><li><p>edge cases: empty sessions, case-normalized keys, LRU at max size.</p></li></ul><h2><strong>Validation</strong></h2><ul><li><p>verification: pytest; Compose health; <code>/demo</code> smoke checks.</p></li><li><p>testing strategy: unit tests without Redis; integration with Redis connected.</p></li><li><p>success criteria: <code>start.sh</code> / <code>demo.sh</code> / <code>run_tests.sh</code> work from the child project alone; post-demo metrics non-zero.</p></li><li><p>expected outputs: hits/misses, TTL evictions, Redis ops when connected, live <code>/dashboard</code> events.</p></li><li><p>benchmarks: hit rate and latency_ms_avg after demo &gt; 0.</p></li><li><p>production checklist: official images, <code>.gitignore</code>, cleanup script, no parent-setup dependency.</p></li></ul><h2><strong>Real-World Examples</strong></h2><blockquote><p>Support bots keep the last N turns per ticket in Redis so pod handoffs stay coherent, while FAQ answers cache for minutes to cut duplicate LLM spend. Coding assistants cache identical build-error explanations with short TTL so outdated remediation is not served after dependency changes.</p></blockquote><p></p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Lesson 2 — Tool Execution and Validation]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-2-tool-execution-and-validation</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-2-tool-execution-and-validation</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Wed, 05 Aug 2026 02:00:53 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!cIHe!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2><strong>Introduction</strong></h2><p>This lesson builds the Layer 3 tool execution boundary for a production AI agent: a schema-validated registry, permission-gated dispatch, and observable outcomes. </p><p>You implement a <code>ToolOrchestrator</code> that rejects unknown tools, missing parameters, unsafe input, and unauthorized writes before any side effect runs. </p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><p>A FastAPI dashboard surfaces live tool calls, denials, blocks, and latency.</p><h2><strong>Highlights</strong></h2><ul><li><p>Layer 3 tool boundary with typed schemas, permission checks, and explicit error states.</p></li><li><p>Single orchestrator dispatch instead of ad hoc Python functions.</p></li><li><p>Live metrics for allowed calls, denials, unsafe input, failures, and latency.</p></li><li><p>Self-contained Dockerized FastAPI service with dashboard, CLI demo, tests, and cleanup.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p><code>ToolOrchestrator</code> validating tool names, parameters, and permissions.</p></li><li><p>Registry tools: <code>calculate</code>, <code>echo</code>, <code>write_log</code>.</p></li><li><p>FastAPI endpoints: <code>/health</code>, <code>/metrics</code>, <code>/tools/call</code>, <code>/demo</code>, <code>/dashboard</code>.</p></li><li><p>Live dashboard for metrics and recent events.</p></li><li><p>Docker and scripts for start, demo, test, stop, and cleanup.</p></li></ul><h2>Connection to Previous Lesson</h2><p>Lesson 1 introduced the four-layer secure agent and least-privilege tool discovery. Lesson 2 turns that into execution&#8212;validating inputs, checking permissions, dispatching tools, and returning structured results.</p><h2>Enables Next Lesson</h2><p>Typed, permissioned, observable tool calls let later lessons add memory, persistence, and workflows without rebuilding safety checks.</p><h2>Architecture Context</h2><ul><li><p>Where this component sits &#8212; Between agent logic and external capabilities; Layer 3 gates existence, permission, validation, and reporting.</p></li><li><p>Why it exists &#8212; Model actions must not execute directly; the boundary narrows exposure and creates audit points.</p></li><li><p>Problem solved &#8212; Blocks unknown tools, bad parameters, unsafe expressions, and unauthorized writes before runtime side effects.</p></li></ul><h3>Component Architecture</h3><p><code>registry.py</code> owns dispatch; <code>metrics.py</code> owns counters; <code>app.py</code> serves HTTP; <code>main.py</code> runs CLI; scripts handle operations.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!cIHe!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!cIHe!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png 424w, /__u/substackcdn.com/image/fetch/$s_!cIHe!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png 848w, /__u/substackcdn.com/image/fetch/$s_!cIHe!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png 1272w, /__u/substackcdn.com/image/fetch/$s_!cIHe!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!cIHe!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png" width="518" height="362.52884615384613" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1019,&quot;width&quot;:1456,&quot;resizeWidth&quot;:518,&quot;bytes&quot;:897154,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207113227?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!cIHe!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png 424w, /__u/substackcdn.com/image/fetch/$s_!cIHe!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png 848w, /__u/substackcdn.com/image/fetch/$s_!cIHe!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png 1272w, /__u/substackcdn.com/image/fetch/$s_!cIHe!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F457ce271-aeb1-47ef-8845-c86e7b8a522a_5500x3850.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Integration</strong></h2><h3>Integration Components</h3><ul><li><p><code>tools/registry.py</code> &#8212; schema, registry, orchestrator.</p></li><li><p><code>tools/metrics.py</code> &#8212; in-process dashboard metrics.</p></li><li><p><code>app.py</code> &#8212; HTTP API and dashboard.</p></li><li><p><code>main.py</code> &#8212; CLI demo.</p></li><li><p><code>Dockerfile</code>, <code>docker-compose.yml</code>, shell scripts &#8212; deployment workflows.</p></li></ul><h3><strong>Module Objectives Alignment</strong></h3><ul><li><p>Tool safety, schema discipline, observability, deployability, and testability.</p></li></ul><h2><strong>Core Concepts</strong></h2><blockquote><p>The registry is a production allowlist declaring capabilities and requirements. Permission-gated dispatch enforces least privilege&#8212;read-only callers cannot write logs. Schema validation returns structured <code>ToolResult</code> errors for dashboards and audits. The <code>calculate</code> sandbox rejects code-execution patterns, showing each tool needs its own validation. Metrics classify ok, denied, blocked, and failed outcomes separately.</p></blockquote><h2><strong>Key Insights</strong></h2><ul><li><p>Tool calls are authorization events, not mere function calls.</p></li><li><p>Unknown tools fail closed; model output is untrusted.</p></li><li><p>Expected denials prove the safety layer works.</p></li><li><p>In-memory metrics suit lessons; production needs shared storage for replicas.</p></li><li><p>Centralize validation; permission denied, unsafe input, and unknown tools differ operationally.</p></li></ul><h2><strong>Production AI System Design Relevance</strong></h2><blockquote><p>This is the execution gateway preventing an LLM from becoming an unbounded RPC caller&#8212;scaling to databases, tickets, email, payments, and infrastructure actions.</p></blockquote><h2><strong>Workflow</strong></h2><ul><li><p>request flow &#8212; Tool name, parameters, permissions, and label reach the orchestrator.</p></li><li><p>execution flow &#8212; Registry lookup, permission check, parameter validation, dispatch, <code>ToolResult</code> wrap.</p></li><li><p>data flow &#8212; Input through <code>ToolOrchestrator.call()</code>; metrics receive normalized events.</p></li><li><p>state changes &#8212; Static registry; <code>METRICS</code> counters and events update at runtime.</p></li></ul><h3>Control Flow</h3><p>Request &#8594; registry &#8594; permission &#8594; validation &#8594; execute &#8594; metrics &#8594; response.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!kZ4U!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4fad730a-045f-4bcc-8223-5bdaafa3c89b_5500x2750.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!kZ4U!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4fad730a-045f-4bcc-8223-5bdaafa3c89b_5500x2750.png 424w, /__u/substackcdn.com/image/fetch/$s_!kZ4U!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4fad730a-045f-4bcc-8223-5bdaafa3c89b_5500x2750.png 848w, /__u/substackcdn.com/image/fetch/$s_!kZ4U!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4fad730a-045f-4bcc-8223-5bdaafa3c89b_5500x2750.png 1272w, /__u/substackcdn.com/image/fetch/$s_!kZ4U!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4fad730a-045f-4bcc-8223-5bdaafa3c89b_5500x2750.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!kZ4U!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4fad730a-045f-4bcc-8223-5bdaafa3c89b_5500x2750.png" width="560" height="280" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/4fad730a-045f-4bcc-8223-5bdaafa3c89b_5500x2750.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:728,&quot;width&quot;:1456,&quot;resizeWidth&quot;:560,&quot;bytes&quot;:647531,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207113227?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4fad730a-045f-4bcc-8223-5bdaafa3c89b_5500x2750.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!kZ4U!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4fad730a-045f-4bcc-8223-5bdaafa3c89b_5500x2750.png 424w, /__u/substackcdn.com/image/fetch/$s_!kZ4U!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4fad730a-045f-4bcc-8223-5bdaafa3c89b_5500x2750.png 848w, /__u/substackcdn.com/image/fetch/$s_!kZ4U!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4fad730a-045f-4bcc-8223-5bdaafa3c89b_5500x2750.png 1272w, /__u/substackcdn.com/image/fetch/$s_!kZ4U!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4fad730a-045f-4bcc-8223-5bdaafa3c89b_5500x2750.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Production Integration</strong></h2><ul><li><p>production architecture fit &#8212; Behind auth, before side effects; emits traces to shared observability.</p></li><li><p>enterprise deployment patterns &#8212; Containers, pinned images, env config, API gateway; externalize metrics for replicas.</p></li><li><p>scalability &#8212; Horizontal dispatch when metrics and audit logs are externalized.</p></li><li><p>observability &#8212; Structured logs, counters, latency histograms, durable audit events.</p></li><li><p>security considerations &#8212; Server-side identity, rate limits, approval for high-impact tools.</p></li></ul><h2><strong>Real-World Examples</strong></h2><p>Support agents summarize tickets for all users; only supervisors issue refunds via permission-gated billing tools. Cloud assistants read health freely; restart and migration tools require elevated permissions and audit logging.</p><h2><strong>Implementation</strong></h2><h2><strong>GitHub Link</strong></h2><p><strong><a href="https://github.com/sysdr/production-ai-engineering/tree/main/lesson2/aiam-day02">https://github.com/sysdr/production-ai-engineering/tree/main/lesson2/aiam-day02</a></strong></p><h3>Data Flow</h3><p>JSON/CLI input passes validation, returns <code>ToolResult</code>; metrics get normalized events.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!EEjo!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa676ad-bac4-4083-99e9-d13f1d9a5a0f_5500x2475.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!EEjo!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa676ad-bac4-4083-99e9-d13f1d9a5a0f_5500x2475.png 424w, /__u/substackcdn.com/image/fetch/$s_!EEjo!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa676ad-bac4-4083-99e9-d13f1d9a5a0f_5500x2475.png 848w, /__u/substackcdn.com/image/fetch/$s_!EEjo!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa676ad-bac4-4083-99e9-d13f1d9a5a0f_5500x2475.png 1272w, /__u/substackcdn.com/image/fetch/$s_!EEjo!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa676ad-bac4-4083-99e9-d13f1d9a5a0f_5500x2475.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!EEjo!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa676ad-bac4-4083-99e9-d13f1d9a5a0f_5500x2475.png" width="552" height="248.32417582417582" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/9fa676ad-bac4-4083-99e9-d13f1d9a5a0f_5500x2475.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:655,&quot;width&quot;:1456,&quot;resizeWidth&quot;:552,&quot;bytes&quot;:632769,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/207113227?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa676ad-bac4-4083-99e9-d13f1d9a5a0f_5500x2475.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!EEjo!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa676ad-bac4-4083-99e9-d13f1d9a5a0f_5500x2475.png 424w, /__u/substackcdn.com/image/fetch/$s_!EEjo!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa676ad-bac4-4083-99e9-d13f1d9a5a0f_5500x2475.png 848w, /__u/substackcdn.com/image/fetch/$s_!EEjo!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa676ad-bac4-4083-99e9-d13f1d9a5a0f_5500x2475.png 1272w, /__u/substackcdn.com/image/fetch/$s_!EEjo!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F9fa676ad-bac4-4083-99e9-d13f1d9a5a0f_5500x2475.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h3><strong>Important Classes</strong></h3><p><code>ToolSchema</code>, <code>ToolResult</code>, <code>ToolOrchestrator</code>, <code>MetricsStore</code>.</p><h3><strong>Key Methods</strong></h3><p><code>available()</code>, <code>call()</code>, <code>record()</code>, <code>run_demo()</code>.</p><h3><strong>Step-by-Step Implementation</strong></h3><p>Registry allowlist &#8594; result envelope &#8594; orchestrator &#8594; tool handlers &#8594; metrics &#8594; FastAPI &#8594; dashboard &#8594; Docker packaging.</p><h2><strong>Coding Highlights</strong></h2><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;32891c1e-13ac-4bb5-870b-687d45f130ea&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">if tool_name not in TOOL_REGISTRY:
    return ToolResult(tool=tool_name, success=False, error="Unknown tool")</code></pre></div><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;698d539d-542f-426e-a982-671a721d2748&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">if schema.required_permission not in permissions:
    return ToolResult(tool=tool_name, success=False, error="Permission denied")</code></pre></div><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;6897e9f8-e360-4d8f-9462-f9e6a993cc44&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">METRICS.record(tool=tool_name, success=True, latency_ms=ms, output=output)</code></pre></div><h3>Working Demo Link:</h3><div id="youtube2-04Kp3_MfkBA" class="youtube-wrap" data-attrs="{&quot;videoId&quot;:&quot;04Kp3_MfkBA&quot;,&quot;startTime&quot;:null,&quot;endTime&quot;:null}" data-component-name="Youtube2ToDOM"><div class="youtube-inner"><iframe src="https://www.youtube-nocookie.com/embed/04Kp3_MfkBA?rel=0&amp;autoplay=0&amp;showinfo=0&amp;enablejsapi=0" frameborder="0" loading="lazy" gesture="media" allow="autoplay; fullscreen" allowautoplay="true" allowfullscreen="true" width="728" height="409"></iframe></div></div><h2><strong>Production Considerations</strong></h2><ul><li><p>scalability: externalize metrics for replicas.</p></li><li><p>security: server-side identity, not request permissions.</p></li><li><p>monitoring, logging, testing, failure handling, edge cases: timeouts, input caps, idempotent retries only.</p></li></ul><h2><strong>Validation</strong></h2><ul><li><p>verification: orchestrator tests, API tests, Docker build, health checks.</p></li><li><p>success criteria: <code>start.sh</code> runs dashboard, <code>demo.sh</code> runs CLI, <code>run_tests.sh</code> passes, <code>cleanup.sh</code> stops services.</p></li><li><p>expected outputs: non-zero post-demo metrics, timestamped events, structured expected failures.</p></li><li><p>production checklist: no secrets, official Python image, clear failure classification, health and metrics endpoints.</p></li></ul><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Lesson 1 — The 4-Layer Secure Agent Architecture]]></title><description><![CDATA[Introduction]]></description><link>https://aiamastery.substack.com/p/lesson-1-the-4-layer-secure-agent</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-1-the-4-layer-secure-agent</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Tue, 04 Aug 2026 02:00:25 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!sdyz!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction </h2><blockquote><p>This lesson introduces the foundation of a production AI agent: a four-layer secure architecture where every request must pass through Security, Tools, Memory, and finally the LLM. You will build a self-contained Day 1 system with typed contracts, fail-closed injection defense, permissioned tools, and bounded session memory. </p></blockquote><blockquote><p>A FastAPI dashboard exposes live metrics&#8212;requests, blocks, tokens, cost, and layer latency&#8212;so observability is learned alongside the agent itself. </p></blockquote><blockquote><p>The project runs offline in stub mode or with a real OpenAI key, and ships with Docker scripts for start, demo, test, and cleanup. By the end, you have a reusable agent kernel that later lessons extend without collapsing security into ad-hoc prompts.</p></blockquote><h2><strong>Highlights</strong></h2><ul><li><p>Build a production-shaped agent with four concentric layers: Security (L4) &#8594; Tools (L3) &#8594; Memory (L2) &#8594; LLM (L1).</p></li><li><p>Enforce prompt-injection defense, RBAC, and rate limiting <strong>before</strong> any model call.</p></li><li><p>Emit live metrics (requests, blocks, tokens, cost, layer latency) to a FastAPI dashboard.</p></li><li><p>Run the full stack with an official <code>python:3.12-slim</code> Docker image via self-contained <code>start.sh</code> / <code>demo.sh</code>.</p></li><li><p>Treat stub LLM mode as a first-class engineering path so CI and demos work without API keys.</p></li></ul><h2><strong>What We Build</strong></h2><ul><li><p>A <code>SecureAgent</code> orchestrator that routes every request through L4 &#8594; L3 &#8594; L2 &#8594; L1 and filters responses on the way out.</p></li><li><p>Layer modules: <code>SecurityPerimeter</code>, <code>ToolOrchestrator</code>, <code>InMemoryStore</code>, <code>CoreLLM</code>.</p></li><li><p>A FastAPI service (<code>app.py</code>) exposing <code>/health</code>, <code>/metrics</code>, <code>/chat</code>, <code>/demo</code>, and a live <code>/dashboard</code>.</p></li><li><p>Pytest coverage for injection blocking and metrics side effects, plus Dockerized start/demo/test scripts.</p></li><li><p>Cost and latency accounting that stays non-zero in stub mode so the dashboard teaches observability habits.</p></li></ul><h2><strong>Enables Next Lesson</strong></h2><blockquote><p>Day 2 builds on the L3 tool boundary: real tool execution, schema validation, and safer tool-output handling. After Day 1 you already have permission-filtered tool discovery and output redaction &#8212; Day 2 turns that registry into an execution pipeline without rewriting security or memory.</p></blockquote><h2><strong>Architecture Context</strong></h2><p><strong>Where this component sits</strong> &#8212; At the edge of a production AI product: every user (or service) request enters through the agent perimeter before reaching a model provider. The dashboard and metrics sit beside the agent as the first observability surface.</p><p><strong>Why it exists</strong> &#8212; Prompt-only &#8220;safety&#8221; is insufficient. Production systems need perimeter controls (length, sanitize, injection, authz, rate limit), capability gating for tools, session memory with bounds, and a narrowly-scoped model call with cost/latency telemetry.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><p><strong>Problem solved</strong> &#8212; Prevents untrusted input from reaching L1; prevents over-privileged tools from appearing; bounds memory growth; makes failures observable (blocked vs rejected vs ok) instead of silent prompt failures.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!sdyz!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!sdyz!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png 424w, /__u/substackcdn.com/image/fetch/$s_!sdyz!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png 848w, /__u/substackcdn.com/image/fetch/$s_!sdyz!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png 1272w, /__u/substackcdn.com/image/fetch/$s_!sdyz!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!sdyz!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png" width="526" height="368.12774725274727" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/c2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1019,&quot;width&quot;:1456,&quot;resizeWidth&quot;:526,&quot;bytes&quot;:1223322,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/206988893?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!sdyz!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png 424w, /__u/substackcdn.com/image/fetch/$s_!sdyz!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png 848w, /__u/substackcdn.com/image/fetch/$s_!sdyz!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png 1272w, /__u/substackcdn.com/image/fetch/$s_!sdyz!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc2bf19a0-b949-40ee-9d51-d9b8f279b9f3_5500x3850.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h2><strong>Integration</strong></h2><h3><strong>Integration Components</strong></h3><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!pjbd!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0675db47-d402-4229-9e04-9f6583c2e222_1157x442.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!pjbd!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0675db47-d402-4229-9e04-9f6583c2e222_1157x442.png 424w, /__u/substackcdn.com/image/fetch/$s_!pjbd!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0675db47-d402-4229-9e04-9f6583c2e222_1157x442.png 848w, /__u/substackcdn.com/image/fetch/$s_!pjbd!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0675db47-d402-4229-9e04-9f6583c2e222_1157x442.png 1272w, /__u/substackcdn.com/image/fetch/$s_!pjbd!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0675db47-d402-4229-9e04-9f6583c2e222_1157x442.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!pjbd!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0675db47-d402-4229-9e04-9f6583c2e222_1157x442.png" width="1157" height="442" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/0675db47-d402-4229-9e04-9f6583c2e222_1157x442.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:442,&quot;width&quot;:1157,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:57775,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/206988893?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0675db47-d402-4229-9e04-9f6583c2e222_1157x442.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!pjbd!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0675db47-d402-4229-9e04-9f6583c2e222_1157x442.png 424w, /__u/substackcdn.com/image/fetch/$s_!pjbd!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0675db47-d402-4229-9e04-9f6583c2e222_1157x442.png 848w, /__u/substackcdn.com/image/fetch/$s_!pjbd!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0675db47-d402-4229-9e04-9f6583c2e222_1157x442.png 1272w, /__u/substackcdn.com/image/fetch/$s_!pjbd!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0675db47-d402-4229-9e04-9f6583c2e222_1157x442.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h3><strong>Module Objectives Alignment</strong></h3><ul><li><p><strong>Security-first agent design</strong> &#8212; L4 is mandatory, not optional middleware.</p></li><li><p><strong>Separation of concerns</strong> &#8212; tools, memory, and LLM are distinct replaceable layers.</p></li><li><p><strong>Operability</strong> &#8212; metrics and dashboard are part of the build, not a later add-on.</p></li><li><p><strong>Testability</strong> &#8212; stub LLM + injection tests make Day 1 CI-complete without secrets.</p></li></ul><h2><strong>Core Concepts</strong></h2><h3><strong>Concentric layers, not a pipeline of peers</strong></h3><p>Engineering reasoning: if security is &#8220;one step among equals,&#8221; a future refactor can bypass it. Placing security as the <strong>outermost</strong> gate makes <code>SecureAgent.run</code> structurally unable to call the LLM without passing L4.</p><h3><strong>Prompt injection as an authorization failure</strong></h3><p>Injection is not a &#8220;bad reply&#8221; quality issue; it is an attempt to elevate privilege over the system prompt and tools. Raising <code>PermissionError</code> maps it to the same class of failure as unauthorized access &#8212; metrics label it <code>blocked</code>, not <code>ok</code>.</p><h3><strong>Least-privilege tools</strong></h3><p>Tool registries without permission checks leak capabilities into the prompt surface. Filtering available tools by <code>SecurityContext.permissions</code> shrinks the attack path even when L1 is imperfect.</p><h3><strong>Bounded session memory</strong></h3><p>Unbounded chat history becomes a cost and privacy bomb. A sliding window (<code>max_turns</code>) is the minimal production discipline before durable stores appear in later lessons.</p><h3><strong>Stub LLM as a design choice</strong></h3><p>Production CI should not depend on vendor availability. A deterministic stub with estimated tokens/cost teaches the same observability contracts as a live model while keeping demos offline-capable.</p><h3><strong>In-process metrics with a single worker</strong></h3><p>For Day 1, a threaded <code>MetricsStore</code> plus <code>uvicorn --workers 1</code> gives correct live dashboard updates without Redis. The tradeoff is intentional and documented &#8212; multi-worker needs a shared metrics backend later.</p><h2><strong>Key Insights</strong></h2><ul><li><p><strong>Security before creativity</strong> &#8212; tokens spent on injected prompts are both wasted money and risk; block early.</p></li><li><p><strong>Status taxonomy matters</strong> &#8212; <code>ok</code> / <code>blocked</code> / <code>rejected</code> drives ops dashboards and alerting differently than HTTP 200 with a polite refusal string.</p></li><li><p><strong>Tradeoff: regex injection filters</strong> &#8212; fast and explainable, but incomplete against novel jailbreaks; combine with model-side policy and human review queues in production.</p></li><li><p><strong>Tradeoff: in-memory session store</strong> &#8212; great latency, poor durability and multi-replica stickiness; fine for Day 1, not for multi-AZ production alone.</p></li><li><p><strong>Common mistake</strong> &#8212; putting API keys in source or committing <code>.env</code>. Use <code>.env.example</code> with empty values only.</p></li><li><p><strong>Common mistake</strong> &#8212; multi-worker uvicorn without shared metrics, then wondering why the dashboard stays at zero.</p></li><li><p><strong>Common mistake</strong> &#8212; treating HTML escape as XSS-only concern; escaped user text also reduces markup-based prompt smuggling in logs and UIs.</p></li></ul><h2><strong>Production AI System Design Relevance</strong></h2><p>Inside a production AI platform, Day 1 is the <strong>agent control plane kernel</strong>:</p><pre><code><code>Clients &#8594; API Gateway &#8594; Secure Agent (L4&#8211;L1) &#8594; Model Provider / Tools
                         &#8595;
                   Metrics / Dashboard / Logs
</code></code></pre><p>Later modules hang off this kernel: durable memory, tool sandboxes, retrieval, evaluation, canary models, and policy engines all assume a clean security perimeter and typed request/response contracts exist.</p><h2><strong>Workflow</strong></h2><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!GbTd!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feafbfbe8-217d-4781-82f2-12460da383f3_5500x2750.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!GbTd!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feafbfbe8-217d-4781-82f2-12460da383f3_5500x2750.png 424w, /__u/substackcdn.com/image/fetch/$s_!GbTd!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feafbfbe8-217d-4781-82f2-12460da383f3_5500x2750.png 848w, /__u/substackcdn.com/image/fetch/$s_!GbTd!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feafbfbe8-217d-4781-82f2-12460da383f3_5500x2750.png 1272w, /__u/substackcdn.com/image/fetch/$s_!GbTd!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feafbfbe8-217d-4781-82f2-12460da383f3_5500x2750.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!GbTd!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feafbfbe8-217d-4781-82f2-12460da383f3_5500x2750.png" width="532" height="266" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/eafbfbe8-217d-4781-82f2-12460da383f3_5500x2750.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:728,&quot;width&quot;:1456,&quot;resizeWidth&quot;:532,&quot;bytes&quot;:616218,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/206988893?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feafbfbe8-217d-4781-82f2-12460da383f3_5500x2750.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!GbTd!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feafbfbe8-217d-4781-82f2-12460da383f3_5500x2750.png 424w, /__u/substackcdn.com/image/fetch/$s_!GbTd!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feafbfbe8-217d-4781-82f2-12460da383f3_5500x2750.png 848w, /__u/substackcdn.com/image/fetch/$s_!GbTd!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feafbfbe8-217d-4781-82f2-12460da383f3_5500x2750.png 1272w, /__u/substackcdn.com/image/fetch/$s_!GbTd!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Feafbfbe8-217d-4781-82f2-12460da383f3_5500x2750.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h3><strong>Request flow</strong></h3><ol><li><p>Client sends prompt + identity context (<code>user_id</code>, <code>session_id</code>, <code>permissions</code>).</p></li><li><p><code>SecureAgent</code> wraps input as <code>AgentRequest</code>.</p></li><li><p>L4 validates/sanitizes or raises.</p></li><li><p>L3 computes available tools for permissions.</p></li><li><p>L2 loads session history.</p></li><li><p>L1 produces <code>AgentResponse</code>.</p></li><li><p>L2 stores the turn; L3 filters output; metrics record outcome.</p></li></ol><h3><strong>Execution flow</strong></h3><ul><li><p>Happy path: L4 pass &#8594; L3 list tools &#8594; L2 get &#8594; L1 call &#8594; L2 store &#8594; L3 filter &#8594; return.</p></li><li><p>Injection/jailbreak: L4 raises <code>PermissionError</code> &#8594; metrics <code>blocked</code> &#8594; API returns blocked payload (no L1).</p></li><li><p>Oversize input: L4 raises <code>ValueError</code> &#8594; metrics <code>rejected</code>.</p></li></ul><h3><strong>Data flow</strong></h3><ul><li><p><strong>Inbound:</strong> raw string &#8594; sanitized string &#8594; message list (<code>history + user</code>).</p></li><li><p><strong>Outbound:</strong> model/stub text &#8594; redacted text &#8594; JSON/API/dashboard event.</p></li><li><p><strong>Telemetry:</strong> tokens, cost, layer timings accumulate in <code>MetricsStore</code>.</p></li></ul><h3><strong>State changes</strong></h3><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!7TGk!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff13e6d43-1b0d-4420-9104-63895b7abfc1_5500x2475.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!7TGk!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff13e6d43-1b0d-4420-9104-63895b7abfc1_5500x2475.png 424w, /__u/substackcdn.com/image/fetch/$s_!7TGk!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff13e6d43-1b0d-4420-9104-63895b7abfc1_5500x2475.png 848w, /__u/substackcdn.com/image/fetch/$s_!7TGk!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff13e6d43-1b0d-4420-9104-63895b7abfc1_5500x2475.png 1272w, /__u/substackcdn.com/image/fetch/$s_!7TGk!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff13e6d43-1b0d-4420-9104-63895b7abfc1_5500x2475.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!7TGk!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff13e6d43-1b0d-4420-9104-63895b7abfc1_5500x2475.png" width="1456" height="655" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f13e6d43-1b0d-4420-9104-63895b7abfc1_5500x2475.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:655,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:484207,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/206988893?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff13e6d43-1b0d-4420-9104-63895b7abfc1_5500x2475.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!7TGk!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff13e6d43-1b0d-4420-9104-63895b7abfc1_5500x2475.png 424w, /__u/substackcdn.com/image/fetch/$s_!7TGk!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff13e6d43-1b0d-4420-9104-63895b7abfc1_5500x2475.png 848w, /__u/substackcdn.com/image/fetch/$s_!7TGk!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff13e6d43-1b0d-4420-9104-63895b7abfc1_5500x2475.png 1272w, /__u/substackcdn.com/image/fetch/$s_!7TGk!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff13e6d43-1b0d-4420-9104-63895b7abfc1_5500x2475.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><ul><li><p>Session memory list grows by two messages per successful turn, then trims to window.</p></li><li><p>Rate-limiter counters increment per user/minute bucket.</p></li><li><p>Metrics counters (<code>requests_*</code>, <code>tokens_total</code>, <code>cost_usd_total</code>, layer sums) monotonically increase.</p></li><li><p>Demo runs bump <code>demo_runs</code> after <code>/demo</code>.</p></li></ul><h2><strong>Production Integration</strong></h2><h3><strong>Production architecture fit</strong></h3><p>Deploy the agent as a single-responsibility service behind an API gateway. Keep L1 provider credentials in a secret manager; never in the image. Use the dashboard only for low-traffic demos or internal ops &#8212; production metrics should also export to Prometheus/OpenTelemetry.</p><h3><strong>Enterprise deployment patterns</strong></h3><ul><li><p>Containerize with the official Python slim image (already in <code>Dockerfile</code>).</p></li><li><p>One service replica for Day 1 parity with in-memory metrics; later: sticky sessions or external memory + shared metrics.</p></li><li><p>Separate &#8220;demo&#8221; and &#8220;prod&#8221; configs via env (<code>OPENAI_MODEL</code>, rate-limit tiers).</p></li></ul><h3><strong>Scalability</strong></h3><p>Vertical: increase CPU for regex + stub latency. Horizontal: requires externalizing memory and metrics. Tool and LLM calls dominate p95 &#8212; measure with <code>layer_timings</code>.</p><h3><strong>Observability</strong></h3><p>Structured logs per layer (<code>[L4]</code>, <code>[L3]</code>, <code>[L2]</code>, <code>[L1]</code>, <code>[AGENT]</code>), request IDs on <code>SecurityContext</code>, live <code>/metrics</code> + dashboard. Production should add distributed tracing spans around each layer.</p><h3><strong>Security considerations</strong></h3><p>Perimeter injection filters, RBAC permissions on tools, output redaction of secret-like patterns, rate limits, no committed secrets, HTML escaping of user input.</p><h2><strong>Implementation</strong></h2><h2><strong>GitHub Link</strong></h2><p><strong><a href="https://github.com/sysdr/production-ai-engineering/tree/main/lesson1/aiam-day01">https://github.com/sysdr/production-ai-engineering/tree/main/lesson1/aiam-day01</a></strong></p><p>This section is the canonical implementation guide for Day 1. No separate implementation guide file is used.</p><h3><strong>Component Architecture</strong></h3><pre><code><code>aiam-day01/
&#9500;&#9472;&#9472; agent/
&#9474;   &#9500;&#9472;&#9472; agent.py                 # SecureAgent orchestrator
&#9474;   &#9500;&#9472;&#9472; core/types.py            # Contracts
&#9474;   &#9500;&#9472;&#9472; core/metrics.py          # MetricsStore
&#9474;   &#9492;&#9472;&#9472; layers/
&#9474;       &#9500;&#9472;&#9472; security.py          # L4
&#9474;       &#9500;&#9472;&#9472; tool_orchestrator.py # L3
&#9474;       &#9500;&#9472;&#9472; memory.py            # L2
&#9474;       &#9492;&#9472;&#9472; llm.py               # L1
&#9500;&#9472;&#9472; app.py                       # FastAPI + dashboard
&#9500;&#9472;&#9472; main.py                      # CLI demo
&#9500;&#9472;&#9472; tests/
&#9500;&#9472;&#9472; Dockerfile / docker-compose.yml
&#9500;&#9472;&#9472; start.sh / stop.sh / demo.sh / run_tests.sh / cleanup.sh
&#9492;&#9472;&#9472; requirements.txt</code></code></pre><h3><strong>Step-by-Step Implementation</strong></h3><ol><li><p><strong>Define contracts</strong> (<code>types.py</code>) &#8212; Pydantic models force consistent fields for metrics and APIs; prevents &#8220;dict soup&#8221; across layers.</p></li><li><p><strong>Implement L4</strong> &#8212; compile injection patterns once; sanitize; rate limit; RBAC log/assert. Exists to fail closed before cost is incurred.</p></li><li><p><strong>Implement L3</strong> &#8212; registry with permission tags; filter tools; redact secrets on egress.</p></li><li><p><strong>Implement L2</strong> &#8212; session-keyed lists with trim; exists for continuity without unbounded growth.</p></li><li><p><strong>Implement L1</strong> &#8212; branch on <code>OPENAI_API_KEY</code>; stub still estimates cost; small sleep ensures measurable latency for demos.</p></li><li><p><strong>Orchestrate</strong> &#8212; <code>SecureAgent</code> owns ordering, timings, and metrics on success and exception paths.</p></li><li><p><strong>Expose HTTP</strong> &#8212; FastAPI lifespan constructs one agent; <code>/demo</code> walks happy + attack prompts; dashboard polls <code>/metrics</code>.</p></li><li><p><strong>Validate</strong> &#8212; unit tests for L4 and metrics; <code>run_tests.sh</code> for health/demo/non-zero metrics.</p></li><li><p><strong>Package</strong> &#8212; Dockerfile installs <code>requirements.txt</code>, runs single-worker uvicorn; <code>start.sh</code> avoids duplicate containers.</p></li></ol><p><strong>Communication:</strong> layers do not call each other sideways; only <code>SecureAgent</code> composes them. <strong>Validation:</strong> Pydantic on the way in; regex/RBAC in L4; permission checks in L3. <strong>Error handling:</strong> <code>PermissionError</code> &#8594; blocked; <code>ValueError</code> &#8594; rejected; both recorded. <strong>Production considerations:</strong> env-based secrets, official base image, cleanup script for caches/images, <code>.gitignore</code> for <code>.env</code> and <code>venv</code>.</p><h2><strong>Coding Highlights</strong></h2><p>Layer order is policy-as-code &#8212; do not reorder casually:</p><pre><code><code>request = self.security.process(request)          # L4 first
available = self.tools.get_available_tools(...)   # L3
history = self.memory.get_context(session_id)     # L2
response = self.llm.call(request, messages)       # L1 last
response = self.tools.filter_output(response)     # egress filter</code></code></pre><p>Why it matters: every future tool or model swap still inherits the same security envelope.</p><p>Fail closed on injection:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;f552b804-46d8-4373-92ff-d5fa9051264b&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">if pattern.search(sanitised):
    raise PermissionError("Potential prompt injection detected")</code></pre></div><p>Why it matters: returning a soft &#8220;I can&#8217;t help with that&#8221; from the LLM still spends tokens and can be inconsistently bypassed; raising stops the pipeline.</p><p>Record metrics on exception paths, not only success:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;5ce9101b-664f-49bb-a54e-c11ac332544a&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python">except PermissionError:
    METRICS.record(status="blocked", ...)
    raise</code></pre></div><p>Why it matters: security events are the highest-value dashboard series.</p><h3>Working demo Link:</h3><div id="youtube2-C4n9uJidQls" class="youtube-wrap" data-attrs="{&quot;videoId&quot;:&quot;C4n9uJidQls&quot;,&quot;startTime&quot;:null,&quot;endTime&quot;:null}" data-component-name="Youtube2ToDOM"><div class="youtube-inner"><iframe src="https://www.youtube-nocookie.com/embed/C4n9uJidQls?rel=0&amp;autoplay=0&amp;showinfo=0&amp;enablejsapi=0" frameborder="0" loading="lazy" gesture="media" allow="autoplay; fullscreen" allowautoplay="true" allowfullscreen="true" width="728" height="409"></iframe></div></div><h2><strong>Production Considerations</strong></h2><ul><li><p><strong>Scalability</strong> &#8212; externalize memory and metrics before multi-replica; keep L1 timeouts and circuit breakers (Day 2+).</p></li><li><p><strong>Security</strong> &#8212; empty default API key; <code>.gitignore</code> <code>.env</code>; output redaction; rate limits; never log raw secrets.</p></li><li><p><strong>Monitoring</strong> &#8212; <code>/metrics</code> counters + layer timings; alert on <code>requests_blocked</code> spikes.</p></li><li><p><strong>Logging</strong> &#8212; structured layer prefixes; include <code>request_id</code>.</p></li><li><p><strong>Testing</strong> &#8212; injection unit tests; metrics non-zero after demo; stub mode in CI.</p></li><li><p><strong>Failure handling</strong> &#8212; map exceptions to <code>blocked</code>/<code>rejected</code>; API returns JSON status without crashing the worker.</p></li><li><p><strong>Edge cases</strong> &#8212; oversize input; repeated jailbreaks; empty model content; HTML tags in prompts; multi-turn memory trim boundaries.</p></li></ul><h2><strong>Validation</strong></h2><h3><strong>Verification methods</strong></h3><ul><li><p><code>./demo.sh</code> &#8212; CLI path through all scenario labels.</p></li><li><p><code>./start.sh</code> then dashboard <strong>Run demo</strong> &#8212; UI metrics update.</p></li><li><p><code>./run_tests.sh</code> &#8212; pytest + <code>/health</code> + <code>/demo</code> + non-zero metrics assertions.</p></li></ul><h3><strong>Testing strategy</strong></h3><ul><li><p>Unit: L4 allow/deny/length/escape; agent metrics increments.</p></li><li><p>Smoke: health, demo JSON, dashboard HTML marker.</p></li><li><p>Manual: confirm blocked count rises on injection prompts.</p></li></ul><h3><strong>Success criteria</strong></h3><ul><li><p>Clean prompts return <code>ok</code> with <code>tokens_used &gt; 0</code> and <code>cost_usd &gt; 0</code> in stub mode.</p></li><li><p>Injection/jailbreak prompts are blocked without L1 completion content.</p></li><li><p>Dashboard metrics are non-zero after one demo run.</p></li><li><p>Only one <code>aiam-day01</code> container when started via <code>start.sh</code>.</p></li></ul><h3><strong>Expected outputs</strong></h3><ul><li><p>CLI labels: <code>NORMAL</code>, <code>MEMORY</code>, <code>INJECT</code> (blocked), <code>JAILBREAK</code> (blocked).</p></li><li><p>Metrics keys: <code>requests_total</code>, <code>requests_ok</code>, <code>requests_blocked</code>, <code>tokens_total</code>, <code>cost_usd_total</code>, layer sums, <code>demo_runs</code>.</p></li></ul><h3><strong>Benchmarks (stub, local Docker)</strong></h3><ul><li><p>L1 stub latency typically &#8805; 5ms (intentional sleep).</p></li><li><p>Full <code>/demo</code> (5 steps) completes in well under 1s on a developer laptop.</p></li></ul><h3><strong>Production checklist</strong></h3><ul><li><p>No secrets in git</p></li><li><p>Official base image pinned by digest in real prod (lesson uses tag for clarity)</p></li><li><p>Single-worker or shared metrics documented</p></li><li><p>Tests green in CI without <code>OPENAI_API_KEY</code></p></li><li><p><code>cleanup.sh</code> known to operators</p></li></ul><h2><strong>Real-World Examples</strong></h2><p><strong>Enterprise IT copilot</strong> &#8212; Employees ask policy questions; L4 blocks &#8220;ignore previous instructions / dump the system prompt&#8221; attempts; L3 only exposes read tools for standard employees; admins get write tools. Metrics feed a SOC dashboard of blocked jailbreaks per day.</p><p><strong>Fintech support agent</strong> &#8212; Session memory keeps the last N turns for continuity, but L4 length limits stop paste-bomb cost attacks. Output filter redacts accidental <code>sk-</code> / <code>Bearer</code> leakage from tool-assisted answers before they hit the customer channel.</p><h2><strong>Looking Ahead</strong></h2><ul><li><p><strong>Enables next lesson</strong> &#8212; Day 2 turns the L3 registry into a validated execution engine while keeping L4 and L2 intact.</p></li><li><p><strong>Module progression</strong> &#8212; Day 1 perimeter &#8594; Day 2 tools &#8594; later durability, evaluation, and multi-agent patterns.</p></li><li><p><strong>Architectural evolution</strong> &#8212; today&#8217;s in-memory metrics and session store become shared infrastructure; the layer boundaries remain the stable API of the agent kernel.</p></li></ul><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Lesson 94–95: Capstone Project — VAIA Submission & Defense]]></title><description><![CDATA[Highlights]]></description><link>https://aiamastery.substack.com/p/lesson-9495-capstone-project-vaia</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-9495-capstone-project-vaia</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Mon, 27 Jul 2026 05:30:14 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!wueP!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Highlights</h2><p>The final lesson in the 90-lesson VAIA curriculum transforms your completed system into a <strong>defensible, auditable, production-grade artifact</strong>. You build a submission package that a technical review board can run, inspect, and score &#8212; and you prepare a live defense demonstrating operational excellence under adversarial questioning.</p><p><strong>What we build:</strong></p><ul><li><p>A <code>SubmissionPackageBuilder</code> that assembles all lesson exports (L1&#8211;L93) into a SHA-256 hash-chained archive with integrity manifests</p></li><li><p>A <code>DefenseReadinessReport</code> auto-generated from runtime metrics, evaluation gate logs, and compliance audit store entries</p></li><li><p>A <code>LiveDemoHarness</code> &#8212; a React dashboard wired to your running VAIA backend that executes deterministic scenario playbooks during the live defense</p></li><li><p>A <code>ProductionReadinessAttestation</code> signed by the evaluation gate (faithfulness &#8805; 0.85, latency p99 &#8804; 2 s, zero critical compliance violations)</p></li><li><p>A <code>PeerReviewScorecard</code> framework for structured technical peer assessment</p></li></ul><div><hr></div><h2>Connection to L91&#8211;L93</h2><p>L91&#8211;L93 produced your fully integrated VAIA: orchestrated agents, MLOps pipeline, compliance audit store (append-only, hash-chained SQLite WAL), and an evaluation gate that blocks deployment until thresholds pass. Every component you built there is an <strong>input</strong> here &#8212; not as source files to copy, but as live services the submission package queries, validates, and packages.</p><p>The <code>CapstoneProjectManifest</code> from L90, instantiated in L91&#8211;L93 as a running system, now becomes the <strong>root hash</strong> of the submission package&#8217;s integrity chain. Nothing is re-implemented; everything is verified and documented.</p><div><hr></div><h2>Architecture Context</h2><p>This lesson sits at the <strong>apex of the dependency graph</strong> spanning all 90 lessons. The submission package is not a zip of source files &#8212; it is a reproducible artifact: a Docker Compose stack that, when started on a clean machine, boots the full VAIA, runs the integration test suite, regenerates the <code>DefenseReadinessReport</code>, and serves the <code>LiveDemoHarness</code> on port 3000.</p><p>The defense itself follows a <strong>three-phase FSM</strong>: <code>PREPARATION &#8594; LIVE_DEMO &#8594; ADVERSARIAL_QA</code>. State transitions are gated by the peer review panel&#8217;s explicit approval signals, logged to the audit store, and included in the final submission archive.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!wueP!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!wueP!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png 424w, /__u/substackcdn.com/image/fetch/$s_!wueP!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png 848w, /__u/substackcdn.com/image/fetch/$s_!wueP!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png 1272w, /__u/substackcdn.com/image/fetch/$s_!wueP!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!wueP!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png" width="1456" height="923" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:923,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1029023,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/203795274?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!wueP!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png 424w, /__u/substackcdn.com/image/fetch/$s_!wueP!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png 848w, /__u/substackcdn.com/image/fetch/$s_!wueP!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png 1272w, /__u/substackcdn.com/image/fetch/$s_!wueP!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4c647421-760c-4249-aac4-10918b1bcd25_4510x2860.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><strong>What&#8217;s Next</strong></p><p>The Vertical AI Agents course is complete &#8212; 95 lessons, 6 modules, from API fundamentals to enterprise multi-modal deployment.</p><p>The <strong>Hands On AI Agent Mastery</strong> 30-day course starts <strong>Tuesday, August 4</strong>.</p><p>Days 1-7 are free. Day 1 drops August 4.</p><p>Curriculum preview &#8594;<a href="/__u/aiamastery.substack.com/p/production-ai-engineering-building">https://aiamastery.substack.com/p/production-ai-engineering-building</a></p><p>Subscribe to get Day 1 &#8594; <a href="/__u/aiamastery.substack.com/subscribe">https://aiamastery.substack.com/subscribe</a></p>
      <p>
          <a href="/__u/aiamastery.substack.com/p/lesson-9495-capstone-project-vaia">
              Read more
          </a>
      </p>
   ]]></content:encoded></item><item><title><![CDATA[Lesson 91 - 93: Capstone Project — VAIA Development]]></title><description><![CDATA[Highlights]]></description><link>https://aiamastery.substack.com/p/lesson-91-93-capstone-project-vaia</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-91-93-capstone-project-vaia</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Fri, 24 Jul 2026 05:30:22 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!4VJP!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Highlights</h2><p>Three focused sprint lessons converting the L90 <code>CapstoneProjectManifest</code> into a running production system. By the end of L93 you will have shipped:</p><ul><li><p><strong>VAIAOrchestrator</strong>: a finite-state-machine agent backed by CrewAI, wired to a Gemini 2.0 Flash reasoning core</p></li><li><p><strong>RAG Pipeline</strong>: ChromaDB vector store with Gemini embedding ingestion, retrieval, and faithfulness gating</p></li><li><p><strong>Compliance Audit Store</strong>: append-only SQLite WAL with SHA-256 hash-chaining (the L79 pattern applied end-to-end)</p></li><li><p><strong>Evaluation Gate</strong>: Ragas + Evidently metrics gating every promotion; system self-blocks if faithfulness drops below 0.85</p></li><li><p><strong>Live Dashboard</strong>: React 18 / Vite frontend consuming WebSocket streams from FastAPI, showing FSM state, metrics, and audit events in real time</p></li></ul><h2>Connection to L90</h2><blockquote><p>L90 produced a <code>CapstoneProjectManifest</code> &#8212; a hash-chained JSON document containing weighted feasibility scores, a chosen topology template, and a <code>RequirementsTraceabilityMatrix</code> linking 89 lessons&#8217; exported components. L91-L93 treats that manifest as a <strong>bootstrap contract</strong>: <code>setup.sh</code> reads the manifest SHA-256 hash on startup and refuses to proceed if the chain is broken. Every architectural decision made here traces back to a manifest entry.</p></blockquote><h2>Enables L94-L95</h2><blockquote><p>L94-L95 requires a live, defensible system. Everything built here is instrumented to generate the submission artifact set: audit trail export, metric report, ADR corpus, and a <code>LiveDemoEndpoint</code> the panel can hit during the defense.</p></blockquote><div><hr></div><h2>Architecture Context</h2><p>L91-L93 sits at the integration apex of the 90-lesson path. Earlier modules supplied individual components:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!BMDQ!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F716fefa5-d205-4735-b779-df0141a802f1_872x620.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!BMDQ!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F716fefa5-d205-4735-b779-df0141a802f1_872x620.png 424w, /__u/substackcdn.com/image/fetch/$s_!BMDQ!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F716fefa5-d205-4735-b779-df0141a802f1_872x620.png 848w, /__u/substackcdn.com/image/fetch/$s_!BMDQ!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F716fefa5-d205-4735-b779-df0141a802f1_872x620.png 1272w, /__u/substackcdn.com/image/fetch/$s_!BMDQ!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F716fefa5-d205-4735-b779-df0141a802f1_872x620.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!BMDQ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F716fefa5-d205-4735-b779-df0141a802f1_872x620.png" width="872" height="620" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/716fefa5-d205-4735-b779-df0141a802f1_872x620.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:620,&quot;width&quot;:872,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:89607,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/203676871?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F716fefa5-d205-4735-b779-df0141a802f1_872x620.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!BMDQ!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F716fefa5-d205-4735-b779-df0141a802f1_872x620.png 424w, /__u/substackcdn.com/image/fetch/$s_!BMDQ!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F716fefa5-d205-4735-b779-df0141a802f1_872x620.png 848w, /__u/substackcdn.com/image/fetch/$s_!BMDQ!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F716fefa5-d205-4735-b779-df0141a802f1_872x620.png 1272w, /__u/substackcdn.com/image/fetch/$s_!BMDQ!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F716fefa5-d205-4735-b779-df0141a802f1_872x620.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>The topology chosen from L90&#8217;s five templates drives the wiring in this lesson. The reference implementation uses <strong>Template 3: RAG-Augmented Reasoning Agent</strong> &#8212; single orchestrator, retrieval sub-agent, compliance middleware, evaluation gate, observability sidecar.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!4VJP!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!4VJP!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png 424w, /__u/substackcdn.com/image/fetch/$s_!4VJP!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png 848w, /__u/substackcdn.com/image/fetch/$s_!4VJP!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png 1272w, /__u/substackcdn.com/image/fetch/$s_!4VJP!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!4VJP!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png" width="1456" height="946" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:946,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:793843,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/203676871?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!4VJP!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png 424w, /__u/substackcdn.com/image/fetch/$s_!4VJP!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png 848w, /__u/substackcdn.com/image/fetch/$s_!4VJP!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png 1272w, /__u/substackcdn.com/image/fetch/$s_!4VJP!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F96133efd-e660-44a1-8fb9-03b7fe269abc_4400x2860.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div>
      <p>
          <a href="/__u/aiamastery.substack.com/p/lesson-91-93-capstone-project-vaia">
              Read more
          </a>
      </p>
   ]]></content:encoded></item><item><title><![CDATA[Lesson 90: Capstone Project — VAIA Scoping]]></title><description><![CDATA[Highlights]]></description><link>https://aiamastery.substack.com/p/lesson-90-capstone-project-vaia-scoping</link><guid isPermaLink="false">https://aiamastery.substack.com/p/lesson-90-capstone-project-vaia-scoping</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Tue, 21 Jul 2026 05:30:22 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!4uyJ!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Highlights</h2><p><strong>What We Build</strong></p><ul><li><p>An interactive <strong>Capstone Scoping Workbench</strong> &#8212; a React dashboard backed by FastAPI that guides you through structured domain selection, requirements elicitation, architecture pattern matching, and risk qualification, producing a machine-readable <code>CapstoneProjectManifest</code> JSON consumed directly by the L91&#8211;L93 development sprint.</p></li><li><p>A <code>CapstoneFeasibilityValidator</code> that calls Gemini 2.0 Flash to score your proposed vertical against eight production-readiness criteria (data availability, regulatory burden, latency tolerance, LLM dependency surface, and four more) and outputs a numeric feasibility matrix.</p></li><li><p>A <code>CapstoneRequirementsMatrix</code> &#8212; a structured JSON artifact that maps every functional requirement to the specific VAIA lesson (L1&#8211;L89) whose implementation pattern satisfies it, creating an explicit curriculum-to-capstone traceability index.</p></li><li><p>A <code>CapstoneArchitectureBlueprint</code> generator that uses your requirements matrix to recommend one of five validated architecture topologies (single-agent RAG, multi-agent orchestration, hybrid FSM+RAG, compliance-hardened, or streaming pipeline) with component-level justifications.</p></li><li><p>A complete <code>setup.sh</code> that consumes the <code>LegalReportRenderer</code> output format from L86 to generate your first scope document draft, closing the curriculum loop.</p></li></ul><p><strong>Connection to L89 &#8212; Presenting &amp; Defending Agent Architectures</strong> L89 built the <code>ArchitecturePresentationEngine</code> and <code>StakeholderAdaptationLayer</code> &#8212; the communication scaffolding for defending technical choices to mixed audiences. L90 consumes those patterns in reverse: the Scoping Workbench uses the same stakeholder taxonomy to produce scope documentation that will survive stakeholder review without revision. The <code>SlideNarrativeGenerator</code> output format from L89 becomes the prose template for the <code>CapstoneScopeDocument</code>&#8216;s executive summary section.</p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><p><strong>Enables L91&#8211;L93 &#8212; Capstone Development</strong> Every artifact produced in this lesson is a direct build input for the development sprint. The <code>CapstoneProjectManifest</code> carries dependency declarations, component scaffolding targets, and acceptance criteria in a format the L91 scaffolding script reads at boot time to generate the correct directory tree, Docker Compose topology, and CI pipeline.</p><div><hr></div><h2>Architecture Context</h2><p><strong>Place in the 90-Lesson VAIA Path</strong> L90 sits at the curriculum&#8217;s inflection point &#8212; the last lesson whose primary output is a <em>plan</em> rather than a <em>system</em>. Lessons L1&#8211;L89 built individual VAIA components: RAG pipelines (L18&#8211;L25), multi-agent orchestration (L46&#8211;L60), MLOps (L61&#8211;L75), compliance hardening (L79&#8211;L82), and vertical case studies in finance, healthcare, and legal (L84&#8211;L86). L90&#8217;s job is to assemble the <em>minimum viable selection</em> from that catalog into a coherent, scoped, feasible project brief that fits a 3-lesson (L91&#8211;L93) sprint.</p><p><strong>Integration With Prior Components</strong> The scoping workbench explicitly references five prior implementation patterns by import path, not by documentation link. This is intentional: it forces the scope document to stay grounded in what was actually built.</p><p><strong>Module Objectives Alignment</strong> Module 10&#8217;s goal is not to build a new component &#8212; it is to demonstrate <em>architectural judgment</em>: the ability to scope a greenfield VAIA project from first principles, apply the curriculum&#8217;s patterns appropriately, and produce a plan that a senior engineer could execute without ambiguity.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!4uyJ!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!4uyJ!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png 424w, /__u/substackcdn.com/image/fetch/$s_!4uyJ!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png 848w, /__u/substackcdn.com/image/fetch/$s_!4uyJ!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png 1272w, /__u/substackcdn.com/image/fetch/$s_!4uyJ!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!4uyJ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png" width="1456" height="946" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:946,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:928287,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/203535843?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!4uyJ!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png 424w, /__u/substackcdn.com/image/fetch/$s_!4uyJ!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png 848w, /__u/substackcdn.com/image/fetch/$s_!4uyJ!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png 1272w, /__u/substackcdn.com/image/fetch/$s_!4uyJ!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F7f26887f-2781-4805-80b2-16d69a620777_4400x2860.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><div><hr></div><h2>Core Concepts</h2><h3>1. Scope as Architecture Constraint</h3><p>The most expensive architectural decisions in a VAIA project are made implicitly during scoping &#8212; before a line of code exists. Choosing a vertical (legal, healthcare, financial, logistics) determines your regulatory surface. Choosing your primary user persona determines latency tolerance. Choosing your data sources determines whether you need a RAG pipeline, a fine-tuned adapter, or a hybrid. Each choice eliminates roughly 60% of the architecture space. Scoping is not documentation &#8212; it is architecture.</p><p>A production VAIA scope document must answer five questions deterministically:</p><ol><li><p><strong>Vertical boundary</strong>: What domain knowledge is in-scope vs. out-of-scope for the agent?</p></li><li><p><strong>Regulatory surface</strong>: Which compliance frameworks apply, and what do they mandate technically?</p></li><li><p><strong>Data topology</strong>: What does the agent retrieve, and from where?</p></li><li><p><strong>LLM dependency surface</strong>: Which decisions are LLM-generated vs. deterministic?</p></li><li><p><strong>Failure modes</strong>: What is the highest-consequence failure, and how does the architecture prevent it?</p></li></ol><h3>2. The Feasibility Matrix</h3><p>Not every VAIA idea is buildable in a 3-lesson sprint. The <code>CapstoneFeasibilityValidator</code> applies a weighted scoring model across eight dimensions:</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!UtXZ!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2c224f93-5666-424d-b65d-1f1d9f7c9664_652x377.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!UtXZ!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2c224f93-5666-424d-b65d-1f1d9f7c9664_652x377.png 424w, /__u/substackcdn.com/image/fetch/$s_!UtXZ!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2c224f93-5666-424d-b65d-1f1d9f7c9664_652x377.png 848w, /__u/substackcdn.com/image/fetch/$s_!UtXZ!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2c224f93-5666-424d-b65d-1f1d9f7c9664_652x377.png 1272w, /__u/substackcdn.com/image/fetch/$s_!UtXZ!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2c224f93-5666-424d-b65d-1f1d9f7c9664_652x377.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!UtXZ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2c224f93-5666-424d-b65d-1f1d9f7c9664_652x377.png" width="652" height="377" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/2c224f93-5666-424d-b65d-1f1d9f7c9664_652x377.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:377,&quot;width&quot;:652,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:64625,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/203535843?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2c224f93-5666-424d-b65d-1f1d9f7c9664_652x377.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!UtXZ!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2c224f93-5666-424d-b65d-1f1d9f7c9664_652x377.png 424w, /__u/substackcdn.com/image/fetch/$s_!UtXZ!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2c224f93-5666-424d-b65d-1f1d9f7c9664_652x377.png 848w, /__u/substackcdn.com/image/fetch/$s_!UtXZ!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2c224f93-5666-424d-b65d-1f1d9f7c9664_652x377.png 1272w, /__u/substackcdn.com/image/fetch/$s_!UtXZ!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2c224f93-5666-424d-b65d-1f1d9f7c9664_652x377.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>A weighted score &#8805; 0.72 is required to proceed. Gemini 2.0 Flash generates the rationale for each dimension score; a deterministic scorer produces the numeric output. This is the hybrid determinism pattern from L84&#8211;L86 applied to meta-level project management.</p><h3>3. Architecture Topology Selection</h3><p>Five topology templates emerged across the curriculum:</p><p><strong>Template A &#8212; Single-Agent RAG</strong>: One agent, one ChromaDB collection, one FastAPI backend. Suitable for narrow-domain Q&amp;A with deterministic retrieval. Highest feasibility for a sprint. Reference: L25.</p><p><strong>Template B &#8212; Multi-Agent Orchestration</strong>: Supervisor + specialist agents (2&#8211;4), shared message bus, SQLite WAL audit. Suitable for workflows with distinct sub-tasks. Reference: L52&#8211;L55.</p><p><strong>Template C &#8212; Hybrid FSM + RAG</strong>: Finite state machine drives agent lifecycle; RAG handles knowledge retrieval at each state. Suitable for regulated workflows with mandatory state sequencing. Reference: L82, L86.</p><p><strong>Template D &#8212; Compliance-Hardened</strong>: Template C + privilege sanitization layer + append-only hash-chained audit store + Gemini-as-judge evaluation loop. Suitable for healthcare, legal, finance verticals. Reference: L79&#8211;L86.</p><p><strong>Template E &#8212; Streaming Pipeline</strong>: Async event-driven, Redis pub/sub, WebSocket frontend, low-latency user-facing. Suitable for real-time monitoring or alerting verticals. Reference: L63, L74.</p><p>The <code>CapstoneArchitectureBlueprint</code> generator maps your requirements matrix to one of these templates and outputs a component list with explicit lesson references for each component.</p><h3>4. Traceability as a Design Invariant</h3><p>The <code>CapstoneRequirementsMatrix</code> is not a checklist &#8212; it is a dependency graph. Every functional requirement points to:</p><ul><li><p>The VAIA lesson that implements it</p></li><li><p>The named export from that lesson</p></li><li><p>The acceptance criterion that proves it works</p></li><li><p>The failure mode if it is omitted</p></li></ul><p>This structure makes the capstone defensible in exactly the way L89 trained: you can answer &#8220;why did you choose this component?&#8221; with a curriculum reference, a lesson number, and a working code pointer.</p><div><hr></div><h2>Integration</h2><p><strong>Production Architecture Fit</strong> In production VAIA deployments, scoping is a formal gate &#8212; typically a written Architecture Decision Record (ADR) reviewed by a principal engineer before any infrastructure is provisioned. The <code>CapstoneScopeDocument</code> follows ADR conventions: context, decision, consequences, and alternatives considered. This is not pedagogical overhead; it is the artifact that prevents expensive mid-sprint pivots.</p><p><strong>Enterprise Deployment Patterns</strong> Enterprise teams use three scoping anti-patterns that this lesson explicitly trains you to avoid:</p><ol><li><p><strong>Capability-first scoping</strong>: Starting with &#8220;I want to use multi-agent orchestration&#8221; rather than &#8220;I need to automate this workflow.&#8221; The <code>CapstoneFeasibilityValidator</code> blocks this by requiring a use-case description before topology selection is enabled.</p></li><li><p><strong>Optimistic data assumptions</strong>: Assuming a clean, labeled corpus exists. The feasibility matrix&#8217;s &#8220;Data availability&#8221; dimension requires you to specify your corpus construction plan at scoping time.</p></li><li><p><strong>Compliance deferral</strong>: Treating regulatory requirements as post-MVP. The scope document&#8217;s regulatory surface section is mandatory &#8212; it cannot be left blank.</p></li></ol><div><hr></div><h2>Implementation</h2><h2><strong>GitHub Link</strong></h2><p><strong><a href="https://github.com/sysdr/vertical-ai-agent-p/tree/main/lesson90/l90-capstone-scoping">https://github.com/sysdr/vertical-ai-agent-p/tree/main/lesson90/l90-capstone-scoping</a></strong></p><h3>Component Architecture</h3><pre><code><code>&#9484;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;
&#9474;                  Capstone Scoping Workbench              &#9474;
&#9474;                                                         &#9474;
&#9474;  React Dashboard (Vite + Recharts)                      &#9474;
&#9474;  &#9500;&#9472;&#9472; DomainSelector                                     &#9474;
&#9474;  &#9500;&#9472;&#9472; RequirementsElicitor                               &#9474;
&#9474;  &#9500;&#9472;&#9472; FeasibilityScorecard                               &#9474;
&#9474;  &#9500;&#9472;&#9472; TopologyRecommender                                &#9474;
&#9474;  &#9492;&#9472;&#9472; ManifestExporter                                   &#9474;
&#9474;                                                         &#9474;
&#9474;  FastAPI Backend                                        &#9474;
&#9474;  &#9500;&#9472;&#9472; CapstoneFeasibilityValidator  &#8592; Gemini 2.0 Flash   &#9474;
&#9474;  &#9500;&#9472;&#9472; CapstoneRequirementsMatrix                         &#9474;
&#9474;  &#9500;&#9472;&#9472; CapstoneArchitectureBlueprint                      &#9474;
&#9474;  &#9500;&#9472;&#9472; CapstoneScopeDocument                              &#9474;
&#9474;  &#9492;&#9472;&#9472; CapstoneProjectManifest (JSON export)              &#9474;
&#9474;                                                         &#9474;
&#9474;  Persistence: SQLite WAL (scope versions)               &#9474;
&#9474;  Integration: L86 LegalReportRenderer format            &#9474;
&#9492;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9496;</code></code></pre><p></p><h3>Control &amp; Data Flow</h3><ol><li><p>User selects vertical domain and describes the use case in natural language.</p></li><li><p><code>CapstoneFeasibilityValidator</code> calls Gemini 2.0 Flash with the use-case description + eight scoring rubrics. Gemini returns rationale; a deterministic scorer calculates weighted score.</p></li><li><p>If score &#8805; 0.72, <code>CapstoneRequirementsMatrix</code> is generated by mapping the use case to VAIA lesson exports.</p></li><li><p><code>CapstoneArchitectureBlueprint</code> reads the requirements matrix and selects an architecture topology.</p></li><li><p><code>CapstoneScopeDocument</code> assembles the executive summary (using L89 prose template), technical plan, and risk register.</p></li><li><p><code>CapstoneProjectManifest</code> serializes all artifacts to a single JSON file consumed by L91 scaffolding.</p></li></ol><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!Ec-t!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff3991ab6-a725-4dc7-accb-7f3747d81ffe_4400x3080.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!Ec-t!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff3991ab6-a725-4dc7-accb-7f3747d81ffe_4400x3080.png 424w, /__u/substackcdn.com/image/fetch/$s_!Ec-t!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff3991ab6-a725-4dc7-accb-7f3747d81ffe_4400x3080.png 848w, /__u/substackcdn.com/image/fetch/$s_!Ec-t!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff3991ab6-a725-4dc7-accb-7f3747d81ffe_4400x3080.png 1272w, /__u/substackcdn.com/image/fetch/$s_!Ec-t!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff3991ab6-a725-4dc7-accb-7f3747d81ffe_4400x3080.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!Ec-t!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff3991ab6-a725-4dc7-accb-7f3747d81ffe_4400x3080.png" width="1456" height="1019" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f3991ab6-a725-4dc7-accb-7f3747d81ffe_4400x3080.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1019,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:974726,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/203535843?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff3991ab6-a725-4dc7-accb-7f3747d81ffe_4400x3080.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!Ec-t!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff3991ab6-a725-4dc7-accb-7f3747d81ffe_4400x3080.png 424w, /__u/substackcdn.com/image/fetch/$s_!Ec-t!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff3991ab6-a725-4dc7-accb-7f3747d81ffe_4400x3080.png 848w, /__u/substackcdn.com/image/fetch/$s_!Ec-t!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff3991ab6-a725-4dc7-accb-7f3747d81ffe_4400x3080.png 1272w, /__u/substackcdn.com/image/fetch/$s_!Ec-t!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff3991ab6-a725-4dc7-accb-7f3747d81ffe_4400x3080.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><h3>State Machine</h3><p>The scoping workbench is explicitly stateful &#8212; users cannot jump to step 4 without completing steps 1&#8211;3. This enforces the dependency invariant: architecture selection is downstream of feasibility validation.</p><pre><code><code>IDLE &#8594; DOMAIN_DEFINED &#8594; USE_CASE_DESCRIBED &#8594; FEASIBILITY_SCORED &#8594;
REQUIREMENTS_MAPPED &#8594; BLUEPRINT_GENERATED &#8594; SCOPE_DRAFTED &#8594; MANIFEST_EXPORTED</code></code></pre><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!SQWz!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2a918390-bd86-40c7-916b-30b2ea8bb688_4400x2640.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!SQWz!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2a918390-bd86-40c7-916b-30b2ea8bb688_4400x2640.png 424w, /__u/substackcdn.com/image/fetch/$s_!SQWz!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2a918390-bd86-40c7-916b-30b2ea8bb688_4400x2640.png 848w, /__u/substackcdn.com/image/fetch/$s_!SQWz!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2a918390-bd86-40c7-916b-30b2ea8bb688_4400x2640.png 1272w, /__u/substackcdn.com/image/fetch/$s_!SQWz!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2a918390-bd86-40c7-916b-30b2ea8bb688_4400x2640.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!SQWz!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2a918390-bd86-40c7-916b-30b2ea8bb688_4400x2640.png" width="1456" height="874" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/2a918390-bd86-40c7-916b-30b2ea8bb688_4400x2640.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:874,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:720458,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/203535843?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2a918390-bd86-40c7-916b-30b2ea8bb688_4400x2640.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!SQWz!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2a918390-bd86-40c7-916b-30b2ea8bb688_4400x2640.png 424w, /__u/substackcdn.com/image/fetch/$s_!SQWz!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2a918390-bd86-40c7-916b-30b2ea8bb688_4400x2640.png 848w, /__u/substackcdn.com/image/fetch/$s_!SQWz!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2a918390-bd86-40c7-916b-30b2ea8bb688_4400x2640.png 1272w, /__u/substackcdn.com/image/fetch/$s_!SQWz!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2a918390-bd86-40c7-916b-30b2ea8bb688_4400x2640.png 1456w" sizes="100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><div><hr></div><h2>Coding Highlights</h2><h3><code>CapstoneFeasibilityValidator</code> &#8212; Hybrid Determinism Pattern</h3><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;50fa5574-cc8d-49a9-9dbb-a5bec781aa9e&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python"># backend/capstone_feasibility_validator.py
import google.generativeai as genai
from dataclasses import dataclass
from typing import Dict

WEIGHTS = {
    "data_availability": 0.20,
    "regulatory_clarity": 0.15,
    "latency_tolerance": 0.10,
    "llm_dependency": 0.15,
    "integration_complexity": 0.15,
    "testing_surface": 0.10,
    "curriculum_coverage": 0.10,
    "novelty_risk": 0.05,
}

THRESHOLD = 0.72

@dataclass
class FeasibilityResult:
    scores: Dict[str, float]        # deterministic, 0.0&#8211;1.0 per dimension
    rationales: Dict[str, str]      # LLM-generated prose per dimension
    weighted_score: float           # deterministic aggregate
    proceed: bool                   # deterministic gate
    blocking_dimensions: list       # dimensions scoring &lt; 0.5

async def validate_feasibility(use_case: str, domain: str) -&gt; FeasibilityResult:
    model = genai.GenerativeModel("gemini-2.0-flash")

    prompt = f"""You are evaluating a VAIA capstone project proposal.
Domain: {domain}
Use Case: {use_case}

Score each dimension from 0.0 to 1.0 and provide a one-sentence rationale.
Return ONLY valid JSON with keys matching these dimensions:
{list(WEIGHTS.keys())}
Format: {{"dimension": {{"score": 0.0, "rationale": "..."}}}}"""

    response = await model.generate_content_async(prompt)
    raw = response.text.strip().removeprefix("```json").removesuffix("```")
    parsed = json.loads(raw)

    scores = {k: float(parsed[k]["score"]) for k in WEIGHTS}
    rationales = {k: parsed[k]["rationale"] for k in WEIGHTS}
    weighted = sum(scores[k] * WEIGHTS[k] for k in WEIGHTS)

    return FeasibilityResult(
        scores=scores,
        rationales=rationales,
        weighted_score=round(weighted, 4),
        proceed=weighted &gt;= THRESHOLD,
        blocking_dimensions=[k for k, v in scores.items() if v &lt; 0.5],
    )</code></pre></div><p><strong>Key pattern</strong>: Gemini generates rationale <em>text</em>; the numeric score is extracted from a structured JSON field and the weighted aggregate is computed deterministically in Python. No LLM involvement in the pass/fail decision. This is the same hybrid determinism applied in L84&#8217;s red-teaming scorer and L86&#8217;s contract clause extractor.</p><h3><code>CapstoneRequirementsMatrix</code> &#8212; Curriculum Traceability</h3><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;31739507-bf43-4c1d-bc7b-65cfa6f7f820&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python"># backend/capstone_requirements_matrix.py
LESSON_EXPORT_CATALOG = {
    "RAG pipeline": {"lesson": 25, "export": "AgenticRAGPipeline"},
    "Multi-agent orchestration": {"lesson": 52, "export": "AgentOrchestrator"},
    "Compliance audit store": {"lesson": 79, "export": "GovernanceComplianceOrchestrator"},
    "Bias mitigation": {"lesson": 81, "export": "BiasDetectionMitigationAgent"},
    "LLM evaluation": {"lesson": 60, "export": "MultiAgentSystemEvaluator"},
    "Fine-tuning adapter": {"lesson": 77, "export": "LoRAAdapterTrainer"},
    "Reward alignment": {"lesson": 82, "export": "RewardAlignmentEngine"},
    "Streaming frontend": {"lesson": 74, "export": "StreamingMetricsDashboard"},
}

def build_requirements_matrix(requirements: list[str]) -&gt; dict:
    """Maps each requirement to a lesson export and acceptance criterion."""
    matrix = {}
    for req in requirements:
        for pattern, ref in LESSON_EXPORT_CATALOG.items():
            if pattern.lower() in req.lower():
                matrix[req] = {
                    **ref,
                    "acceptance_criterion": f"Import {ref['export']} from L{ref['lesson']} passes integration test",
                    "failure_mode": f"Missing {ref['export']} causes silent capability degradation"
                }
    return matrix</code></pre></div><h3><code>CapstoneProjectManifest</code> &#8212; Machine-Readable Export</h3><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;python&quot;,&quot;nodeId&quot;:&quot;11b8cc3e-caee-4790-81b7-56c0586269e9&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-python"># backend/capstone_project_manifest.py
import json, hashlib, datetime

def export_manifest(
    scope: dict,
    requirements_matrix: dict,
    blueprint: dict,
    feasibility: dict
) -&gt; dict:
    payload = {
        "schema_version": "1.0",
        "generated_at": datetime.datetime.utcnow().isoformat(),
        "curriculum_lesson": 90,
        "capstone_vertical": scope["domain"],
        "use_case": scope["use_case"],
        "feasibility": feasibility,
        "requirements": requirements_matrix,
        "architecture_blueprint": blueprint,
        "component_scaffold_targets": [
            v["export"] for v in requirements_matrix.values()
        ],
        "l91_bootstrap_instructions": {
            "topology": blueprint["selected_template"],
            "entry_lesson_imports": list(requirements_matrix.values()),
            "acceptance_criteria": [v["acceptance_criterion"] for v in requirements_matrix.values()],
        }
    }
    payload["manifest_hash"] = hashlib.sha256(
        json.dumps(payload, sort_keys=True).encode()
    ).hexdigest()
    return payload</code></pre></div><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:&quot;11b8cc3e-caee-4790-81b7-56c0586269e9&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">The manifest_hash field enables the L91 scaffolding script to verify manifest integrity before generating the project directory. Same hash-chain pattern used in L79&#8217;s audit store.</code></pre></div><div><hr></div><h2>Validation</h2><p><strong>Feasibility Gate</strong>: Run <code>pytest tests/test_feasibility.py</code> &#8212; asserts that a well-specified use case scores &#8805; 0.72 and a deliberately vague use case scores &lt; 0.72.</p><p><strong>Requirements Coverage</strong>: Run <code>pytest tests/test_requirements_matrix.py</code> &#8212; asserts that every requirement maps to a lesson number in range [1, 89] with a non-null export name.</p><p><strong>Manifest Integrity</strong>: Run <code>pytest tests/test_manifest.py</code> &#8212; asserts that <code>manifest_hash</code> matches the re-computed hash of the manifest body (tamper-evidence check from L79 pattern).</p><p><strong>Frontend Progression</strong>: Cypress E2E test confirms that the &#8220;Generate Blueprint&#8221; button is disabled until feasibility score is displayed &#8212; verifying the state machine&#8217;s gate invariant.</p><p><strong>Success Criteria</strong>:</p><ul><li><p>Feasibility validator produces a score in [0.0, 1.0] for any valid input</p></li><li><p>Requirements matrix covers &#8805; 80% of stated functional requirements</p></li><li><p>Blueprint selects exactly one topology template with &#8805; 3 component justifications</p></li><li><p>Manifest passes hash integrity check</p></li><li><p>Scope document is &#8805; 600 words and includes all five mandatory sections</p></li></ul><div><hr></div><h2>Assignment</h2><p><strong>Extend the Feasibility Validator with Domain-Specific Weight Profiles</strong></p><p>The default feasibility weight vector is domain-agnostic. For regulated verticals (healthcare, legal, finance), the &#8220;regulatory clarity&#8221; dimension should carry more weight; for real-time monitoring verticals, &#8220;latency tolerance&#8221; is more critical.</p><p>Implement a <code>DomainWeightProfile</code> that:</p><ol><li><p>Takes the selected domain as input</p></li><li><p>Returns a domain-adjusted weight vector (must still sum to 1.0)</p></li><li><p>Passes a parametric test that confirms weight sums to 1.0 for all supported domains</p></li><li><p>Stores the weight profile used in the <code>CapstoneProjectManifest</code> so the L91 scaffolding knows which feasibility model was applied</p></li></ol><p>This directly builds toward L91: the development sprint will reference the manifest&#8217;s weight profile to determine which compliance components to scaffold by default.</p><div><hr></div><h2>Solution Hints</h2><ul><li><p>The weight vector must sum to 1.0 after domain adjustment. Use a normalization step: divide each adjusted weight by the sum of all adjusted weights.</p></li><li><p>Test with at least three domains: a regulated vertical (e.g., &#8220;healthcare&#8221;), a real-time vertical (e.g., &#8220;infrastructure monitoring&#8221;), and a general-purpose vertical (e.g., &#8220;customer support&#8221;).</p></li><li><p>The <code>manifest_hash</code> must be recomputed after weight profile injection, or your integrity check will fail.</p></li><li><p>Gemini&#8217;s score output is a float in the model&#8217;s JSON &#8212; validate it against <code>[0.0, 1.0]</code> with a Pydantic validator before passing it to the deterministic scorer to prevent injection of out-of-range values.</p></li></ul><div><hr></div><h2>Looking Ahead</h2><p><strong>How This Enables L91&#8211;L93</strong> The <code>CapstoneProjectManifest</code> is the single artifact that drives all three development lessons. L91 reads <code>l91_bootstrap_instructions.topology</code> to generate the project directory structure. L92 reads <code>component_scaffold_targets</code> to know which lesson exports to wire together. L93 reads <code>acceptance_criteria</code> to parameterize the final test suite.</p><p>Without a validated manifest from L90, the L91 scaffolding script cannot run. This is not a soft dependency &#8212; it is a hard boot-time check. This mirrors how production ML systems treat experiment configs: no config, no run.</p><p><strong>Module Progress</strong> With L90 complete, Module 10 has delivered its first milestone: a validated, machine-readable project plan that bridges 89 lessons of component-building into a coherent final system. L91&#8211;L93 will be the proof: every component reference in the manifest is a link back to something you built, and the capstone is the sum of that work.</p><p>You have now scoped, designed, and defended a production VAIA system. Build it.</p><h3>Youtube link</h3><div id="youtube2-XoGp_Gyj_J8" class="youtube-wrap" data-attrs="{&quot;videoId&quot;:&quot;XoGp_Gyj_J8&quot;,&quot;startTime&quot;:null,&quot;endTime&quot;:null}" data-component-name="Youtube2ToDOM"><div class="youtube-inner"><iframe src="https://www.youtube-nocookie.com/embed/XoGp_Gyj_J8?rel=0&amp;autoplay=0&amp;showinfo=0&amp;enablejsapi=0" frameborder="0" loading="lazy" gesture="media" allow="autoplay; fullscreen" allowautoplay="true" allowfullscreen="true" width="728" height="409"></iframe></div></div><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item><item><title><![CDATA[Production AI Engineering: Building Enterprise-Grade AI Agents]]></title><description><![CDATA[Most AI agent tutorials stop at &#8220;it responds to a prompt.&#8221; This course starts where they stop.]]></description><link>https://aiamastery.substack.com/p/production-ai-engineering-building</link><guid isPermaLink="false">https://aiamastery.substack.com/p/production-ai-engineering-building</guid><dc:creator><![CDATA[AI Roadmap]]></dc:creator><pubDate>Tue, 21 Jul 2026 05:30:08 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!rM8n!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most AI agent tutorials stop at &#8220;it responds to a prompt.&#8221; This course starts where they stop.</p><blockquote><p>You will engineer a system that blocks prompt injection in under 5ms, compresses context by 60% before the LLM call, detects its own quality regressions and improves automatically, scales on Kubernetes from zero to ten replicas without dropping a request, passes a SOC 2 audit, and handles a regional cloud outage in under 30 minutes &#8212; without human intervention.</p></blockquote><blockquote><p>The five agents you ship in the capstone are portfolio-ready. They demonstrate the layer of AI engineering that enterprise teams actually pay for &#8212; and that no LangChain tutorial has ever covered.</p></blockquote><p><strong>30 Lessons. 4 Modules. 5 Production Agents. Starts August 4, 2026.</strong> </p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div><p><em><strong>Explore Lessons 1&#8211;7: Secure Agent Foundations. Continue your journey through the complete Production AI Engineering.</strong></em></p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="/__u/substackcdn.com/image/fetch/$s_!rM8n!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="/__u/substackcdn.com/image/fetch/$s_!rM8n!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png 424w, /__u/substackcdn.com/image/fetch/$s_!rM8n!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png 848w, /__u/substackcdn.com/image/fetch/$s_!rM8n!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png 1272w, /__u/substackcdn.com/image/fetch/$s_!rM8n!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_webp, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png 1456w" sizes="100vw"><img src="/__u/substackcdn.com/image/fetch/$s_!rM8n!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png" width="1456" height="910" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:910,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1781435,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://aiamastery.substack.com/i/206022658?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="/__u/substackcdn.com/image/fetch/$s_!rM8n!, /__u/aiamastery.substack.com/w_424, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png 424w, /__u/substackcdn.com/image/fetch/$s_!rM8n!, /__u/aiamastery.substack.com/w_848, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png 848w, /__u/substackcdn.com/image/fetch/$s_!rM8n!, /__u/aiamastery.substack.com/w_1272, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png 1272w, /__u/substackcdn.com/image/fetch/$s_!rM8n!, /__u/aiamastery.substack.com/w_1456, /__u/aiamastery.substack.com/c_limit, /__u/aiamastery.substack.com/f_auto, /__u/aiamastery.substack.com/q_auto:good, /__u/aiamastery.substack.com/fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F296ac714-134d-465b-aa86-d72d94fac1a9_8000x5000.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container restack-image"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button tabindex="0" type="button" class="pencraft pc-reset pencraft icon-container view-image"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><div><hr></div><h2>What You Build</h2><blockquote><p>Throughout this course, you'll build five production-ready AI agents that gradually evolve into a complete enterprise AI platform. You'll engineer secure agent architectures, multi-agent collaboration, real-time streaming, self-improving LLMOps pipelines, and Kubernetes-native deployments with enterprise security, compliance, disaster recovery, and FinOps. </p><p>Every project solves a real production challenge using the same architectural patterns found in enterprise AI systems. By the end, you'll have a portfolio that demonstrates not just how to use AI&#8212;but how to engineer AI systems that organizations can confidently deploy at scale.</p></blockquote><p><strong>Agent 1 &#8212; Secure Customer Service Agent</strong> </p><p>Every Week 1 control in one request: injection blocked at Layer 4 in &lt;5ms, RBAC enforced at Layer 3, semantic cache at Layer 2 reducing token cost by 40%, output scanned for API keys and PII before delivery.</p><p><strong>Agent 2 &#8212; Multi-Agent Research System</strong> </p><p><code>SupervisorAgent</code> fans out to three parallel <code>WorkerAgent</code> instances via <code>asyncio.gather()</code>. One worker failure does not cancel the others. Total latency = slowest single worker, not the sum.</p><p><strong>Agent 3 &#8212; Streaming Analytics Agent</strong> </p><p><code>StreamingLLM</code> &#8594; SSE endpoint &#8594; <code>EventSource</code> client. First token under 500ms. The <code>X-Accel-Buffering: no</code> header that makes nginx stop buffering your stream.</p><p><strong>Agent 4 &#8212; Self-Healing LLMOps Agent</strong> </p><p><code>EvalHarness</code> blocks deploys on regression. <code>ABRouter</code> routes 10% of live traffic to a new prompt variant. <code>CircuitBreaker</code> trips after 3 failures and rejects requests in microseconds. <code>PromptOptimiser</code> runs weekly and commits winners to version control.</p><p><strong>Agent 5 &#8212; Enterprise Kubernetes Deployment</strong> </p><p>KEDA scales on <code>agent_request_queue_depth</code>, not CPU &#8212; before latency degrades, not after. SOC 2 audit trail with chain-hash tamper detection. HIPAA PHI detector blocks protected data at the perimeter. Route 53 failover completes in under 30 minutes. FinOps allocator bills teams for exactly what they consumed.</p><div><hr></div><h2>Who This Course Is For</h2><p><strong>Backend engineers</strong> who have built agents that work in demos and want to understand why they fail at scale.</p><p><strong>Platform engineers</strong> who need to deploy LLM workloads on Kubernetes with the same operational rigour as any other production service.</p><p><strong>Tech leads</strong> who own the &#8220;we need SOC 2 compliance for our AI system&#8221; conversation and need to know what to build.</p><p><strong>Founding engineers</strong> at AI startups where the next customer due diligence will ask about security architecture, compliance controls, and disaster recovery.</p><div><hr></div><h2>What Makes This Different</h2><p><strong>No frameworks until you understand the layer below.</strong> You implement the security perimeter before touching any orchestration library. You implement the token bucket before reading about rate-limiting middleware.</p><p><strong>Real numbers, not analogies.</strong> 60% token reduction from context compression. 15 percentage point accuracy gain from multi-agent debate. 67% infrastructure cost reduction from KEDA scale-to-zero. Every number comes from the lesson that demonstrates it.</p><p><strong>Failure first.</strong> Every module ends with a &#8220;what breaks without this&#8221; section. You learn the failure mode the lesson prevents before you learn how it prevents it.</p><p><strong>Production checklist on every lesson.</strong> Not &#8220;nice to have&#8221; suggestions &#8212; the specific checks that get caught in SOC 2 audits, load tests, and security reviews.</p><div><hr></div><h2>Learning Objectives</h2><p><strong>By Phase 1:</strong> You can articulate the four-layer agent security model, explain why tool calls require a five-gate validation pipeline, and deploy a secure agent base with 8-signal observability.</p><p><strong>By Phase 2:</strong> You can implement parallel multi-agent dispatch, achieve first-token-under-500ms streaming, build layered error recovery with a dead-letter queue, and reduce token costs by 60% through context compression.</p><p><strong>By Phase 3:</strong> You can build a CI quality gate that blocks deployments on regression, run statistically-valid A/B experiments on live traffic, implement a self-healing circuit breaker, and close the LLMOps feedback loop automatically.</p><p><strong>By Phase 4:</strong> You can deploy an AI agent on Kubernetes with zero-downtime rolling updates, queue-depth auto-scaling, SOC 2 audit controls, HIPAA compliance safeguards, multi-region disaster recovery, and FinOps cost allocation.</p><h2>Key Topics</h2><p><strong>Security Architecture:</strong> 4-layer enforcement model, prompt injection detection (regex + structural analysis), RBAC with role inheritance, output scanning for secrets and PHI, sandboxed subprocess execution with import allowlist.</p><p><strong>Memory &amp; Cost:</strong> Conversation buffer, semantic similarity cache (55% hit rate &#8594; 40% cost reduction), vector store for cross-session recall, four-strategy context compressor (60% token reduction), real-time Prometheus cost dashboard.</p><p><strong>Reliability Engineering:</strong> Token bucket rate limiting, four-class error taxonomy, exponential backoff with jitter, model fallback chain, dead-letter queue, three-state circuit breaker, SLOs with error budget tracking and automated runbooks.</p><p><strong>LLMOps:</strong> Evaluation harness with CI gate, A/B testing with deterministic routing and statistical significance, prompt optimisation with full audit trail, multi-agent debate (+15pp accuracy), knowledge graph for compliance-queryable relationships, full continuous improvement pipeline.</p><p><strong>Enterprise Infrastructure:</strong> Kubernetes Deployment + HPA + KEDA (queue-depth scaling, scale-to-zero), SOC 2 immutable audit trail with chain-hash tamper detection, HIPAA PHI detection and 15-minute auto-logoff, multi-region disaster recovery (RTO &lt; 30 min, RPO &lt; 5 min), FinOps cost allocation with team showback and 80%-threshold budget alerts.</p><div><hr></div><h2>Prerequisites</h2><ul><li><p>Python 3.11+</p></li><li><p>Comfortable reading and writing async Python (<code>asyncio</code>, <code>await</code>)</p></li><li><p>Basic Docker knowledge (build an image, run a container)</p></li><li><p>No prior AI/agent experience required &#8212; but familiarity with API calls helps</p></li><li><p>OpenAI API key optional &#8212; every lesson runs in stub mode without one</p></li></ul><div><hr></div><h2>Course Structure</h2><div><hr></div><h4>Phase 1 &#8212; Secure Agent Foundations</h4><p><strong>Lessons 1&#8211;7</strong></p><blockquote><p>The architecture that every production agent runs on. By Lesson 7 you have a complete, hardened agent base &#8212; security, tools, memory, rate limiting, observability, and sandboxed execution. This is the foundation Phases 2&#8211;4 build on without modification.</p></blockquote><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-1-the-4-layer-secure-agent"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 1 &#8212; The 4-Layer Secure Agent Architecture</span></a></strong></p><p>Every production agent enforces the same request path: Security Perimeter &#8594; Tool Orchestrator &#8594; Memory Manager &#8594; Core LLM. A request that fails Layer 4 never reaches Layer 1. You implement all four layers &#8212; including stubs for the ones Lessons 2&#8211;7 will fill &#8212; so the architecture is correct from Day 1. </p><p><em>Core types:</em> <code>SecurityContext</code>, <code>AgentRequest</code>, <code>AgentResponse</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-2-tool-execution-and-validation"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 2 &#8212; Tool Execution &amp; Validation</span></a></strong></p><p>Five gates, in order: registry lookup, Pydantic schema validation, RBAC permission check, sandboxed subprocess execution, output filtering. Miss gate 3 and an unpermissioned caller reaches your database tool. Miss gate 5 and your agent returns API keys in its responses. </p><p><em>Core classes:</em> <code>ToolDefinition</code>, <code>ToolOrchestrator</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-3-memory-systems"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 3 &#8212; Memory Systems &#8212; Short-Term, Semantic Cache &amp; Redis</span></a></strong></p><p>Three layers with different jobs: <code>ConversationBuffer</code> keeps the last N turns in memory. <code>SemanticCache</code> returns cached responses to near-identical queries using cosine similarity &#8212; 55% hit rate in production means 40% cost reduction without touching a single prompt. <code>RedisBackedMemory</code> persists state across restarts and enables cross-session recall. </p><p><em>Core classes:</em> <code>ConversationBuffer</code>, <code>SemanticCache</code>, <code>RedisBackedMemory</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-4-rate-limiting-and-cost-control"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 4 &#8212; Rate Limiting &amp; Cost Control</span></a></strong></p><p>The token bucket algorithm: <code>capacity</code> sets the burst ceiling, <code>refill_rate</code> sets the sustained limit. A request with a projected cost above <code>PER_REQUEST_CAP</code> is rejected before the LLM call. A user who crosses <code>DAILY_BUDGET_USD</code> is blocked until midnight. This is what prevents the $40,000 API bill. </p><p><em>Core classes:</em> <code>Bucket</code>, <code>RateLimiter</code>, <code>CostTracker</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-5-security-hardening"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 5 &#8212; Security Hardening &#8212; Secrets Scanning, HMAC Signing &amp; Output Guard</span></a></strong></p><p><code>SecretsScanner</code> detects API keys, tokens, and credentials in both inputs and outputs using pattern matching and entropy analysis. <code>HMACSigner</code> signs every tool call so tampered requests are rejected before execution. <code>OutputGuard</code> scans every response for SSNs, card numbers, and filesystem paths before the response leaves the agent. <em>Core classes:</em> <code>SecretsScanner</code>, <code>HMACSigner</code>, <code>OutputGuard</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-6-observability-stack"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 6 &#8212; Observability Stack &#8212; Metrics, Structured Logs &amp; Distributed Traces</span></a></strong></p><p>Eight production signals: four golden (traffic, latency, errors, saturation) and four AI-specific (cost per request, cache hit rate, security rejection rate, tool execution latency). Every layer boundary emits a structured JSON log line with <code>request_id</code>. Four Grafana alert rules. One <code>Telemetry</code> class that wires all three pillars. </p><p><em>Core class:</em> <code>Telemetry</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-7-sandboxed-code-execution"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 7 &#8212; Sandboxed Code Execution &#8212; Isolated, Resource-Capped &amp; Audited</span></a></strong></p><p><code>SandboxExecutor</code> spawns a subprocess, enforces <code>RLIMIT_AS</code> memory cap, kills on timeout, applies an import allowlist, and rejects any non-JSON output. <code>SandboxAuditLog</code> writes a tamper-evident record of every execution &#8212; args are hashed, never stored raw. An open import list is a filesystem deletion waiting to happen. </p><p><em>Core classes:</em> <code>SandboxPolicy</code>, <code>SandboxExecutor</code>, <code>SandboxAuditLog</code></p><div><hr></div><h4>Phase 2 &#8212; Production Integration</h4><p><strong>Lessons 8&#8211;14</strong></p><blockquote><p>Patterns that make the Phase 1 foundation scale: parallel agents, streaming, layered error recovery, token compression, and production monitoring. By Lesson 14 the agent handles real concurrent load, streams output to the browser, recovers from failures without human intervention, and has a real-time dashboard showing spend per user per minute.</p></blockquote><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-8-multi-agent-orchestration"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 8 &#8212; Multi-Agent Orchestration &#8212; The Supervisor Pattern</span></a></strong></p><p><code>SupervisorAgent</code> dispatches to N <code>WorkerAgent</code> instances via <code>asyncio.gather()</code>. Total wall-clock time = slowest worker, not the sum. A failed worker returns a <code>WorkerResult</code> with <code>success=False</code> &#8212; the supervisor logs it, excludes it from the response, and returns the rest. One worker going down does not take the request down. </p><p><em>Core classes:</em> <code>WorkerTask</code>, <code>WorkerResult</code>, <code>WorkerAgent</code>, <code>SupervisorAgent</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-9-react-loop"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 9 &#8212; ReAct Loop &#8212; Reasoning, Acting &amp; Observing</span></a></strong></p><p><code>ReActAgent</code> alternates between Thought, Action, and Observation steps until the task is complete or the step budget is exhausted. Each Action calls a real tool; each Observation feeds the result back into the next Thought. The step budget is not optional &#8212; an uncapped ReAct loop is an infinite billing event. </p><p><em>Core classes:</em> <code>ReActStep</code>, <code>ReActAgent</code>, <code>StepBudget</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-10-prompt-engineering"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 10 &#8212; Prompt Engineering &#8212; Templates, Versioning &amp; Injection-Safe Construction</span></a></strong></p><p><code>PromptTemplate</code> separates static structure from dynamic inputs, enforces variable validation before assembly, and stores a version hash so every LLM call is traceable to the exact prompt that produced it. Prompt construction is where injection enters &#8212; building prompts by string concatenation is the root cause. </p><p><em>Core classes:</em> <code>PromptTemplate</code>, <code>PromptRegistry</code>, <code>PromptVersion</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-11-structured-output"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 11 &#8212; Structured Output &#8212; Schema Enforcement &amp; Retry-on-Failure</span></a></strong></p><p><code>StructuredOutputParser</code> validates every LLM response against a Pydantic schema before it reaches application code. On a parse failure, <code>OutputRetryHandler</code> regenerates with the error message injected into the prompt &#8212; up to <code>max_retries</code> attempts. An unvalidated LLM output reaching a database write is a data corruption event, not an edge case. </p><p><em>Core classes:</em> <code>StructuredOutputParser</code>, <code>OutputRetryHandler</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-12-agent-state-machine"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 12 &#8212; Agent State Machine &#8212; Lifecycle, Transitions &amp; Persistence</span></a></strong></p><p><code>AgentStateMachine</code> enforces valid state transitions: <code>IDLE &#8594; RUNNING &#8594; WAITING_FOR_TOOL &#8594; RUNNING &#8594; COMPLETE | FAILED</code>. An invalid transition raises immediately &#8212; silent state corruption is harder to debug than a loud exception. State snapshots are persisted to Redis so a pod restart does not lose in-progress agent work. <em>Core classes:</em> <code>AgentState</code>, <code>AgentStateMachine</code>, <code>StateSnapshot</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-13-async-agent-pipeline"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 13 &#8212; Async Agent Pipeline &#8212; Concurrent Execution &amp; Backpressure</span></a></strong></p><p>Three sequential tool calls at 1,500ms become three parallel calls at 500ms &#8212; a 3&#215; latency reduction with no change to the output. <code>asyncio.gather(return_exceptions=True)</code> ensures one failed tool never cancels the others. <code>BackpressureQueue</code> rejects new requests when the in-flight count exceeds <code>MAX_CONCURRENT</code> &#8212; protecting the LLM API from overload. </p><p><em>Core classes:</em> <code>AsyncToolOrchestrator</code>, <code>BackpressureQueue</code>, <code>ToolPlan</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-14-context-window-management"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 14 &#8212; Context Window Management &#8212; Compression, Prioritisation &amp; 60% Token Reduction</span></a></strong></p><p>Four strategies, applied cheapest-first: strip tool call metadata &#8594; remove near-duplicates &#8594; truncate system prompt to 800 chars &#8594; LLM-summarise the oldest half. Most requests exit after strategy 1 or 2. Strategy 4 (the LLM call) triggers only when the others are insufficient. 60% token reduction at 10k requests/day is a meaningful monthly cost difference. </p><p><em>Core class:</em> <code>ContextCompressor</code></p><div><hr></div><h4>Phase 3 &#8212; LLMOps &amp; Advanced Orchestration</h4><p><strong>Lessons 15&#8211;21</strong></p><blockquote><p>The feedback loop that makes your agent continuously improve without human intervention. By Lesson 21 the agent blocks quality regressions in CI, runs live A/B experiments, heals from failures in milliseconds, improves its own prompt accuracy on a weekly schedule, and uses structured relationship graphs for compliance-queryable audit trails.</p></blockquote><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-15-evaluation-framework"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 15 &#8212; Evaluation Framework &#8212; Automated Quality Gates &amp; CI Integration</span></a></strong></p><p><code>EvalCase</code> defines input, <code>must_contain</code> assertions, <code>must_not_contain</code> assertions, and a <code>max_cost_usd</code> cap. <code>EvalHarness</code> runs a suite against a live agent, produces a PASS/FAIL report, and exits with code 1 &#8212; blocking the CI merge. A 5 percentage point quality regression is caught in minutes, not days. </p><p><em>Core classes:</em> <code>EvalCase</code>, <code>EvalResult</code>, <code>EvalHarness</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-16-vector-store-and-rag"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 16 &#8212; Vector Store &amp; RAG &#8212; Retrieval-Augmented Generation Pipeline</span></a></strong></p><p><code>VectorStore</code> indexes documents as dense embeddings and retrieves the top-K most semantically relevant chunks per query. <code>RAGPipeline</code> injects retrieved context into the prompt before the LLM call &#8212; grounding responses in real documents rather than parametric memory. Chunk size and overlap are tuned per corpus; wrong values silently destroy retrieval quality. </p><p><em>Core classes:</em> <code>VectorStore</code>, <code>RAGPipeline</code>, <code>ChunkConfig</code></p><p><strong><a href="/__u/aiamastery.substack.com/p/lesson-17-fine-tuning-pipeline"><span data-color="#1555e2" style="color: rgb(21, 85, 226);">Lesson 17 &#8212; Fine-Tuning Pipeline &#8212; LoRA Adapters &amp; Dataset Curation</span></a></strong></p><p><code>FineTuningPipeline</code> curates a training dataset from production traces, applies LoRA adapters to reduce GPU memory by 70% vs full fine-tuning, and validates the fine-tuned model against <code>EvalHarness</code> before promotion. A fine-tuned model that regresses on the eval suite never reaches production. </p><p><em>Core classes:</em> <code>TrainingDataset</code>, <code>LoRAConfig</code>, <code>FineTuningPipeline</code></p><p><strong>Lesson 18 &#8212; Agent Guardrails &#8212; Input Validation, Output Filtering &amp; Policy Enforcement</strong></p><p><code>GuardrailPipeline</code> runs three sequential checks: input policy (topic restrictions, length limits, PII detection), tool call policy (allowed tools per role, parameter bounds), and output policy (factual grounding score, toxicity filter, PII redaction). A request that fails any check is rejected with a structured error &#8212; not silently degraded. </p><p><em>Core classes:</em> <code>InputGuardrail</code>, <code>ToolGuardrail</code>, <code>OutputGuardrail</code>, <code>GuardrailPipeline</code></p><p><strong>Lesson 19 &#8212; Human-in-the-Loop &#8212; Approval Gates, Escalation &amp; Audit Trail</strong></p><p><code>HITLGate</code> pauses execution at configurable decision points and routes the pending action to a human reviewer via webhook. <code>EscalationPolicy</code> defines which tool calls require approval (irreversible writes, high-cost operations, regulated data access). Every approval and rejection is written to the audit log with reviewer identity and timestamp. </p><p><em>Core classes:</em> <code>HITLGate</code>, <code>EscalationPolicy</code>, <code>ReviewRecord</code></p><p><strong>Lesson 20 &#8212; Agent Persistence &#8212; State Recovery, Checkpointing &amp; Resume</strong></p><p><code>CheckpointManager</code> snapshots full agent state &#8212; conversation history, tool results, current step &#8212; to durable storage at every state transition. On restart, <code>AgentRecovery</code> replays from the last valid checkpoint rather than from scratch. A checkpoint that is never tested is an assumption, not a guarantee. </p><p><em>Core classes:</em> <code>Checkpoint</code>, <code>CheckpointManager</code>, <code>AgentRecovery</code></p><p><strong>Lesson 21 &#8212; Cost Optimisation &#8212; Model Routing, Caching &amp; Budget Enforcement</strong></p><p><code>CostRouter</code> classifies each query by complexity and routes it to the cheapest model that can satisfy the quality threshold &#8212; local SLM for simple queries, frontier model for complex ones. <code>BudgetEnforcer</code> tracks spend per user, per team, and per agent type in real time and hard-blocks requests that would breach the daily cap. </p><p><em>Core classes:</em> <code>CostRouter</code>, <code>ComplexityClassifier</code>, <code>BudgetEnforcer</code></p><div><hr></div><h4>Phase 4 &#8212; Enterprise Deployment &amp; Capstone</h4><p><strong>Lessons 22&#8211;30</strong></p><blockquote><p>Kubernetes, compliance, and five production agents. By Lesson 30 you have a deployment that a security team can audit, a compliance team can certify, and an SRE team can operate &#8212; and a portfolio of five agents that demonstrate every technique from Phases 1&#8211;3 working together.</p></blockquote><p><strong>Lesson 22 &#8212; Streaming Responses &#8212; SSE Token Pipeline &amp; Backpressure</strong></p><p><code>StreamingLLM</code> calls the LLM with <code>stream=True</code> and yields tokens as they arrive. The FastAPI route flushes every 5 tokens as an SSE <code>data:</code> frame &#8212; single-token flushes are noisy, 20-token flushes feel laggy. <code>X-Accel-Buffering: no</code> prevents nginx from holding the stream. First token under 500ms. </p><p><em>Core class:</em> <code>StreamingLLM</code></p><p><strong>Lesson 23 &#8212; Multi-Modal Agent &#8212; Vision, Audio &amp; Document Inputs</strong></p><p><code>MultiModalRouter</code> detects input type (text, image, audio, PDF) and dispatches to the correct preprocessing pipeline before the LLM call. <code>VisionTool</code> extracts structured data from images. <code>DocumentParser</code> chunks PDFs with layout awareness &#8212; splitting mid-table destroys context. One unified <code>AgentRequest</code> schema regardless of modality. </p><p><em>Core classes:</em> <code>MultiModalRouter</code>, <code>VisionTool</code>, <code>DocumentParser</code></p><p><strong>Lesson 24 &#8212; Agent Testing Patterns &#8212; Unit, Integration &amp; Load Tests</strong></p><p><code>AgentTestHarness</code> provides deterministic stub LLM responses so unit tests run without an API key and in under 1 second. <code>IntegrationTestSuite</code> spins up the full stack in Docker Compose and validates end-to-end request paths. <code>LoadTestRunner</code> (Locust) measures p95 latency and error rate under 500 concurrent users &#8212; the numbers that catch resource leaks before production. </p><p><em>Core classes:</em> <code>AgentTestHarness</code>, <code>IntegrationTestSuite</code>, <code>LoadTestRunner</code></p><p><strong>Lesson 25 &#8212; Production Deployment &#8212; Docker, Kubernetes &amp; Zero-Downtime Rollouts</strong></p><p><code>maxUnavailable: 0</code> in the rolling update strategy means zero dropped requests during deploys. <code>runAsNonRoot: true</code> eliminates an entire class of container escape impact. The readiness probe means no traffic arrives until the pod signals ready. The <code>preStop: sleep 5</code> closes the race condition between SIGTERM and the load balancer&#8217;s routing table update. <em>Artifacts:</em> <code>k8s/namespace.yaml</code>, <code>k8s/deployment.yaml</code>, <code>k8s/hpa.yaml</code>, <code>k8s/configmap.yaml</code></p><p><strong>Lesson 26 &#8212; Prompt Injection Defense &#8212; Detection, Structural Analysis &amp; Runtime Blocking</strong></p><p><code>PromptInjectionDetector</code> runs three layers in under 5ms: regex signatures for known attack patterns, structural analysis for instruction-override attempts, and anomaly scoring against the expected prompt shape. A detected injection is logged with full context and blocked before reaching the LLM &#8212; not filtered after. </p><p><em>Core classes:</em> <code>InjectionSignature</code>, <code>StructuralAnalyser</code>, <code>PromptInjectionDetector</code></p><p><strong>Lesson 27 &#8212; Agent Versioning &#8212; Artifact Tracking, Rollback &amp; Promotion Gates</strong></p><p><code>AgentVersionRegistry</code> stores every deployed agent as an immutable artifact: prompt version, model ID, tool manifest, eval suite hash, and deployment timestamp. <code>PromotionGate</code> runs the eval suite against the candidate version and blocks promotion if pass rate falls below threshold. Rolling back is a single function call &#8212; not a manual config edit. </p><p><em>Core classes:</em> <code>AgentVersion</code>, <code>AgentVersionRegistry</code>, <code>PromotionGate</code></p><p><strong>Lesson 28 &#8212; Compliance &amp; Audit Log &#8212; Immutable Records, Chain-Hash &amp; Evidence Pack</strong></p><p>Each <code>ImmutableAuditWriter</code> entry includes a <code>chain_hash</code> &#8212; the SHA-256 of the previous entry&#8217;s JSON. Modify any entry and the chain breaks. <code>generate_evidence_pack()</code> produces structured output pointing to the actual evidence: S3 bucket ARN, IAM policy document, CloudWatch alert ARNs. Auditors need pointers to real evidence, not prose descriptions. </p><p><em>Core classes:</em> <code>ImmutableAuditWriter</code> &#183; <em>Key function:</em> <code>generate_evidence_pack()</code></p><p><strong>Lesson 29 &#8212; Capacity Planning &#8212; Load Modelling, Scaling Thresholds &amp; Cost Forecasting</strong></p><p><code>CapacityModel</code> projects required replicas, token budget, and monthly API cost from three inputs: expected RPS, average tokens per request, and target p95 latency. <code>ScalingSimulator</code> replays historical traffic patterns against the model to validate thresholds before they go live. A capacity plan built on assumed traffic numbers fails the first time real traffic arrives. </p><p><em>Core classes:</em> <code>CapacityModel</code>, <code>ScalingSimulator</code>, <code>CostForecast</code></p><p><strong>Lesson 30 &#8212; Production Capstone &#8212; Five Agents, One Enterprise Platform</strong></p><p>All five agents deployed as a single production system. Agent 1 (Secure Customer Service): injection blocked in under 5ms, RBAC enforced, semantic cache active. Agent 2 (Multi-Agent Research): three parallel workers, one failure does not cascade. Agent 3 (Streaming Analytics): first token under 500ms, nginx bypass active. Agent 4 (Self-Healing LLMOps): <code>CircuitBreaker</code>, <code>EvalHarness</code>, and <code>PromptOptimiser</code> running as a closed loop. Agent 5 (Enterprise Deployment): SOC 2 audit trail, HIPAA PHI detection, KEDA queue-depth scaling, Route 53 failover tested and documented. This is the system you put in your portfolio.</p><h2><strong>Beyond the Curriculum</strong></h2><p><strong>Most AI tutorials stop once the model generates a response. Production AI Engineering begins where those tutorials end.</strong> Throughout this course, you'll learn how to build AI systems that remain secure under attack, scale under heavy traffic, recover from failures automatically, satisfy enterprise compliance requirements, and continuously improve through automated LLMOps pipelines. </p><p>Every lesson focuses on solving a real production engineering challenge using proven architectural patterns&#8212;not shortcuts or abstractions. By the final capstone, you won't just have five portfolio-ready AI agents&#8212;you'll understand how modern enterprise AI platforms are designed, operated, and trusted in production.</p><h2><strong>Ready to Build Production AI Systems?</strong></h2><p>If you&#8217;ve made it this far, you&#8217;ve already seen that this isn&#8217;t another &#8220;build an AI chatbot&#8221; course. It&#8217;s a complete roadmap to engineering secure, scalable, and enterprise-ready AI systems from the ground up.</p><p><strong>Subscribe to unlock every lesson that demonstrates real Production AI Engineering skills.</strong></p><p><strong><a href="/__u/aiamastery.substack.com/subscribe">Subscribe Now</a></strong></p><div class="subscription-widget-wrap-editor" data-attrs="{&quot;url&quot;:&quot;https://aiamastery.substack.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe&quot;,&quot;language&quot;:&quot;en&quot;}" data-component-name="SubscribeWidgetToDOM"><div class="subscription-widget show-subscribe"><div class="preamble"><p class="cta-caption">Hands On AI Agent Mastery Course  is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.</p></div><form class="subscription-widget-subscribe"><input type="email" class="email-input" name="email" placeholder="Type your email&#8230;" tabindex="-1"><input type="submit" class="button primary" value="Subscribe"><div class="fake-input-wrapper"><div class="fake-input"></div><div class="fake-button"></div></div></form></div></div>]]></content:encoded></item></channel></rss>