<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sergio Azevedo on Medium]]></title>
        <description><![CDATA[Stories by Sergio Azevedo on Medium]]></description>
        <link>https://medium.com/@sergioazevedo?source=rss-f1a998f2a5ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vhIBr_2Kta_iBFhaO2HamQ.jpeg</url>
            <title>Stories by Sergio Azevedo on Medium</title>
            <link>https://medium.com/@sergioazevedo?source=rss-f1a998f2a5ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:38:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sergioazevedo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Breaking the Deterministic Trap in RAG]]></title>
            <link>https://medium.com/@sergioazevedo/breaking-the-deterministic-trap-in-rag-3890dd002ea1?source=rss-f1a998f2a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/3890dd002ea1</guid>
            <dc:creator><![CDATA[Sergio Azevedo]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 23:15:00 GMT</pubDate>
            <atom:updated>2026-05-10T21:46:27.606Z</atom:updated>
            <content:encoded><![CDATA[<p>My ‘Hybrid’ RAG approach was supposed to save tokens and latency. Instead, it created a deterministic trap that frustrated users. Here is why I moved to Pure Agentic RAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4D4PM2E-9fAmKMjC" /></figure><p>I used to be a firm advocate for the “Hybrid” RAG compromise.</p><p>When I first transitioned my meal planner from a static “Push” model to an autonomous “Pull” model (as I wrote in <a href="https://sergioazevedo.me/from-push-to-pull-giving-my-ai-agents-agency">From Push to Pull</a>), I was worried about the “cold start” problem. I didn’t want my agents to sit there “thinking” for an extra turn every single time they needed a recipe. So, I implemented a compromise: I would <strong>Push</strong> a small, high-confidence set of recipes (10 items) based on the user’s initial query, and only let the agent <strong>Pull</strong> more if those weren’t enough.</p><p>It felt like a smart engineering trade-off. It saved latency. It saved tokens. <strong>And it was a complete failure for my users.</strong></p><p>Here is how a single bug report exposed the “Deterministic Vector Trap” and why I finally decided to go “Pure Agentic.”</p><h3>The User Report: “It’s Always the Same Meals”</h3><p>The feedback was consistent and frustrating: “Every time I ask for a ‘plan for the week,’ the tool gives me the exact same five dishes. It doesn’t matter how many new recipes I add to my database.”</p><p>I checked the logs. I verified the exclusion logic (which prevents using recipes from the last three weeks). The code was working perfectly. The “Push” logic was fetching the 10 most “relevant” recipes, and the agent was picking 5 of them.</p><p>Then I looked at the search terms.</p><p>When a user asks for something specific like “spicy Korean chicken,” semantic search (Vector RAG) is a miracle. It finds exactly what you want. But when a user uses a generic, exploratory query like <strong>“generate a plan for the week,”</strong> semantic search becomes a deterministic trap.</p><h3>The Deterministic Vector Trap</h3><p>In a Vector DB, a query is just a coordinate in a high-dimensional space. The phrase “plan for the week” doesn’t have a culinary meaning; it has a mathematical location.</p><p>Every time the user sends that generic request, the embedding model generates the <em>exact same vector</em>. My “Hybrid” logic then fetches the <em>exact same 10 nearest neighbors</em>.</p><p>Even if the user has 500 recipes, the top 10 results for that specific meaningless vector stay the same. By “Pushing” these 10 recipes into the agent’s context upfront, I was effectively blindfolding the AI. It couldn’t “think” of other recipes because I had already told it: “Here are the most relevant items.”</p><h3>Solving the Cold Start with Agency</h3><p>To break this trap, I had to stop trying to be “helpful” at the orchestrator level. I had to embrace <strong>Pure Agentic RAG</strong>.</p><p>Instead of pre-fetching recipes, I now send the agent into the loop with an empty pool and a set of specialized tools. This moves the “intelligence” from a static Go function to the LLM itself.</p><h3>Before: The Hybrid (Push + Pull)</h3><p>The orchestrator made a guess, often poisoning the well with irrelevant or repetitive data.</p><h3>After: The Pure Agentic (Pull Only)</h3><p>The agent analyzes the query first. If it’s generic, the agent <em>knows</em> it needs to explore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ckrKMm9VfBeiP5qH9lnKaA.png" /></figure><h3>Splitting the Search: Semantic vs. Random</h3><p>The key to making Pure Agentic RAG work isn’t just giving the agent a search tool; it’s giving it <strong>choices</strong>.</p><p>I split my single search_recipes tool into two distinct capabilities:</p><ol><li><strong>search_recipes_semantic(query) (The Scalpel):</strong> Uses vector embeddings. Great for specific dietary needs, cuisines, or ingredients (e.g., &quot;spicy chicken&quot;, &quot;low-carb&quot;).</li><li><strong>search_recipes_random(limit) (The Shotgun):</strong> Uses a simple SQL ORDER BY RANDOM() query with an exclusion list. This is the antidote to the deterministic trap, used for broad requests like &quot;plan for the week&quot;.</li></ol><p>I updated the Analyst’s prompt to explain the difference. Now, when the user says “plan for the week,” the agent realizes the query lacks semantic direction and chooses the <strong>Random</strong> tool to gather a diverse base of inspiration.</p><p>When I first mapped out this migration, I was hyper-focused on the Analyst agent-the one responsible for generating the initial plan. I was ready to rip out the old search_recipes tool and replace it with the split tools.</p><p>Then I realized I was about to hit a compile-time wall.</p><p>In my architecture, I use a generic ExecuteAgentLoop (which I wrote about in <a href="https://sergioazevedo.me/refactoring-for-autonomy-building-a-generic-agent-engine-in-go">Refactoring for Autonomy</a>). The engine itself is beautifully decoupled-it just takes a list of tools and handlers as parameters. Technically, I could have given the Analyst new tools while leaving the PlanReviewer on the old ones.</p><p>Even though the agents are independent, they share a critical piece of infrastructure: the <strong>RecipeSearcher interface</strong>.</p><p>When I started updating the interface to support both semantic and random searches, I hit a massive compile-time wall: <strong>Import Cycles</strong>. My shared package (which defined the interface) needed to return recipe.Recipe structs. But the recipe package needed to import shared to access AgentMeta data for logging. By moving to a Pure Agentic model where multiple domains need to interact with search, my shared contracts became a tangled mess.</p><p>I couldn’t just “split a tool.” I had to perform a domain-driven refactor. I had to extract the core data structure into a new, isolated value package ( value.Recipe) so both shared and recipe could depend on it without depending on each other. Moving to Pure Agentic RAG isn&#39;t just about changing one prompt; it forces you to enforce strict boundary layers in your application architecture.</p><h3>Trusting the Context Window</h3><p>The final step in going “Pure Agentic” was letting go of my own code’s state management.</p><p>Previously, my Go orchestrator was maintaining a recentlyUsed array during the multi-turn loop to ensure the agent didn&#39;t fetch the same recipe twice in a single conversation. It looked like this:</p><pre>// Before: Babysitting the state with closures<br>recentlyUsed := recipesRecentlyUsed<br>searchHandler := func(ctx context.Context, toolCall llm.ToolCall) (llm.Message, []value.Recipe, error) {<br>    recipes, msg, _ := HandleRecipeSearch(ctx, searcher, toolCall, recentlyUsed)<br>    <br>    // Go-side tracking to prevent the LLM from seeing duplicates<br>    for _, r := range recipes {<br>        recentlyUsed = append(recentlyUsed, r.ID)<br>    }<br>    return msg, recipes, nil<br>}</pre><p>Once I split the tools, I realized this was redundant babysitting. A high-reasoning model can read its own tool-call history. If it calls search_recipes_random and sees a meal it already evaluated, it simply ignores it.</p><p>By removing the Go-side closure state, the engine code became significantly cleaner. We only pass the “Historical” exclusions (meals eaten last week) to the database layer, and we let the LLM manage its immediate thoughts.</p><pre>// After: Trusting the LLM&#39;s context window<br>handlers := map[string]ToolHandler[[]value.Recipe]{<br>    searchRecipesSemanticTool.Name: func(ctx context.Context, toolCall llm.ToolCall) (llm.Message, []value.Recipe, error) {<br>        // No local state appending. Just straight pass-through.<br>        return HandleRecipeSemanticSearch(ctx, a.searcher, toolCall, recipesRecentlyUsed)<br>    },<br>    // ... random handler ...<br>}</pre><h3>The Cost of Purity</h3><p>Is it slower? Yes. Every request now takes at least one extra LLM turn. To accommodate this, I had to increase the safety ceiling of my agent loop from <strong>5 turns</strong> to <strong>15 turns</strong>.</p><p>Giving the agent more “slack” allows it to be exhaustive-it can now perform 5–7 searches, reject bad results, and re-fetch until it finds exactly what the user needs. It’s the difference between a “rushed” agent that gives up early and an “exhaustive” one that truly explores the database.</p><p>But as soon as I ran my first live test with the new 15-turn ceiling, the application crashed with a 413 Rate Limit Exceeded error.</p><h3>The Token Bloat Reality</h3><p>The error message was brutal: Limit 12000, Requested 12302. I had hit the strict Tokens Per Minute (TPM) limit on Groq&#39;s free tier.</p><p>Because the agent was now executing multiple search loops to explore its options, the entire conversation history (including the massive JSON outputs of previous searches) was being passed back to the LLM on every turn. The context window was expanding exponentially.</p><p>I couldn’t lower the 15-turn limit, but I could reduce the size of the payload. I realized the Analyst agent doesn’t need to know the exact Ingredients or step-by-step Instructions to select a meal plan-it only needs the Title, Tags, PrepTime, and Servings.</p><p>I had to introduce a strict filtering helper in my Go handlers to strip the full value.Recipe struct before marshaling it into JSON for the tool response:</p><pre>// The structural tax for Pure Agentic RAG<br>func simplifyForTool(recipes []value.Recipe) []value.Recipe {<br>    var content []value.Recipe<br>    for _, r := range recipes {<br>        content = append(content, value.Recipe{<br>            ID:       r.ID,<br>            Title:    r.Title,<br>            PrepTime: r.PrepTime,<br>            Tags:     r.Tags,<br>            Servings: r.Servings,<br>        })<br>    }<br>    return content<br>}</pre><p>Crucially, I also had to update the struct tags in value/recipe.go to use omitempty so the stripped fields didn&#39;t still consume tokens as empty arrays or strings (&quot;ingredients&quot;: null).</p><p>This is the hidden cost of purity. If you trust the model’s agency, you must be ruthlessly disciplined with your data structures to avoid blowing up your context window.</p><h3>Lessons in Intellectual Honesty</h3><p>In my previous posts, I advocated for the Hybrid model as a pragmatic middle ground. I was wrong. Pragmatism in AI architecture often means “trying to hide the LLM’s nature from itself.”</p><p>By trying to avoid the “cold start,” I accidentally built a system that was consistently mediocre for the most common user behavior. Moving to Pure Agentic RAG was a lesson in trusting the model’s ability to reason about its own data needs, even if it requires a strict diet of tokens to pull it off.</p><p>If you are building RAG systems and your users are complaining about “repetitive” or “stale” results, before you spend days tuning your re-rankers or tweaking embedding dimensions, you might want to look at your orchestrator. Consider whether your “helpful” pre-fetching logic is actually pushing them into a trap.</p><h3>References &amp; Resources</h3><ul><li><a href="https://sergioazevedo.me/taming-the-pull-infinite-loops-context-bloat-and-the-blessing-of-free-tiers"><strong>Taming the Pull: Infinite Loops and Context Bloat</strong></a> — How I managed the side effects of giving agents more autonomy.</li><li><a href="https://sergioazevedo.me/from-push-to-pull-giving-my-ai-agents-agency"><strong>From Push to Pull: Giving My AI Agents Agency</strong></a> — The original (and now corrected) advocacy for the Hybrid approach.</li><li><a href="https://github.com/tagatsu/meal-planner/blob/main/docs/plans/agentic-rag-migration.md?ref=sergioazevedo.me"><strong>Agentic RAG Migration Plan</strong></a> — The internal design document for this transition.</li></ul><p><em>Originally published at </em><a href="https://sergioazevedo.me/breaking-the-deterministic-trap-why-i-abandoned-the-hybrid-rag-compromise/"><em>https://sergioazevedo.me</em></a><em> on April 12, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3890dd002ea1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming Autonomous LLM Agents: Infinite Loops and Context Bloat]]></title>
            <link>https://medium.com/@sergioazevedo/taming-autonomous-llm-agents-infinite-loops-and-context-bloat-47159b5ee8c0?source=rss-f1a998f2a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/47159b5ee8c0</guid>
            <dc:creator><![CDATA[Sergio Azevedo]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 23:12:54 GMT</pubDate>
            <atom:updated>2026-05-10T21:41:49.591Z</atom:updated>
            <content:encoded><![CDATA[<p>Moving to an autonomous ‘Pull’ architecture sounded great until my agent hit an infinite loop. Here is how I solved context bloat, fixed the loop, and why the free tier saved my wallet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jon5jgVQIj04tG1i" /></figure><p>In my previous post about <a href="https://sergioazevedo.me/from-push-to-pull">moving from a “Push” to a “Pull” architecture</a>, I wrote about the joy of finally giving an LLM agent the steering wheel. Instead of statically injecting data into a prompt, I built a generic ExecuteAgentLoop that let the agent iteratively search for its own data using tools.</p><p>The theory was sound. The agent was autonomous. And then, as soon as it hit production, the pipeline violently crashed:</p><pre>{ &quot;error&quot;: { <br>  &quot;message&quot;: &quot;Request too large... on tokens per minute (TPM): Limit 12000, Requested 13073&quot;, <br>   &quot;code&quot;: &quot;rate_limit_exceeded&quot; } <br> }</pre><p>Groq’s 12,000 Tokens Per Minute (TPM) limit had slammed the brakes on my autonomous agent. But as I dug into the logs, I realized something important: <strong>hitting the free tier limit was the best thing that could have happened.</strong></p><p>Had I been using a paid tier with massive limits, this agent would have silently burned through a massive bill. The hard constraint forced me to stop, look at the architecture, and uncover two massive traps I had inadvertently set for myself.</p><p>Here is how I investigated the crash, the “ah-ha” moment that solved the context bloat, and the mechanical guardrails required to keep autonomous agents from spinning out of control.</p><h3>The Context Bloat and the DTO Trap</h3><p>Because the agent was in a conversational loop, every new turn meant sending the <em>entire history</em> of the previous turns back to the API.</p><p>I was returning up to 10 Recipe structs in a single tool call. But these weren&#39;t just titles and ingredients; they included massive, HTML-extracted cooking instructions. At 150-200 tokens per recipe, Turn 1 was fine. By Turn 3, the compounding history was pushing payloads over 10,000 tokens.</p><p>My first instinct was the classic enterprise developer reflex: create Data Transfer Objects (DTOs). I started drafting RecipeSummary and ChefRecipe structs to strip out the instructions before passing the data to the LLM.</p><pre>// The initial, over-engineered fix <br>type RecipeSummary struct { <br>  ID string `json:&quot;id&quot;` <br>  Title string `json:&quot;title&quot;` <br>  Tags []string `json:&quot;tags&quot;` // Look at me, I&#39;m hiding data from the LLM! <br>}</pre><p>But then I had an “ah-ha” moment: <strong>YAGNI (You Aren’t Gonna Need It).</strong></p><p>The Analyst and Chef agents <em>never</em> actually used the instructions for meal planning or generating shopping lists. I was carrying around a heavy, expensive piece of data that no feature required.</p><p>Because my project uses a document-store architecture-storing recipes as raw JSON blobs inside an SQLite TEXT column-I didn&#39;t need complex DTOs or a painful database migration. I just deleted the Instructions field from the primary Go domain model entirely.</p><pre>// Before <br>type Recipe struct { <br>   ID string `json:&quot;id&quot;` <br>   Title string `json:&quot;title&quot;` <br>   Ingredients []string `json:&quot;ingredients&quot;` <br>   Instructions []string `json:&quot;instructions&quot;` // The culprit <br>} <br><br>// After <br>type Recipe struct { <br>   ID string `json:&quot;id&quot;` <br>   Title string `json:&quot;title&quot;` <br>   Ingredients []string `json:&quot;ingredients&quot;` <br>}</pre><p>Because of how Go’s json.Unmarshal works, it silently ignores the instructions key when reading old records from the database. It was an instant, zero-effort, backwards-compatible schema migration. Context bloat slashed in half, no DTOs required.</p><h3>The Infinite Loop</h3><p>I deployed the fix, confident the TPM errors were gone.</p><p>They weren’t.</p><p>The payloads were smaller, but the agent was still hitting the ceiling. It wasn’t the size of the request anymore; it was the <em>frequency</em>. The agent was caught in an infinite loop.</p><p>When I tracked the tool calls, I found a subtle but fatal bug in my RecipeService. To prevent the agent from picking the same meals twice, I pass an excludeIDs list to the semantic search. If the database ran low on un-seen recipes, my service was trying to be &quot;helpful&quot;:</p><pre>// The fatal flaw: trying to be too helpful <br>if len(recipeIds) &lt; searchLimit { <br>  log.Printf(&quot;Warning: Recipe pool exhausted. Dropping exclusions.&quot;) <br>  // Let&#39;s just return the same recipes they already rejected! <br>  recipeIds, err = s.vectorRepo.FindSimilar(ctx, queryEmbedding, searchLimit, nil) <br>}</pre><p>This created a catastrophic feedback loop:</p><ol><li>The agent searches for 5 unique recipes.</li><li>The service runs out of fresh options, drops exclusions, and returns 5 recipes the agent has <em>already seen</em>.</li><li>The agent analyzes them, realizes they violate its strict “5 unique recipes” system prompt, rejects them, and queries the tool again.</li><li>The service returns the exact same duplicates.</li><li>The agent rejects them again.</li></ol><p>The LLM and the Go service were locked in a fight to the death, looping infinitely until Groq’s TPM limit stepped in as the executioner.</p><h3>Adding Mechanical Guardrails</h3><p>Autonomy is powerful, but software still needs circuit breakers.</p><p>First, I removed the “helpful” exclusion dropping. It is much better for the service to return an empty array and let the LLM know the search genuinely failed, rather than lying to it and feeding it duplicates.</p><p>Second, I added a mechanical guardrail to the generic engine. An LLM loop should never be trusted to terminate itself.</p><pre>func ExecuteAgentLoop[T any](/*...*/) (<br>  llm.ContentResponse, <br>  []T, <br>   []shared.ToolCallMeta, error) { <br>   // ... <br>   const maxTurns = 5 <br>   turnCount := 0 <br>   for { <br>      if turnCount &gt;= maxTurns { <br>        return llm.ContentResponse{}, <br>               nil, <br>               nil, <br>               fmt.Errorf(<br>                  &quot;agent exceeded maximum tool execution turns (%d)&quot;, <br>                   maxTurns<br>               ) <br>      } <br>      turnCount++ <br>      // ... execute LLM and tools ... <br>   } <br>}</pre><p>If the agent gets confused or the tools fail to provide the right data, it halts after 5 turns, throws a Go error, and exits gracefully.</p><h3>The Tool Hallucination Trap</h3><p>With the loops capped and the context bloat resolved, the pipeline was finally stable. Until I hit <em>another</em> crash entirely.</p><p>This time, it wasn’t a rate limit. It was a 400 Bad Request from Groq with a highly specific error: tool_use_failed.</p><p>When the Analyst agent successfully finished its tool loops and tried to output the final JSON plan, it started its response with the requested top-level key: &quot;selected_recipes_audit&quot;.</p><p>Because Llama 3 on Groq’s backend uses a strict, internal XML-like syntax for function calling (e.g., &lt;function=&quot;name&quot;&gt;), the LLM sometimes hallucinates that JSON keys are actually function names if tools are still present in its context window. It tried to invoke a tool called selected_recipes_audit. Groq&#39;s backend intercepted it, realized that tool didn&#39;t exist in my registered schema, and instantly killed the generation.</p><p>The fix wasn’t in Go; it was in the prompt. I had to build a mechanical switch to force the LLM out of “tool execution mode”.</p><p>I updated the output instructions with a bold, explicit directive:</p><pre>### Output <br>Format When you are ready to provide your final plan, **DO NOT call any tools**. <br>Instead, reply with a standard message containing ONLY a raw JSON object...</pre><h3>Refined Alerting for the “Pull” Era</h3><p>Finally, I had to update my own internal monitoring. I had a “Context Bloat Alert” set to fire whenever a prompt exceeded 4,000 tokens.</p><p>In the “Push” era, 4,000 tokens was a massive anomaly. In the “Pull” era, 4,000 tokens is just a Tuesday. Between the base system prompts, the rolling conversation history, and the recipe payloads, hitting 4,000 tokens is now a standard part of a multi-turn tool loop.</p><p>To reduce noise while still maintaining a safety margin for Groq’s 12,000 TPM limit, I increased my alert threshold to <strong>8,000 tokens</strong>. I also took a final pass at my agent prompts-specifically the PlanReviewer -stripping out redundant examples and analysis steps to keep the base overhead as lean as possible.</p><h3>Constraints Breed Better Architecture</h3><p>When I started building this meal planner, the free API tier felt like a limitation. Today, I view it as an architectural blessing.</p><p>Without that strict 12,000 TPM limit, my infinite loop would have deployed to production, happily spinning CPU cycles and burning API credits until I noticed a spike in a billing dashboard days later.</p><p>Moving to a “Pull” architecture shifts your complexity from orchestration logic to context management and loop safety. Give your agents the steering wheel, but never forget to install the brakes.</p><h3>References &amp; Resources</h3><p><em>Originally published at </em><a href="https://sergioazevedo.me/taming-the-pull-infinite-loops-context-bloat-and-the-blessing-of-free-tiers/"><em>https://sergioazevedo.me</em></a><em> on April 10, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47159b5ee8c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring for Autonomy: Building a Generic Agent Engine in Go]]></title>
            <link>https://medium.com/@sergioazevedo/refactoring-for-autonomy-building-a-generic-agent-engine-in-go-9173c0ad1e47?source=rss-f1a998f2a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/9173c0ad1e47</guid>
            <dc:creator><![CDATA[Sergio Azevedo]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 04:00:29 GMT</pubDate>
            <atom:updated>2026-04-15T08:36:48.196Z</atom:updated>
            <content:encoded><![CDATA[<p>How I leveraged Go Generics to move from a brittle ‘Push’ model to a clean, reusable ‘Pull’ engine for my AI agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IsnJDs7w6x9uusWW" /></figure><p>When I first started giving my AI agents agency, I moved them from a <strong>Push</strong> model-where I statically injected data into their prompts-to a <strong>Pull</strong> model, where they decide what data they need and fetch it themselves. I documented that initial transition in <a href="https://sergioazevedo.me/from-push-to-pull-giving-my-ai-agents-agency/">From Push to Pull: Giving My AI Agents Agency</a>.</p><p>But as I added more specialized agents like the <strong>PlanReviewer</strong>, I found myself drowning in a sea of duplicated boilerplate. Every agent needed the same “While-Loop” logic to handle the turn-taking between the LLM and the Go tools. I realized that if I wanted to scale my autonomous squad, I needed a cleaner, more generic abstraction.</p><p>I solved this by building a <strong>Generic Agent Engine</strong> in Go.</p><h3>The Solution: A Generic Execution Loop</h3><p>Instead of each agent managing its own multi-turn state, I extracted the core conversational logic into a single, reusable function powered by Go 1.18+ Generics. This allows the agent to handle tool calls and side effects (like retrieving recipes) with total type safety.</p><h3>Before: Duplicated Boilerplate</h3><p>Initially, every agent had a custom, hardcoded loop like this:</p><pre>func (a *Analyst) executeLoop(ctx context.Context, chat llm.Conversation) (llm.ContentResponse, error) {<br>    for {<br>        resp, err := a.llm.GenerateContent(ctx, chat, tools)<br>        if err != nil {<br>            return llm.ContentResponse{}, err<br>        }<br>        chat = append(chat, resp.Message)<br>        <br>        if !resp.Message.IsAToolCall() {<br>            break // Exit loop on final JSON<br>        }<br><br>        // Hardcoded tool logic...<br>        toolCall := resp.Message.ToolCalls[0]<br>        results, _ := a.handleSearch(ctx, toolCall)<br>        chat = append(chat, results)<br>    }<br>    return resp, nil<br>}</pre><h3>After: The Generic Engine</h3><p>By introducing a generic type T for &quot;side effects,&quot; I created a single engine that any agent can hire.</p><pre>// The engine doesn&#39;t care WHAT the tool returns, just THAT it returns something of type T.<br>func ExecuteAgentLoop[T any](<br> ctx context.Context,<br> generator llm.TextGenerator,<br> chat llm.Conversation,<br> tools []llm.Tool,<br> handlers map[string]ToolHandler[T],<br>) (llm.ContentResponse, []T, []shared.ToolCallMeta, error) {<br>    // ... turn-taking logic ...<br>}</pre><h3>Architectural Shift: From Hardcoded to Handler-Based</h3><p>The real power of this refactor isn’t just the reduced lines of code; it’s the <strong>decoupling</strong>.</p><p>I moved from a world where the agent was responsible for the <em>execution</em> of the loop, to a world where the agent only defines its <strong>Handlers</strong>. The ExecuteAgentLoop handles the &quot;orchestration,&quot; and the agent provides the &quot;implementation.&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*xzIgg3R_cEkOFdAFSQheYw.png" /></figure><h3>Why This Matters for My AI Squad</h3><p>This refactor achieved three critical things for my meal planner:</p><ol><li><strong>Strict Type Safety:</strong> Using ExecuteAgentLoop[[]recipe.Recipe] ensures that my side effects are always correctly typed without using any and casting later.</li><li><strong>Autonomous PlanReviewer:</strong> The <strong>PlanReviewer</strong> is now a first-class citizen in the “Pull” world. It no longer needs me to search for recipes upfront; it decides if the user’s feedback requires a search and pulls the data itself.</li><li><strong>DRY Tooling:</strong> I moved the HandleRecipeSearch logic into a shared helper in engine.go. Now, if I improve how I search for recipes, every agent in my squad gets smarter instantly.</li></ol><h3>The Pragmatic Evolution</h3><p>This wasn’t an “over-engineered” decision I made on day one. It was a response to the friction I felt while adding the third agent to the system. As I described in <a href="https://sergioazevedo.me/scaling-my-ai-personas-from-manual-prompts-to-native-skill-commands-2/">Scaling My AI Personas</a>, my workflow is about solving frictions as they arise.</p><p>Building a generic engine might seem like “more work” initially, but it’s the foundation that allows my agents to move from simple “chatbots” to a truly <strong>Autonomous Squad</strong>.</p><h3>References &amp; Resources</h3><ul><li><a href="https://sergioazevedo.me/from-push-to-pull-giving-my-ai-agents-agency/">From Push to Pull: Giving My AI Agents Agency</a></li><li><a href="https://sergioazevedo.me/scaling-my-ai-personas-from-manual-prompts-to-native-skill-commands-2/">Scaling My AI Personas: From Manual Prompts to Native Skill Commands</a></li><li><a href="https://go.dev/doc/tutorial/generics?ref=sergioazevedo.me">Go Generics Tutorial</a></li><li><a href="https://github.com/tagatsu/meal-planner?ref=sergioazevedo.me">Meal Planner Repository</a></li></ul><p><em>Originally published at </em><a href="https://sergioazevedo.me/refactoring-for-autonomy-building-a-generic-agent-engine-in-go/"><em>https://sergioazevedo.me</em></a><em> on April 8, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9173c0ad1e47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring AI-Generated Tech Debt in Go]]></title>
            <link>https://medium.com/@sergioazevedo/refactoring-ai-generated-tech-debt-in-go-bf4dc949cfe7?source=rss-f1a998f2a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf4dc949cfe7</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Sergio Azevedo]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 04:31:07 GMT</pubDate>
            <atom:updated>2026-04-11T08:24:59.561Z</atom:updated>
            <content:encoded><![CDATA[<p>Vibecoding gives you incredible momentum, but eventually, you hit a wall of tight coupling. Here is how I use AI to refactor the technical debt it helped me create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2tAV-eHFG7Yyui8_" /></figure><p>Vibecoding-the process of rapidly generating features alongside an AI-is an incredible productivity boost. You can spin up entire architectures, agent loops, and database integrations in an afternoon. The momentum is addictive.</p><p>But momentum has a cost. Recently, after successfully <a href="https://sergioazevedo.me/the-hangover-of-vibecoding-paying-down-ai-generated-tech-debt/draft_push_to_pull_agents.md">transitioning my agents from a static ‘Push’ model to an autonomous ‘Pull’ model</a>, I hit a wall. I wanted to verify the quality of my new tool loop with a simple unit test, but I found it nearly impossible.</p><p>The AI had helped me build the feature fast, but it had built it as a <strong>God Object</strong>. The `Planner` struct knew <em>everything</em> about the system, tightly coupling my business logic to my infrastructure.</p><p>Here is how I recognized the smell, and more importantly, how I guided the AI to help me clean up the mess it made.</p><h3>The Smell of the God Object</h3><p>The issue surfaced when I tried to verify the `Analyst` agent’s new tool loop. I wanted a deterministic, fast unit test that mocked the search results.</p><p>When I looked at the code, I realized every single agent-the <strong>Analyst</strong>, the <strong>Chef</strong>, and the <strong>PlanReviewer</strong> -were methods bound directly to the `*Planner` struct.</p><pre>// The original &quot;God Object&quot; approach: Too many responsibilities<br>type Planner struct {<br> recipeRepo        *recipe.Repository<br> vectorRepo        *llm.VectorRepository<br> planRepo          *PlanRepository<br> analystGenerator  llm.TextGenerator <br> chefGenerator     llm.TextGenerator<br> reviewerGenerator llm.TextGenerator<br>    // ... several other dependencies<br>}<br><br>// The analyst logic was tightly bound to the Planner&#39;s heavy dependencies<br>func (p *Planner) runAnalyst(...) {<br>   // ...<br>   // This call implicitly relied on the vectorRepo and embedGen<br>   recipes, err := p.getRecipeCandidates(ctx, toolCall.Args[&quot;query&quot;], exclude) <br>}</pre><p>This is a classic code smell. To test the `Analyst` logic (the “GPS”), I had to build the entire `Planner` (the “Car”). If I wanted to test how the <strong>Chef</strong> formatted a shopping list, I still needed a database connection just to instantiate the parent struct.</p><h3>Steering the AI: Architect over Doer</h3><p>One of the traps of vibecoding is accepting the first working solution. The AI is eager to please; if you ask it to “make the agent call a tool,” it will bolt that tool onto whatever struct happens to be nearby.</p><p>To fix this, I had to stop prompting for <em>features</em> and start prompting for <em>architecture</em>. I explicitly invoked a more rigorous <strong>“Architect over Doer”</strong> principle. I told the AI:</p><blockquote><em>“Don’t just bolt on features to existing structs to make them work. If a request introduces tight coupling or a code smell, pause and propose a structural refactor.”</em></blockquote><p>By calling out the tight coupling, I forced the AI to evaluate the code against solid software engineering principles rather than just checking if it compiled.</p><h3>The Decoupling Strategy: Dismantling the God Object</h3><p>Together, we mapped out a comprehensive refactor to dismantle the God Object and isolate the agents into their own domain logic.</p><ol><li><strong>The Abstraction Boundary:</strong> We identified that the Analyst doesn’t care about vector databases; it just needs a way to find recipes. We defined a narrow `RecipeSearcher` interface.</li><li><strong>The “Implicit” Advantage:</strong> In Go, we don’t need to define the interface where we implement it. We defined `RecipeSearcher` right inside the `Analyst` package.</li><li><strong>The Isolated Agent Structs:</strong> We moved the logic for each agent into its own struct with only the dependencies it actually uses.</li></ol><h4>The “Interface vs. Concrete” Debate</h4><p>During the refactor, a question arose: <em>“If there’s only one implementation of the searcher, why not just pass the concrete struct?”</em></p><p>The answer is <strong>Testability</strong>. Even if there is only one <em>production</em> implementation, there is always a second implementation: the <strong>Mock</strong>. By using an interface, I can test the Analyst’s tool loop with a simple five-line mock, completely ignoring the complex vector embedding logic.</p><h3>The Refactored Architecture</h3><p>Here is what the decoupled `Analyst` looks like now. It’s clean, isolated, and “dumb” to the rest of the system:</p><pre>// internal/planner/analyst.go<br><br>// The narrow contract the Analyst needs<br>type RecipeSearcher interface {<br> GetRecipeCandidates(ctx context.Context, query string, excludeIDs []string) ([]recipe.Recipe, error)<br>}<br><br>// The isolated agent: Only depends on what it needs<br>type Analyst struct {<br> llm      llm.TextGenerator<br> searcher RecipeSearcher<br>}<br><br>func (a *Analyst) Run(ctx context.Context, ...) (AnalystResult, error) {<br>    // ... clean execution loop using a.searcher ...<br>}</pre><h3>The Final Boss: Unburdening the Orchestrator</h3><p>Even after isolating the agents, my `Planner` struct was still doing too much. It was satisfying the `RecipeSearcher` interface itself, which meant it still carried the weight of embedding generators and vector repositories.</p><p>The final step of this architectural cleanup was to extract that search logic into a dedicated <strong>`RecipeService`</strong>.</p><pre>// The new &quot;Backbone&quot; of our data layer<br>type RecipeService struct {<br>    recipeRepo *recipe.Repository<br>    vectorRepo *llm.VectorRepository<br>    embedGen   llm.EmbeddingGenerator<br>}<br><br>func (s *RecipeService) GetRecipeCandidates(...) ([]recipe.Recipe, error) {<br>    // Hidden complexity: Embeddings -&gt; Vector Search -&gt; DB Lookup<br>}</pre><p>Now, the `Planner` is a true orchestrator. It doesn’t know <em>how</em> to find recipes; it just knows <em>who</em> to ask and how to coordinate the agents.</p><pre>// The final, lean Planner<br>type Planner struct {<br> recipeService     *RecipeService    // Focused data capability<br> planRepo          *PlanRepository<br> analystGenerator  llm.TextGenerator // Orchestrates these workers...<br> chefGenerator     llm.TextGenerator<br> reviewerGenerator llm.TextGenerator<br>}<br><br>// GeneratePlan now looks like a clean script<br>func (p *Planner) GeneratePlan(...) {<br>    // 1. Get data via the service<br>    recipes, _ := p.recipeService.GetRecipeCandidates(...)<br>    <br>    // 2. Delegate to the Analyst (passing the service as the searcher)<br>    analyst := NewAnalyst(p.analystGenerator, p.recipeService)<br>    res, _ := analyst.Run(..., recipes)<br>    <br>    // 3. Handover to the Chef<br>    chef := NewChef(p.chefGenerator)<br>    return chef.Run(...)<br>}</pre><h3>The Payoff: Decoupled &amp; Testable</h3><p>Moving the “mechanics” of searching into a service and the “thinking” into isolated agents made the code significantly more modular. While I haven’t yet quantified the quality improvement of the plans themselves, the <strong>developer flow</strong> is already much better. I can now write pure unit tests for the Analyst’s reasoning without needing a single database connection.</p><h3>Reflections on Vibecoding</h3><p>Vibecoding is not a silver bullet. It trades architectural rigor for initial velocity.</p><p>I found that you <em>can</em> use AI to write clean, decoupled systems, but you have to actively manage the “vibe.” You have to switch personas. When you are prototyping, let the AI bolt things together. But once the feature works, you must put on your <strong>“Staff Engineer”</strong> hat, review the shape of the code, and instruct the AI to pay down the technical debt it just created.</p><p>The speed of vibecoding isn’t just about writing code fast; it’s also about having an untiring pair-programmer ready to execute a massive refactor the moment you identify a code smell.</p><p><em>Originally published at </em><a href="https://sergioazevedo.me/the-hangover-of-vibecoding-paying-down-ai-generated-tech-debt/"><em>https://sergioazevedo.me</em></a><em> on April 7, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf4dc949cfe7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Workflow Automation: Global Hooks, Skills, and Sub-agents]]></title>
            <link>https://medium.com/@sergioazevedo/ai-workflow-automation-global-hooks-skills-and-sub-agents-c011b79ee1a4?source=rss-f1a998f2a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/c011b79ee1a4</guid>
            <category><![CDATA[sub-agents]]></category>
            <category><![CDATA[ai-skills]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[gemini-cli]]></category>
            <dc:creator><![CDATA[Sergio Azevedo]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 22:35:20 GMT</pubDate>
            <atom:updated>2026-04-09T21:09:45.247Z</atom:updated>
            <content:encoded><![CDATA[<p>Building on my work with AI Personas and Agency, I moved beyond manual slash commands into fully automated environment hooks and specialized sub-agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UMNr6r6B8BDoG6Ue" /></figure><p>In my previous posts, I shared my journey of building a personal AI control plane. I moved from <a href="https://sergioazevedo.me/scaling-my-ai-personas-from-manual-prompts-to-native-skill-commands-2/">manual prompts to native slash commands</a> by packaging my engineering philosophy into a Gemini Extension. Shortly after, I detailed how I transitioned my agents from a <a href="https://sergioazevedo.me/from-push-to-pull-giving-my-ai-agents-agency/">“Push” to a “Pull” model</a>, giving them the tools to autonomously fetch the exact data they need.</p><p>However, as I continued building out the architecture for my Go-based LLM agents, I hit a final bottleneck. Even with fast slash commands and high-agency tools, there was still a significant cognitive load in managing the <em>collaboration</em>. I had to manually remember to trigger the tutor mode in every new session, and when I tasked the agent with “dirty work”-like running migrations or crunching logs-it cluttered my main chat history.</p><p><strong>The final step in this evolution was to stop managing the agent and start engineering its environment as code.</strong></p><p>By introducing <strong>Automated Hooks</strong> and <strong>Specialized Sub-agents</strong> into my extension, I transformed my CLI from a reactive toolset into an active, autonomous squad.</p><h3>Moving from Explicit Commands to Implicit Hooks</h3><p>My goal for the meal planner project wasn’t just to build a tool; it was to <strong>master the architecture of LLM agents in Go</strong>. While I rely heavily on the AI as a fast-paced coding partner for general tasks, when it comes to learning the core LLM agent logic, I specifically need my Tutor persona to guide me through the concepts without just writing the code for me.</p><p>Previously, I handled this by typing /tutor. But humans are forgetful. If I started a fresh session and asked a question, the eager default agent would just dump a completed code snippet before I could stop it. I needed the context to be <strong>implicit and unavoidable</strong>.</p><p>I achieved this using a <strong>BeforeAgent Hook</strong>. Instead of a slash command, I wrote a bash script that intercepts every prompt I send.</p><p><strong>The Dynamic “Tutor-Sync” Hook (</strong><strong>hooks/tutor-sync.sh):</strong></p><pre>#!/usr/bin/env bash<br># Project Guard: Only run if I&#39;m working in the meal-planner<br>if [[ &quot;$PWD&quot; != *&quot;/meal-planner&quot;* ]]; then echo &quot;{\&quot;decision\&quot;: \&quot;allow\&quot;}&quot;; exit 0; fi<br><br>FILE=&quot;docs/plans/TUTOR_PLAN.md&quot;<br>if [ -f &quot;$FILE&quot; ]; then<br>  # Dynamically find the first lesson that is NOT marked complete (✅)<br>  CURRENT_LESSON_HEADER=$(grep &quot;### Lesson&quot; &quot;$FILE&quot; | grep -v &quot;✅&quot; | head -n 1)<br>  <br>  # Extract the context for that specific lesson<br>  LESSON_CONTEXT=$(awk -v header=&quot;$CURRENT_LESSON_HEADER&quot; &#39;$0 ~ header {flag=1; next} /###/ {flag=0} flag&#39; &quot;$FILE&quot;)<br>  <br>  # Inject progress, behavioral boundaries, and a proactive update rule<br>  FULL_CONTEXT=&quot;CRITICAL TUTOR MANDATE: You are a Mentor. DO NOT write code without permission. Progress: $CURRENT_LESSON_HEADER\n$LESSON_CONTEXT\nWhen the user finishes the lesson, proactively offer to mark it complete (✅) in the plan.&quot;<br>  <br>  echo &quot;{\&quot;decision\&quot;: \&quot;allow\&quot;, \&quot;context\&quot;: \&quot;$FULL_CONTEXT\&quot;}&quot;<br>fi</pre><p>By linking this hook in my global ~/.gemini/settings.json, the Tutor mandate is now baked into the runtime. Not only does it enforce the teaching boundaries, but it dynamically tracks my progress through the lesson file and even offers to update my &quot;to-do&quot; list when we finish a topic. I never have to type /tutor for this project again.</p><h3>Delegating the “Dirty Work” to Sub-agents</h3><p>While hooks change <em>how</em> the main agent behaves, I needed a way to change <em>who</em> does the heavy lifting.</p><p>Tasks like running sqlc migrations or analyzing verbose go test outputs are noisy. If the main agent does them, my chat history gets filled with SQL schemas and stack traces. To fix this, I introduced <strong>Sub-agents</strong>.</p><p>Unlike the main orchestrator, sub-agents run in their own isolated, hidden sandboxes. I created two new agents in my extension repository: @migration-agent and @eval-agent.</p><p><strong>The Migration Specialist (</strong><strong>agents/migration-agent.md):</strong></p><pre>---<br>name: migration-agent<br>description: Executes end-to-end database migrations (Schema -&gt; Queries -&gt; sqlc generate).<br>tools: [read_file, write_file, run_shell_command]<br>---<br>You are a Database Expert. Follow the strict sqlc pipeline. Never edit .sql.go files manually. Ensure the Go code compiles after generation.</pre><p>Now, instead of walking the main agent through the database pipeline, I simply delegate the task:</p><blockquote><em>`@migration-agent Add a calories column to the recipes table and update the repository.`</em></blockquote><p>The sub-agent spins up, edits the schema, runs the Makefile, checks the build, and then terminates-passing only a concise success summary back to my main chat window.</p><h3>The Orchestrated Architecture</h3><p>My personal-ai-skills repository has evolved into a full-fledged local AI infrastructure. It now contains Skills (for on-demand expertise), Agents (for delegated labor), and Hooks (for silent environment enforcement).</p><h3>Why This Matters</h3><p>By automating the boundaries of the conversation and offloading the noisy tasks to sub-agents, I protected my main focus. The AI is no longer a guest I have to guide; it is an environment that enforces my learning goals, tracks my specific curriculum, and manages its own specialized sub-tasks. It’s a shift from <strong>operating a toolset</strong> to <strong>orchestrating an infrastructure.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9Vw9h2yLuT5tLkhHI-19Q.png" /></figure><h3>References &amp; Resources</h3><p>To dive deeper into the technical setup of this orchestrated environment, check out these resources:</p><ul><li><a href="https://geminicli.com/docs/hooks/index?ref=sergioazevedo.me"><strong>Gemini CLI Hooks</strong></a><strong>:</strong> Documentation for intercepting and injecting context into the agent’s session.</li><li><a href="https://geminicli.com/docs/core/subagents?ref=sergioazevedo.me"><strong>Sub-agents Documentation</strong></a><strong>:</strong> Learn how to create and delegate work to specialized, isolated agents.</li><li><a href="https://sergioazevedo.me/scaling-my-ai-personas-from-manual-prompts-to-native-skill-commands-2/"><strong>Scaling My AI Personas</strong></a><strong>:</strong> The previous post on building the foundation of this extension.</li><li><a href="https://sergioazevedo.me/from-push-to-pull-giving-my-ai-agents-agency/"><strong>From Push to Pull Models</strong></a><strong>:</strong> Insights into giving AI agents the agency to fetch their own context.</li></ul><p><em>Originally published at </em><a href="https://sergioazevedo.me/engineering-my-ai-environment-from-slash-commands-to-autonomous-squads/"><em>https://sergioazevedo.me</em></a><em> on April 4, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c011b79ee1a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents: Transitioning from Push to Pull Models]]></title>
            <link>https://medium.com/@sergioazevedo/ai-agents-transitioning-from-push-to-pull-models-b6fee5771f8a?source=rss-f1a998f2a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6fee5771f8a</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Sergio Azevedo]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 23:09:08 GMT</pubDate>
            <atom:updated>2026-04-07T19:04:12.995Z</atom:updated>
            <content:encoded><![CDATA[<p>Standard AI prompts often ‘push’ data into the model. Here’s why I moved to a ‘pull’ model, giving my agents the tools to fetch their own context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1-664YfX5mx3d851" /></figure><p>When I first started building my AI meal planner, the architecture was straightforward. The orchestrator (the “brain”) would look at the user’s request, search the database for a few relevant recipes, and then <strong>push</strong> all that data into the AI’s prompt.</p><p>It worked… until it didn’t.</p><p>I soon realized that by “pushing” the context, I was limiting the AI’s intelligence to my own orchestrator’s initial search. If the user asked for something specific that my first search missed, the agent was stuck.</p><p>Here is why I am moving to a <strong>Pull</strong> model, and how it transforms my agents from “prompt-fillers” into true autonomous workers.</p><h3>My Personal Lab: Learning to Build Agents</h3><p>Beyond just the technical friction, there was a deeper driver for this change: <strong>I wanted to learn.</strong></p><p>This entire meal planner project is a “lab” for me. It’s where I experiment with how to actually build autonomous agents, how to design tool definitions that an LLM can understand, and how to manage the multi-turn loops that make these agents “think.” Moving to a Pull model was the perfect excuse to dive deep into these techniques.</p><h3>The Problem with the “Push” Model</h3><p>In a Push model, the orchestrator has to be perfect. It has to anticipate everything the AI might need.</p><pre>// The old &quot;Push&quot; way<br>func (p *Planner) GeneratePlan(ctx context.Context, request string) {<br>    // 1. The orchestrator guesses what the AI needs<br>    recipes, _ := p.searchRecipes(request)<br>    <br>    // 2. The data is &quot;pushed&quot; into the prompt<br>    prompt := fmt.Sprintf(&quot;Here are recipes: %v. Plan a meal.&quot;, recipes)<br>    p.llm.GenerateContent(prompt)<br>}</pre><p>This creates several frictions:</p><ol><li><strong>Context Bloat:</strong> You often push too much data “just in case,” wasting tokens.</li><li><strong>Brittle Search:</strong> If the initial search for “chicken” misses a “poultry” recipe the user would have loved, the AI can’t fix it.</li><li><strong>Low IQ:</strong> The agent isn’t “thinking”; it’s just summarizing the data you gave it.</li></ol><h3>Enabling the Conversation: Stateless to Stateful</h3><p>Before I could implement the “Pull” loop, I had to fix a fundamental flaw in my Go LLM client. My initial implementation was too simple: it was essentially a “stateless” function that took a string and returned a string.</p><pre>// The original, limited interface<br>type TextGenerator interface {<br>    GenerateText(ctx context.Context, prompt string) (string, error)<br>}</pre><p>To support tool calling, the client needed to understand <strong>State</strong>. It needed to handle a sequence of messages where the agent can say, “I want to call this tool,” and the system can reply with, “Here is the result.”</p><p>I refactored the client to use a unified Conversation type (a slice of Message structs) and updated the GenerateContent signature.</p><pre>// The refactored, stateful interface<br>type Message struct {<br>    Role    string<br>    Content string<br>    // Support for tool-calling state<br>    ToolCalls []ToolCall <br>}<br><br>type Conversation []Message<br><br>type TextGenerator interface {<br>    GenerateContent(<br>        ctx context.Context, <br>        conversation Conversation, <br>        tools []Tool,<br>    ) (ContentResponse, error)<br>}</pre><p>This shift from “stateless text” to “stateful conversation” was the structural foundation that made everything else possible.</p><h3>The Solution: The “Pull” Model (Tooling)</h3><p>In a Pull model, you give the AI <strong>agency</strong>. Instead of giving it the data, you give it the <strong>tool</strong> to find the data.</p><p>I defined a `search_recipes` tool and updated the `Analyst` agent to use it. Now, the agent starts with a minimal set of context and a clear instruction: <em>“If you need more recipes to satisfy the user’s request, use the `search_recipes` tool.”</em></p><h4>The “Hybrid” Compromise</h4><p>Pure “Pull” can be slow (it requires an extra LLM turn). To maintain the developer <strong>flow</strong>, I implemented a hybrid approach:</p><ol><li><strong>Push</strong> a small, high-confidence set of recipes (the “best guesses”).</li><li><strong>Pull</strong> more recipes autonomously if those aren’t enough.</li></ol><pre>// The new &quot;Pull&quot; tool definition<br>var searchRecipesTool = llm.Tool{<br> Name:        &quot;search_recipes&quot;,<br> Description: &quot;Search for recipes based on a query to find meals that fit the user&#39;s requirements.&quot;,<br> Parameters: llm.ToolParameters{<br>  Type: llm.ParameterTypeObject,<br>  Properties: map[string]llm.Property{<br>   &quot;query&quot;: {Type: llm.PropertyTypeString},<br>  },<br>  Required: []string{&quot;query&quot;},<br> },<br>}</pre><h3>The “How”: The Autonomous Loop</h3><p>With the stateful client in place, the agent can now run in a loop. Instead of one single trip to the LLM, we iterate until the agent is satisfied.</p><pre>// The engine of our &quot;Pull&quot; model<br>func (a *Analyst) executeAnalystLoop(ctx context.Context, chat llm.Conversation) {<br>    for {<br>        // 1. Ask the LLM (providing the available tools)<br>        resp, _ := a.llm.GenerateContent(ctx, chat, tools)<br><br>        // 2. Add the response to the conversation history<br>        chat = append(chat, resp.Message)<br><br>        // 3. Break if it&#39;s a final answer, not a tool call<br>        if !resp.Message.IsAToolCall() {<br>            break <br>        }<br><br>        // 4. If it IS a tool call, execute the search<br>        toolCall := resp.Message.ToolCalls[0]<br>        recipes, toolMsg, _ := a.handleSearchTool(ctx, toolCall)<br><br>        // 5. Add the tool result back to the chat and loop!<br>        chat = append(chat, toolMsg)<br>        <br>        // This is where the &quot;Pull&quot; happens: <br>        // The next iteration now has the new recipes in its context.<br>    }<br>}</pre><h3>Testing and Evals: Confirming the Theory</h3><p>The <strong>hope</strong> is that this model will significantly improve the agent’s ability to handle complex, nuanced requests. For instance, if a user asks for “high-protein meals, but no spicy food,” a push model might fail if the initial search is overwhelmed by popular spicy high-protein recipes. With a tool, the agent can recognize the conflict and refine its own search.</p><p>To prove this, I’m currently adding <strong>eval tests</strong>. I’m building a suite of “hard” scenarios to quantitatively measure how often the agent successfully uses its tools to resolve constraints.</p><h3>Measuring Agency with Metrics</h3><p>You can’t manage what you don’t measure. Giving an agent the “keys to the kingdom” (the ability to call tools) means you need to watch its costs and performance very closely.</p><p>As part of this refactor, I’ve added <strong>metrics</strong> to track exactly what happens during these autonomous loops. I defined a shared metadata structure to capture the operation of every agent execution:</p><pre>// Shared telemetry for our agents<br>type ToolCallMeta struct {<br>    ToolName string        \`json:&quot;tool_name&quot;\`<br>    Latency  time.Duration \`json:&quot;latency&quot;\`<br>    Input    any           \`json:&quot;input&quot;\`<br>}<br><br>type AgentMeta struct {<br>    AgentName string<br>    Usage     TokenUsage      // Tokens, model, etc.<br>    Latency   time.Duration   // Total execution time<br>    ToolCalls []ToolCallMeta  // Detailed tool usage<br>}</pre><p>By recording these in my SQLite database, I can look back at real usage and answer critical questions: How many times does the agent <em>actually</em> feel it needs more data? Is the latency hit worth it? Is it getting stuck in loops?</p><h3>Reflections on Agency</h3><p>Moving from Push to Pull is more than just a technical refactor; it’s a shift in how you view AI. You aren’t just “programming” a model with a prompt; you are <strong>designing a worker</strong> and giving it the tools it needs to succeed.</p><p>This transition is the first step toward true autonomy in my system. But as I’m discovering, giving an agent more agency also means you need better ways to test and decouple that agency-a story for the next post.</p><p><em>Originally published at </em><a href="https://sergioazevedo.me/from-push-to-pull-giving-my-ai-agents-agency/"><em>https://sergioazevedo.me</em></a><em> on April 3, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6fee5771f8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Personas: From Manual Prompts to Native Skill Commands]]></title>
            <link>https://medium.com/@sergioazevedo/ai-personas-from-manual-prompts-to-native-skill-commands-5502566f4233?source=rss-f1a998f2a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/5502566f4233</guid>
            <category><![CDATA[gemini-cli]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Sergio Azevedo]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 23:20:19 GMT</pubDate>
            <atom:updated>2026-04-03T20:51:04.745Z</atom:updated>
            <content:encoded><![CDATA[<p>How I moved from repetitive prompt engineering to a seamless, context-aware flow by leveraging Gemini CLI’s native skill commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W-PVoAhrFfuEgIQt" /></figure><p>I like having specialized AI personas for different tasks, but I quickly realized that constantly typing out the same instructions just to switch between “Go Engineer” or “Tutor” mode was breaking my flow. In almost every session, I found myself repeating the same core philosophies-like my preference for <strong>Stateless Clients</strong> and <strong>Strict DTOs</strong> -over and over again.</p><p>To fix this, I moved away from manual prompt engineering and restructured my setup into a formal <strong>Gemini Extension</strong>. This change allows me to trigger complex, persona-driven behaviors with native slash commands like /tutor or /go-engineer without the friction of repetitive prompting.</p><h3>Moving to Native Skill Commands</h3><p>The real architectural shift happened when I learned that <strong>Skills are automatically exposed as slash commands</strong> in the Gemini CLI. There is no need to manually create task-based commands just to trigger a persona; if you define a skill, the CLI handles the routing natively.</p><p>To make this feel like a first-class feature of my workspace, I adjusted my extension manifest:</p><pre>// gemini-extension.json <br>// This manifest binds my skills into a unified toolset <br>// and disables prefixing for clean, instant commands. <br>{<br>  &quot;name&quot;: &quot;personal-ai-skills&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;My personal collection of skills and commands&quot;,<br>  &quot;features&quot;: {<br>    &quot;commands&quot;: {<br>      &quot;prefix&quot;: false<br>    }<br>  }<br>}</pre><p>That &quot;prefix&quot;: false setting is what makes the workflow feel so light. Without it, I&#39;d be stuck typing /personal-ai-skills.go-engineer. By turning off the prefix, my local personas act as native, global commands in my terminal.</p><h3>The Logic of a Streamlined Architecture</h3><p>Instead of managing separate prompt files and command triggers, I now rely entirely on the skills/ directory. Each SKILL.md file defines the <strong>persona</strong> (the constraints, tools, and philosophy) and simultaneously acts as the command that activates it.</p><p>Here is what the updated flow looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*R4xVXvMYmlHrQ1p_GmKfdw.png" /></figure><p>Now, I simply run /go-engineer &quot;Refactor this slice to a type alias&quot; and the agent immediately adopts my specific engineering style without any middleman configuration or &quot;just-in-case&quot; prompt chaining.</p><h3>Why This Simplicity Matters</h3><p>This native, skill-based approach has effectively turned my CLI into a <strong>context-aware IDE</strong>. By removing the layer of manual prompt repetition, the extension is fundamentally more predictable and easier to manage.</p><ol><li><strong>Skills</strong> live in skills/ (the &quot;What to do&quot; AND the &quot;How to trigger&quot;).</li><li><strong>Commands</strong> are strictly reserved for non-persona tasks (like /publish or /deploy), which keeps my workspace free of naming collisions and configuration bloat.</li></ol><p>When I run gemini extensions link ../personal-ai-skills, the CLI registers everything instantly.</p><p>The result is a shift from “chatting with an AI” to “operating a specialized toolset.” When I’m in “Reviewer” mode, the agent is meticulous about performance traps. When I switch to “Tutor,” it stops writing code for me and starts asking the right guiding questions. It’s a pragmatic evolution that keeps the focus exactly where it belongs: on the code and the creative flow.</p><h3>References &amp; Resources</h3><p>To build your own AI control plane, check out these sections of the Gemini CLI documentation:</p><ul><li><a href="https://docs.gemini-cli.com/cli/skills?ref=sergioazevedo.me"><strong>Agent Skills</strong></a><strong>:</strong> How to create SKILL.md files that define personas and automatically generate slash commands.</li><li><a href="https://docs.gemini-cli.com/extensions/reference?ref=sergioazevedo.me"><strong>Extensions Reference</strong></a><strong>:</strong> The specification for the gemini-extension.json manifest.</li></ul><p><em>Originally published at </em><a href="https://sergioazevedo.me/scaling-my-ai-personas-from-manual-prompts-to-native-skill-commands-2/"><em>https://sergioazevedo.me</em></a><em> on March 25, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5502566f4233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Controlling AI Hallucinations with a SQLite State Machine]]></title>
            <link>https://medium.com/@sergioazevedo/controlling-ai-hallucinations-with-a-sqlite-state-machine-2caabd0ea6ad?source=rss-f1a998f2a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/2caabd0ea6ad</guid>
            <dc:creator><![CDATA[Sergio Azevedo]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 22:58:02 GMT</pubDate>
            <atom:updated>2026-02-25T23:59:54.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9OFTNnetQhfTHltZ" /></figure><p>I found that my multi-agent meal planner was great at generating plans, but terrible at changing them. If I wanted to swap just one meal, the system would often hallucinate or lose the context of the rest of the week. I realized that treating every interaction as a fresh “one-shot” generation was a mistake. Instead of trying to force a stateless LLM to “remember” through long prompts, I decided to handle the memory myself using a SQLite state machine. Here is how I built a stateful feedback loop that makes the bot actually useful for day-to-day tweaks.</p><h3>The “Take It or Leave It” Problem</h3><p>My initial dual-agent system was great at taking a schedule and generating a cohesive plan. The “Analyst” figured out the meals, and the “Chef” immediately built the shopping list. It was a beautiful, but perfectly linear, pipeline.</p><p>But what if I only wanted to change <em>one</em> day? Standard LLM wrappers lose context immediately. To fix the draft, I would either have to regenerate the entire week (burning tokens and losing the meals I actually liked) or build a massive, complex conversational memory system just to remember what we were talking about 30 seconds ago.</p><p>I needed the Telegram bot to hold a conversation about a <em>specific</em> draft plan.</p><h3>Explicit State Machines over “Chat History”</h3><p>Instead of dumping raw chat logs into the LLM and hoping it figures out what we are talking about, I introduced an explicit state machine backed by SQLite.</p><p>When the initial draft plan is generated, the bot opens a Session. This session holds the current state ( awaiting_feedback), the user&#39;s original request, and a reference to the active draft plan.</p><pre>// internal/telegram/session_repository.go<br><br>// Session represents an active user session (e.g., awaiting adjustment feedback)<br>type Session struct {<br> ID          int64<br> UserID      string<br> SessionType string<br> State       string<br> ContextData string<br> ExpiresAt   time.Time<br> CreatedAt   time.Time<br>}<br><br>// GetActive retrieves the most recent active session for a user (non-expired)<br>func (sr *SessionRepository) GetActive(ctx context.Context, userID string, now time.Time) (*Session, error) {<br> row, err := sr.queries.GetActiveSession(ctx, sessiondb.GetActiveSessionParams{<br>  UserID:    userID,<br>  ExpiresAt: now,<br> })<br> // ... error handling<br> return &amp;Session{<br>        // ... mapping fields<br> }, nil<br>}</pre><p>Now, when a user sends a message on Telegram, the bot intercepts it. If an active awaiting_feedback session exists, the bot knows this isn&#39;t a <em>new</em> request; it&#39;s an <em>adjustment</em> to the active draft.</p><h3><strong>The Dual-State System: Sessions and Drafts</strong></h3><p>The <strong>Session</strong> tracks the <strong><em>conversation</em></strong>, but the meal plan itself also needed a lifecycle. I updated the `user_meal_plans` table to include a `status` field with three distinct states:</p><pre>// internal/planner/mealplan.go<br>type PlanStatus string<br><br>const (<br>  StatusDraft PlanStatus = &quot;DRAFT&quot;<br>  StatusFinal PlanStatus = &quot;FINAL&quot;<br>  StatusAdjusting PlanStatus = &quot;ADJUSTING&quot;<br>)</pre><p>When the Analyst generates a new week, it is saved as `DRAFT`. If the user asks for a change, the status temporarily shifts to `ADJUSTING` to lock it from concurrent modifications. Only when the user types “Confirm” does the plan transition to `FINAL`. This separation of concerns — Conversation State vs. Entity State — makes the database the ultimate source of truth, completely independent of the LLM.</p><h3>The PlanReviewer Agent</h3><p>With the state securely anchored in the database, I needed an agent capable of targeted mutations. Enter the PlanReviewer.</p><p>Unlike the initial Analyst agent, which builds a week from scratch, the PlanReviewer&#39;s sole job is to take an <em>existing</em> plan, a user&#39;s <em>critique</em>, and output a <em>modified</em> plan without breaking the batch-cooking cadence.</p><p>By passing the existing JSON structure back into the prompt alongside the feedback, we severely constrain the LLM’s hallucination space:</p><pre># internal/planner/plan_reviewer_prompt.md (Snippet)<br><br>You are a Meal Plan Review Specialist. Your role is to intelligently revise an existing meal plan based on user feedback, without regenerating the entire plan from scratch.<br><br>**Current Meal Plan**:<br>{{ range .CurrentPlan }}<br>- **{{ .Day }}**: {{ .RecipeTitle }} ({{ .PrepTime }})<br>{{ end }}<br><br>**User Feedback/Adjustment Request**:<br>{{ .AdjustmentFeedback }}<br><br>## Task<br>1. **Parse Feedback**: Identify which specific days or meal types the user wants to change.<br>2. **Preserve Good Parts**: Only change what the user specifically asked for. Keep recipes that weren&#39;t mentioned in feedback.<br>3. **Maintain Batch-Cooking Patterns**: If changing Monday (Cook), also consider changing Tuesday (Reuse) to maintain consistency.</pre><h3>Deferring Execution: Patience is a Virtue</h3><p>This new interactive loop required a fundamental change to the architecture: <strong>Deferred Execution.</strong></p><p>Previously, the Analyst generated the plan and immediately handed it to the Chef to build a shopping list. Now, the Chef has to wait.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*NgOpifRl9HNm7-VXzvdN5Q.png" /></figure><p>The system only runs the expensive ingredient-scaling and shopping-list generation tasks <em>after</em> the user explicitly confirms the plan. This saves tokens, reduces API calls to Groq, and ensures we only process finalized data.</p><h3>The Message Router: Intercepting State</h3><p>Most AI wrapper bots operate on a simple loop: Receive Message -&gt; Send to LLM -&gt; Return Output. Because we introduced explicit state management, the Telegram webhook handler ( processMessage) now acts more like an API gateway. It decides <em>which</em> operational mode the system should be in before the LLM ever sees the text.</p><ol><li><strong>State Interception First</strong>: Before looking at the text, the bot checks SQLite for an active, unexpired session. If a session exists with State == &quot;awaiting_feedback&quot;, the bot short-circuits and routes the message to the PlanReviewer. It knows you aren&#39;t asking for a <em>new</em> plan; you&#39;re talking about the draft.</li><li><strong>Clipper Mode (Regex Routing)</strong>: If the text is a URL, the bot knows you want to save a recipe, not chat. It routes to the Extractor/Clipper workflow.</li><li><strong>Default Generation</strong>: Only if the message fails all previous checks does it get sent to the Analyst as a brand new request.</li></ol><p>This strict routing is what makes the bot feel deterministic. You aren’t “prompt engineering” the AI to realize you sent a URL or want to change a draft; the Go code enforces the context before the AI ever turns on.</p><h3>The Architect’s Takeaway</h3><p>Vibe coding can get you a functional single-pass AI script in minutes. But making an AI feel truly conversational and reliable requires traditional software engineering.</p><p>By forcing the LLM to operate within strict, predictable boundaries dictated by a SQLite state machine, we solve the hallucination and memory drift problems common in raw chat wrappers. It’s a stark reminder: the LLM is a powerful engine, but your application code still has to be the steering wheel.</p><p><em>Originally published at </em><a href="https://sergioazevedo.me/controlling-ai-hallucinations-with-a-sqlite-state-machine/"><em>https://sergioazevedo.me</em></a><em> on February 25, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2caabd0ea6ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding is a Superpower — If You’re a Sharp Architect]]></title>
            <link>https://medium.com/@sergioazevedo/vibe-coding-is-a-superpower-if-youre-a-sharp-architect-43555a7defef?source=rss-f1a998f2a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/43555a7defef</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Sergio Azevedo]]></dc:creator>
            <pubDate>Sat, 31 Jan 2026 13:33:53 GMT</pubDate>
            <atom:updated>2026-01-31T20:44:56.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tMbb-IjhnW6pGGiZ" /></figure><p>In my <a href="https://sergioazevedo.me/building-a-zero-cost-multi-agent-meal-planner/">previous post</a>, I laid out the blueprint for a zero-cost, multi-agent meal planner. Since then, I’ve been “vibe coding” the implementation using the Gemini CLI.</p><p>It’s been an incredible experience in speed, but it also proved a vital point: <strong>AI is a “Super-Junior” with a jetpack.</strong> It can write 1000 lines of code in seconds, but without a human developer acting as an <strong>Architectural Guardrail</strong>, you’ll quickly find yourself flying into a mountain of technical debt.</p><p>Here is how I navigated the transition from a “cool demo” to a robust, observable system.</p><h3>The Reality Check: 20 Requests per Day</h3><p>The first wall I hit wasn’t technical-it was a quota. The Gemini free API tier is generous but limited to 20 requests per day. In a “vibe coding” session where you’re iterating fast, 20 requests can disappear in 30 minutes.</p><p><strong>The Human Intervention:</strong> Instead of stopping, I guided the AI to implement a <strong>Hybrid Model Strategy</strong>.</p><ul><li><strong>Gemini 1.5 Pro:</strong> Reserved for the heavy lifting (complex data extraction and generating vector embeddings).</li><li><strong>Groq (Llama 3):</strong> Used for the fast, tactical reasoning steps (like the Analyst and Chef agents).</li></ul><p>This bridge allowed the project to stay “zero cost” while gaining the resilience of a multi-provider setup.</p><h3>The Issue: When the “Vibe” gets Soupy</h3><p>As the project grew, the AI started taking the path of least resistance. It was doing what I asked, but the design was getting “soupy”:</p><ul><li><strong>Naming Collisions:</strong> Every function returned a generic Result, making it impossible to tell a domain entity from an API response.</li><li><strong>The Observability Black Box:</strong> LLM calls were happening, but I had no idea how many tokens I was burning or where the latency was hiding.</li><li><strong>Generic Patterns:</strong> The AI defaulted to pointers (*Struct) for everything, cluttering the code with if res != nil checks.</li></ul><h3>The Solution: 3 Critical Human Interventions</h3><p>I had to step in and “steer the vibe.” These weren’t AI suggestions-they were moments where I had to stop the AI and re-frame the architecture.</p><h4>1. The “Agent” Pivot</h4><p>One of the most important moments was when I looked at a hardcoded prompt sitting inside a standard Go function. I asked: <em>“Does it make sense to have a Normalization Agent for this too? Similar to the Chef and Analyst?”</em></p><p><strong>The Fix:</strong> We moved to the <strong>Extractor Agent</strong>.</p><ul><li><strong>Extractor Agent:</strong> A dedicated component with its own Markdown prompt and structured logic.</li><li><strong>NormalizedRecipe:</strong> A separate domain entity that combines the Recipe with its vector Embedding.<br> This created a clear mental model: The Extractor produces a Recipe, which then becomes searchable.</li></ul><h4>2. Forcing Self-Identifying Metrics</h4><p>I wanted to track costs. The AI initially gave me a generic Meta struct with just tokens and time. I intervened and insisted on an AgentName field.</p><pre>type AgentMeta struct { <br>  AgentName string // &quot;Chef&quot;, &quot;Analyst&quot;, &quot;Extractor&quot; <br>  Usage TokenUsage <br>  Latency time.Duration <br>}</pre><p><strong>Why it mattered:</strong> By making the metadata self-identify, my SQLite metrics store became instantly searchable. I can now see exactly which agent is my “heavy hitter” in terms of cost and latency.</p><h4>3. Value Returns over Pointers</h4><p>The AI loves pointers because it’s a “safe” default in many training sets. But in our ingestion loop, it was making the code noisy. I made the call to switch to <strong>Value returns</strong> for the normalized recipes.</p><h3>Reflection: The Architect’s Role in the AI Era</h3><p>This experiment confirmed my suspicion: <strong>Vibe coding isn’t about being lazy; it’s about accelerating the work so you can focus on the design.</strong></p><p>The LLM handled the repetitive test boilerplate and the boring Go interfaces. But it took a human eye to:</p><ul><li>Navigate the <strong>Quota constraints</strong> by building a hybrid bridge.</li><li>Spot <strong>Naming collisions</strong> before they became debt.</li><li>Ask the <strong>Architectural questions</strong> that turned a script into a system.</li></ul><p><strong>The takeaway?</strong> Don’t treat the AI as an Autopilot. Treat it as a highly capable but slightly clumsy co-pilot. You’re still the pilot, and you better keep your eyes on the instruments.</p><p><em>Originally published at </em><a href="https://sergioazevedo.me/vibe-coding-is-a-superpower-if-youre-a-sharp-architect/"><em>https://sergioazevedo.me</em></a><em> on January 31, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43555a7defef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a “Zero-Cost” Multi-Agent Meal Planner]]></title>
            <link>https://medium.com/@sergioazevedo/building-a-zero-cost-multi-agent-meal-planner-495825b421b7?source=rss-f1a998f2a5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/495825b421b7</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Sergio Azevedo]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 21:54:25 GMT</pubDate>
            <atom:updated>2026-02-04T20:51:07.435Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZUUd2KL-UbNIIKrD" /></figure><p>Recently, I’ve been diving deep into the world of AI agents and LLMs. I wanted to build something practical: a tool that could “read” my Ghost blog, understand my recipes, and generate a weekly meal plan without me having to lift a finger.</p><p>But I had a constraint: it had to be <strong>zero-cost</strong>. No expensive managed databases, no $20/month LLM subscriptions. Just pure, lean engineering.</p><p>For the interface, I chose <strong>Telegram</strong>. Why? Because it’s one of the few platforms that still lets you create bots and access a powerful API completely for free. It’s the perfect “frontend” for a project where the goal is $0 operational overhead.</p><p>Here is the story of how this project evolved from a messy single prompt into a structured multi-agent system.</p><h3>TLDR — The main lesson</h3><p>If you’re building with LLMs, <strong>split the brain</strong>. Don’t ask one prompt to handle strategy, formatting, and math simultaneously. By creating a <strong>“Handover” pattern</strong> between a Strategic Analyst and an Executive Chef, I reduced hallucinations and built a system that actually understands how to cook for a family.</p><h3>The “Aha!” Moment: Why one agent isn’t enough</h3><p>When I started, I had a single prompt. I’d feed it my recipes and say, “Give me a plan.” It was a mess. The AI would forget my kid hates spicy food, or it would suggest cooking a 2-hour lasagna on a busy Tuesday lunch.</p><p>I realized that a single prompt was suffering from <strong>cognitive overload</strong>. It was trying to be a strategist and a sous-chef at the same time, and failing at both.</p><h3>The Fix: A Multi-Agent Role-Based Architecture</h3><p>I moved away from “vibe coding” and implemented a structured handover using Go.</p><ul><li><strong>The Analyst (Strategy):</strong> This agent is pure strategy. It looks at the week and decides <em>what</em> we should cook and when. It’s responsible for the “batch cooking” logic — making sure we cook on Monday so we can reuse leftovers on Tuesday.</li><li><strong>The Chef (Execution):</strong> Once the Analyst creates a schedule, it “hands over” the plan to the Chef. The Chef doesn’t care about strategy; its job is pure execution. It scales the ingredients for my household (2 adults, 1 kid) and consolidates the shopping list.</li></ul><h3>Deep Dive: The Handover Pattern</h3><p>To make this work reliably, I had to define a strict contract between the agents. In Go, this looks like a shared context that ensures the Chef has exactly what it needs to succeed without re-calculating the Analyst’s logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*afHboH1658a4mBdT7iVLmQ.png" /></figure><p><strong>The “Handover” Contract in Code:</strong></p><pre>// This struct ensures the Chef doesn&#39;t have to guess.<br>type MealPlanContext struct {<br>    SelectedRecipes []Recipe `json:&quot;selected_recipes&quot;` // From Analyst<br>    Strategy        string   `json:&quot;strategy&quot;`         // The &quot;Why&quot;<br>    Household       config.Household `json:&quot;scaling&quot;`  // The &quot;How much&quot;<br>}</pre><p>By isolating these concerns, the “Chef” can focus 100% of its context window on formatting and math, which practically eliminated the “hallucinated ingredient” problem.</p><h3>Engineering for Zero-Cost</h3><p>To keep this project truly free, I had to get creative with the stack:</p><ul><li><strong>The Brains:</strong> I use a dual-provider approach with <strong>Google Gemini</strong> (for embeddings) and <strong>Groq</strong> (for fast inference). Both have generous free tiers that easily handle a daily planning session.</li><li><strong>The Interface:</strong> By using Telegram, I got a professional UI (chat, buttons, notifications) without writing a single line of CSS or paying for hosting a complex frontend.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SXmADtC1bMrxsRII.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T9lQSiEk4sofquFc.png" /></figure><ul><li><strong>The Memory:</strong> Instead of a paid vector database, I used a <strong>Hybrid Storage</strong> approach. Recipes are stored as flat-file JSONs (perfect for RAG), and I used a pure-Go SQLite implementation for observability metrics.</li><li><strong>The Hardware:</strong> The entire bot runs on less than 15MB of RAM. It’s lean enough to run on a home server or the smallest cloud instance you can find.</li></ul><h3>Observability on a budget</h3><p>One issue I ran into was “context bloat” — the prompts getting so big they’d hit rate limits. Since I didn’t want to pay for monitoring tools, I built my own metrics store in SQLite.</p><p>Now, I can just type /metrics in Telegram and see exactly how many tokens I&#39;ve used and the latency of each agent. It&#39;s professional-grade monitoring for $0, delivered right to my phone.</p><h3>Final Thoughts</h3><p>This journey taught me that “Agentic” workflows aren’t just hype — they are a pragmatic solution to LLM unreliability. By treating my AI like a small, specialized workforce rather than a single magic box, I built something that actually works for my family’s daily life.</p><p><strong>Architecture beats prompts every time.</strong></p><p><strong>Show me the code?</strong><br> You can check out the full architecture and the Handover implementation on my <a href="https://github.com/your-repo">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=495825b421b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>