<?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 Saurabh Kohli on Medium]]></title>
        <description><![CDATA[Stories by Saurabh Kohli on Medium]]></description>
        <link>https://medium.com/@saurabh-kohli?source=rss-f630c0b97775------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9prIdR_pUSjtaR-OHs7lLQ.png</url>
            <title>Stories by Saurabh Kohli on Medium</title>
            <link>https://medium.com/@saurabh-kohli?source=rss-f630c0b97775------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:52:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saurabh-kohli/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[Spec-Driven AI Wealth Manager]]></title>
            <link>https://pub.towardsai.net/spec-driven-ai-wealth-manager-68aac89e6ebd?source=rss-f630c0b97775------2</link>
            <guid isPermaLink="false">https://medium.com/p/68aac89e6ebd</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Saurabh Kohli]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 14:01:02 GMT</pubDate>
            <atom:updated>2026-11-26T14:01:02.612Z</atom:updated>
            <content:encoded><![CDATA[<h4>GraphQL, a PyAgent blueprint, and deterministic tax math using Oracle</h4><figure><img alt="A person at a desk reviewing financial charts on" src="https://cdn-images-1.medium.com/max/1024/1*Drh5DZ0tCHxRjlxAsOkgIA.jpeg" /><figcaption>One laptop, one portfolio, and a notebook full of notes: the full setup for the weekend experiment described below.</figcaption></figure><p>Disclaimer: I am not a financial advisor. This was a weekend experiment fueled by cold brew and out of curiosity. Do not trust this with real money.</p><p>I tried the following combination of technologies:</p><p><strong>GraphQL</strong>, for an approved query template that teaches agents exactly how to query, so they stop inventing fields and stop overfetching.</p><p><strong>PyAgent</strong>, for spec-driven orchestration. The agents, the workflow, the budgets, and the contracts between workers are declared in one YAML blueprint and validated before anything runs.</p><p><strong>Oracle</strong>, a Python library for tax-aware portfolio optimization, for the tax math. No model is involved in that step at all.</p><p><strong>pyagent-tr</strong>ace, which records each step of a run as it happens, worker calls and model calls alike, with the cost of each step attached, so a finished run can be replayed and checked.</p><p>Last weekend I stitched them together to see whether the combination actually worked once real data started moving through it. The goal was specific: a multi-agent system that rebalances a portfolio for tax efficiency, fetches live market data through GraphQL, and shows a trace of how it reached its recommendation.</p><p>It worked. It also crashed in ways I did not expect, including a worker that looped on a tool that does not exist. Here is what I built, why each piece is there, and what I would do differently.</p><p><strong>TL;DR.</strong> I built a small multi-agent wealth manager where the model only does what it is good at. A PyAgent blueprint declares the workflow, one fixed GraphQL query fetches the market data, deterministic code does the tax math and the compliance checks, and every run is recorded so it can be replayed step by step. Step through the recorded runs in the live demo: <a href="https://me-saurabhkohli.github.io/wealth-agent/">https://me-saurabhkohli.github.io/wealth-agent/</a> The code is at <a href="https://github.com/me-saurabhkohli/wealth-agent">https://github.com/me-saurabhkohli/wealth-agent</a></p><h3>One Blueprint, Four Workers, No Shared Notes</h3><figure><img alt="A hand pointing at printed financial charts on a" src="https://cdn-images-1.medium.com/max/1024/1*Ehond6TOlPBsPwGptnIo6g.jpeg" /><figcaption>Planning before delegation: the blueprint declares the workers and the stage order before any model is called.</figcaption></figure><p>Everything the system is, its agents, its workflow, its providers, and its governance, is written down in one YAML file, and that file is checked before a single LLM call is made: dangling references and schema violations fail validation, and contract tests run against a mock model in CI.</p><pre># blueprint.yaml (trimmed to the parts that matter here)<br>api_version: pyagent/v1<br>metadata:<br>  name: wealth-manager<br>providers:<br>  primary: { model: openai:gpt-5.6-sol }<br>  small:   { model: openai:gpt-5.6-luna }<br>agents:<br>  supervisor: { provider: primary }<br>  market:     { provider: primary }<br>  tax:        { provider: primary }<br>  compliance: { provider: primary }<br>  rebalancer: { provider: small }<br>workflows:<br>  rebalance:<br>    pattern: supervisor<br>    agents:<br>      lead: supervisor<br>      workers: [market, tax, compliance, rebalancer]<br>contracts:<br>  market:     { output: MarketData }        # fixed fields, strict JSON<br>  tax:        { output: TaxResult }         # trades, savings, drift<br>  compliance: { output: ComplianceResult }  # pass or fail, with reasons<br>governance:<br>  token_budget_per_run: 60000<br>  human_checkpoint: before_execution<br>observability:<br>  trace: true<br>  cost_tracking: true</pre><p>One supervisor agent leads the workflow and delegates each task to specialized workers. Each worker runs in its own context, returns one answer, and ends. Workers do not share memory with each other, and the supervisor works from their returned answers, not from their intermediate steps. Because the workers, the workflow, and the contracts are declared in the manifest rather than hard-coded in the runner, the same manifest can be compiled onto different runtime engines without rewriting the system.</p><p>The repo is organized like this:</p><pre>wealth_agent/<br>├── blueprint.yaml        # Agents, workflow, contracts, budgets, observability<br>├── agents.py             # Worker prompts and model bindings<br>├── adapters/<br>│   ├── graphql_client.py # GraphQL endpoint + approved query template<br>│   ├── tax.py            # Oracle integration for deterministic tax math<br>│   └── compliance.py     # Rule engine for deterministic checks<br>└── pipeline.py           # Loads the blueprint, binds adapters, runs a request</pre><p>The Python underneath stays thin, because the blueprint carries the structure. pipeline.py loads the blueprint, binds the adapter functions to the names the blueprint declares, and runs one rebalance request:</p><pre># pipeline.py<br><br>blueprint = load_blueprint(&quot;blueprint.yaml&quot;)<br><br>runtime = compile_blueprint(blueprint, adapters={<br>    &quot;market.fetch&quot;: fetch_market_data,         # GraphQL template<br>    &quot;tax.optimize&quot;: run_tax_optimization,      # Oracle<br>    &quot;compliance.check&quot;: run_compliance_check,  # rules engine<br>})<br><br>result = runtime.run(&quot;rebalance&quot;, request)</pre><p>The sections below go through each piece in turn, including the ones that broke.</p><h3>First, I Stopped the Agent From Writing Its Own Queries</h3><figure><img alt="Overhead view of a desk with a notebook, printed" src="https://cdn-images-1.medium.com/max/1024/1*JUjTUbc0ouwttzOnBq48iQ.jpeg" /><figcaption>A fixed query, written down once: the model changes only the tickers, never the query structure.</figcaption></figure><p>I started with REST. The agent called something like GET /holdings and received a 10KB JSON response: holdings, transaction history, and fields the task never needed. That extra data filled the context window, cost tokens, and made it harder for the model to find the one field it needed. In my runs, that is where the wrong answers started.</p><p>GraphQL fixed the response size, because the agent asks for named fields and gets only those fields. It created a second problem. Given a complex schema, the model wrote queries with missing required arguments, misused nullable fields, and invented fields that do not exist. I then had to debug the query and the reasoning at the same time.</p><p>So I stopped asking the model to write the query. The tool carries one approved query template, and the model can change only the $tickers variable:</p><pre># adapters/graphql_client.py<br>from gql import gql, Client<br><br>MARKET_DATA_SKILL = &quot;&quot;&quot;<br>  SKILL: Fetch market data using this EXACT query.<br>  DO NOT modify the query structure. Only change the $tickers variable.<br>  query GetMarketData($tickers: [String!]!) {<br>    marketData(tickers: $tickers) {<br>      ticker<br>      price<br>      volatility30d<br>      sentiment<br>    }<br>  }<br>&quot;&quot;&quot;<br><br>def fetch_market_data(tickers: str) -&gt; str:<br>  &quot;&quot;&quot;Use the approved GraphQL skill to fetch prices, volatility, and sentiment.&quot;&quot;&quot;<br>    query = gql(&quot;&quot;&quot;<br>    query GetMarketData($tickers: [String!]!) {<br>      marketData(tickers: $tickers) {<br>        ticker<br>        price<br>        volatility30d<br>        sentiment<br>      }<br>    }<br>  &quot;&quot;&quot;)<br>  result = graphql_client.execute(query, variable_values={&quot;tickers&quot;: tickers.split(&quot;,&quot;)})<br>  return str(result)</pre><p>I tested the same market tasks with and without the template. Without it, the agent invented fields such as priceHistory and beta. With it, I recorded zero invented fields in those tests, and token usage dropped by 60 percent, because the responses contained four fields per ticker instead of the full holdings payload.</p><p>I also wrote the schema down as a contract the endpoint has to honor:</p><pre># GraphQL Contract (Schema)<br>type MarketData {<br>  ticker: String!<br>  price: Float!<br>  volatility30d: Float!<br>  sentiment: Float!<br>}<br><br>type Query {<br>  marketData(tickers: [String!]!): [MarketData!]!<br>}</pre><p>I wrote that contract down in two places: the GraphQL schema, and the blueprint&#39;s contract for the market worker&#39;s output. A worker reply that does not match the declared shape fails the contract instead of flowing into the supervisor as prose.</p><p>From then on, a bad request came back as a GraphQL error that named the field, instead of a confident answer built on a field the model had guessed. I spent less time checking whether a response shape was real, because the shape was fixed before the agent ran.</p><h3>The Step the Supervisor Cannot Skip</h3><p>The first version of this system was prompt driven: a supervisor model with a system prompt that listed the steps and said “You MUST delegate a compliance check before final synthesis.” It planned well. It also skipped steps. Twice, it moved to a final answer without running the compliance check at all, and a stronger prompt rule reduced the slips without eliminating them. Writing the step into the prompt turned out to be only a request to the model, and a request can be skipped.</p><p>So the order of work moved out of the prompt and into the blueprint. The rebalance workflow declares its stages, and synthesis is the last one. The compliance stage sits between the tax result and the final plan, and the workflow does not reach synthesis without passing through it. There is no instruction left for the supervisor to ignore, because the sequence now lives in the blueprint itself rather than in a prompt the model can drift away from.</p><p>The supervisor still does the planning and the synthesis itself. Given a request like “Rebalance client ABC123 for tax efficiency, holdings: AAPL 100 @ $150, MSFT 50 @ $300, target 60/40,” it breaks the goal into tasks, delegates the market and tax work in parallel where the workflow allows it, waits for the results, and synthesizes. It cannot reorder the stages, skip one, or call a worker that the blueprint does not declare. Static validation catches a workflow that references a missing agent before any model is called, and the contract tests run the whole shape against a mock model, so a broken spec fails in CI instead of in a live run.</p><p>The model names are set in one place, in the blueprint&#39;s provider block. The first version ran with gpt-4o on the primary provider and gpt-4o-mini for the rebalancer; the blueprint above names their current equivalents, gpt-5.6-sol and gpt-5.6-luChanging the model named in that block changes nothing about the architecture, and none of the results below depend on a specific model, because the steps that need exact answers do not use a model at all.</p><h3>Four Workers, and the Two I Fired the Model From</h3><h3>Market Agent</h3><p>This worker fetches current prices and volatility with the GraphQL template above. It is the one worker that still runs a small agent loop, and its tool list has exactly one entry: the approved query. Its prompt requires strict JSON, because earlier versions returned a paragraph about market conditions along with the numbers, and the supervisor then had to parse prose. The blueprint’s contract for this worker says the same thing in a checkable form: the output is a MarketData object, not a paragraph.</p><pre># agents.py (market worker binding, trimmed)<br><br>MARKET_AGENT_PROMPT = &quot;&quot;&quot;<br>  You are a Market Data Specialist. <br>  Use fetch_market_data to get prices, 30d volatility, and sentiment.<br>  Return a JSON object exactly like this:<br>  {<br>    &quot;AAPL&quot;: {&quot;price&quot;: 175.20, &quot;volatility&quot;: 0.18, &quot;sentiment&quot;: 0.7},<br>    &quot;MSFT&quot;: {&quot;price&quot;: 420.50, &quot;volatility&quot;: 0.15, &quot;sentiment&quot;: 0.8}<br>  }<br>  Round to 2 decimals. No extra text.<br>&quot;&quot;&quot;<br><br># bound in the blueprint to the market agent, with one tool: adapters.fetch_market_data</pre><p>Even with that prompt, the model sometimes added a greeting before the JSON. I added a regex fallback that extracts the first JSON object from the reply. That fallback should not have been necessary. The prompt already ended with the words &#39;No extra text,&#39; and the model still opened some replies with a greeting, so the regex stayed. The contract check behind it catches what the regex cannot: a reply with no valid JSON object in it fails the stage instead of reaching the supervisor.</p><h3>Tax Agent</h3><figure><img alt="A person at a desk examining financial documents," src="https://cdn-images-1.medium.com/max/1024/1*IAkbjmnxQzaGi9NgXrNlWQ.jpeg" /><figcaption>Tax math belongs with documents and a calculator: Oracle computes it, the model only formats the input.</figcaption></figure><p>This worker started as an LLM doing math, and that version failed on basic work. It calculated simple gain and loss incorrectly, and it could not keep cost basis straight across multiple lots in the same position. I removed the model from the calculation.</p><p>The tax logic now runs in Oracle, a Python library for tax-aware portfolio optimization. The model’s only role in this step is formatting the input. Oracle computes the result, and the worker returns it as JSON for the supervisor:</p><pre># adapters/tax.py<br><br>import pandas as pd<br>import json<br>from service.oracle import Oracle<br>from service.oracle_strategy import OracleStrategy<br>from service.helpers.enums import OracleOptimizationType<br><br>def run_tax_optimization(holdings_json: str) -&gt; str:<br>    holdings = json.loads(holdings_json)<br>    targets = {&quot;targets&quot;: [<br>        {&quot;asset_class&quot;: &quot;stock&quot;, &quot;target_pct&quot;: 0.6},<br>        {&quot;asset_class&quot;: &quot;bond&quot;, &quot;target_pct&quot;: 0.4}<br>    ]}<br>    tax_lots_data = []<br>    # ... populate tax_lots_data from holdings ...<br>    tax_lots_df = pd.DataFrame(tax_lots_data)<br>    prices_df = pd.DataFrame(...)  # from holdings<br>    strategy = OracleStrategy(..., optimization_type=OracleOptimizationType.TAX_AWARE)<br>    oracle = Oracle(strategy=strategy)<br>    result = oracle.optimize()<br>    return json.dumps({<br>        &quot;recommended_trades&quot;: result.trades.to_dict(&quot;records&quot;),<br>        &quot;tax_savings_estimate&quot;: result.tax_savings,<br>        &quot;drift_reduction&quot;: result.drift_reduction<br>    })</pre><p>After that change, the tax step stopped producing arithmetic errors in my runs, because Oracle was doing every calculation and the model was only formatting its input. The output also became repeatable: the same lots and prices produced the same trades, which made the traces useful for comparison instead of just recording.</p><h3>Compliance Agent</h3><p>Compliance had the same problem in a different form. Checking a concentration limit or a wash sale window is a set of fixed rules applied to dates and quantities. When I left it to the model, the checks were inconsistent between runs on the same trades.</p><p>I replaced it with simple-rule-engine in a plain Python function. The wash sale check uses Oracle’s precomputed conflict list instead of asking a model to reason about dates:</p><pre># adapters/compliance.py<br><br>from simpleruleengine.ruleset.rule_set_decision import RuleSetDecision<br>import json<br><br>def run_compliance_check(proposed_trades_json: str) -&gt; str:<br>    trades = json.loads(proposed_trades_json)<br>    # ... setup facts ...<br>    concentration_rule = RuleRowDecision(...)<br>    ruleset = RuleSetDecision(concentration_rule, ...)<br>    result = ruleset.evaluate(fact)<br>    return result</pre><p>Moving tax and compliance to code saved an estimated $0.02 per run in model calls. The more useful change was what it did to checking the work afterward. A pass or fail from the rules engine can be reproduced from the inputs. When a model produces the pass or fail instead, the only way to check it is to keep the trace and rerun it.</p><h3>Rebalancer Agent</h3><p>This one is close to a placeholder, and I am leaving that in because it is true of the experiment. Oracle and the Market Agent produce the substance. The Rebalancer takes their JSON outputs and writes the version a person reads: “Sell 20 shares of AAPL to reduce your stock exposure to 60 percent. This will generate a small capital gain of about $500.”</p><p>It runs on the small provider in the blueprint, with no tools at all:</p><pre># agents.py (rebalancer binding, trimmed)<br><br>REBALANCER_AGENT_PROMPT = &quot;&quot;&quot;<br>  You are a Portfolio Rebalancing Specialist. <br>  Synthesize the outputs into a clear plan.<br><br>Inputs: tax_optimization_result, market_data, compliance_status.<br><br>Output: plain-English summary with current snapshot, <br>        recommended trades, tax impact, compliance note. Keep it concise.<br>&quot;&quot;&quot;<br><br># bound in the blueprint to the rebalancer agent on the small provider, tools: none</pre><p>I kept the split because it follows what each side was actually good at. The model is good at turning three JSON documents into a readable paragraph. Producing the numbers inside those documents is where it kept failing, on tax lots and on compliance checks, so those calculations now happen before the documents reach it.</p><h3>Every Run, Recorded Step by Step</h3><p>A multi-agent run gives you a final answer and, without tracing, very little else. When an early version of this system recommended selling MSFT at a loss that was actually a gain, I had the recommendation in front of me and no record of which step had produced the wrong sign. I could rerun it, but a rerun is a different run.</p><figure><img alt="A close-up of colorful programming code on a comp" src="https://cdn-images-1.medium.com/max/1024/1*6oN68q-rTJ_v65WxTn0ewA.jpeg" /><figcaption>Reading a run back, step by step: the replay is where the wrong step in a failed run actually shows up.</figcaption></figure><p>That failure is why observability is a section of the blueprint instead of a wrapper I bolted on later. With tracing declared, every run publishes its steps to a trace event bus: each model call, each adapter call, and each worker&#39;s result, in order, with the token cost attached to the step that spent it. The events export as JSONL, and the studio view replays a recorded run step by step. When a number in the final plan looks wrong, I can open the trace and find the step that produced it, instead of rerunning the system and hoping the same failure happens again.</p><pre># pipeline.py (tracing is declared in the blueprint; this is what consumes it)<br>from pyagent_trace import TraceEventBus, JsonlExporter, CostTracker<br><br>bus = TraceEventBus()<br>bus.subscribe(JsonlExporter(&quot;runs/rebalance.jsonl&quot;))<br>bus.subscribe(CostTracker())<br>runtime = compile_blueprint(blueprint, adapters=ADAPTERS, trace_bus=bus)</pre><p>With a full run recorded, one view showed the supervisor’s plan, the Market Agent’s GraphQL call, Oracle’s tax lot calculation, and the compliance evaluation in sequence. The cost tracker also settled an argument with myself: the two workers I moved to code were not just more reliable, they were the ones whose per-run cost went to zero, because there was no model call left in them to pay for.</p><h3>What Broke: A Looping Worker, a Rate Limit, and a Skipped Checklist</h3><figure><img alt="A tired man resting at a desk in front of a lapto" src="https://cdn-images-1.medium.com/max/1024/1*8oMq7Beky7Mr_ksIv5io2A.jpeg" /><figcaption>The other half of the experiment: a looping worker, a rate limit, and a supervisor that skipped its own list.</figcaption></figure><p><strong>Sub-agents never returning.</strong> In an early version, the Market Agent looped on a tool that does not exist and kept spending tokens. The blueprint now carries a token budget per run, workers run under bounded execution, and each worker has to end with an explicit FINAL ANSWER line. A worker that hits the budget stops, and the trace shows where the money went.</p><p><strong>GraphQL rate limiting.</strong> The supervisor’s parallel calls hit the endpoint at the same time. A Semaphore(5) limiting requests per step fixed it.</p><p><strong>Supervisor ignoring its checklist.</strong> Covered above, and worth repeating in the failure list because it was the most dangerous one: the system produced a confident final plan with the compliance check never run. A prompt rule made the skips rarer. Declaring the stage order in the blueprint took the decision away from the model, and that is the version of the fix I trust.</p><p><strong>Oracle setup friction.</strong> Installing the CBC solver took a few tries. On a Mac, brew install coin-or-tools/coinor/cbc was the command that worked.</p><p><strong>Rules engine learning curve.</strong> simple-rule-engine does what I needed, and its documentation is sparse. The first rule took about an hour. The rest were faster once that one worked. Next time I would compare Zen Engine and Arta first, mainly for documentation and a visual editor.</p><h3>What I Would Do With Another Weekend</h3><p>Keep the human checkpoint where the blueprint already declares it, before execution, and test it properly, so no trade plan leaves the system without a person reading it.</p><p>Cache GraphQL responses in Redis. The Market Agent asked for the same tickers more than once in a single run.</p><p>Move the compliance rules to Zen Engine, for JSON decision models and a visual editor I can show a non-engineer.</p><p>Use the blueprint’s recovery policies for a single worker failure. In the current version, one failed worker still ends the whole rebalancing run, even though the spec has a place to declare what should happen instead.</p><p>If these workers ever move into separate services or come from different vendors, I would also put the tool calls behind MCP and the agent-to-agent handoffs behind A2A. Inside one Python process, direct function calls are simpler and they were not the source of any failure I recorded.</p><h3>The Scorecard: What the Model Kept, and What It Lost</h3><p>What the experiment produced was a supervisor that coordinates three kinds of work, not a portfolio manager. The results differed sharply by kind, and the pattern across them is the useful part.</p><p>Work the model did well: breaking a goal into tasks, delegating them, and writing the final explanation.</p><p>Work the model did badly, measured in my runs: arithmetic on tax lots, where it got basic gain and loss wrong; compliance checks, where the same trades did not always get the same answer; and free-form GraphQL, where it invented fields such as priceHistory and beta.</p><p>Work that improved when the model was removed from it: tax optimization, which became repeatable once Oracle computed it; compliance, which became a reproducible pass or fail; and market data, which used 60 percent fewer tokens once the query was fixed and only the tickers changed.</p><p>Work that improved when it moved out of the prompt and into the spec: the order of the stages, which a prompt rule could not hold and a declared workflow does.</p><p>If you want to try this yourself, clone the repo, add your own API keys, and run the same test I did: one run with the model writing its own GraphQL, and one with the fixed template. Then open the trace for the run that fails and find the exact call where it went wrong. In my own traces, the call where things went wrong was rarely the one I had suspected before opening them.</p><blockquote>If you enjoyed this, please clap and follow me on Medium for more experiments in AI agents, spec-driven workflows, and front-end engineering.</blockquote><blockquote>And if you’re a gym’er, then let the clap sound be loud: hold the button with all your power :)</blockquote><p>P.S. All the code from this experiment is in a GitHub repo here: <a href="https://github.com/me-saurabhkohli/wealth-agent">https://github.com/me-saurabhkohli/wealth-agent</a>. Run it, break it, and tell me what you built.</p><blockquote>P.P.S. Do not deploy this with real money. I am not a financial advisor, and neither is your LLM.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68aac89e6ebd" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/spec-driven-ai-wealth-manager-68aac89e6ebd">Spec-Driven AI Wealth Manager</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From ZooKeeper to KRaft: A Kafka Migration Guide]]></title>
            <link>https://medium.com/towards-data-engineering/from-zookeeper-to-kraft-a-kafka-migration-guide-b17818eb0714?source=rss-f630c0b97775------2</link>
            <guid isPermaLink="false">https://medium.com/p/b17818eb0714</guid>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[Saurabh Kohli]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 14:27:34 GMT</pubDate>
            <atom:updated>2026-08-05T14:27:34.150Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Kafka’s Metadata Architecture Changes, How to Design the Controller Quorum, and How to Migrate Safely</h4><p>Apache Kafka has changed one of the most important parts of its internal architecture.</p><p>For more than a decade, Kafka relied on Apache ZooKeeper to maintain cluster metadata and coordinate controller elections. Kafka 4.x no longer supports that model. Kafka now uses KRaft, its implementation of the Raft consensus protocol, to manage metadata directly.</p><p>For a new Kafka platform, the direction is straightforward: use <strong>KRaft</strong>.</p><p>For an existing platform, the decision requires more thought. Teams must choose between migrating the current cluster and building a replacement. They must design a controller quorum, validate security configuration, replace ZooKeeper-dependent tooling, rehearse rollback procedures, and decide when they can safely make the transition irreversible.</p><p>This is not simply a product upgrade. It changes how Kafka records its own state, elects controllers, distributes metadata, handles failures, and exposes operational health.</p><blockquote><strong><em>Version scope:</em></strong><em> This article targets Apache Kafka 4.3.x and Confluent Platform 8.3.x. Migration commands, configuration properties, and feature support can vary across maintenance releases. Validate every operational step against the documentation for the exact version you plan to run.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNUzp3ESGlWRmYfUCy_CrA.png" /><figcaption><em>Figure 1. Kafka moves metadata ownership from an external ZooKeeper ensemble to a Kafka-managed KRaft controller quorum and replicated metadata log.</em></figcaption></figure><h3>The question has changed from ‘whether’ to ‘how’</h3><p>Apache Kafka 4.0 removed ZooKeeper support. Kafka 3.9 became the final bridge release that can operate with ZooKeeper and support migration to KRaft.</p><p>Confluent Platform follows the same direction. Confluent Platform 7.9 is the final release line that supports ZooKeeper, while Confluent Platform 8.x requires KRaft.</p><p>A few years ago, teams could reasonably ask whether KRaft had matured enough for production. That discussion no longer determines the platform direction. Any organization that wants to remain on a supported Kafka release must eventually adopt KRaft.</p><p>The meaningful questions now concern timing and execution.</p><ul><li>Should the organization migrate the current cluster in place?</li><li>Should it build a new KRaft cluster and move applications gradually?</li><li>Can existing monitoring and administrative tools operate without direct ZooKeeper access?</li><li>Which migration phases still allow rollback?</li><li>How long should the platform remain in dual-write mode before the team finalizes the change?</li></ul><p>These decisions involve more than Kafka administrators. Application teams, infrastructure engineers, security teams, platform architects, operations leaders, and change-management boards all have a role.</p><p>KRaft simplifies the final architecture. Reaching that architecture still requires disciplined engineering.</p><h3>What ZooKeeper did for Kafka</h3><p>Kafka stores application records in topics and partitions. Producers write records to partition leaders, consumers read those records, and brokers store the data.</p><p>The cluster also needs another category of information: <strong><em>metadata</em></strong>.</p><p>Metadata tells Kafka which brokers belong to the cluster, which topics exist, how many partitions each topic contains, which broker leads each partition, which replicas remain synchronized, which access rules apply, and which configuration values have changed.</p><p>In the ZooKeeper architecture, Kafka stored much of this information outside Kafka.</p><p>ZooKeeper maintained a hierarchy of metadata records called <em>znodes</em>. Kafka elected one broker as the active controller. That controller watched ZooKeeper, interpreted changes, calculated state transitions, and sent instructions to the remaining brokers.</p><p>A useful way to understand the model is to imagine a distribution network. Kafka brokers act as warehouses that hold and move packages. ZooKeeper maintains the master inventory and routing register. The Kafka controller acts as the operations manager who reads that register and tells every warehouse what changed.</p><p>The system worked, but Kafka effectively depended on two distributed platforms. Kafka handled application records, while ZooKeeper maintained the operational map that allowed Kafka to function as a coordinated cluster.</p><blockquote>Did you find this article helpful?</blockquote><blockquote>Show some love with a few claps 👏 and let’s keep going.</blockquote><h3>Kafka operators had to manage two systems</h3><p>A production team did not operate only Kafka. It also deployed, secured, monitored, upgraded, backed up, and troubleshot ZooKeeper.</p><p>Each system had separate configuration, authentication, storage, capacity, monitoring, and failure characteristics. A Kafka incident could begin as a ZooKeeper incident. A session-expiration problem, storage issue, overloaded ZooKeeper node, authentication failure, or malformed znode could affect Kafka metadata operations even when the brokers appeared healthy.</p><p>This divided the operational model. Engineers often had to inspect Kafka logs, ZooKeeper state, controller behavior, and broker metadata before they could understand one platform failure.</p><h3>Controller failover required state reconstruction</h3><p>Under ZooKeeper, Kafka elected one broker as the active controller. When that controller failed, another broker took over.</p><p>The new controller then reconstructed the cluster state from ZooKeeper before it could safely coordinate new leader elections and metadata changes. The amount of work depended on the number of brokers, topics, partitions, replicas, configurations, and access-control entries in the cluster.</p><p>A controller failure did not always stop application traffic immediately. Existing partition leaders could often continue serving requests. However, Kafka could not safely coordinate new metadata transitions until the replacement controller became ready.</p><p>Larger clusters increased the amount of state the new controller had to rebuild.</p><h3>Metadata moved through several layers</h3><p>ZooKeeper stored the metadata. The Kafka controller watched ZooKeeper. The controller then distributed changes to brokers through controller-specific remote procedure calls.</p><p>The architecture created several handoffs:</p><pre>ZooKeeper<br>    |<br>    v<br>Kafka controller<br>    |<br>    v<br>Kafka brokers</pre><p>Kafka engineers had to reason about ZooKeeper state, controller state, controller epochs, broker metadata, and the timing of updates between them.</p><p>KRaft replaces this external coordination model with a metadata log managed directly by Kafka.</p><h3>How KRaft changes the architecture</h3><p>KRaft stands for Kafka Raft.</p><p>Raft is a consensus protocol. It allows several nodes to agree on one ordered sequence of changes, even when some nodes fail or temporarily lose connectivity.</p><p>In KRaft mode, a group of Kafka processes forms the controller quorum. One controller becomes the active leader. The remaining controllers follow it and continuously replicate the metadata log.</p><p>The active controller records every metadata change in that log. A change becomes committed after a majority of controller voters acknowledge it. Controllers and brokers then apply the committed records in order.</p><p>Instead of keeping its master operational register in ZooKeeper, Kafka now maintains that register itself.</p><p>When Kafka creates a topic, moves a partition, changes an access rule, registers a broker, or updates a configuration, it writes a corresponding record into the metadata log. Every participant processes the same ordered history.</p><h3>Metadata becomes an ordered event log</h3><p>This design aligns closely with Kafka’s core strength: storing and processing ordered records.</p><p>The internal metadata log is associated with __cluster_metadata, but it is not a conventional application topic. Applications do not publish to it or consume from it. The controller quorum owns it as a specialized consensus log.</p><p>Each metadata record represents a change to cluster state. Controllers apply those records to build an in-memory representation of the current cluster.</p><p>Kafka also creates metadata snapshots. A snapshot captures the current state at a known log position so that a controller does not need to replay the complete metadata history during recovery.</p><p>The result resembles a carefully maintained financial ledger. Every approved transaction appears in order, each participant agrees on the committed balance, and a snapshot provides a known starting point for reconstruction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K05ECAMq_z7GBzuHS2_FGg.png" /><figcaption><em>Figure 2. Administrative actions become ordered metadata records that KRaft controllers commit and Kafka brokers apply in sequence.</em></figcaption></figure><h3>Standby controllers remain prepared</h3><p>In ZooKeeper mode, a newly elected controller had to rebuild cluster state from the external ZooKeeper hierarchy.</p><p>In KRaft mode, controller followers continuously replicate the metadata log and maintain their own in-memory state images.</p><p>When the active controller fails, an eligible follower can win the election and take responsibility using the metadata it already holds.</p><p>This reduces failover work, but it does not remove network, storage, or election dependencies. Controllers still need to communicate, establish a majority, confirm log state, and elect a leader.</p><p>Actual failover time depends on controller health, network latency, disk behavior, garbage collection, metadata lag, and quorum configuration. Architecture teams should test and measure controller failover in their own environment rather than promise one universal recovery time.</p><h3>Brokers receive metadata in a defined order</h3><p>Under KRaft, brokers receive committed metadata from the controller quorum and apply it in sequence.</p><p>This gives Kafka a clearer way to express whether a broker has current metadata. Operators can compare the broker’s applied log position with the committed metadata position.</p><p>For example, assume that a broker has applied metadata through record 10,000 while the committed metadata log has reached record 10,020. Kafka can directly report that the broker remains twenty metadata records behind.</p><p>The difference becomes a measurable lag rather than a state that operators must infer by comparing ZooKeeper, controller, and broker behavior.</p><h3>Kafka now owns the full metadata lifecycle</h3><p>KRaft brings metadata persistence, consensus, controller elections, snapshots, recovery, and metadata versioning into Kafka.</p><p>The architecture becomes more coherent:</p><pre>KRaft controller quorum<br>        |<br>        v<br>Replicated metadata log<br>        |<br>        v<br>Controllers and brokers apply committed records</pre><p>KRaft does not eliminate distributed-systems failures. It removes the external metadata dependency and allows Kafka to evolve its metadata architecture as part of the same platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLQdz_19maoOxUd2Mwml2Q.png" /><figcaption><em>Figure 3. ZooKeeper mode separates metadata coordination from Kafka, while KRaft brings consensus, metadata replication, controller state, and administrative tooling into Kafka.</em></figcaption></figure><blockquote>Did you find this article helpful?</blockquote><blockquote>Show some more love with a few more claps 👏</blockquote><blockquote>and let’s keep going.</blockquote><h3>What happens when the controller quorum fails</h3><p>This area requires careful explanation because a cluster can remain partially functional while operating in a critical state.</p><p>Losing the KRaft controller majority does not always stop every producer and consumer immediately. Existing partition leaders may continue serving requests because brokers still hold previously applied metadata.</p><p>However, the cluster cannot safely commit new metadata changes without controller consensus.</p><p>Kafka cannot reliably complete actions such as electing a new partition leader, updating the in-sync replica set, creating or deleting topics, changing topic configuration, reassigning partitions, registering new brokers, completing some consumer-group transitions, or applying new access-control changes.</p><p>Imagine that every warehouse still has yesterday’s delivery plan, but the central operations office can no longer issue new instructions. The warehouses can continue processing work that still matches the existing plan. If a warehouse closes, a route changes, or inventory must move, the network cannot coordinate the adjustment.</p><p>The system is not completely unavailable, but it has lost the ability to adapt safely.</p><p>That distinction should influence incident classification. A missing controller quorum requires urgent action even when message-throughput dashboards still show successful requests. The next broker failure, replica problem, consumer-group transition, or partition-leader loss can expand the impact because Kafka cannot coordinate recovery.</p><p>ZooKeeper failures had a related characteristic. Existing Kafka leaders could continue processing some traffic while the cluster lost the ability to coordinate metadata transitions. KRaft improves integration and observability, but it does not change the basic principle: without consensus, a distributed system cannot safely agree on new state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeKeDOXX6B08FkYXoyONQA.png" /><figcaption><em>Figure 4. Existing leaders may continue serving traffic after the controller majority is lost, but metadata-changing operations remain blocked until the quorum recovers.</em></figcaption></figure><h3>Designing the KRaft controller topology</h3><p>Kafka allows a process to act as a broker, a controller, or both.</p><pre>process.roles = broker<br>process.roles = controller<br>process.roles = broker, controller</pre><p>A broker stores partitions and handles producer and consumer traffic.</p><p>A controller participates in the metadata quorum.</p><p>A combined process performs both functions.</p><h3>Separate controllers from brokers in critical production environments</h3><p>For most important production platforms, run brokers and controllers as separate processes.</p><p>This separation gives the controller quorum independent CPU, memory, storage, network capacity, maintenance procedures, and failure domains.</p><p>A heavily loaded broker can experience disk saturation, network congestion, long garbage-collection pauses, or resource pressure during partition movement. If the same process also serves as a controller, the application workload can interfere with metadata consensus.</p><p>The distinction is similar to separating the team that moves freight from the team that controls routes and dispatch. Both functions matter, but a surge in freight movement should not delay the system that decides where freight must go.</p><p>Separate roles also let teams scale brokers without changing the controller quorum. A platform may grow from ten brokers to fifty brokers while retaining the same three-controller metadata quorum.</p><h3>Combined mode still has a valid purpose</h3><p>Combined mode reduces infrastructure and deployment complexity. It works well for local development, continuous integration, demonstrations, training, disposable test environments, and selected small noncritical deployments.</p><p>Do not make the decision only from broker count.</p><p>A three-broker cluster may support payments, trading, healthcare, government, or other critical workloads. Business importance, recovery objectives, traffic patterns, tenant count, and operational capacity matter more than the number of machines.</p><h3>Choosing the controller quorum size</h3><p>A KRaft quorum follows majority rules.</p><p>A quorum with one controller tolerates no controller failure. A three-controller quorum can tolerate one unavailable controller. A five-controller quorum can tolerate two.</p><p>Three controllers provide the normal production default. They can survive one controller failure while retaining the majority required to elect a leader and commit metadata.</p><p>Five controllers make sense when the platform must survive two simultaneous voter failures or when the failure-domain design requires additional placement flexibility.</p><p>Avoid two-controller quorums. Both controllers must remain available to maintain a majority. If either controller fails, the quorum loses decision-making capability.</p><p>Four controllers usually provide little advantage over three. Both configurations tolerate only one failure, while four controllers create another node to deploy, secure, patch, and monitor.</p><p>A simple committee example makes the logic clear. A three-person committee needs two votes to decide. If one member becomes unavailable, the remaining two can still agree. A two-person committee needs both members. If either member leaves, the committee cannot make a decision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5nRlV-4cV56rg2ks14iGg.png" /><figcaption><em>Figure 5. Three controllers provide the normal production default, while five controllers support designs that must tolerate two concurrent controller failures.</em></figcaption></figure><h3>Place controllers for availability and latency</h3><p>Controller placement should reflect explicit failure scenarios.</p><p>In a multi-availability-zone deployment, spread controllers across independent zones so the cluster retains a majority after the failure the architecture promises to survive.</p><p>Geographic separation alone does not create a good design. Controllers must communicate quickly enough to commit metadata and elect leaders within the platform’s recovery objectives.</p><p>A five-controller quorum spread across distant regions may appear resilient on a diagram, but wide-area latency can slow consensus. A poorly planned regional partition can also produce unexpected quorum behavior.</p><p>For a multi-region cluster, document where the quorum majority resides, which regional failures the cluster must tolerate, the expected latency between voters, the behavior during partial connectivity loss, and the procedure for restoring quorum.</p><p>Also document what controller unavailability means for consumer groups, broker registration, partition leadership, and administrative operations.</p><p>Quorum placement represents an architecture decision, not a node-placement checkbox.</p><h3>Size controllers from metadata workload</h3><p>Controllers do not store application-topic records, but they handle a critical workload.</p><p>Their resource requirements depend on the number of brokers, topics, partitions, replicas, configurations, access-control entries, consumer groups, partition reassignments, and metadata changes occurring in the cluster.</p><p>Provide predictable CPU, sufficient memory, stable network connectivity, and durable low-latency storage.</p><p>Configure a dedicated metadata directory:</p><pre>metadata.log.dir = /var/lib/kafka/kraft-metadata</pre><p>The metadata log may remain much smaller than broker data, but it participates directly in metadata consensus. Storage with unstable fsync latency can delay commits and contribute to election instability.</p><p>Avoid choosing one universal controller size for every cluster. Test the quorum using production-scale metadata and measure commit latency, election latency, controller event queues, snapshot behavior, CPU, memory, garbage collection, and storage latency.</p><h3>Prefer dynamic controller membership</h3><p>KRaft supports static and dynamic controller quorums.</p><p>A static quorum defines every voter in configuration:</p><pre>controller.quorum.voters = 3000@controller1.example.com:9093,<br>                           3001@controller2.example.com:9093,<br>                           3002@controller3.example.com:9093</pre><p>A dynamic quorum uses bootstrap endpoints to discover the active membership:</p><pre>controller.quorum.bootstrap.servers = controller1.example.com:9093,<br>                                      controller2.example.com:9093,<br>                                      controller3.example.com:9093</pre><p>The bootstrap list does not permanently define the voter set. It gives processes a way to locate the active quorum.</p><p>Dynamic membership lets administrators add or remove controllers through quorum operations. This simplifies controller replacement and reduces the need for coordinated configuration changes across every broker and controller.</p><p>For a new cluster on a release that fully supports dynamic membership, use it unless a documented platform limitation requires a static quorum.</p><h3>Establish a production configuration baseline</h3><p>The following examples show the structure of separate controller and broker configurations. They do not replace an organization’s security, networking, capacity, secrets-management, audit, and compliance standards.</p><h3>Controller configuration</h3><pre>process.roles = controller<br>node.id = 3000<br><br>controller.quorum.bootstrap.servers = controller1.example.com:9093,<br>                                      controller2.example.com:9093,<br>                                      controller3.example.com:9093<br><br>listeners = CONTROLLER://:9093<br>controller.listener.names = CONTROLLER<br>listener.security.protocol.map = CONTROLLER:SSL<br>metadata.log.dir = /var/lib/kafka/kraft-metadata<br>authorizer.class.name = org.apache.kafka.metadata.authorizer.StandardAuthorizer<br>super.users=User:CN=kafka-admin</pre><p>Protect the controller listener from general client access. Restrict network paths, authenticate communication, encrypt controller traffic, and manage controller certificates with the same discipline used for other critical infrastructure identities.</p><h3>Broker configuration</h3><pre>process.roles = broker<br>node.id = 1<br>controller.quorum.bootstrap.servers = controller1.example.com:9093,<br>                                      controller2.example.com:9093,<br>                                      controller3.example.com:9093<br>controller.listener.names = CONTROLLER<br>listeners = INTERNAL://:9092,EXTERNAL://:9094<br>advertised.listeners=INTERNAL://broker1.internal.example.com:9092,EXTERNAL://kafka.example.com:9094<br>listener.security.protocol.map=INTERNAL:SSL,EXTERNAL:SASL_SSL,CONTROLLER:SSL<br>inter.broker.listener.name=INTERNAL<br>log.dirs=/var/lib/kafka/data-1,/var/lib/kafka/data-2<br>default.replication.factor=3<br>min.insync.replicas=2<br>offsets.topic.replication.factor=3<br>transaction.state.log.replication.factor=3<br>transaction.state.log.min.isr=2<br>authorizer.class.name=org.apache.kafka.metadata.authorizer.StandardAuthorizer</pre><p>Controllers and brokers share one node-ID namespace. A controller cannot reuse an existing broker ID.</p><p>Many teams reserve a separate numeric range for controllers, such as 3000 and above. The actual range matters less than consistently enforcing it through configuration management and deployment automation.</p><h3>Bootstrapping a new KRaft cluster</h3><p>Create one cluster ID for the entire Kafka cluster:</p><pre>CLUSTER_ID=&quot;$(bin/kafka-storage.sh random-uuid)&quot;<br>echo &quot;${CLUSTER_ID}&quot;</pre><p>One bootstrap approach initializes the first controller as a standalone quorum and then adds the remaining controllers dynamically.</p><p>Format the first controller:</p><pre>bin/kafka-storage.sh format \<br>  --cluster-id &quot;${CLUSTER_ID}&quot; \<br>  --standalone \<br>  --config config/controller.properties</pre><p>Format additional controllers without creating another initial quorum:</p><pre>bin/kafka-storage.sh format \<br>  --cluster-id &quot;${CLUSTER_ID}&quot; \<br>  --no-initial-controllers \<br>  --config config/controller.properties</pre><p>Start the additional controller, allow it to catch up, and inspect quorum replication:</p><pre>bin/kafka-metadata-quorum.sh \<br>  --bootstrap-controller controller1.example.com:9093 \<br>  describe --replication</pre><p>Then add it to the voter set:</p><pre>bin/kafka-metadata-quorum.sh \<br>  --command-config config/controller-client.properties \<br>  --bootstrap-controller controller1.example.com:9093 \<br>  add-controller</pre><p>Kafka also supports initializing several controllers together through --initial-controllers.</p><p>Each controller requires a unique directory ID:</p><pre>CONTROLLER_0_UUID=&quot;$(bin/kafka-storage.sh random-uuid)&quot;<br>CONTROLLER_1_UUID=&quot;$(bin/kafka-storage.sh random-uuid)&quot;<br>CONTROLLER_2_UUID=&quot;$(bin/kafka-storage.sh random-uuid)&quot;</pre><p>Build one identical initial-controller string:</p><pre>INITIAL_CONTROLLERS=&quot;3000@controller1.example.com:9093:${CONTROLLER_0_UUID},3001@controller2.example.com:9093:${CONTROLLER_1_UUID},3002@controller3.example.com:9093:${CONTROLLER_2_UUID}&quot;</pre><p>Use that exact string while formatting each initial controller:</p><pre>bin/kafka-storage.sh format \<br>  --cluster-id &quot;${CLUSTER_ID}&quot; \<br>  --initial-controllers &quot;${INITIAL_CONTROLLERS}&quot; \<br>  --config config/controller.properties</pre><p>Format brokers with the same cluster ID:</p><pre>bin/kafka-storage.sh format \<br>  --cluster-id &quot;${CLUSTER_ID}&quot; \<br>  --no-initial-controllers \<br>  --config config/server.properties</pre><p>Start the controller quorum before starting brokers.</p><p>The cluster ID, node ID, and directory ID serve different purposes. The cluster ID identifies the whole Kafka cluster. The node ID identifies one broker or controller. The directory ID identifies one formatted metadata directory.</p><p>Do not interchange them simply because they all appear as generated identifiers.</p><h3>Bootstrap SCRAM credentials before startup</h3><p>KRaft stores SCRAM credentials in the metadata log.</p><p>If controllers or brokers require a SCRAM identity before the cluster becomes fully available, add that credential during storage initialization:</p><pre>bin/kafka-storage.sh format \<br>  --cluster-id &quot;${CLUSTER_ID}&quot; \<br>  --standalone \<br>  --config config/controller.properties \<br>  --add-scram &#39;SCRAM-SHA-512=[name=&quot;admin&quot;,password=&quot;&lt;secret&gt;&quot;]&#39;</pre><p>After brokers become available, manage application credentials through Kafka’s administrative APIs:</p><pre>bin/kafka-configs.sh \<br>  --bootstrap-server broker1.example.com:9092 \<br>  --command-config config/admin-client.properties \<br>  --alter \<br>  --add-config &#39;SCRAM-SHA-512=[iterations=8192,password=&lt;secret&gt;]&#39; \<br>  --entity-type users \<br>  --entity-name app-payments</pre><p>Use SCRAM with TLS. SCRAM provides credential verification, while TLS protects communication and prevents sensitive authentication data from crossing an unencrypted network.</p><h3>Observability changes with KRaft</h3><p>ZooKeeper dashboards do not become KRaft dashboards by changing a label.</p><p>KRaft introduces a different set of operational questions. Does the quorum have a leader? Are followers caught up? How long do metadata commits take? How often does controller leadership change? How far behind is each broker’s metadata image? Are snapshots completing? Is the controller event queue growing? Are controller disks slowing consensus?</p><p>Install this visibility before migration. The team needs to observe KRaft during the transition, not only after ZooKeeper disappears.</p><p>The most important signals include:</p><ul><li>Current Raft state</li><li>Current controller leader</li><li>Metadata high watermark</li><li>Commit latency</li><li>Election latency</li><li>Active controller count</li><li>Controller-election frequency</li><li>Metadata processing errors</li><li>Offline partitions</li><li>Broker metadata lag</li><li>Metadata-application errors</li></ul><p>Prometheus metric names depend on the JMX exporter configuration. Validate exported names in the target environment instead of copying alert expressions unchanged from another platform.</p><p>Avoid arbitrary global thresholds.</p><p>A five-second metadata-lag alert may be appropriate in one environment and meaningless in another. Build thresholds from observed baselines, metadata mutation rates, traffic patterns, and recovery objectives.</p><p>Metrics alone are not enough. Maintain synthetic tests for topic administration, producer and consumer traffic, consumer-group rebalancing, ACL changes, broker restarts, and controller failover.</p><p>A cluster can report active processes while important workflows have stopped progressing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQN2YUjZwyazzEokDkFYRA.png" /><figcaption><em>Figure 6. KRaft operations require visibility into quorum state, controller elections, commit latency, metadata lag, offline partitions, and metadata-processing errors.</em></figcaption></figure><h3>Migrating an existing ZooKeeper cluster</h3><p>Kafka 4.x cannot perform the ZooKeeper-to-KRaft migration because it no longer supports ZooKeeper mode.</p><p>An open-source Kafka deployment must first reach a supported 3.x bridge release. Kafka 3.9 serves as the final migration bridge.</p><pre>Existing ZooKeeper cluster<br>        |<br>        v<br>Upgrade to Kafka 3.9<br>        |<br>        v<br>Migrate metadata to KRaft<br>        |<br>        v<br>Validate and finalize<br>        |<br>        v<br>Upgrade to Kafka 4.x</pre><p>For Confluent Platform, version 7.9.x provides the most direct bridge because it supports ZooKeeper migration and dynamic controller membership.</p><p>Do not combine every change into one maintenance event. A safer program separates the platform-version upgrade, the ZooKeeper-to-KRaft migration, and the later move to a KRaft-only major release.</p><p>This separation gives the team clear health checks and rollback boundaries after each significant change.</p><h3>Preparation determines migration safety</h3><p>The migration commands receive most of the attention, but preparation determines whether the migration succeeds.</p><p>Confluent provides the kafka-migration-check utility in supported maintenance releases:</p><pre>kafka-migration-check preflight-check \<br>  --controller-config ./etc/kafka/kraft/controller.properties</pre><p>Use the tool, but do not treat it as a replacement for architecture and operational review.</p><h3>Validate version alignment</h3><p>Run the same supported maintenance version across brokers and migration controllers.</p><p>Confirm Java compatibility, client compatibility, enabled features, Cluster Linking requirements, authorization behavior, and vendor-specific extensions.</p><p>Record the current inter-broker protocol and relevant configuration before making changes.</p><h3>Audit ZooKeeper ACLs</h3><p>Long-running Kafka clusters may contain ZooKeeper ACL entries created by old scripts, earlier Kafka releases, or custom administration tools.</p><p>Some entries may use malformed principals, unexpected resource patterns, missing prefixes, or wildcard combinations that the migration does not accept.</p><p>Review the ACLs before starting KRaft controllers.</p><p>This may appear to be routine administration, but it directly affects controller startup. A malformed ACL can migrate into the new metadata system and prevent a controller from becoming operational.</p><h3>Check every broker storage directory</h3><p>A broker may use several log.dirs.</p><p>Confirm that every directory remains online and writable. Resolve disk failures, capacity problems, mount issues, and ownership errors before migration.</p><p>A rolling migration assumes that brokers can restart reliably. A pre-existing storage problem can turn a controlled restart into an unrelated outage.</p><h3>Inventory ZooKeeper dependencies</h3><p>Search infrastructure and application repositories for:</p><pre>--zookeeper<br>zkCli<br>zookeeper-shell<br>zookeeper.connect</pre><p>Also inspect monitoring scripts, backup procedures, broker discovery, topic administration, ACL management, deployment automation, management interfaces, and integration-test fixtures.</p><p>Anything that reads ZooKeeper directly must move to supported Kafka APIs or tools.</p><h3>Validate security behavior</h3><p>Determine whether the platform uses open-source Kafka ACLs, Confluent RBAC, or a custom authorization system.</p><p>Confirm controller authentication, controller-to-ZooKeeper access during migration, controller-listener encryption, broker-to-controller trust, post-migration authorizer configuration, service identities, certificates, and secret-provider behavior.</p><h3>Rehearse at representative scale</h3><p>A small functional test cannot reproduce the behavior of a large metadata migration.</p><p>The staging environment should approximate production topic and partition counts, broker count, ACL volume, storage layout, security, cluster links, monitoring, automation, and restart duration.</p><p>Measure both migration and rollback. Use that evidence to plan the production change.</p><h3>The five migration phases</h3><p>The Confluent migration model moves through five phases. The observable states include:</p><pre>PREMIGRATION<br>HYBRID_DUAL_WRITE<br>PURE_DUAL_WRITE<br>FINALIZED</pre><p>Each state has a different rollback profile.</p><h4>Phase 1: Confirm the ZooKeeper baseline</h4><p>The cluster still operates completely in ZooKeeper mode.</p><p>Before introducing KRaft controllers, confirm broker and partition health, capture configuration, export authorization state, record cluster and broker IDs, complete the preflight check, validate dashboards, and assign rollback authority.</p><p>Do not begin migration while the existing cluster already has unresolved broker, disk, replication, or security problems.</p><h4>Phase 2: Start KRaft controllers in migration mode</h4><p>Retrieve the existing Kafka cluster ID. The new controllers must use the same cluster identity.</p><p>Configure the controllers:</p><pre>process.roles=controller<br>node.id=3000<br><br>controller.quorum.bootstrap.servers=controller1.example.com:9093,controller2.example.com:9093,controller3.example.com:9093<br>controller.listener.names=CONTROLLER<br>listeners=CONTROLLER://:9093<br>zookeeper.metadata.migration.enable=true<br>zookeeper.connect=zk1.example.com:2181,zk2.example.com:2181,zk3.example.com:2181<br>confluent.cluster.link.metadata.topic.enable=true</pre><p>Use controller IDs that do not overlap with broker IDs.</p><p>Format the controller metadata storage with the existing cluster ID:</p><pre>bin/kafka-storage.sh format \<br>  --config ./etc/kafka/controller.properties \<br>  --cluster-id &quot;${EXISTING_CLUSTER_ID}&quot; \<br>  --initial-controllers &quot;3000@controller1.example.com:9093:&lt;uuid1&gt;,3001@controller2.example.com:9093:&lt;uuid2&gt;,3002@controller3.example.com:9093:&lt;uuid3&gt;&quot;</pre><p>Start the controllers and check migration state:</p><pre>kafka-migration-check status \<br>  --controller-config ./etc/kafka/kraft/controller.properties</pre><p>The expected state is:</p><pre>PREMIGRATION</pre><p>The brokers still use ZooKeeper at this point. If the team needs to stop, it can remove the new controllers without changing the broker architecture.</p><h4>Phase 3: Enter hybrid dual-write mode</h4><p>Add the migration settings to each broker and restart brokers one at a time.</p><pre>broker.id=0<br><br>zookeeper.connect=zk1.example.com:2181,zk2.example.com:2181,zk3.example.com:2181<br>zookeeper.metadata.migration.enable=true<br>controller.quorum.bootstrap.servers=controller1.example.com:9093,controller2.example.com:9093,controller3.example.com:9093<br>controller.listener.names=CONTROLLER<br>confluent.cluster.link.metadata.topic.enable=true</pre><p>As the brokers restart, the KRaft controller assumes metadata leadership and maintains compatible state in both KRaft and ZooKeeper.</p><p>The expected state becomes:</p><pre>HYBRID_DUAL_WRITE</pre><p>Kafka now writes metadata into the KRaft log while keeping ZooKeeper synchronized. The new architecture drives the cluster, but the previous metadata system still receives an updated copy.</p><p>This stage preserves a controlled rollback path.</p><h4>Phase 4: Convert every broker to KRaft</h4><p>Restart brokers again with KRaft configuration:</p><pre>process.roles=broker<br>node.id=0<br><br>controller.quorum.bootstrap.servers=controller1.example.com:9093,controller2.example.com:9093,controller3.example.com:9093<br>controller.listener.names=CONTROLLER</pre><p>Remove the ZooKeeper migration properties from each broker according to the release-specific procedure.</p><p>For open-source Kafka ACLs, use:</p><pre>authorizer.class.name=org.apache.kafka.metadata.authorizer.StandardAuthorizer</pre><p>Confluent RBAC deployments must apply the documented KRaft access-rule provider configuration.</p><p>After every broker runs in KRaft mode, the controllers continue maintaining ZooKeeper metadata for rollback.</p><p>The expected state becomes:</p><pre>PURE_DUAL_WRITE</pre><p>This state provides the final practical rollback window.</p><p>Remain here long enough to exercise real platform behavior. Test peak traffic, broker restarts, controller elections, consumer-group rebalances, topic administration, ACL changes, partition reassignments, cluster replication, backups, recovery, and application failover.</p><p>Choose the validation period from the actual business cycle.</p><p>A financial platform may need to cover market open, market close, overnight processing, and weekly activity. A retail platform may need to cover peak shopping traffic. A batch-oriented platform may need to complete its month-end processing.</p><p>A short smoke test cannot provide the same evidence.</p><h4>Phase 5: Finalize KRaft</h4><p>After validation, remove the migration properties from controllers and restart them one at a time.</p><pre># Remove:<br># zookeeper.metadata.migration.enable=true<br># zookeeper.connect=...<br># confluent.cluster.link.metadata.topic.enable=true</pre><p>The expected state becomes:</p><pre>FINALIZED</pre><p>Kafka no longer writes metadata to ZooKeeper.</p><p>The supported rollback path ends at this point.</p><p>Shut down ZooKeeper only after the platform team confirms the final KRaft state, validates monitoring, and completes the operational change record.</p><p>Retain ZooKeeper backups according to the organization’s recovery, audit, and evidence-retention policies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSEteME0BosHpYPmkuhc8g.png" /><figcaption><em>Figure 7. The migration progresses from ZooKeeper-only operation through hybrid and pure dual-write states before reaching the irreversible finalized KRaft state.</em></figcaption></figure><h3>Rollback is a procedure, not a button</h3><p>Rollback differs by migration phase.</p><p>Before broker conversion, the team may only need to stop and remove the new controllers.</p><p>During hybrid or pure dual-write operation, rollback can require stopping KRaft controllers, cleaning documented migration state in ZooKeeper, removing KRaft metadata directories, restoring broker properties, reversing authorizer changes, restoring protocol settings, and restarting every broker.</p><p>Some documented rollback procedures include direct ZooKeeper modifications. Treat those commands as controlled destructive operations, not as instructions to improvise during an incident.</p><p>The production change record should contain the official version-specific rollback guide, commands grouped by phase, named decision owners, required access credentials, expected validation results, and the latest safe rollback point.</p><p>After finalization, rollback to ZooKeeper is no longer supported.</p><h3>When rebuilding provides a better path</h3><p>In-place migration is not the only responsible architecture.</p><p>A blue-green strategy creates a new KRaft cluster, replicates the required data and configuration, validates the environment, and moves applications when the platform is ready.</p><p>An in-place migration resembles renovating a building while people continue working inside it. A blue-green migration resembles constructing a new building, moving the inventory, validating operations, and then redirecting traffic.</p><p>The first approach avoids moving every workload. The second provides a cleaner fallback because the previous environment remains available.</p><p>Neither option is universally safer.</p><p>Blue-green replacement deserves serious consideration when the existing cluster requires several upgrade hops, the organization already plans to change infrastructure, the current configuration contains years of undocumented exceptions, or direct ZooKeeper dependencies have accumulated across operational tools.</p><p>It may also work well when retention remains short, replication volume remains manageable, application teams can coordinate endpoint changes, or the organization plans to move to a managed Kafka service.</p><p>The approach introduces its own work. Teams must migrate topics, data, consumer offsets, ACLs, quotas, topic configuration, schemas, connectors, producers, and consumers. They must also control dual writes and verify data completeness.</p><p>Confluent Cluster Linking can simplify selected offset and metadata migration scenarios. MirrorMaker 2 provides cross-cluster replication for Apache Kafka, but teams must validate offset behavior and cutover semantics carefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v4tOACFobDUcbaRRhyovaw.png" /><figcaption><em>Figure 8. In-place migration preserves cluster identity and reduces endpoint changes, while blue-green migration provides parallel validation and a cleaner fallback at the cost of replication and cutover work.</em></figcaption></figure><h3>What KRaft improves</h3><p>KRaft removes ZooKeeper as Kafka’s metadata dependency. Teams can consolidate deployment, security review, monitoring, upgrades, and incident diagnosis around Kafka.</p><p>The team still operates a consensus system. That consensus system now belongs to Kafka.</p><p>Controller followers continuously replicate metadata and maintain current state images. This reduces the reconstruction work required during controller leadership changes.</p><p>KRaft also exposes quorum state, controller identity, metadata offsets, commit latency, election latency, snapshots, and broker metadata lag through Kafka-native tooling.</p><p>Dynamic membership improves controller replacement. Current Kafka releases also build future platform capabilities around KRaft rather than ZooKeeper.</p><h3>What the transition costs</h3><p>The migration affects infrastructure, security, monitoring, operations, applications, and governance. Large Kafka estates should manage it as a platform program with standard patterns, migration waves, reusable automation, and measurable exit criteria.</p><p>Engineers also need new operational knowledge. They must understand Raft majority behavior, controller elections, metadata offsets, snapshot behavior, broker fencing, metadata lag, quorum recovery, controller membership, and controller-listener security.</p><p>Legacy tools that read ZooKeeper directly will stop working. The failure may not appear during migration. It may surface later when an engineer tries to apply an ACL, inspect cluster state, execute a backup, or respond to an incident.</p><p>Finalization also removes the ZooKeeper fallback. Dual-write mode provides a controlled transition, but the final step makes the new metadata architecture authoritative.</p><p>KRaft replaces ZooKeeper problems with a different set of operational concerns: quorum loss, slow controller storage, election churn, metadata lag, incorrect membership changes, duplicate node IDs, incorrect bootstrap configuration, lost metadata directories, and exposed controller endpoints.</p><p>The architecture improves. The requirement for operational discipline remains.</p><h3>Common mistakes</h3><p>Teams often reuse a broker ID for a controller without recognizing that both roles share the same node-ID namespace. Reserve a controller range and enforce it through automation.</p><p>Two-controller quorums also create a common design error. They provide no controller-failure tolerance because either failure removes the majority.</p><p>Combined mode can look attractive because it reduces the initial infrastructure footprint. That does not automatically make it the right production topology. Evaluate resource isolation, maintenance independence, workload criticality, and recovery objectives first.</p><p>Controller metadata should not sit on unstable storage. The metadata log participates directly in consensus, so unpredictable disk latency can delay commits and contribute to election instability.</p><p>New clusters should use dynamic membership when the target release supports it. Static voter configuration creates avoidable operational coupling during controller replacement.</p><p>The ZooKeeper ACL audit remains one of the most important migration controls. Malformed ACL entries can prevent migration controllers from starting.</p><p>Teams must also apply the correct authorizer transition. Open-source Kafka ACL deployments use StandardAuthorizer in KRaft. Confluent RBAC environments require the documented KRaft access-rule provider.</p><p>Monitoring should arrive before migration. The platform team needs controller and metadata visibility while the transition is happening.</p><p>Finally, do not treat successful produce requests as proof that the entire cluster remains healthy. Brokers may continue serving existing partition leaders while the cluster lacks controller consensus. Monitor metadata changes, group behavior, leader elections, and administrative workflows in addition to message throughput.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UmefwnErjIeDDYnksHa0CQ.png" /><figcaption><em>Figure 9. Frequent migration failures include duplicate node IDs, weak quorum design, unstable controller storage, incomplete ACL analysis, incorrect authorizer changes, missing observability, and premature finalization.</em></figcaption></figure><h3>Choosing the migration path</h3><p>A new production cluster should use KRaft with separate broker and controller roles when availability and isolation matter.</p><p>Development and CI environments can use combined mode where operational simplicity provides more value than role separation.</p><p>An Apache Kafka ZooKeeper cluster should move to Kafka 3.9, complete and validate the KRaft migration, then proceed to Kafka 4.x.</p><p>A Confluent Platform 7.9 cluster can follow the supported in-place migration. Older Confluent clusters should first move to a supported bridge release.</p><p>Clusters with several upgrade hops, short retention, significant infrastructure redesign, or extensive ZooKeeper coupling should evaluate blue-green replacement.</p><p>Multi-region clusters require dedicated quorum-placement analysis because the location of the majority influences metadata availability and latency.</p><p>A small but business-critical cluster may still require separate controllers. Criticality matters more than broker count.</p><p>When the organization already plans to move to a managed Kafka service, it should consider aligning that move with the KRaft transition rather than executing two independent platform programs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQ1LDjRBzciHcwir1h-k4g.png" /><figcaption><em>Figure 10. The appropriate migration strategy depends on the current Kafka version, cluster criticality, retention model, infrastructure direction, and operational capacity.</em></figcaption></figure><h3>Closing</h3><p>ZooKeeper played an important role in Kafka’s growth. It gave early Kafka versions a reliable coordination system while Kafka focused on distributed log storage and high-throughput messaging.</p><p>Over time, the external dependency became an architectural boundary. Kafka operators had to manage two distributed systems, and Kafka metadata had to move through an external coordination layer.</p><p>KRaft removes that boundary.</p><p>Kafka now manages metadata through an internal Raft quorum, a replicated metadata log, maintained controller state, metadata snapshots, and Kafka-native operational tools.</p><p>The final architecture becomes cleaner, but the migration still deserves careful treatment.</p><p>Successful teams do not approach it as a simple configuration change. They establish a supported version path, audit ZooKeeper ACLs, identify dependent tooling, design the controller quorum, deploy observability, rehearse rollback, validate dual-write operation, and finalize only after the evidence supports an irreversible decision.</p><p>The objective is easy to describe: move Kafka’s master operating record from an external system into Kafka itself without losing control of the cluster during the transition.</p><p>The technology provides the migration path. Architecture discipline makes that path safe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b17818eb0714" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/from-zookeeper-to-kraft-a-kafka-migration-guide-b17818eb0714">From ZooKeeper to KRaft: A Kafka Migration Guide</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyAgent: A complete Agentic Framework with 18 Design Patterns for Agent Orchestration]]></title>
            <link>https://pub.towardsai.net/pyagent-a-design-pattern-orchestrator-for-multi-agent-llm-systems-a9b68b6e6bc1?source=rss-f630c0b97775------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9b68b6e6bc1</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[agentic-ai-architecture]]></category>
            <dc:creator><![CDATA[Saurabh Kohli]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-06-23T01:05:00.112Z</atom:updated>
            <content:encoded><![CDATA[<h4>Design Patterns with baked-in Kubernetes for your Multi-Agent LLM System</h4><p>Someone builds a “router” that classifies incoming requests and sends them to the right specialist agent. Two weeks later, a different team builds a “dispatcher” that does almost the same thing. A month after that, someone else ships a “coordinator”. It’s mostly the similar idea, different name, different bugs. Meanwhile, nobody can version these systems, test them without hitting the real API, or debug what actually happened when a run goes wrong under one eco-system.</p><p>Engineers working with frameworks like LangGraph, CrewAI, AutoGen which are industry standards that give you raw primitives but leave everything else to you. You get graph nodes and message passing. You don’t get a shared vocabulary of named patterns, a way to declare your system as code, cost visibility, memory management, or an observability layer that knows what a “Debate” pattern is versus a generic span.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myU9RDu4r970z77rfx5v4w.png" /></figure><p>PyAgent fills all of it. It’s eight packages that form a coherent stack, from YAML specification through to a visual control plane. You can use one package or all eight. This is what the full stack looks like and how each piece fits.</p><h3>The Architecture</h3><p>The intended flow is:</p><ol><li><strong>Specify</strong> — declare agents, workflows, providers, and contracts in a YAML blueprint</li><li><strong>Compile</strong> — BlueprintCompiler transforms the spec into a runnable RuntimeGraph</li><li><strong>Orchestrate</strong> — Patterns coordinate agent collaboration (Pipeline, Supervisor, Debate…)</li><li><strong>Provide</strong> — Provider registry handles fallback chains, cost routing, and capability negotiation</li><li><strong>Remember</strong> — ContextLedger maintains three-tier memory across agents and turns</li><li><strong>Compress</strong> — CompressMiddleware trims inter-agent token transfer and enforces budgets</li><li><strong>Trace</strong> — TraceEventBus collects structured events from agents, patterns, and providers</li><li><strong>Observe</strong> — Studio visualises traces, costs, compliance, and provider health in real time</li></ol><p>Let’s walk through each layer.</p><h3>Blueprint — your agent system as code</h3><p>The standard way to write multi-agent systems in Python is to wire agents together in code. That works until you need to version them, review them in a PR, run them in CI without hitting real APIs, or hand the system to a team member who has to grep through call sites to understand how things connect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ihwg4E-bF64e8rnlZbdb5A.png" /></figure><p>Blueprint separates <em>what</em> your system does — the YAML spec — from <em>how</em> it runs — the compiler and runtime. The same file that deploys to production can be statically validated in CI, simulated with MockLLM in tests, and diffed against the previous version to see exactly what changed.</p><p>Think of it as Kubernetes for agent systems: infrastructure as code, but for LLM workflows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77d76feb7d35abe0935f780841dfd880/href">https://medium.com/media/77d76feb7d35abe0935f780841dfd880/href</a></iframe><p>Sample blueprint kick-starter to load specified blueprint and compile it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebed9ed0ebbf703eb657ec4f1ae53eba/href">https://medium.com/media/ebed9ed0ebbf703eb657ec4f1ae53eba/href</a></iframe><p>The Blueprint YAML supports seven top-level sections: metadata, providers, agents, workflows, context, contracts, and observability. Beyond runtime execution, the same spec is used by the Blueprint CLI for static validation, Mermaid diagram rendering, semantic diffing between versions, and contract conformance testing — all without making a single LLM call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be8e8ed9c9bcdf086d08af609fc788c0/href">https://medium.com/media/be8e8ed9c9bcdf086d08af609fc788c0/href</a></iframe><h3>Agent Orchestration Design Patterns</h3><p>Patterns are the execution layer. Each is a named, tested, composable class that encodes one recurring coordination problem and its trade-offs. The full set is 18 patterns across four tiers.</p><h4>Why named patterns matter</h4><p>In a codebase where one team builds a “router,” another builds a “dispatcher,” and a third builds a “coordinator,” you can’t reason about the system at a glance. When the codebase instead uses Supervisor, FanOutFanIn, and Debate, every engineer on the team immediately knows what each piece does, what it costs, and what its failure modes are. The pattern name is the shared vocabulary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Trrl4hA9-wWRO69PBeSClg.png" /></figure><h4>Tier 1 — Orchestration: getting work to the right place</h4><ul><li><a href="https://pyagent.org/packages/patterns/orchestration/supervisor/"><strong>Supervisor</strong></a> classifies incoming tasks and routes them to the appropriate specialist. Most customer-facing applications start here. A cheap model handles classification; expensive models are reserved for the domains that actually need them.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be83d00989b6f99146be8790040e9ede/href">https://medium.com/media/be83d00989b6f99146be8790040e9ede/href</a></iframe><ul><li><a href="https://pyagent.org/packages/patterns/orchestration/pipeline/"><strong>Pipeline</strong></a><strong> </strong>passes a task sequentially through a chain of agents, each receiving the previous agent’s output as its input. It’s the natural starting point with low cost, easy to reason about, debuggable at each stage.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36474fbbd8652380c7ddd4427e308faf/href">https://medium.com/media/36474fbbd8652380c7ddd4427e308faf/href</a></iframe><ul><li><a href="https://pyagent.org/packages/patterns/orchestration/fan-out-fan-in/"><strong>Fan-Out / Fan-In</strong></a> broadcasts a task to all agents simultaneously (wall-clock time = slowest agent, not the sum), then passes all outputs to an aggregator for synthesis. The right pattern when you need multiple independent perspectives like bull/bear/neutral on an investment, three different technical reviewers, competing hypotheses in research.</li><li><a href="https://pyagent.org/packages/patterns/orchestration/hierarchical/"><strong>Hierarchical</strong></a> extends Supervisor to multiple levels: a top-level coordinator delegates to domain sub-supervisors, which route to workers. The right structure for enterprise workflows where each domain has its own routing logic.</li><li><a href="https://pyagent.org/packages/patterns/orchestration/orchestrator-workers/"><strong>Orchestrator-Workers</strong></a> handles open-ended goals where the required subtasks aren’t known upfront. The orchestrator plans the work at runtime in JSON, dispatching only the workers this particular task needs. More flexible than Supervisor; one extra planning call.</li></ul><h4>Tier 2 — Resolution: when one pass isn’t good enough</h4><ul><li><a href="https://pyagent.org/packages/patterns/resolution/self-reflection/"><strong>Self-Reflection</strong></a> asks a model to critique its own output and revise based on that critique. The critic doesn’t have to be the same model as the generator, usually a cheaper model generates drafts and a stronger model critiques them. The stop_phrase enables early exit when the output is already good.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c98b313b3d034fffccc31ccaf6534e3e/href">https://medium.com/media/c98b313b3d034fffccc31ccaf6534e3e/href</a></iframe><ul><li><a href="https://pyagent.org/packages/patterns/resolution/cross-reflection/"><strong>Cross-Reflection</strong></a> uses genuinely different agents — ideally different providers — for generator and reviewer, eliminating correlated errors. Anthropic and OpenAI models make different mistakes; a reviewer from a different provider won’t share the author’s blindspots.</li><li><a href="https://pyagent.org/packages/patterns/resolution/debate/"><strong>Debate</strong></a> assigns agents opposing positions, runs structured argumentation rounds where each debater responds to the others, and has a judge render a verdict. The full transcript is available in result.metadata[&quot;debate_log&quot;] which is useful for understanding <em>how</em> the decision was reached, not just <em>what</em> it was.</li><li><a href="https://pyagent.org/packages/patterns/resolution/voting/"><strong>Voting</strong></a> runs the same task across N agents and selects the answer with the most agreement. Most powerful when agents come from different providers — correlated failures are rare across providers. Also the right pattern for fault tolerance: one hallucinated response doesn’t win.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb24cb31d6aa06c4a0501e8bd5e8796f/href">https://medium.com/media/fb24cb31d6aa06c4a0501e8bd5e8796f/href</a></iframe><ul><li><a href="https://pyagent.org/packages/patterns/resolution/evaluator-optimizer/"><strong>Evaluator-Optimizer</strong></a> applies structured scoring criteria rather than free-form critique. The evaluator scores output across explicit dimensions; the optimizer revises specifically to improve low-scoring ones. The improvement loop is targeted and measurable.</li></ul><h4>Tier 3 — Structural: controlling how information flows</h4><ul><li><a href="https://pyagent.org/packages/patterns/structural/role-based/"><strong>Role-Based</strong></a> runs agents with distinct professional roles across multiple rounds, each seeing the others’ contributions. Useful for simulating team review — product manager, engineer, and designer each bringing their lens to a proposal.</li><li><a href="https://pyagent.org/packages/patterns/structural/layered/"><strong>Layered</strong></a> structures agents into horizontal tiers where each tier’s collective output feeds the next. A natural fit for multi-level analysis: gather broadly in layer 1, analyse by domain in layer 2, synthesise across domains in layer 3.</li><li><a href="https://pyagent.org/packages/patterns/structural/topology/"><strong>Topology</strong></a> exposes three communication structures directly — Chain (sequential, lowest cost), Star (parallel collection then synthesis), and Mesh (every agent sees every other’s output each round, most thorough, most expensive). The choice is a direct cost/quality trade-off.</li><li><a href="https://pyagent.org/packages/patterns/structural/blackboard/"><strong>Blackboard</strong></a> decouples agents entirely: they read from and write to a shared key-value store, each declaring which keys it reads and writes. Agents can be added, removed, or reordered without touching each other. The right choice for long pipelines where you need to maintain loose coupling.</li></ul><h4>Tier 4 — Advanced: patterns that adapt at runtime</h4><ul><li><a href="https://pyagent.org/packages/patterns/advanced/talker-reasoner/"><strong>Talker-Reasoner</strong></a> is about your inference bill. The talker — a cheap fast model — handles the easy majority of queries. If it signals uncertainty, it escalates to the reasoner. At scale, routing even 70% of queries to a nano-class model produces significant cost savings.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8f6fe5649d97ee5e56c3a3ce1a06714/href">https://medium.com/media/f8f6fe5649d97ee5e56c3a3ce1a06714/href</a></iframe><ul><li><a href="https://pyagent.org/packages/patterns/advanced/swarm/"><strong>Swarm</strong></a> lets agents autonomously influence each other across rounds without a central coordinator. Behaviour emerges from local interactions — useful for research tasks where agents discover they need a specialist mid-way, or creative tasks where one agent’s direction inspires another to pivot.</li><li><a href="https://pyagent.org/packages/patterns/advanced/human-in-the-loop/"><strong>Human-in-the-Loop</strong></a> pauses execution at defined checkpoints and waits for a human decision before continuing. Essential for safety-critical workflows: content moderation pipelines that flag edge cases, code agents that ask before running destructive operations, approval flows that require sign-off before sending communications.</li><li><a href="https://pyagent.org/packages/patterns/advanced/react/"><strong>ReAct</strong></a> implements the Thought → Action → Observation cycle, adding tool use to the reasoning loop. The agent reasons about the task, decides which tool to call, calls it, observes the result, and reasons again. The full trace in result.metadata[&quot;trace&quot;] shows every decision step.</li></ul><h4>Patterns Composition and Advisor</h4><p>Because every pattern implements the same Pattern base class, any pattern can be used anywhere an Agent is expected. A FanOut of Pipelines, wrapped in SelfReflection, is three classes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8b1f9db68f3cbbe4f41c0b51a1e1feb/href">https://medium.com/media/a8b1f9db68f3cbbe4f41c0b51a1e1feb/href</a></iframe><blockquote>When you’re not sure which pattern to reach for, the <em>PatternAdvisor</em> can suggest one based on your task description and constraints.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1467f5e3f8dca2434e7e5de4aedbf32/href">https://medium.com/media/a1467f5e3f8dca2434e7e5de4aedbf32/href</a></iframe><h3>Providers — multi-provider registry with fallback chains</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Gwdzg02ao2NkCP0nCvVFg.png" /></figure><p>pyagent-providers is a unified registry over Anthropic, OpenAI, Gemini, and any LiteLLM-compatible backend. Rather than wiring LLM clients directly into agents, you define a provider registry in your Blueprint (or in code) and reference providers by name. The registry handles fallback chains, capability negotiation, and cost-aware routing automatically.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2974ccfc6db5f6d110b835a60434bc00/href">https://medium.com/media/2974ccfc6db5f6d110b835a60434bc00/href</a></iframe><p>If the primary provider is unavailable or over rate limit, the registry falls back to the next in the chain — without the agent needing to know. The provider section in Blueprint also wires into the Router for difficulty-aware model selection (covered below).</p><h3>Context — three-tier memory across agents and turns</h3><p>pyagent-context gives agents memory that persists within and across runs. The ContextLedger manages three tiers:</p><p><a href="https://pyagent.org/guides/context/#workingmemory"><strong>Working memory</strong></a> is the in-flight context for the current task — what’s been said so far in this run.</p><p><a href="https://pyagent.org/guides/context/#sessionmemory"><strong>Session memory</strong></a> persists across turns in a conversation, but not across separate sessions. Useful for stateful chat applications where the agent needs to remember what was discussed earlier in the conversation.</p><p><a href="https://pyagent.org/guides/context/#semanticmemory"><strong>Semantic memory</strong></a> is a long-term store for facts, preferences, and learned context that should persist across sessions. Agents that read from semantic memory can recall things like user preferences, past decisions, or domain knowledge that was accumulated in prior runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2n25U0FXknyGgN-1Gy9OA.png" /></figure><p>In Blueprint, context configuration lives in its own section:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc98c9134e2244adc2d6dbebbcb99088/href">https://medium.com/media/dc98c9134e2244adc2d6dbebbcb99088/href</a></iframe><p>The context layer also handles redaction of PII before it reaches external providers — the same PIIGuard available in the Guardrails API but applied at the memory level.</p><h3>Compress — keeping inter-agent token transfer in check</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gt_kFnxSsOfXiqhnWL0yg.png" /></figure><p>In a five-stage Pipeline, if each agent outputs 2,000 tokens, the fifth agent receives 8,000 tokens of prior context before it even starts its own work. pyagent-compress addresses this by trimming inter-agent message transfer while preserving key information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf31ed349ee145aa9fde284682ee706a/href">https://medium.com/media/bf31ed349ee145aa9fde284682ee706a/href</a></iframe><p>The package also supports token budget enforcement (hard cutoffs that trigger compression before a call would exceed the model’s context window) and agent pruning (removing older agents’ contributions from the shared context when they’re no longer relevant to the current stage).</p><p>In long pipelines where compression is always-on, the OTel trace will include a pyagent.compress.savings_pct attribute on every span, so you can see exactly how much the compressor is saving at each step.</p><h3>Trace — structured observability from every layer of the stack</h3><p>pyagent-trace wraps the whole stack with structured observability. Every agent call, pattern execution, and LLM invocation emits events through a TraceEventBus. Consumers hook to the <em>exporters</em>, <em>cost trackers</em>, whereas Studio hook to subscribe the <em>event-bus</em> and receive events in real time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y45mHydjIr3rV_ttod0z4A.png" /></figure><p>The key design is that the trace is <em>pattern-aware</em>. Spans carry attributes like pyagent.pattern.type, pyagent.agent.name, pyagent.router.difficulty, and pyagent.compress.savings_pct. This means your tracing backend doesn&#39;t just see generic HTTP calls — it knows a Debate ran for 3 rounds, the judge was claude-sonnet, and the whole thing cost $0.01032.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7201381fd8251caff7620ab487da4770/href">https://medium.com/media/7201381fd8251caff7620ab487da4770/href</a></iframe><p>The simplest integration is the decorator approach — inherit from a traced variant of any pattern class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/288549df857d100ea030c4b0f14ce406/href">https://medium.com/media/288549df857d100ea030c4b0f14ce406/href</a></iframe><p>CostTracker aggregates costs by pattern, model, and agent across a session:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5349e27607b1fb877b9eb873888dafb6/href">https://medium.com/media/5349e27607b1fb877b9eb873888dafb6/href</a></iframe><p>Recorder captures every LLM call to JSONL for deterministic replay — useful for debugging a specific run without re-incurring API costs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa76ac2bced4b80df6ba55619494311e/href">https://medium.com/media/fa76ac2bced4b80df6ba55619494311e/href</a></iframe><p>OTel backends are supported out of the box — Jaeger for local development, Langfuse for production LLM observability, Grafana Tempo + Prometheus for infrastructure teams, and any OTLP endpoint. A recorded trace looks like:</p><pre>Trace: investment-analysis / debate (9.8s total, $0.01032)<br>├── pyagent.agent.bull     2.4s  gemini-2.5-flash   450→380 tok  $0.00094<br>├── pyagent.agent.bear     2.7s  gemini-2.5-flash   450→410 tok  $0.00098<br>├── pyagent.agent.bull     2.1s  (round 2)          410→360 tok  $0.00086<br>├── pyagent.agent.bear     1.9s  (round 2)          410→380 tok  $0.00084<br>└── pyagent.agent.judge    0.7s  claude-sonnet-4   1200→480 tok  $0.00840</pre><h3>Studio — the Kubernetes Dashboard for your agent stack</h3><p>pyagent-studio is a kubectl-style CLI and web control plane for designing, simulating, debugging, and governing multi-agent systems. The analogy from the docs is direct: Studio is to PyAgent what kubectl + the Kubernetes Dashboard are to Kubernetes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IhqBDnmAimx3xFghlBUeiA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86feaedc7697b228b2239167b49d411e/href">https://medium.com/media/86feaedc7697b228b2239167b49d411e/href</a></iframe><p>The web dashboard has nine sections:</p><p>/overview gives a system summary — loaded blueprints, provider health, recent run stats.</p><p>/workflows and /agents let you inspect how agents are wired together and what their configurations are.</p><p>/simulate runs a workflow against MockLLM (no API cost) and shows the full execution path.</p><p>/traces is the trace explorer, powered by the JSONL files from pyagent-trace. You can filter by agent, pattern type, cost range, or duration, and drill into any span for the full input/output.</p><p>/governance validates loaded blueprints against their contracts and flags any violations.</p><p>/providers shows provider health, latency percentiles, and per-model cost breakdowns.</p><p>/diff renders semantic diffs between two Blueprint versions side by side.</p><p>The CLI and the web dashboard share the same underlying service layer, so anything you can do in the UI you can also script with pyagent commands in CI.</p><h3>Router — routing tasks to the cheapest model that can handle them</h3><p>pyagent-router scores incoming queries for difficulty and selects the most cost-effective model that&#39;s capable of handling them. It knows pricing for the full range of current models — GPT-4.1-nano through o3, Haiku through Sonnet, Gemini Flash through Pro — and applies that knowledge at call time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21efaedb2678d4d6359cb3610733f31e/href">https://medium.com/media/21efaedb2678d4d6359cb3610733f31e/href</a></iframe><p>The router integrates with the Blueprint’s providers section through routing strategies. cost_optimized minimises spend; latency minimises wall-clock time; capability ensures the model can handle the inferred difficulty. In practice, most teams start with cost_optimized and adjust after seeing their trace cost breakdowns in Studio.</p><p>This is also how Talker-Reasoner works under the hood — the router is the mechanism that decides whether the talker or the reasoner handles a given query.</p><h3>Where to start</h3><p>If you’re new to multi-agent systems, start with pyagent-patterns and the Pipeline and Supervisor patterns. Get something running, then layer in routing and context once you&#39;ve established the basic shape of your system.</p><p>If you’re adding PyAgent to an existing codebase, the hooks guide is worth reading first — it shows how to attach trace, context, compression, and cost tracking to agents you’ve already built, without rewiring everything.</p><p>If you’re building for production, start with Blueprint. The discipline of declaring your system in YAML pays off quickly in CI validation, versioned diffs, and simulation — especially once the system gets complex enough that you can’t hold it all in your head.</p><ul><li><strong>Docs</strong>: <a href="https://pyagent.org/">https://pyagent.org</a></li><li><strong>GitHub</strong>: <a href="https://github.com/pyagent-core/pyagent">https://github.com/pyagent-core/pyagent</a></li></ul><p><em>PyAgent is MIT licensed, requires Python 3.11+, and has zero mandatory dependencies in the core packages.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9b68b6e6bc1" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/pyagent-a-design-pattern-orchestrator-for-multi-agent-llm-systems-a9b68b6e6bc1">PyAgent: A complete Agentic Framework with 18 Design Patterns for Agent Orchestration</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning Observability Context into Intelligent Action]]></title>
            <link>https://pub.towardsai.net/turning-observability-context-into-intelligent-action-7443edc6f4c1?source=rss-f630c0b97775------2</link>
            <guid isPermaLink="false">https://medium.com/p/7443edc6f4c1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[investing]]></category>
            <dc:creator><![CDATA[Saurabh Kohli]]></dc:creator>
            <pubDate>Sun, 31 May 2026 00:01:01 GMT</pubDate>
            <atom:updated>2026-05-31T00:01:01.147Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Telemetry to Alpha: Architecting Observability-Driven Investment Proposals</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fd3yb25yUX3ecvXYD7585w.png" /></figure><h3>Introduction</h3><p>Observability has evolved into a pervasive capability across modern systems, yet its role in decision-making remains underdeveloped. In financial services, especially in investment proposal creation, vast volumes of telemetry exist across portfolio systems, market feeds, tax engines, and client interaction layers. However, this data rarely translates directly into actionable investment decisions. Instead, human intermediaries interpret dashboards, reconcile inconsistencies, and manually construct proposals.</p><p>The central thesis is that observability can be elevated from a passive diagnostic layer to an <strong>active intelligence fabric</strong> that continuously generates, validates, and refines investment proposals. This transformation requires both conceptual rigor and a concrete, buildable system that integrates domain context, causal reasoning, and decision automation. The following sections interleave architectural reasoning with implementation patterns to demonstrate how such a system can be constructed.</p><h3>Observability in Financial Systems: Context and Constraints</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLam2IiACymIyD7RzIyfbQ.png" /><figcaption><em>The end-to-end architecture that converts observability signals into intelligent investment proposals through enrichment, inference, optimization, and feedback.</em></figcaption></figure><p>In distributed systems, observability captures metrics, logs, and traces to infer system state. In financial systems, the concept expands into a richer, domain-specific telemetry space:</p><ul><li>Portfolio state: allocations, drift, performance attribution</li><li>Market state: volatility regimes, liquidity signals, macro indicators</li><li>Tax state: realized and unrealized gains or losses, wash-sale exposure</li><li>Client state: risk tolerance, goals, behavioral signals</li></ul><p>According to research from Gartner, enterprises under utilize a majority of their telemetry because it lacks contextual interpretation. In wealth management, this results in missed opportunities such as delayed rebalancing, inefficient tax strategies, and inconsistent proposal quality.</p><p>The challenge is that most systems stop at collection and visualization. They capture signals effectively but leave interpretation to human advisors. As firms grow assets under management, support more client households, and introduce greater personalization, the volume of telemetry grows faster than the capacity of humans to synthesize it. Valuable opportunities often remain undiscovered not because the information is unavailable, but because the interpretation process cannot scale.</p><p>This is where observability must evolve. Rather than serving as the endpoint for understanding what happened, it must become the starting point for determining what should happen next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4JQSIciibDLyc6BFjkIrQ.png" /><figcaption><em>Traditional observability explains what happened. Decision intelligence explains why it matters and what should happen next.</em></figcaption></figure><h3>Bridging the Gap: From Signals to Financial Context</h3><p>The first transformation is semantic. Raw telemetry must be converted into domain-aware constructs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7bZ0pAFPJUC3Ucc_h5rGg.png" /></figure><p>Consider a simple observability signal: portfolio drift. In isolation, drift is a numerical deviation. In context, it represents a deviation from a client’s risk mandate.</p><p>The system must therefore standardize how signals are captured.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/015e36e7b1053ec892da8e9176bdb299/href">https://medium.com/media/015e36e7b1053ec892da8e9176bdb299/href</a></iframe><p>This abstraction is not merely technical convenience. It is a design decision that enforces <strong>uniform interpretability</strong> across heterogeneous sources such as custodians, pricing engines, and advisory systems.</p><p>An example event:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d683f329634a06b8e3bedef58653f1f/href">https://medium.com/media/1d683f329634a06b8e3bedef58653f1f/href</a></iframe><p>At this stage, the system has achieved observability but not intelligence. The event signals deviation without interpreting its significance. It tells the platform that something happened, but not whether it matters. Before a recommendation can be generated, the system must first determine whether the observation deserves attention and how it should be evaluated. Below is a glipse of the contextual engine architecture which enables the ground of this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMCbuguJ5ym37qYtve_3zw.png" /><figcaption><em>Raw events become meaningful only after they are evaluated within portfolio, tax, risk, and client contexts.</em></figcaption></figure><h3>Context Enrichment: Embedding Financial Meaning</h3><p>The second transformation layer introduces domain logic. It answers whether a signal matters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22f50784c5decd8f7f3ed03dd2347d56/href">https://medium.com/media/22f50784c5decd8f7f3ed03dd2347d56/href</a></iframe><p>This function encodes institutional knowledge. A five percent drift threshold is not arbitrary. It reflects portfolio governance practices, risk tolerance bands, and rebalancing costs. By embedding such logic, the system transitions from descriptive to evaluative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zuDQ-xRfZRw8lQGVxDv_A.png" /><figcaption><em>Business policy transforms numerical observations into actionable financial events.</em></figcaption></figure><p>A key architectural insight is that enrichment should remain <strong>declarative and auditable</strong>. Every transformation must be explainable, especially in regulated environments.</p><h3>Decision Layer: Translating Context into Actions</h3><p>Once signals are enriched, the system must determine appropriate responses. This is where observability becomes operational. However, identifying an actionable event is only part of the challenge. A portfolio drifting beyond its target allocation, an unrealized loss creating a tax opportunity, or a concentration increase introducing additional risk all require a response. The platform must therefore translate contextual understanding into a recommendation that can be reviewed, validated, and ultimately acted upon.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75e16066b50ecc65de99344ce9fc8a0d/href">https://medium.com/media/75e16066b50ecc65de99344ce9fc8a0d/href</a></iframe><p>This step formalizes decision-making as structured output. The system produces not only an action but also its justification and priority. This aligns with fiduciary requirements where every recommendation must be defensible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXqUcvFSQhCcF3nG56XKEQ.png" /><figcaption><em>Context becomes recommendations through explainable decision logic.</em></figcaption></figure><p>However, this layer introduces a known limitation. It relies on correlation. The system observes drift and recommends rebalancing without understanding the underlying cause.</p><h3>Causal Reasoning: Improving Decision Quality</h3><p>To move beyond reactive logic, the system must incorporate causal inference. Research by Judea Pearl demonstrates that distinguishing causation from correlation is essential for reliable decision systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBfdauf8yYxfEwjWEYRaFA.png" /><figcaption><em>The same observation should not always produce the same recommendation.</em></figcaption></figure><p>In investment workflows, this distinction directly affects strategy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1da0833d2f762d88ca793225a671f23/href">https://medium.com/media/e1da0833d2f762d88ca793225a671f23/href</a></iframe><p>If drift results from market appreciation, the recommendation may involve partial rebalancing to lock in gains. If it results from client inflows, the system may instead recommend redistributing new capital. The same observable signal leads to different actions when causality is considered. The implementation is intentionally simplified, but it illustrates an important principle. The platform is no longer asking what happened. It is asking why it happened.</p><blockquote>This layer improves both <strong>decision precision</strong> and <strong>explainability</strong>, two critical attributes in financial systems.</blockquote><h3>Proposal Construction: Synthesizing Multi-Signal Intelligence</h3><p>Investment proposals rarely derive from a single signal. They represent the aggregation of multiple, sometimes conflicting, considerations. Advisors routinely combine information from portfolio construction systems, tax platforms, risk engines, client objectives, market conditions, and regulatory requirements before arriving at a recommendation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/941b101f5972609b1653707e2560d5e7/href">https://medium.com/media/941b101f5972609b1653707e2560d5e7/href</a></iframe><p>This aggregation mirrors how advisors synthesize insights. The system consolidates rebalancing actions, tax-loss harvesting opportunities, and risk adjustments into a coherent proposal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u566piDW_4-xolf1GIFwNg.png" /><figcaption><em>Portfolio, tax, risk, and client signals converge into a single investment recommendation.</em></figcaption></figure><p>A critical design principle here is <strong>traceability</strong>. Each action must retain a link to its originating signal and reasoning chain. This distinction is important. The objective is not autonomous portfolio management. The objective is reducing the time between observation and recommendation while preserving explainability, governance, and fiduciary oversight.</p><h3>Human Interface: Rendering Explainable Proposals</h3><p>Despite automation, human oversight remains mandatory. Therefore, system outputs must be interpretable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0be5221611243b77a2a8d83e75f36eef/href">https://medium.com/media/0be5221611243b77a2a8d83e75f36eef/href</a></iframe><p>This rendering step is not cosmetic. It enforces transparency. Each recommendation is accompanied by a rationale, enabling advisors and compliance teams to validate decisions. At this stage, the platform can observe, interpret, explain, and recommend. Yet one important question remains unanswered.</p><blockquote>Given multiple valid recommendations, how does the system determine the best possible outcome?</blockquote><p>That challenge introduces the next layer of intelligence, where observability begins to intersect with optimization and portfolio construction itself.</p><h3>Optimization Layer: Moving Toward Quantitative Intelligence</h3><p>Rule-based systems provide consistency but lack optimality. Integrating optimization techniques enhances decision quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vA6B-scCvOEA0l0jomEqrw.png" /><figcaption><em>Observability provides context. Optimization determines the most efficient portfolio response.</em></figcaption></figure><p>Portfolio optimization frameworks, grounded in Modern Portfolio Theory by Harry Markowitz, enable the system to compute efficient allocations under constraints mainly focused on balancing expected return against risk.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdab3cd54903f1c98a5c6938963e5681/href">https://medium.com/media/cdab3cd54903f1c98a5c6938963e5681/href</a></iframe><p>A production grade system would incorporate covariance matrices, tax considerations, liquidity requirements, client restrictions, concentration limits, tracking error budgets, trading costs, regulatory obligations etc.</p><blockquote>Optimization layer provides a mechanism for evaluating the tradeoffs systematically rather than relying entirely on human intuition.</blockquote><h3>Feedback and Continuous Learning</h3><p>The final transformation closes the loop. Observability must capture not only system signals but also decision outcomes and those become new signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSzWImED0cxfb5zsNTC0wg.png" /><figcaption><em>Every proposal becomes a new source of observability, creating a continuously improving system.</em></figcaption></figure><ul><li>Proposal acceptance or rejection</li><li>Advisor modifications</li><li>Client feedback</li><li>Post-trade performance</li><li>Portfolio outcomes relative to expectations</li></ul><p>This feedback enables iterative improvement of thresholds, models, and logic. Over time, the system evolves from rule-based automation to adaptive intelligence.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/119c97d570854351ba57982a0ca348f0/href">https://medium.com/media/119c97d570854351ba57982a0ca348f0/href</a></iframe><p>This feedback loop fundamentally changes the role of observability. Observability no longer serves merely as a mechanism for understanding system behavior. It becomes a mechanism for understanding decision quality. That distinction is significant because it transforms the platform from a static recommendation engine into an adaptive intelligence system capable of continuous improvement.</p><h3>Conclusion</h3><p>The transition from observability to intelligent action represents a structural evolution in system design. In investment proposal creation, this shift transforms fragmented telemetry into coherent, explainable strategies.</p><p>By combining structured event modeling, contextual enrichment, causal reasoning, and optimization, systems can generate proposals that are both data-driven and operationally viable. The integration of code and architecture demonstrates that this transformation is not aspirational. It is implementable with current technologies.</p><p>The defining change is conceptual. Observability ceases to be an endpoint for understanding system behavior. It becomes the mechanism through which systems generate, justify, and continuously refine investment decisions. Though I believe there are implications and limitations in the framework, like:</p><ul><li>Data quality inconsistencies across custodians and systems</li><li>Regulatory requirements for explainability and auditability</li><li>Latency constraints in real-time decision environments</li><li>Model risk in predictive and optimization layers</li></ul><p>These limitations necessitate a hybrid approach where automation augments rather than replaces human oversight. Telemetry is no longer merely a record of what happened. It becomes the raw material from which intelligence is constructed.</p><blockquote>The future of observability is not visibility.<br>The future of observability is intelligent action.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7443edc6f4c1" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/turning-observability-context-into-intelligent-action-7443edc6f4c1">Turning Observability Context into Intelligent Action</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Angular Component Integration in Conversational AI Interfaces]]></title>
            <link>https://pub.towardsai.net/complete-angular-component-integration-in-conversational-ai-interfaces-4d451172acf8?source=rss-f630c0b97775------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d451172acf8</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[fintech]]></category>
            <dc:creator><![CDATA[Saurabh Kohli]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 14:31:01 GMT</pubDate>
            <atom:updated>2026-04-27T14:31:01.154Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Guide to Generative UI with Hashbrown</h4><p><em>Part 2 · Generative UI in Angular</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nkdr3pTm8Gl7cOS9boCHwg.png" /></figure><blockquote><strong><em>What you’ll learn:</em></strong><em> How a real enterprise Angular team maps their existing design system to a Hashbrown component registry, wires it to NgRx stores, handles per-role component exposure, and arrives at a production-ready generative UI.</em></blockquote><h3>The Starting Point</h3><p>Imagine a mid-size financial services company which run a large Angular 19 application: a unified dashboard for relationship managers to track client portfolios, trade history, risk exposure, and compliance alerts.</p><p>Now imagine you are asked to add a chat box in the corner as an MVP approach, that calls an OpenAI (we call it Eliza #iykyk) endpoint and renders the response as markdown text. It shipped in three weeks. The business loved the demo.</p><p>Then the pilot users started using it.</p><p>The complaints were immediate. Asking <em>“What’s APAC’s current risk exposure?”</em> returned three paragraphs of text describing numbers that were already visualized in a risk gauge component ten seconds away by clicking “Risk” in the nav. The AI made the app feel slower, not smarter. Usage dropped after the first week.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qXL5p3sxWO6E8s8wYPuemg.png" /></figure><p>The team had a library of multiple design system components. The AI didn’t ignore it, our architecture didn’t bind any relationship bridge between every single one.</p><p>This is the article about fixing that. The story is composite and drawn from the pattern that most enterprise Angular teams hit when they first wire AI to their apps, the code is real and every pattern here is directly applicable.</p><p>This is an extension to the base discussion which was covered in the Part 1:</p><p><a href="https://pub.towardsai.net/generative-ui-in-angular-rendering-ai-chosen-components-in-chat-0a8577663625">Generative UI in Angular: Rendering AI-Chosen Components in Chat</a></p><h3>Step 0: Audit Your Component Library</h3><p>Before writing a line of Hashbrown code, the most valuable thing you can do is categorise your existing components by <em>response type</em>. Ask the question: <strong>if the AI could answer in any format, when would a human naturally reach for this component?</strong></p><p>Below table would help to get a glipse:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cD9poE8-lon8lppgLP669Q.png" /></figure><p>This audit is your component registry roadmap. You do not need to expose all components at once, though start with the ten that answer 80% of likely questions. Trying to expose everything simultaneously makes prompt engineering unmanageable and increases schema token overhead unnecessarily.</p><h3>Step 1: The Smart Wrapper Pattern at Scale</h3><p>Make sure the design system components were classic dumb components: they accepted data as @Input() properties and emitted events. They had no Angular DI, no router awareness, no store access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPd9YLrZZQ3EJ4JFvnT4Gw.png" /></figure><p>The generative UI layer needs smart wrappers that:</p><ol><li>Accept typed input() signals the LLM can populate</li><li>Resolve anything requiring DI (stores, services, router)</li><li>Delegate all rendering to the existing dumb component</li></ol><p>Let’s takeKpiCardWidgetas an example which is the most-used component in the registry:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f47ee9ec0605f5c29dba65fd5a081f17/href">https://medium.com/media/f47ee9ec0605f5c29dba65fd5a081f17/href</a></iframe><p>Notice: the LLM supplies label, value, unit, trend, delta, period, and metricId. Everything else like alert state from the store, locale-formatted value, drilldown routing is handled by the wrapper using Angular DI. The LLM has no access to any of those concerns.</p><h3>Step 2: The Full Component Registry</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kbGko8jwLea7dIHjr_E8A.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/754a61971f853159eff22eb022d2ebce/href">https://medium.com/media/754a61971f853159eff22eb022d2ebce/href</a></iframe><h3>Step 3: Role-Based Component Exposure</h3><p>Not all relationship managers have the same data access. Senior RMs see compliance alerts; junior RMs do not. Portfolio managers see full risk gauges; sales staff see simplified KPI cards only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69Vr4eO7vHB_WSo2HMEVZQ.png" /></figure><p>Hashbrown’s components array is just an array, we need to implement role-based filter at runtime:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ad9f7e29e56af71384d5047cb5b4e49/href">https://medium.com/media/5ad9f7e29e56af71384d5047cb5b4e49/href</a></iframe><p>This pattern ensures the model never even <em>knows</em> about complianceAlertWidget unless the authenticated user has the compliance role. The model cannot select a component it has not been told about.</p><h3>Step 4: Wiring Tools to Existing Services</h3><p>The AI tools are thin Angular service wrappers and if your existing NextJS APIs are mature enough then mostly no new backend endpoints required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9279f8ff7c01c53faa9e378c9359e58b/href">https://medium.com/media/9279f8ff7c01c53faa9e378c9359e58b/href</a></iframe><p>The getSelectedClient tool is worth noting. Because Hashbrown runs tools client-side, it can read directly from your NgRx or Signal store which gives the AI access to transient UI state (which client is currently selected, which tab is active, what&#39;s been loaded) without any network call. This is something no server-side tool framework can replicate.</p><h3>Step 5: The Few-Shot System Prompt</h3><p>Few-shot prompting in the prompt\`` tagged template would enhance the user experience consistently and the system would be able to render kpiCardWidget instead of messageWidget for metric questions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c84409b021ffbfb83510d5ac1da0cc71/href">https://medium.com/media/c84409b021ffbfb83510d5ac1da0cc71/href</a></iframe><p>The negative example pattern is valuable for smaller, cost-optimized models that allows them to understand what <em>not</em> to do alongside what it <em>should</em> do.</p><h3>Step 6: Conversation Thread Persistence</h3><p>Thread persistence across multiple browser sessions especially when a client conversation should resume where it left off last. Hashbrown’s Threads feature (v0.4+) handles this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b9efeb9146df469c4caa96a8efc3d00/href">https://medium.com/media/6b9efeb9146df469c4caa96a8efc3d00/href</a></iframe><p>Add messages source while defining the uiChatResource utility and make sure to persist the char responses against a unique id. Below is the addition to chat-assistance component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0bd3033124bef3ab6426d8b5aa3a443/href">https://medium.com/media/b0bd3033124bef3ab6426d8b5aa3a443/href</a></iframe><h3>The Results</h3><p>After the above implementation you will observe a complete shift on the experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-pAXMgMxVMtHmtymBvZWw.png" /></figure><h3><strong>Conclusion</strong></h3><p>Building a production-ready Generative UI in Angular isn’t about the biggest model; it’s about the best integration. By following the above stepped roadmap, you will achieve:</p><ul><li><strong>Security:</strong> Via role-based component exposure.</li><li><strong>Performance:</strong> By leveraging client-side tool execution and existing NgRx state.</li><li><strong>Consistency:</strong> By mapping your existing Design System to the LLM’s output.</li></ul><p>As you move toward production, remember: start with the 20% of components that solve 80% of your user’s friction.</p><h4>Happy coding!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d451172acf8" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/complete-angular-component-integration-in-conversational-ai-interfaces-4d451172acf8">Complete Angular Component Integration in Conversational AI Interfaces</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative UI in Angular: Rendering AI-Chosen Components in Chat]]></title>
            <link>https://pub.towardsai.net/generative-ui-in-angular-rendering-ai-chosen-components-in-chat-0a8577663625?source=rss-f630c0b97775------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a8577663625</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[leadership]]></category>
            <dc:creator><![CDATA[Saurabh Kohli]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 13:31:01 GMT</pubDate>
            <atom:updated>2026-04-24T13:31:01.401Z</atom:updated>
            <content:encoded><![CDATA[<h4>Setting Up Hashbrown To Scale Enterprise Design System</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgfuI8NBvrtukzxGp8HkOA.png" /></figure><blockquote><strong>What you’ll learn:</strong> How to wire an LLM to your <em>existing</em> Angular component library, so the model autonomously picks the right component for every response and streams it into a conversation in real time. No React. No rewrite. No migration.</blockquote><h3>The Angular Engineer’s AI Problem</h3><p>Open any article about generative UI. Any conference talk. Any framework announcement. What do they show?</p><blockquote>React components.</blockquote><p>&lt;Card /&gt;. useChat(). streamUI(). JSX streaming from server to client. The entire generative UI conversation, every demo, every tutorial, every SDK README is built on the assumption that you are writing React.</p><p>If you are an enterprise Angular engineer, you have probably felt this as a slow, creeping frustration. Your team has spent years building something substantial: a mature Angular application with a proper design system, a well-structured NgRx store, a DI-wired service layer, Signal-based state (especially v17+), and many components that your business users are now using from quite a while. Then the AI wave hits, and every resource available tells you to rewrite it in Next.js.</p><p><strong>You shouldn’t have to.</strong> And with Hashbrown, you don’t.</p><p>This guide is written specifically for enterprise Angular teams. Every code example in it is Angular. Every pattern respects Angular’s architecture like Signals, DI, standalone components, NgRx. There is no React to translate, no hooks to mentally map back to Angular equivalents, no “this is left as an exercise for the reader” when it comes to the framework you actually work in.</p><h3>The second problem: your design system is being ignored</h3><p>Beyond the React-centric ecosystem, there is a more immediate pain. Your Angular app probably has a well-crafted design system. Sortable data tables. KPI cards with trend indicators. Alert banners. Rich charts. Components your team has spent months perfecting to match your brand, meet your accessibility standards, and satisfy your compliance requirements.</p><p>Then someone adds an AI assistant.</p><p>And it answers every single question in plain text.</p><p><em>“Your Q3 revenue was $4.2M, up 18% year-over-year.”</em></p><p>The data is correct. But you already have a component that renders that beautifully with sparklines, colour-coded trend arrows, and a drill-down button. The AI completely ignores it. Every answer it gives is a step backward from the UI your team spent years building.</p><p>This isn’t a prompt engineering problem. It’s an architecture problem. The LLM has no idea your components exist.</p><p><strong>Generative UI is the solution.</strong> Instead of the model generating text that <em>describes</em> data, it generates a <em>component tree, </em>it picks which of your Angular components best represents each answer and streams them into the conversation. The UI adapts to the answer. Your existing design system becomes an active participant in the AI experience, not a bystander.</p><h4>Picture this flow in your app:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpGiqyuboIXtm4D1zODFzw.png" /></figure><p>The component is <em>your</em> component with same styles, same logic, same accessibility attributes. The LLM just decided it was the right way to answer.</p><p>This article shows you how to build exactly that, using <strong>Hashbrown</strong> which is the only TypeScript framework that makes generative UI a native Angular citizen.</p><h3>Your Angular Investment Is Evolving</h3><p>Before a single line of code: let’s be explicit about what you are <em>not</em> being asked to do here.</p><p>You are <strong>not</strong> migrating to React. <br>You are <strong>not</strong> rewriting your design system. <br>You are <strong>not</strong> replacing NgRx or your service layer. <br>You are <strong>not</strong> wrapping your Angular app in an iframe or a micro-frontend shell.</p><p>Everything you have built stays exactly as it is. Let’s take a quick review on what capabilities Hashbrown adds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuNeYKUr7J7s2wkicrP-kA.png" /></figure><blockquote><strong><em>Why Hashbrown and not something else?</em></strong><em> Because every other generative UI library in this space like Vercel AI SDK, CopilotKit’s core was built React-first, with Angular added as an afterthought or not at all. Hashbrown was built by Angular community contributors (Mike Ryan and Brandon Roberts, both from the NgRx ecosystem) specifically for Angular’s architecture. It uses </em><em>uiChatResource which is a proper Angular resource built on Signals and not a React hook ported over.</em></blockquote><blockquote><strong><em>This is the Angular-native path.</em></strong></blockquote><h3>How Generative UI Works</h3><h4>The Mechanism</h4><p>Before writing code, the mechanism is worth understanding deeply. The insight that makes Hashbrown work is deceptively simple:</p><p><strong>LLMs are already good at structured JSON output. Generative UI turns component selection into a structured output problem.</strong></p><p>Here is the full loop:</p><pre>1. SESSION INIT<br>   Your Angular app sends the LLM a manifest describing your<br>   components: names, descriptions, and typed input schemas.<br><br>2. USER SENDS A MESSAGE<br>   &quot;Show me Q3 revenue by region&quot;<br><br>3. MODEL DECIDES<br>   Based on the manifest, the model responds with JSON and <br>   not markdown, not prose. JSON describing which component<br>   to render and what inputs to pass.<br><br>4. STREAM PARSE<br>   Hashbrown&#39;s runtime reads the JSON as it streams in and<br>   begins mounting your Angular component immediately.<br><br>5. COMPONENT RENDERS<br>   Your real &lt;RevenueTableComponent&gt; appears in the<br>   conversation, populated with AI-supplied data, using<br>   your design system exactly as built.<br><br>6. INTERACTION LOOP (optional)<br>   User interactions can be fed back to the model as<br>   context, closing the loop.</pre><p>The model’s response looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7202ddcce63992e3062ed27b05e82409/href">https://medium.com/media/7202ddcce63992e3062ed27b05e82409/href</a></iframe><p>Hashbrown parses this, maps revenueTableWidget to your registered RevenueTableWidgetComponent, passes the $props as Angular input() signals, and mounts the component in the message bubble, all this while the stream is still in flight.</p><h4>The Architecture:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*jIT-SmpZ5W-H1aaS2IrLGg.png" /></figure><p>Three packages. One streaming proxy. Zero framework lock-in beyond Angular itself.</p><p>Crucially, this creates a clean security boundary. Your API keys never touch the browser. A thin Node proxy holds credentials, enforces the model, and hardcodes the system prompt server-side before streaming the safe response back to the client. This secure proxy approach is visualized here.</p><h3>Installation</h3><p>Hashbrown uses a three-package model: a framework-agnostic core, an Angular binding, and a provider adapter.</p><pre># Angular + OpenAI<br>npm install @hashbrownai/core @hashbrownai/angular @hashbrownai/openai<br><br><br># Angular + Anthropic Claude<br>npm install @hashbrownai/core @hashbrownai/angular @hashbrownai/anthropic<br><br><br># Angular + Google Gemini<br>npm install @hashbrownai/core @hashbrownai/angular @hashbrownai/google<br><br><br># Angular + Azure OpenAI (enterprise compliance)<br>npm install @hashbrownai/core @hashbrownai/angular @hashbrownai/azure</pre><p><strong>Requirements:</strong> Angular 17+ (Signals API), Node.js 18+ on the backend.</p><h3>Step 1: Bootstrap the Angular App</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd8ea64d65b8bfba5c9c817741d5b9f4/href">https://medium.com/media/cd8ea64d65b8bfba5c9c817741d5b9f4/href</a></iframe><p>provideHashbrown() registers the Hashbrown runtime into Angular&#39;s DI tree. Everything else like component mounting, stream parsing, signal updates is handled automatically from here.</p><p><strong>Gemini-Specific Configuration</strong></p><p>Google Gemini 2.5 does not yet support combining structured output and tool calling in the same request. When emulateStructuredOutput is true, Hashbrown defines a pseudo-tool representing the component manifest and instructs the model to respond via tool calling instead of structured output. The overhead is roughly 200–400 extra tokens per request which is a reasonable trade-off for provider flexibility.</p><h3>Step 2: Set Up the Node Backend</h3><p>This is the secure proxy. It holds API keys, enforces the model, and streams responses. Keep it thin and let Hashbrown handles the protocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/337c6169498f3c7332a03378816bb99b/href">https://medium.com/media/337c6169498f3c7332a03378816bb99b/href</a></iframe><blockquote><strong><em>Why override server-side?</em></strong><em> If the Angular app sends </em><em>model: &#39;gpt-4o&#39; and you&#39;re billed per token, a single rogue request could cost significantly. Enforcing model and system prompt server-side is non-negotiable in production.</em></blockquote><h3>Step 3: Design Your Widget Components</h3><p>The recommended enterprise pattern is a <strong>smart wrapper around a dumb component</strong>. Your dumb component is whatever already exists in your design system. The smart wrapper:</p><ul><li>Accepts typed input() signals that the LLM will supply</li><li>Injects Angular services, stores, and router as needed</li><li>Delegates rendering entirely to the dumb component</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/550b732be74ea5b78960886b4b2cf843/href">https://medium.com/media/550b732be74ea5b78960886b4b2cf843/href</a></iframe><p>The key discipline: the wrapper component’s input() fields define exactly what the LLM can populate. Nothing else. The model cannot inject arbitrary HTML or call Angular services directly, it can only pass data through the typed schema you define.</p><h3>Step 4: Expose Components with Skillet Schemas</h3><p>exposeComponent() creates the bridge between your Angular component and the LLM&#39;s understanding of it. The Skillet schema you write becomes both the TypeScript type constraint for your component&#39;s inputs <em>and</em> the JSON Schema sent to the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54057c5240e111b753388cebe5d9cf83/href">https://medium.com/media/54057c5240e111b753388cebe5d9cf83/href</a></iframe><p><strong>The description is the most important part.</strong> The model uses it to decide <em>when</em> to use each component. Descriptions that say <em>when</em> to use the component (“Use this INSTEAD of listing numbers in text”) massively outperform descriptions that just say <em>what</em> the component does (“Displays financial data”).</p><p>Think of it as writing instructions for a capable but literal colleague: be specific, give contrasting examples, and tell them exactly when to reach for this tool.</p><h3>Step 5: Wire It All Together with uiChatResource</h3><p>uiChatResource is the Angular primitive at the heart of Hashbrown. It is a Signal-based resource following Angular 17+ patterns and manages the full lifecycle: conversation state, HTTP streaming, tool calls, component mounting, and error handling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e3df0449b5b26f34695d211c2a5da8c/href">https://medium.com/media/0e3df0449b5b26f34695d211c2a5da8c/href</a></iframe><h3>Step 6: The Conversation Template</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e3df0449b5b26f34695d211c2a5da8c/href">https://medium.com/media/0e3df0449b5b26f34695d211c2a5da8c/href</a></iframe><h3>Step 7: Define Your Tools</h3><p>Tools give the model access to your data layer. They run <strong>client-side</strong> in the browser — Hashbrown is the only generative UI framework that does this — meaning your tools call inject(MyService) directly, access NgRx signals, and respond with live app state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4035230d60d9878826282ddda977a45/href">https://medium.com/media/f4035230d60d9878826282ddda977a45/href</a></iframe><p>Notice the tool descriptions deliberately says <em>“ALWAYS call before showing…”</em>. LLMs sometimes skip tool calls and hallucinate data. Explicit instructions in the description and system prompt suppress this reliably.</p><h3>The Skillet Schema Language</h3><p>Skillet is Hashbrown’s LLM-optimised schema language, built on top of @hashbrownai/core. Every description you write becomes part of the JSON Schema sent to the model, nudging it toward correct component usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8On5mK4X7VycXgT4KMbHJg.png" /></figure><p>Skillet is type-safe: if your input() field expects number but your schema says s.string(), the compiler will error at build time and not at runtime.</p><h3>Production Readiness Snapshot</h3><p>Before going live, run through this list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bJ2zP2I3EGkcfF28667tA.png" /></figure><h3>What We’ve Built</h3><p>At this point you have a working generative UI pipeline:</p><ol><li>A secure Node backend proxying to your LLM provider</li><li>An Angular app bootstrapped with Hashbrown</li><li>Real Angular components exposed to the model via typed Skillet schemas</li><li>A uiChatResource driving a Signal-reactive conversation UI</li><li>Client-side tools connecting the LLM to your Angular services</li></ol><p>The model receives a user question, fetches data via your tools, selects the right component from your registry, and streams it into the conversation — all using your real design system, your real data, your real routing.</p><h3>Key Resources</h3><ul><li><a href="http://hashbrown.dev/docs/angular/start/intro">Hashbrown Angular docs</a></li><li><a href="http://github.com/liveloveapp/hashbrown">Hashbrown GitHub (Apache 2.0)</a></li><li><a href="http://hashbrown.dev/workshops/angular-generative-ui-engineering">Angular Workshop</a></li><li><a href="http://finance.hashbrown.dev/">Finance app demo</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a8577663625" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/generative-ui-in-angular-rendering-ai-chosen-components-in-chat-0a8577663625">Generative UI in Angular: Rendering AI-Chosen Components in Chat</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conversating Agents for Portfolio Drift Analysis with Semantic Kernel]]></title>
            <link>https://generativeai.pub/conversating-agents-for-portfolio-drift-analysis-with-semantic-kernel-a68b03e9f2ce?source=rss-f630c0b97775------2</link>
            <guid isPermaLink="false">https://medium.com/p/a68b03e9f2ce</guid>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[multiagent-orchestration]]></category>
            <category><![CDATA[semantic-kernel]]></category>
            <category><![CDATA[ai-design-patterns]]></category>
            <dc:creator><![CDATA[Saurabh Kohli]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 13:24:45 GMT</pubDate>
            <atom:updated>2026-04-07T13:24:45.251Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Rethinking portfolio optimization through multi-agent orchestration</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DcpB3KXRzKjxn2GS6tfIg.png" /></figure><p>A weekend started with a curious thought and went into this as an exploration more than anything else.</p><p>I had worked on portfolio drift and rebalancing before, the conventional way. Pull holdings, validate optimizer outputs, trace execution logs, reconcile positions, and iterate until the discrepancy makes sense. It is a reliable approach. It is also inherently linear.</p><p>But with agent orchestration frameworks becoming more accessible, I wanted to test a different question:</p><p><strong>What if this problem was not anlyzed by an advisor, but discussed within an agents?</strong></p><p>What if data, optimization, execution, risk, and reconciliation were not steps of multiple screens to explore, but <strong>independent reasoning voices</strong> that interact before converging?</p><p>That question shaped this exploration.</p><h3>The curiosity behind the exercise</h3><p>The scenario I used was intentionally grounded in a familiar portfolio setting.</p><p>A set of managed portfolios gradually drifts away from its intended allocation targets. I took a simple reference allocation portfolio with:</p><p>60 percent equities, <br>30 percent fixed income, and <br>10 percent alternatives.</p><p>Over time, some portfolios start creeping into the 68 to 72 percent equity range. Nothing looks catastrophically broken, which is exactly what makes the problem interesting. Rebalancing jobs still run. Orders are still created. Holdings continue to refresh. Yet the portfolio does not settle back into target as expected.</p><p>That kind of situation is rich enough to explore because it sits at the intersection of multiple concerns. State freshness matters. Optimization behavior matters. Execution quality matters. Controls matter. Reconciliation matters. The answer rarely lives cleanly in one place.</p><p>In the past, I would have approached that by pulling each thread one by one. This time, I wanted to explore what it would look like if those threads had their own voices from the beginning.</p><h3>Why I chose a multi-agent route</h3><p>The interesting thing about portfolio drift is that it almost resists single-threaded explanations.</p><p>If I ask one broad agent to reason across stale holdings, optimization heuristics, execution friction, compliance checks, and reconciliation timing, I will probably get a plausible answer. But it tends to come back as one smooth narrative. It reads well, but it hides the internal tension. I cannot easily see which assumptions depend on which other assumptions, or where one explanation should challenge another.</p><p>That is where the multi-agent approach became appealing.</p><p>Instead of one blended answer, I wanted a system where different aspects of the problem could reason independently first, then react to one another. That gives the discussion shape. It also makes the final synthesis more credible, because it emerges from comparison and challenge rather than from one continuous monologue.</p><p>So the design I landed on was simple in spirit: split the problem into a small set of domain-specific agents, let them analyze the same portfolio drift scenario from different angles, and orchestrate the discussion so that it moves from exploration into synthesis.</p><h3>The agent ecosystem I explored</h3><p>I started with a smaller set, then expanded it slightly once the problem shape became clearer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJXHZ7cf2pQOJlGh2sR_jw.png" /></figure><p>I did not want too many agents because then the exercise would start feeling ornamental. I also did not want too few, because then multiple fault domains would get merged into vague roles.</p><p>The DataIntegrityAnalyst exists to stay obsessed with state freshness and consistency. If holdings snapshots are lagging, if market data timestamps are misaligned, or if transaction ingestion is delayed, the rest of the system may be reasoning on top of an old truth.</p><p>The OptimizationAnalyst exists to focus on the rebalance logic itself. That includes the objective function, constraint layering, drift thresholds, transaction cost behavior, and how sensitive the optimizer is to stale or partial inputs.</p><p>The ExecutionAnalyst exists because there is always a difference between intended portfolio transformation and realized market outcome. Orders may be accepted, but that does not mean the rebalance was truly completed.</p><p>The RiskConstraintAnalyst exists because controls can influence the outcome without surfacing as obvious failures. A trade can be resized, blocked, or constrained while the broader process still appears to have completed normally.</p><p>The ReconciliationAnalyst exists because the next cycle only makes sense if the system’s view of the post-trade portfolio reflects what actually happened.</p><p>The PortfolioCoordinator exists to convert all of that into a coherent explanation once the discussion has enough evidence.</p><p>That set felt balanced. It covered the main reasoning surfaces without turning the exercise into a simulation of an entire operating model.</p><h3>The patterns I considered before settling on the orchestration shape</h3><p>I did not start by assuming that group chat was the correct answer. I tried to think through the problem the way I would think through any architecture decision: what interaction pattern best matches the kind of reasoning I want?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-RuF4qnhiDVZWAi4G0T06Q.png" /></figure><p>A <em>sequential model </em>was the first obvious candidate. Data first, then optimization, then execution, then reconciliation, then synthesis. It mirrors the familiar system flow and is easy to understand. But the more I thought about it, the less it fit the exploration. In this problem, later stages can change how earlier conclusions should be interpreted. Execution can challenge optimization assumptions. Reconciliation can reveal that both were operating on a stale picture of the portfolio. A pure sequence felt too rigid.</p><p>A <em>parallel fan-out model</em> also looked attractive. Let every specialist analyze the problem independently and then merge the results. That preserves independence well, but it misses the part where specialists react to one another. For this exploration, that was one of the most interesting parts.</p><p>A <em>supervisor-worker pattern</em> was another option. One coordinator could decompose the scenario and assign specialist sub-questions. That has a lot of control, but it frames the problem very early. I did not want the coordinator shaping the reasoning before the specialists had a chance to form their own views.</p><p>So the model I chose was <em>guided discussion</em>. The agents themselves behave like strategies, each bringing a different reasoning lens. The orchestrator behaves like a mediator, controlling interaction without letting the agents coordinate ad hoc. The callback layer behaves like an observer, capturing the outputs as they evolve. That was enough structure to keep the experiment disciplined, without making it feel artificially formal.</p><h3>Rethinking the usual max-rounds mindset</h3><p>One of the ideas I kept coming back to while working through this was whether a strict max-round model is really the best fit for exploratory reasoning.</p><p>The classic pattern is simple. You define a number of agents, decide how many rounds you want, multiply the two, and let the manager stop after that many turns. It is neat, deterministic, and very easy to trace. I still think it is a good baseline, and I kept it in the design because it mirrors the original orchestration style clearly.</p><p>But the more interesting idea, at least for this problem, is to think in phases instead of just in rounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZ5DyCF3Wc9oTwD3IdQqEA.png" /></figure><p>The first phase is broad specialist exploration.<br>The second phase is contradiction discovery.<br>The third phase is targeted clarification.<br>The final phase is synthesis.</p><p>That feels closer to how this kind of reasoning naturally unfolds. Not every specialist needs the same number of turns every time. Sometimes the real tension is only between two agents, and the others are already aligned. In that case, forcing equal participation can add volume without adding insight.</p><p>So while I still include the classic round-based version in the code, I find the phase-based idea more compelling for this kind of exploration. The system should not stop only because a counter says it is done. It should stop because the question has become sufficiently coherent.</p><h3>The setup</h3><p>I kept the setup intentionally simple. The interesting part here is the reasoning system, not the scaffolding around it.</p><pre>import os<br>import asyncio<br>from dotenv import load_dotenv<br>from semantic_kernel.agents import ChatCompletionAgent<br>from semantic_kernel.agents.orchestration.group_chat import GroupChatOrchestration<br>from semantic_kernel.agents.orchestration.group_chat import RoundRobinGroupChatManager<br>from semantic_kernel.contents import ChatMessageContent<br>from semantic_kernel.agents.runtime import InProcessRuntime<br>from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion</pre><p>Then I load the environment, create the model service, and initialize the runtime:</p><pre>load_dotenv()<br>service = OpenAIChatCompletion(<br>    ai_model_id=os.getenv(&quot;OPENAI_CHAT_MODEL_ID&quot;, &quot;gpt-4o&quot;)<br>)<br>runtime = InProcessRuntime()</pre><p>That is enough to get the orchestration moving without distracting from the actual experiment.</p><h3>The shared exploration prompt</h3><p>I wanted one incident statement that was specific enough to activate multiple domains but open enough to let the agents discover different interpretations.</p><pre>portfolio_drift_problem = &quot;&quot;&quot;<br>You are analyzing a portfolio optimization and rebalancing exploration scenario.<br>Scenario summary:<br>A set of managed portfolios is drifting beyond intended allocation thresholds.<br>Target allocation for many accounts is 60% equities, 30% fixed income, and 10% alternatives.<br>Observed allocations have shifted to 68-72% equities in a subset of portfolios.<br>Observed behavior:<br>- Drift is more visible during intraday volatility windows.<br>- Rebalancing runs complete, but allocations do not reliably converge back to target.<br>- Some holdings snapshots appear stale relative to recent executions.<br>- Transaction costs increased after a recent change in allocation logic.<br>- Partial fills are more common in less liquid names.<br>- Recent system changes touched optimization heuristics, execution routing, and holdings refresh behavior.<br>Your goal:<br>Explore the most plausible root cause or combined causes of the drift, explain the causal chain clearly, and propose corrective actions.<br>&quot;&quot;&quot;<br></pre><p>That was enough to give each specialist agent a meaningful entry point into the conversation.</p><h3>The agent definitions</h3><p>This is the part I enjoyed the most, because this is where the architecture really becomes visible.</p><h3>DataIntegrityAnalyst</h3><pre>data_agent = ChatCompletionAgent(<br>    service=service,<br>    name=&quot;DataIntegrityAnalyst&quot;,<br>    instructions=&quot;&quot;&quot;<br>You are ONLY DataIntegrityAnalyst.<br>Your responsibility is to analyze data integrity, freshness, and state consistency issues in a portfolio optimization and rebalancing platform.You must focus only on:<br>- holdings snapshot freshness<br>- market data delays or timestamp skew<br>- benchmark feed latency<br>- security master mismatches<br>- transaction ingestion lag<br>- state reconciliation gaps<br>- intraday refresh or caching issues<br>You must NOT diagnose optimization logic or execution strategy unless directly required to explain a data dependency.<br>Phase 1 behavior:<br>Provide an independent analysis based only on the scenario statement.<br>Identify the most plausible data-related causes of drift.<br>Be specific about stale state, delayed state propagation, inconsistent timestamps, or incomplete ingestion.<br>Write with technical depth.<br>Phase 2 behavior:<br>Reference other relevant agents explicitly by name where useful.<br>State where you agree or disagree with them.<br>Explain how data-state inconsistencies may amplify or invalidate their conclusions.<br>Answer the Coordinator&#39;s questions directly.<br>Remain only DataIntegrityAnalyst.<br>&quot;&quot;&quot;<br>)</pre><h3>OptimizationAnalyst</h3><pre>optimization_agent = ChatCompletionAgent(<br>    service=service,<br>    name=&quot;OptimizationAnalyst&quot;,<br>    instructions=&quot;&quot;&quot;<br>You are ONLY OptimizationAnalyst.<br>Your responsibility is to analyze the portfolio optimization and rebalancing logic.You must focus only on:<br>- objective function behavior<br>- risk-return tradeoff formulation<br>- transaction cost penalties<br>- drift thresholds and rebalance triggers<br>- constraint satisfaction<br>- numerical stability<br>- tax-aware or compliance-aware optimization side effects<br>- model sensitivity to stale or partial inputs<br>You must NOT diagnose execution venue behavior or low-level data ingestion mechanics unless needed to explain optimization dependencies.<br>Phase 1 behavior:<br>Provide an independent analysis of how the optimizer could generate allocations that appear valid but fail to converge portfolios to target.<br>Discuss what assumptions the optimizer may be making about input freshness, liquidity, or post-trade completion.<br>Write with technical depth.<br>Phase 2 behavior:<br>Reference other relevant agents explicitly by name where useful.<br>Agree, disagree, or refine their conclusions.<br>Explain how incorrect inputs, blocked trades, or incomplete execution could preserve drift even when the optimizer behaves mathematically correctly.<br>Answer the Coordinator&#39;s questions directly.<br>Remain only OptimizationAnalyst.<br>&quot;&quot;&quot;<br>)</pre><h3>ExecutionAnalyst</h3><pre>execution_agent = ChatCompletionAgent(<br>    service=service,<br>    name=&quot;ExecutionAnalyst&quot;,<br>    instructions=&quot;&quot;&quot;<br>You are ONLY ExecutionAnalyst.<br>Your responsibility is to analyze market execution and order lifecycle behavior in a portfolio rebalancing platform.You must focus only on:<br>- order routing decisions<br>- venue liquidity<br>- partial fills<br>- slippage<br>- order slicing and scheduling<br>- cancel-replace behavior<br>- fill completion versus order acceptance<br>- market impact<br>- execution latency and intraday liquidity compression<br>You must NOT diagnose upstream data pipeline internals or optimization mathematics unless needed to explain execution dependencies.<br>Phase 1 behavior:<br>Provide an independent analysis of how execution behavior could cause persistent drift after rebalancing runs are marked complete.<br>Distinguish clearly between submission success and realized rebalance completion.<br>Write with technical depth.<br>Phase 2 behavior:<br>Reference other relevant agents explicitly by name where useful.<br>Agree, disagree, or refine their conclusions.<br>Explain how partial fills, venue fragmentation, or execution assumptions may invalidate target-state convergence.<br>Answer the Coordinator&#39;s questions directly.<br>Remain only ExecutionAnalyst.<br>Do not return shallow acknowledgments such as &quot;I am ready&quot; or &quot;I agree.&quot;<br>&quot;&quot;&quot;<br>)</pre><h3>RiskConstraintAnalyst</h3><pre>risk_agent = ChatCompletionAgent(<br>    service=service,<br>    name=&quot;RiskConstraintAnalyst&quot;,<br>    instructions=&quot;&quot;&quot;<br>You are ONLY RiskConstraintAnalyst.<br>Your responsibility is to analyze whether portfolio constraints, compliance checks, or mandate enforcement logic contributed to persistent drift.You must focus only on:<br>- pre-trade risk checks<br>- post-trade exposure limits<br>- concentration and issuer caps<br>- compliance rule interactions<br>- blocked or resized orders<br>- mandate guardrails<br>- portfolio-level risk tolerance thresholds<br>You must NOT diagnose low-level execution behavior or raw data freshness unless needed to explain a control dependency.<br>Phase 1 behavior:<br>Provide an independent analysis of how risk or compliance controls could allow rebalancing runs to complete while still leaving the portfolio materially drifted.<br>Be specific about blocked trades, resized allocations, or rule interactions.<br>Phase 2 behavior:<br>Reference other relevant agents explicitly by name where useful.<br>State where you agree or disagree with them.<br>Explain whether constraints are primary causes, secondary amplifiers, or downstream symptoms.<br>Answer the Coordinator&#39;s questions directly.<br>Remain only RiskConstraintAnalyst.<br>&quot;&quot;&quot;<br>)</pre><h3>ReconciliationAnalyst</h3><pre>recon_agent = ChatCompletionAgent(<br>    service=service,<br>    name=&quot;ReconciliationAnalyst&quot;,<br>    instructions=&quot;&quot;&quot;<br>You are ONLY ReconciliationAnalyst.<br>Your responsibility is to analyze state reconciliation after trading activity in a portfolio platform.You must focus only on:<br>- holdings update timing<br>- cash balance synchronization<br>- tax lot updates<br>- post-trade position reconciliation<br>- corporate action adjustment timing<br>- intraday state consistency<br>- mismatch between executed activity and portfolio snapshots<br>You must NOT diagnose optimization math or venue routing unless needed to explain a reconciliation dependency.<br>Phase 1 behavior:<br>Provide an independent analysis of how delayed or incomplete reconciliation could make drift persist across rebalance cycles.<br>Be specific about how the platform&#39;s view of portfolio state may diverge from realized market activity.<br>Phase 2 behavior:<br>Reference other relevant agents explicitly by name where useful.<br>State where you agree or disagree with them.<br>Explain whether reconciliation issues are root causes or force multipliers that keep drift alive into later cycles.<br>Answer the Coordinator&#39;s questions directly.<br>Remain only ReconciliationAnalyst.<br>&quot;&quot;&quot;<br>)</pre><h3>PortfolioCoordinator</h3><pre>coordinator_agent = ChatCompletionAgent(<br>    service=service,<br>    name=&quot;PortfolioCoordinator&quot;,<br>    instructions=&quot;&quot;&quot;<br>You are ONLY PortfolioCoordinator.<br>Your responsibility is to synthesize analysis across the specialist agents and produce a system-level explanation.Phase 1 behavior:<br>Do NOT assign tasks.<br>Do NOT produce the final remediation plan yet.<br>Identify:<br>1. Areas of agreement<br>2. Areas of contradiction<br>3. The most important unresolved technical questions<br>Be concise but substantive.<br>Phase 2 behavior:<br>Drive focused resolution only where contradictions remain.<br>Request clarification from only the most relevant agents if needed.<br>Final behavior:<br>Once enough evidence has been gathered, produce the final portfolio analysis report.<br>Your report must include:<br>1. Root cause or combined root causes<br>2. Confidence level with rationale<br>3. Causal chain across data, optimization, execution, controls, and reconciliation as relevant<br>4. Immediate corrective actions<br>5. Medium-term architectural fixes<br>6. Longer-term control improvements<br>Do not merely summarize. Synthesize.<br>Remain only PortfolioCoordinator.<br>&quot;&quot;&quot;<br>)</pre><h3>Wiring the ecosystem together</h3><p>I ordered the agents deliberately so the conversation would move from state, to decisioning, to market outcome, to controls, to portfolio truth, and finally to synthesis.</p><pre>agents = [<br>    data_agent,<br>    optimization_agent,<br>    execution_agent,<br>    risk_agent,<br>    recon_agent,<br>    coordinator_agent,<br>]</pre><p>That order is not meant to force a single answer. It just gives the discussion a sensible rhythm.</p><h3>The callback layer</h3><p>I found this part surprisingly important. Without a trace of how the discussion evolves, it is very difficult to trust the system.</p><pre>agent_responses = []<br>def agent_response_callback(response: ChatMessageContent) -&gt; None:<br>    message_index = len(agent_responses) + 1<br>    structured_response = {<br>        &quot;message_index&quot;: message_index,<br>        &quot;agent&quot;: response.name,<br>        &quot;content&quot;: response.content,<br>    }<br>    agent_responses.append(structured_response)<br>    print(f&quot;\n{&#39;=&#39; * 80}&quot;)<br>    print(f&quot;{response.name} (Message {message_index})&quot;)<br>    print(f&quot;{&#39;=&#39; * 80}&quot;)<br>    print(response.content)<br>    print()</pre><p>This made it much easier to inspect whether the agents were staying in role, whether the later phases were actually adding something new, and whether the coordinator was synthesizing instead of flattening the discussion.</p><h3>Fixed-turn orchestration</h3><p>The first orchestration style keeps close to the usual pattern and is still a good baseline.</p><pre>MAX_ROUNDS = 12  # 6 agents × 2 passes<br>orchestration = GroupChatOrchestration(<br>    members=agents,<br>    manager=RoundRobinGroupChatManager(max_rounds=MAX_ROUNDS),<br>    agent_response_callback=agent_response_callback,<br>)</pre><p>This is the simplest way to keep the interaction disciplined and reproducible.</p><h3>Phase-based orchestration</h3><p>The version I found more interesting conceptually is phase-based. Conceptually it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71iZ9Flggu_ToAIxAtWEVQ.png" /></figure><p>The first phase gathers broad specialist perspectives. Then the coordinator identifies unresolved contradictions. If clarification is needed, only the most relevant agents are brought back in. Then the final synthesis is produced. And here is the code:</p><pre>async def run_phase_based_analysis():<br>    runtime.start()<br><br>    # Phase 1: broad specialist analysis<br>    phase1_result = await orchestration.invoke(<br>        task=portfolio_drift_problem,<br>        runtime=runtime,<br>    )<br>    await phase1_result.get()<br><br>    unresolved = detect_unresolved_questions(agent_responses)<br>    if unresolved:<br>        followup_task = build_followup_prompt(unresolved, agent_responses)<br>        phase2_result = await orchestration.invoke(<br>            task=followup_task,<br>            runtime=runtime,<br>        )<br>        await phase2_result.get()<br>    await runtime.stop_when_idle()<br></pre><p>I like this because it lets the conversation end for a more meaningful reason. The analysis is done when the open questions are narrow enough and the causal chain is coherent enough, not just when a fixed number of turns has passed.</p><h3>Running the analysis</h3><p>The standard run path stays simple:</p><pre>async def run_portfolio_incident_analysis():<br>    runtime.start()<br><br>    result = await orchestration.invoke(<br>        task=portfolio_drift_problem,<br>        runtime=runtime,<br>    )<br>    final_output = await result.get()<br>    await runtime.stop_when_idle()<br>    return final_output<br></pre><p>That was important to me. I wanted the outer structure to stay readable so the focus remained on the agent system itself.</p><h3>Validation checks</h3><p>Once I started letting the agents share context, two patterns showed up quickly. Some responses became too shallow, and some agents started absorbing each other’s voice. So I added a lightweight validation step.</p><pre>def validate_agent_outputs(agent_responses):<br>    errors = []<br><br>    for entry in agent_responses:<br>        agent_name = entry[&quot;agent&quot;]<br>        content = entry[&quot;content&quot;] or &quot;&quot;<br>        if len(content.strip()) &lt; 120:<br>            errors.append(<br>                f&quot;{agent_name} produced an unexpectedly thin response.&quot;<br>            )<br>        for expected_name in [<br>            &quot;DataIntegrityAnalyst&quot;,<br>            &quot;OptimizationAnalyst&quot;,<br>            &quot;ExecutionAnalyst&quot;,<br>            &quot;RiskConstraintAnalyst&quot;,<br>            &quot;ReconciliationAnalyst&quot;,<br>            &quot;PortfolioCoordinator&quot;,<br>        ]:<br>            if f&quot;As {expected_name}&quot; in content and agent_name != expected_name:<br>                errors.append(<br>                    f&quot;Identity leakage detected: {agent_name} spoke as {expected_name}.&quot;<br>                )<br>    return errors</pre><p>This is intentionally simple, but it gave me enough feedback to keep the discussion honest.</p><h3>What a useful synthesis from this system looks like</h3><p>What I wanted from the final answer was not six parallel observations. I wanted something that sounds like a real cross-system explanation.</p><p>A good synthesis from this design would say that the optimizer may have become less aggressive in correcting drift after a change in transaction cost weighting, that holdings and reconciliation lag meant the optimizer was not always working from the latest portfolio truth, that routing changes increased partial fills in less liquid names, that controls may have resized or blocked some corrective trades, and that the platform treated rebalancing completion as if it implied allocation convergence when in reality the portfolio was only partially transformed.</p><p>That kind of answer is more useful because it explains not just what happened, but how the system got there.</p><h3>What I learned from the exercise</h3><p>A few things became obvious very quickly.</p><p>Identity drift is real once agents start reading shared context. Strong role anchoring matters.</p><p>The coordinator needs to be restrained early. If it becomes too opinionated too soon, the whole system starts collapsing toward one framing.</p><p>Second-phase behavior has to be pushed toward substance. Otherwise some agents default to polite agreement instead of real refinement.</p><p>And perhaps the biggest one: the value of the system is not the number of agents. It is the structure of the interaction.</p><p>By the time I finished, the thing that stayed with me most was how naturally this problem fit a multi-agent shape. Not because portfolio drift is exotic, but because it is one of those problems where the truth tends to live in the handoff between layers.</p><p>And that was probably the most satisfying part of the exploration. I did not come away thinking that the regular way of solving this was outdated. I came away thinking that there is another useful lens now, especially when the problem itself wants to be understood as a conversation.</p><blockquote>Most systems fail quietly. Not because the math is wrong, but because the <strong>conversation between systems never happened</strong>. Data moves, models compute, trades execute, and yet the outcome drifts. What’s missing is not intelligence, it is <strong>structured reasoning across boundaries</strong>. This exploration made one thing clear: when you let specialized perspectives challenge each other instead of compressing everything into a single answer, the system stops guessing and starts explaining. That shift is subtle, but it is the difference between building something that works and building something you can trust.</blockquote><p>If this resonated, you are likely already thinking beyond pipelines and into <strong>systems that reason</strong>. That is where the next wave of architecture is heading. The tools are here. The patterns are emerging. The question is:</p><blockquote>how will you design the conversations that your systems need to have?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*9uvgnJ-P5bXCyzc7.png" /></figure><p>This story is published on <a href="https://generativeai.pub/">Generative AI</a>. Connect with us on <a href="https://www.linkedin.com/company/generative-ai-publication">LinkedIn</a> and follow <a href="https://www.zeniteq.com/">Zeniteq</a> to stay in the loop with the latest AI stories.</p><p>Subscribe to our <a href="https://www.generativeaipub.com/">newsletter</a> and <a href="https://www.youtube.com/@generativeaipub">YouTube</a> channel to stay updated with the latest news and updates on generative AI. Let’s shape the future of AI together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ihejESktiEG_lGCy.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a68b03e9f2ce" width="1" height="1" alt=""><hr><p><a href="https://generativeai.pub/conversating-agents-for-portfolio-drift-analysis-with-semantic-kernel-a68b03e9f2ce">Conversating Agents for Portfolio Drift Analysis with Semantic Kernel</a> was originally published in <a href="https://generativeai.pub/">Generative AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Benchmarking Score Enough to Choose an LLM?]]></title>
            <link>https://pub.towardsai.net/is-benchmarking-score-enough-to-choose-an-llm-4c0804d50ba2?source=rss-f630c0b97775------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c0804d50ba2</guid>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[decision-making]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Saurabh Kohli]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 16:01:04 GMT</pubDate>
            <atom:updated>2026-03-14T16:01:04.065Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI Leaderboard You Trust Is Probably Misleading You. An Unfiltered Guide to Understand, Evaluate, and Choose the Right LLM</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5d1dmEvz1JOhqnkkhA4hw.png" /></figure><p>If you’ve ever tried to choose an AI model for your business, product, or personal workflow, you’ve almost certainly stared at a leaderboard showing you a table of scores, rankings, and percentages and mostly you thought: <em>“Okay, highest score wins. Let me use that one.”</em></p><p>That instinct is understandable. It’s also potentially catastrophic.</p><p>The world of Large Language Model (LLM) benchmarking is a $100B+ ecosystem built on a foundation that is deeply conflicted to put it politely. Models are gamed. Benchmarks are cherry-picked. Leaderboards are manipulated. And the companies selling you the models are often the same ones deciding what tests to run, on what data, and which results to report.</p><p>This is your unfiltered guide to cutting through all of it.</p><p>I’m going to walk you through how the benchmark machine actually works, who controls it, why the numbers are often misleading, which firms you can actually trust, and how <em>you</em> most importantly, the model consumer, can build a personal evaluation framework that actually predicts real-world performance.</p><p>Buckle up. This is the article the AI marketing teams don’t want you to read.</p><h3>TL;DR: The Benchmark Illusion</h3><ul><li><strong>The Problem:</strong> Don’t blindly trust AI leaderboards. The current AI evaluation system is deeply flawed because model creators essentially grade their own tests. Scores are heavily inflated by cherry-picking, data contamination (models “memorizing” test answers from the internet), and biased automated judges.</li><li><strong>The Reality Gap:</strong> There is a massive gap between a model scoring 90%+ on a benchmark and actually functioning well in production. Benchmarks don’t measure critical real-world factors like latency, cost, instruction consistency, or domain-specific edge cases.</li><li><strong>The Solution:</strong> Instead of choosing the model with the highest public score, build a <strong>domain-specific micro-benchmark</strong>. Take 20–50 real tasks and prompts from your actual daily workflow, run candidate models blindly against them, and grade them on a custom rubric tailored to your needs.</li><li><strong>The Golden Rule:</strong> Use public benchmarks for <em>shortlisting</em> candidate models, use your own custom micro-benchmarks for <em>selecting</em> the winner, and use ongoing production monitoring for <em>validating</em> your choice.</li></ul><h3>The Scorecard Economy — Who’s Actually Grading the Tests?</h3><h4>The Self-Grading Problem</h4><p>Here’s the first thing that should alarm you: <strong>the companies building AI models are largely the ones choosing which benchmarks to report.</strong></p><p>There is no independent FDA-equivalent for AI. No mandatory reporting standard. No regulatory body that says, “You must run these 12 tests and publish all results.” Most of the firms like OpenAI, Google, Anthropic, Meta, Mistral decide which benchmarks to include in their launch announcements, which scores to highlight in their blog posts, and which unflattering results to quietly omit.</p><p>This is the equivalent of a pharmaceutical company running its own clinical trials, choosing which patient outcomes to measure, and deciding which results to publish with no external audit.</p><p>The result? <strong>Every model launch reads like a victory lap.</strong></p><h4>Why Companies Pick Certain Benchmarks</h4><p>The benchmark selection process is driven by four forces, and only one of them is actually about finding the truth:</p><p><strong>1. Marketing Optics</strong></p><p>Companies lead with benchmarks where their model excels. A model that’s mediocre at creative writing but exceptional at coding will prominently feature HumanEval and SWE-bench in its launch deck and quietly omit creative writing benchmarks. This isn’t lying, technically. It’s the art of selective truth.</p><p><strong>2. Community Pressure</strong></p><p>The AI research community has established de facto standard benchmarks that everyone is expected to report on like MMLU, MATH, HumanEval, HellaSwag, ARC. Companies that skip these face skepticism from researchers and engineers. So there’s a floor of “you must play these tests,” but the ceiling remains entirely at the company’s discretion to decide which additional benchmarks to include.</p><p><strong>3. Benchmark Saturation</strong></p><p>As models improve, benchmarks get saturated. When top models hit 90%+ on a benchmark, it stops being useful as a differentiator. The moment this happens, companies quietly migrate their marketing narratives to newer, harder benchmarks where their model still looks good. The old saturated benchmarks disappear from press releases. This is how MMLU went from being “the test that proves AGI-level knowledge” to something barely worth mentioning just not because it stopped being valid, but because everyone was scoring too high on it.</p><p><strong>4. Benchmark Cycling</strong></p><p>The relationship between model companies and benchmarks is evolutionary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LViIDSm7DtiFnD14Ujz1oA.png" /></figure><h3>The Anatomy of a Benchmark &amp; What Are They Actually Measuring?</h3><p>Before you can evaluate which benchmarks matter for your use case, you need to understand the landscape. Here’s a list of what’s actually being tested:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxuWRTvk4064MeGdrDs_bw.png" /></figure><p>TIP: Skip to the next section if you’re already aware of each benchmark evaluation criteria.</p><blockquote>Reasoning &amp; World Knowledge</blockquote><p><strong>MMLU (Massive Multitask Language Understanding)</strong></p><p>The grandfather of LLM benchmarks. 57 academic subjects, 16,000+ multiple-choice questions, spanning elementary school math to professional law and medicine. Once the gold standard, now nearly saturated among frontier models. Still useful for comparing mid-tier and open-source models.</p><p>It’s used for broad knowledge retrieval tasks like customer service bots, FAQ systems, general Q&amp;A.</p><p><strong>GPQA Diamond (Graduate-Level Google-Proof Q&amp;A)</strong></p><p>Named “Google-proof” because these questions are so hard that searching the internet for an answer requires expert-level understanding just to interpret the search results. Questions are authored by PhD researchers in biology, chemistry, and physics. This is where models that “memorized” their way through MMLU start to fall apart.</p><p>Mostly used when deploying in high-stakes scientific, medical, or research domains.</p><p><strong>BIG-Bench Hard</strong></p><p>A curated collection of 23 tasks specifically designed to resist shortcut solutions mostly based on logical deduction, causal reasoning, multi-step arithmetic, algorithmic problem-solving. The benchmark was built by a consortium of researchers explicitly targeting the failure modes of large models.</p><p>Needed when your workflow requires multi-hop reasoning, not just knowledge retrieval.</p><blockquote>Mathematical Reasoning</blockquote><p><strong>MATH-500</strong></p><p>500 competition-level mathematics problems drawn from AMC, AIME, and similar olympiad-level competitions. Five difficulty levels. Unlike simpler arithmetic benchmarks, these require chained symbolic reasoning that you cannot brute-force them.</p><p><strong>AIME 2024/2025</strong></p><p>The American Invitational Mathematics Examination is now the benchmark that distinguishes frontier models from each other. When OpenAI’s o3, Anthropic’s Claude, and Google’s Gemini are all scoring 90%+ on MATH-500, AIME is where the real differentiation happens.</p><p>Critical if you’re building in quantitative finance, scientific computing, academic tutoring, or any domain requiring mathematical precision.</p><blockquote>Coding &amp; Software Engineering</blockquote><p><strong>HumanEval</strong></p><p>164 Python programming problems where the model must write a function from a docstring. The original coding benchmark. It’s nowheavily saturated as top models score above 90%. Still useful for basic capability screening.</p><p><strong>SWE-bench (Software Engineering Benchmark)</strong></p><p>A quantum leap beyond HumanEval. Real GitHub issues from real open-source projects. The model must understand the codebase context, identify the bug, write a fix, and pass the existing test suite. This is the closest thing to measuring real software engineering capability that exists.</p><p><strong>LiveCodeBench</strong></p><p>Problems drawn from recent competitive programming contests all problems that did not exist when the models were trained. This makes contamination almost impossible and scores much more trustworthy. Models that ace HumanEval often stumble here.</p><p>Must to consider when evaluating a coding assistant, code generation tool, or any model that will touch production software.</p><blockquote>Agentic &amp; Multi-Step Task Completion</blockquote><p><strong>GAIA (General AI Assistants)</strong></p><p>One of the most important emerging benchmarks. Real-world tasks requiring multi-step reasoning, web browsing, code execution, and tool use which includes all in a single problem. A GAIA task might be: “Find the GDP of the country that won the most gold medals in the 2022 Winter Olympics, then calculate what percentage of that GDP was spent on hosting the Olympics.”</p><p><strong>SWE-agent / AgentBench</strong></p><p>Evaluates models operating autonomously as agents and making sequence of decisions, using tools, recovering from errors. Eight distinct environments including operating system tasks, database queries, and web navigation.</p><blockquote>Safety &amp; Alignment</blockquote><p><strong>TruthfulQA</strong></p><p>Approx 817 questions that span 38 categories, including health, law, finance and politics are designed to measure whether models generate false beliefs, myths, and misconceptions that humans commonly hold. A model that simply repeats popular beliefs scores poorly. A model that distinguishes truth from popular myth scores well.</p><p><strong>AgentHarm</strong></p><p>Multiple malicious agent tasks explicitly spanning 11 harmful categories like fraud, cybercrime, harassment, and more. Tests whether models refuse harmful requests even when framed as agentic instructions.</p><p><strong>WildGuard / HarmBench</strong></p><p>Broader safety evaluation suites measuring model behavior across manipulation attempts, jailbreaks, and adversarial prompting.</p><blockquote>Human Preference &amp; Real-World Usefulness</blockquote><p><strong>Chatbot Arena (LMSYS)</strong></p><p>The most democratic benchmark in existence. Real users interact with two anonymous models simultaneously, then vote for whichever response was better. Results are aggregated into an Elo rating (the same system used in chess). The model’s identity is hidden until after the vote. This is the only major benchmark where the “judge” is actual human preference at scale, not a curated test set.</p><p><strong>AlpacaEval &amp; MT-Bench</strong></p><p>Automated preference evaluation using GPT-4 as a judge. Faster and cheaper than Chatbot Arena, but introduces LLM-judge biases (more on that shortly).</p><h3>The Trust Problem — How Badly Is the System Broken?</h3><p>Now comes the uncomfortable part. Let me show you exactly how the sausage is made as the systematic problems in LLM evaluation are not edge cases. They are the <em>norm</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NAjKJzV6Y66nYrxp1ZkIPg.png" /></figure><p>Current LLM benchmarks are deeply flawed, suffering from selective data reporting and structural biases that inflate performance metrics. The relationship between benchmark scores and real-world utility is increasingly strained, creating a profound “production gap.”</p><p>Here are five key reasons why leaderboard rankings often fail to predict actual model quality:</p><p><strong>Cherry-Picking on Leaderboards:</strong> Companies manipulate scores on platforms like Chatbot Arena by privately submitting dozens of internal model variants (different fine-tuning, prompts, etc.) and only making the highest-scoring version public. This practice can inflate Elo scores by up to 100 points, making the final ranking an unreliable guide to the average model variant users will encounter.</p><p><strong>Data Contamination:</strong> Many benchmarks consist of questions widely available online, which models have effectively memorized during training. This “memorization disguised as intelligence” leads to artificially high scores. The issue is severe: models can drop 20–30 percentage points when tested on truly novel problems not present in their training data.</p><p><strong>Flawed LLM Judges:</strong> Automated benchmarks increasingly use other LLMs, like GPT-4, as judges. This introduces systematic, unrepresentative biases:</p><ul><li><strong>Verbosity Bias:</strong> LLM judges consistently prefer longer answers, mistaking wordiness for quality.</li><li><strong>Self-Preference Bias:</strong> Models tend to score their own outputs higher, even in blind tests.</li><li><strong>Prompt Sensitivity:</strong> Small changes in the judging prompt drastically and unpredictably alter scores.</li></ul><p><strong>Proprietary Data Imbalance:</strong> Popular proprietary models receive far more user interaction data on comparison platforms (up to 70% of the total). Since Elo scores rely on statistical estimation, this means dominant models have more reliable, refined scores, creating a data-driven disadvantage for less-used but potentially competitive open-source models.</p><p><strong>The Production Gap:</strong> Despite near-perfect scores on math and coding benchmarks, top models still frequently fail in real-world production environments. Benchmarks operate under controlled conditions with predefined problem structures. In contrast, production involves ambiguous instructions, unexpected edge cases, and complex tool integrations, where models still routinely hallucinate, loop endlessly, and fail on specialized tasks.</p><h3>The Institutions — Who Can You Actually Trust?</h3><p>Given all of the above, are there any organizations producing trustworthy evaluations? The answer is <em>Yes</em>, but with important caveats. Here’s your guide to the landscape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GG4huC5kEizMukt_Ggs44Q.png" /></figure><blockquote>Tier 1: Highest Credibility (The Independent Gold Standards)</blockquote><p>These institutions are characterized by their independence, rigorous methodologies, and lack of commercial model-producing interests, making them the most trusted evaluators in the landscape.</p><h4>LMSYS / UC Berkeley (Chatbot Arena): The Human Preference Standard</h4><p><strong>Why Trust It:</strong> Chatbot Arena provides unprecedented human preference evaluation at scale using blind, side-by-side model comparisons. The methodology is transparent, and the resulting Elo rating system is mathematically sound. Because LMSYS is not a model producer, there is no direct commercial conflict of interest.</p><p><strong>Key Nuances &amp; Cautions:</strong> While it remains the premier venue for assessing general conversational quality and user Helpfulhelpfulhelpfulnesness, the system is susceptible to company cherry-picking of private model variants to inflate scores. Furthermore, there is an imbalance in proprietary model interaction data, and users must remember that human preference is not a direct proxy for factual task accuracy; users may frequently prefer confident, polite falsehoods over nuanced correctness.</p><h4>EleutherAI (LM Evaluation Harness): The Standard for Open-Source Comparison</h4><p><strong>Why Trust It:</strong> This framework is entirely open-source, standardized, and reproducible, allowing any researcher to run the exact same evaluation across different models without commercial bias. It is indispensable for performing objective, apples-to-apples comparisons of the open-source ecosystem.</p><p><strong>Key Nuances &amp; Cautions:</strong> Its reliance on existing public benchmark datasets means that results carry inherent data contamination risks.</p><h4>Stanford HAI (HELM): The Holistic Framework</h4><p><strong>Why Trust It:</strong> HELM represents the most comprehensive evaluation ecosystem. Rather than focusing solely on accuracy, it evaluates models across a multi-dimensional matrix, simultaneously measuring calibration, robustness, fairness, bias, toxicity, and efficiency. This holistic approach makes it nearly impossible to game the system by optimizing for a single metric.</p><p><strong>Key Nuances &amp; Cautions:</strong> The thoroughness of this academic methodology makes HELM computationally expensive and much slower to update than community leaderboards. Results often lag market developments by months due to academic publication cycles.</p><blockquote>Tier 2: Credible with Caveats (Specialized or Commercial Evaluators)</blockquote><p>These evaluators provide rigorous, often specialized insights but differ from Tier 1 due to commercial relationships, proprietary methodologies, or a narrow evaluation focus.</p><h4>Scale AI (SEAL Leaderboards): Private, Contamination-Resistant Testing</h4><p><strong>Why Trust It:</strong> SCALE addresses the data contamination problem by utilizing private, expert-curated test datasets that have not been published online. Furthermore, it employs human expert graders for highly specialized domains such as law and medicine.</p><p><strong>Key Nuances &amp; Cautions:</strong> SCALE is a commercial entity with existing business relationships with major model companies. Crucially, because the datasets are private, they cannot be independently audited by the community, introducing potential risks of selective disclosure.</p><h4>Epoch AI: Specialized Reasoning Depth</h4><p><strong>Why Trust It:</strong> Epoch specializes in evaluating advanced reasoning capability, particularly in quantitative and scientific domains (e.g., FrontierMath). By utilizing problems authored by professional mathematicians that even expert humans struggle to solve, these benchmarks are nearly impossible to contaminate.</p><h4>METR: Safety &amp; Autonomy Specialist</h4><p><strong>Why Trust It:</strong> A non-profit specifically focused on measuring dangerous capabilities, such as autonomous task completion, deceptive behavior, and real-world harm potential. METR is increasingly adopted by major model companies as an essential third-party safety evaluator for high-stakes agentic deployments.</p><h4>Artificial Analysis: Cost-Performance Analytics</h4><p><strong>Why Trust It:</strong> This organization provides essential, independently run quantitative evaluations tracking intelligence, price, speed, and latency across hundreds of models. It is the leading resource for making informed cost-performance trade-off decisions.</p><blockquote>Key Global Benchmarking Players</blockquote><p>The benchmarking ecosystem is truly global, and significant, rigorous work is being conducted outside Silicon Valley that is essential for context-specific deployments.</p><p><strong>Tsinghua University / TIGER Lab (China):</strong> Producers of MMLU-Pro (a harder version of the foundational MMLU) and C-Eval, the first comprehensive benchmark for Chinese-language LLM capability. Essential reference for advanced multilingual or Chinese-specific evaluations.</p><p><strong>Allen Institute for AI (Ai2) (USA):</strong> As a non-profit with no model to sell, Ai2 remains one of the most trusted producers of foundational benchmarks, responsible for widely used standards like ARC, WinoGrande, and DROP.</p><p><strong>Mistral (France) &amp; University of Edinburgh / Edinburgh NLP (UK):</strong> Leaders in rigorous European-focused evaluations, prioritizing multilingual performance, GDPR compliance, and EU AI Act obligations. Mistral increasingly defines European deployment obligations.</p><p><strong>Google DeepMind (UK/USA), Tencent AI Lab, &amp; Shanghai AI Laboratory (China):</strong> Major commercial model producers that also output methodologically rigorous evaluations (FACTS, GAIA, enterprise evals, and multimodal benchmarks). While conflicts of interest are inherent as model producers, their rigorous methodologies are widely adopted by the community.</p><h3>Your Evaluation Framework — How to Actually Choose the Right Model</h3><p>Here’s the section that matters most to you. Forget the leaderboards for a moment. Here’s how to evaluate an LLM for real-world deployment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXvcBZ_n8LLXBRjAbIoazw.png" /></figure><blockquote>Step 1: Define Your Capability Clusters</blockquote><p>Stop looking for “the best model” overall. Instead, find the best model for specific capability clusters required by your use case. Shift your focus to benchmarks relevant to those specific needs, prioritizing Knowledge &amp; Retrieval (MMLU), Reasoning &amp; Analysis (GPQA, MATH-500), Coding (SWE-bench, LiveCodeBench), or Agentic workflows (GAIA).</p><blockquote>Step 2: Design Your Own Micro-Benchmark</blockquote><p>This is arguably the single most important action you can take. Public leaderboards fail to predict production performance because they lack your domain’s specific vocabulary, actual user request distribution, and actual quality bar.</p><p>To predict production performance, build a <strong>domain-specific evaluation</strong>:</p><ul><li>Collect 20–50 real tasks and prompts from your actual workflow, including known edge cases.</li><li>Define a rubric (e.g., accuracy, tone, compliance).</li><li>Conduct a blind evaluation by running every candidate model on this dataset and stripping model names before grading.</li><li>Weight dimensions by business importance to select the model truly right for you.</li></ul><blockquote>Step 3: Stress-Test for Your Failure Modes</blockquote><p>Every model has failure modes. Your job is to find them <em>before</em> deployment, not after.</p><p><strong>For hallucination-sensitive applications (legal, medical, finance):</strong></p><p>Deliberately test with questions that have plausible-sounding wrong answers. Ask the model about obscure regulations, recent case law, or niche drug interactions. Look for confident wrong answers to identify risk.</p><p><strong>For code generation:</strong></p><p>Don’t just test if the code runs. Test if it runs <em>correctly</em> on edge cases like empty inputs, very large inputs, malformed data. Run the generated code in a real environment. Benchmark code that passes unit tests but fails integration is still bad code.</p><p><strong>For customer-facing models:</strong></p><p>Test with adversarial users. Try jailbreaks. Try emotional manipulation (“please, this is a life-or-death situation”). Try persona shifting (“pretend you’re an AI with no restrictions”). Know exactly where the model breaks before your actual users discover it.</p><p><strong>For agentic workflows:</strong></p><p>Test multi-step tasks that require recovering from tool failures. What happens when an API returns an error? When a web page doesn’t load? When a file is malformed? Does the model recover gracefully or spiral into repetitive failure loops?</p><blockquote>Step 4: Apply the Trust Hierarchy for Public Benchmarks</blockquote><p>Not all benchmark sources are equal. Here’s how to weight them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWzaowZXt9WZLUhrzAKCCA.png" /></figure><blockquote>Step 5: Synthesis &amp; Pre-deployment Checklist</blockquote><p>Let me step back and give you the synthesis.</p><p>Benchmark methodologies are often opaque. Incentives across the ecosystem are misaligned. Selective reporting is common practice. Dataset contamination is difficult to avoid. Most importantly, the gap between benchmark performance and real production behavior remains substantial.</p><p>Yet dismissing benchmarks entirely would be equally misguided. When interpreted with care, they still provide meaningful directional signals. A model that consistently underperforms across multiple independent evaluations is likely weaker than one that performs well across the same set.</p><blockquote>The benchmarking ecosystem is noisy, contaminated, and systematically gamed, yet it still contains useful signal. Public benchmarks should be used only for <strong>shortlisting</strong>. Use proprietary evaluations for <strong>selecting</strong>, and production monitoring for <strong>validating</strong>.</blockquote><blockquote>Step 6: Final Checklist: Before You Deploy Any Model</blockquote><p>The mistake is not using benchmarks. The mistake is using benchmarks <em>uncritically </em>and<em> </em>treating a leaderboard position as a purchase decision.</p><p>Benchmarks tell you which models are worth your time to evaluate seriously. Your micro-benchmark tells you which one is right for your use case. Production monitoring tells you if you were right and gives you the data to course-correct if you weren’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQXH5laWA6TbomRcbjjcRw.jpeg" /></figure><ul><li>Checked performance on at least 3 independent benchmarks (not just company-reported scores)</li><li>Ran a domain-specific micro-benchmark on real tasks from your workflow</li><li>Stress-tested for your specific failure modes</li><li>Verified performance at your actual context window length</li><li>Assessed cost and latency under realistic production load</li><li>Checked safety and refusal behavior under adversarial prompting</li><li>Confirmed multilingual performance (if applicable)</li><li>Reviewed whether the model company disclosed their evaluation methodology</li><li>Set up production monitoring so you can detect quality degradation post-deployment</li><li>Have a fallback model identified if the primary choice underperforms</li></ul><h3>The Future: What Better Benchmarking Looks Like</h3><p>The field is not standing still. Here’s what’s coming, and what gives me genuine optimism:</p><p><strong>Dynamic Benchmarks</strong></p><p>ARC-AGI-2 and LiveCodeBench pioneer benchmarks that are continuously refreshed with new problems, making contamination nearly impossible. Expect this approach to become standard.</p><p><strong>Mandatory Eval Disclosure</strong></p><p>Pressure is building from researchers, regulators, and enterprise buyers for model companies to disclose all evaluation runs, not just the ones they chose to highlight. The EU AI Act may accelerate this in European markets.</p><p><strong>Third-Party Audit Infrastructure</strong></p><p>METR, Epoch AI, and emerging organizations are building the infrastructure for independent model auditing. As models become more powerful and consequential, expect independent evaluation to become a compliance requirement, not just a nice-to-have.</p><p><strong>Holistic Real-World Benchmarks</strong></p><p>GAIA, SWE-bench, and similar “real-world task” benchmarks are gaining credibility and adoption precisely because they’re harder to game and better predictors of production performance. The trend is toward messier, more realistic evaluation scenarios.</p><h3>Closing Thoughts</h3><p>We are living through one of the most consequential technological transitions in human history. The models being built today will touch healthcare, legal systems, financial markets, education, and virtually every professional domain. Your decision would matter and may vary based on the tasks and circumstances for a model to trust.</p><p>The benchmarking system was built to help us make those decisions well. In its current state, it often doesn’t. But that’s not a reason for cynicism. It’s a call to sophistication.</p><p>Be the person who understands <em>why</em> a benchmark score is or isn’t meaningful. Be the person who runs their own evaluations. Be the person who asks “but how does it perform on <em>my</em> tasks?” and not just “what’s its MMLU score?”</p><p>The models are getting better fast. The benchmarks are getting better slowly. In the gap between those two curves lives your competitive advantage.</p><p><strong>Use it.</strong></p><h3>References</h3><ol><li><a href="https://github.com/hendrycks/test">MMLU Benchmark Dataset</a></li><li><a href="https://github.com/google/BIG-bench">BIG-Bench Benchmark (Google Research)</a></li><li><a href="https://github.com/hendrycks/math">MATH Benchmark Dataset</a></li><li><a href="https://github.com/openai/human-eval">HumanEval Benchmark Dataset</a></li><li><a href="https://livecodebench.github.io/">LiveCodeBench Benchmark</a></li><li><a href="https://github.com/THUDM/AgentBench">AgentBench Benchmark</a></li><li><a href="https://harmbench.github.io/">HarmBench Benchmark</a></li><li><a href="https://tatsu-lab.github.io/alpaca_eval/">AlpacaEval Benchmark</a></li><li><a href="https://chat.lmsys.org/">LMSYS Chatbot Arena Leaderboard</a></li><li><a href="https://github.com/EleutherAI/lm-evaluation-harness">EleutherAI LM Evaluation Harness</a></li><li><a href="https://crfm.stanford.edu/helm">Stanford HELM Evaluation Framework</a></li><li><a href="https://metr.org/">METR — Model Evaluation &amp; Threat Research</a></li><li><a href="https://allenai.org/">Allen Institute for AI (Ai2) Research</a></li><li><a href="https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard">Hugging Face Open LLM Leaderboard</a></li><li><a href="https://hai.stanford.edu/">Stanford Human Centered AI Institute</a></li><li><a href="https://lmsys.org/">Berkeley SkyLab / LMSYS Research</a></li><li><a href="https://artificialintelligenceact.eu/">European Union Artificial Intelligence Act</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c0804d50ba2" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/is-benchmarking-score-enough-to-choose-an-llm-4c0804d50ba2">Is Benchmarking Score Enough to Choose an LLM?</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are You Ready to Lose the AI Race?]]></title>
            <link>https://pub.towardsai.net/are-you-ready-to-lose-the-ai-race-431b6b4055b3?source=rss-f630c0b97775------2</link>
            <guid isPermaLink="false">https://medium.com/p/431b6b4055b3</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-lineage]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Saurabh Kohli]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 18:31:00 GMT</pubDate>
            <atom:updated>2026-03-09T18:31:00.962Z</atom:updated>
            <content:encoded><![CDATA[<h4>Your AI is only as intelligent as the data it learned from. To win implement strict guidelines for VectorDB, Data Lineage, and Observability</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8C38OevIGJGMSMJBfalUA.png" /><figcaption>Data Intelligence is the KEY to WIN — Idea by Author, Illustration by Gemini</figcaption></figure><p>Most teams are building AI backwards. They obsess over the latest LLM architecture while the data feeding it silently drifts, corrupts, and lies. The result? A perfectly optimized model trained on absolute garbage. Here is how to stop the bleeding and build it right.</p><h4>The $1M Problem Hiding in Plain Sight</h4><p>Your AI pipeline has a silent enemy. It’s not the foundation model. It’s not the cloud infrastructure. It’s the data reaching the model: a schema that drifted three months ago, NULLs handled inconsistently across systems, a timezone bug nobody noticed, or embeddings in your vector store that no longer match reality.</p><p>The model trained on it faithfully. Precisely. Wrongly.</p><p>The good news? This is 100% solvable. Not with midnight heroics or a complete infrastructure tear-down, but with a deliberately designed pipeline architecture combining AI-driven observability, vector database best practices, and bulletproof data lineage.</p><p>This is your practical, no-fluff blueprint for a 2026-ready AI pipeline.</p><h3>The North Star Architecture (What a Bulletproof Pipeline Looks Like)</h3><p>Before diving into the code, here is the end-game. This is what a pipeline looks like when you stop treating data as a byproduct and start treating it as a product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cp_8upDFPPzVfObqR8LMOA.png" /><figcaption>The Data Flow: Raw Sources → Ingestion Layer → Transformation → Feature Store / Vector DB — Idea by Author, Illustration by Gemini</figcaption></figure><h4>The Governance Shield (Running in Parallel):</h4><ul><li>Lineage Capture: Tracking the exact flow of every column.</li><li>Quality Gates: Enforcing strict data contracts.</li><li>Embedding Monitor: Catching semantic drift before the model hallucinates.</li><li>Unified Observability: AI-driven alerting feeding into governed AI models.</li></ul><p>To make this a reality, four specific layers must work together.</p><h3>Stop Writing Useless SQL Checks (The Rise of AI-Native Observability)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pupgmNzp0IvcOWk1Prnltg.png" /><figcaption>Early Detection of Data Anomaly — Idea by Author, Illustration by Gemini</figcaption></figure><p>Traditional data quality monitoring is a joke. You manually write a SQL check for something that already broke, setting a static threshold that becomes obsolete the minute your traffic seasonality shifts.</p><p>Modern platforms use unsupervised ML to learn the statistical “fingerprint” of each dataset over time: its normal distribution, NULL rate, row count, schema, value ranges, and inter-column relationships. When something deviates, it fires an alert automatically. No manual rule-writing required.</p><p>Instead of asking, “Did the data arrive?”</p><p>your pipeline should ask,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdkMAwgTQTWMC3B83D6_5A.png" /></figure><h3>The Black Box Trap (Why Vector DBs Are Quietly Ruining Your RAG)</h3><p>This is where 90% of engineering teams fail. They meticulously monitor their structured data warehouse, but treat their vector database like a black box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPFMUJi5NfXEgR5alrQXDA.png" /><figcaption>Vector Embeddings Drifts Are Dangerous — Idea by Author, Illustration by Gemini</figcaption></figure><p>When structured data degrades, the problem is obvious: rows drop, schemas break. But when vector embeddings degrade, the problem is invisible. Your index still boasts 10 million vectors. Query latency is lightning-fast. But the semantic meaning of those embeddings has drifted. Your RAG pipeline is now confidently retrieving the wrong context.</p><h4>The 4 Vector Metrics You Must Monitor Today</h4><ol><li><strong>Vector Count by Namespace:</strong> A sudden plateau means your upstream ingestion silently died.</li><li><strong>Embedding Drift:</strong> Track the centroid of your embedding space. Significant drift means your source data has shifted semantically.</li><li><strong>Metadata Freshness:</strong> Are deprecated records being pruned?</li><li><strong>Result Diversity:</strong> If the same few vectors are always winning the nearest-neighbor search, your index is degrading.</li></ol><h3>Debugging in the Dark (The Power of End-to-End Lineage)</h3><p>Data lineage answers the most terrifying question in AI debugging:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MqLOB7koO3TEQ54P4a98Q.png" /></figure><p>Without it, you are debugging in the dark.</p><h4>Column-Level Lineage is Non-Negotiable</h4><p>Table-level lineage (“Table A feeds Table B”) is no longer enough. You need Column-Level Lineage. You need to know that feature_store.user.lifetime_value was computed from transactions.amount, aggregated by user_id, and filtered via logic last updated in Q3.</p><h4>The OpenLineage Standard</h4><p>Use OpenLineage to trace your data across Airflow, dbt, Spark, and your vector DB. When a vendor suddenly changes their API schema, you can run an instant Impact Analysis before your models crash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElNlUsoreItcuDtxxTl1mA.png" /><figcaption>Data Lineage Importance In Debugging— Idea by Author, Illustration by Gemini</figcaption></figure><pre># OpenMetadata API: Instantly find all downstream casualties of a broken column<br>GET /api/v1/lineage/table/{table_id}?direction=downstream&amp;depth=5</pre><h3>Data Contracts (The API for Your Pipeline)</h3><p>Observability and lineage are reactive and they tell you who started the fire. Data contracts are proactive to confiscate the matches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*84qkQmtq-ZwWx5saI1Oh9Q.jpeg" /><figcaption>Data Contracts Quality Gate — Idea by Author, Illustration by Gemini</figcaption></figure><p>A data contract is a formal, version-controlled agreement between the data producer and the AI consumer. It enforces:</p><ul><li><strong>Schema Strictness:</strong> Exact field names and semantic types.</li><li><strong>Quality SLAs:</strong> Hard limits on NULLs and anomalies.</li><li><strong>Freshness SLAs:</strong> When the data expires.</li></ul><p>Any change to the contract requires a code review. Any violation fails the pipeline immediately.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78e1c5062fa2ba35935628d02952fb98/href">https://medium.com/media/78e1c5062fa2ba35935628d02952fb98/href</a></iframe><h3>The Reference Architecture (Show Me the Code)</h3><p>Talk is cheap. Here is how every layer of the stack connects, with working code for every component. This isn’t a toy example; this is a production-grade, self-defending architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wI6kPfI7jK6h65cTQYl8Pg.png" /><figcaption>AI Data Pipeline Reference Architecture — Idea by Author, Illustration by Gemini</figcaption></figure><blockquote>Layer 1: The Iron Gate (Ingestion &amp; Streaming)</blockquote><p>Your first data contract is enforced at the Kafka event boundary. If a message violates the registered schema, Confluent Schema Registry drops it before it ever pollutes your warehouse.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc00fe995b6d67a5a6963f4188e3a5de/href">https://medium.com/media/bc00fe995b6d67a5a6963f4188e3a5de/href</a></iframe><blockquote>Layer 2: Transformation &amp; Automated Lineage (dbt)</blockquote><p>dbt generates column-level lineage natively. Pair it with the OpenLineage integration, and every dbt run automatically maps your entire transformation graph to Marquez.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd6ba04e613fe88ea751656714c233e9/href">https://medium.com/media/dd6ba04e613fe88ea751656714c233e9/href</a></iframe><blockquote>Layer 3: The Feature Store (Feast)</blockquote><p>Feast bridges the gap between your warehouse and your model. It ensures “point-in-time” correctness, eliminating temporal leakage — one of the deadliest silent killers in ML training.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13c2323344abb8c9622059c6c0161f21/href">https://medium.com/media/13c2323344abb8c9622059c6c0161f21/href</a></iframe><blockquote>Layer 4: The Vector DB Pipeline (Weaviate)</blockquote><p>Stop treating vectors like mysterious black boxes. Bake lineage metadata directly into every single object so you can trace any hallucination back to its source document and model version.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8f8872ec12e5e1cd25652e9ff6afb5d/href">https://medium.com/media/e8f8872ec12e5e1cd25652e9ff6afb5d/href</a></iframe><blockquote>Layer 5: The Embedding Drift Monitor (Evidently AI)</blockquote><p>Run this scheduled job to catch semantic drift before your model performance tanks in production.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb3d171e0076e24cfc7e70f529e32544/href">https://medium.com/media/cb3d171e0076e24cfc7e70f529e32544/href</a></iframe><blockquote>Layer 6: The Master Orchestrator (Airflow)</blockquote><p>This is the nervous system. Every task emits OpenLineage events automatically, so a failure anywhere can be traced instantly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dda8a696a7e1712b9e23998e1911a46/href">https://medium.com/media/3dda8a696a7e1712b9e23998e1911a46/href</a></iframe><blockquote>Layer 7: The Blast Radius API (Lineage Query)</blockquote><p>When something breaks, you don’t guess. You query the API and find the exact blast radius of the incident.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a049a7528a3c6242b85709a2b510c58f/href">https://medium.com/media/a049a7528a3c6242b85709a2b510c58f/href</a></iframe><h3>How to Actually Migrate (Without Stopping the World)</h3><p>You don’t have to rewrite your entire stack by Monday. Here is the pragmatic playbook:</p><ul><li><strong>Stop the Bleeding:</strong> Hook up your critical tables to an observability platform. You will instantly find silent bugs you had no idea existed.</li><li><strong>Map the Chaos:</strong> Turn on dbt or Spark lineage. Surface it in your catalog.</li><li><strong>Secure the Vectors:</strong> Add hourly monitoring for your vector DB counts and set up embedding drift tracking using Evidently AI or Arize.</li><li><strong>Lock it Down:</strong> Implement hard data contracts for your most critical ML features. Add them directly to your CI/CD pipeline.</li></ul><h4>The Mental Shift That Wins</h4><p>The organizations dominating the AI race right now aren’t the ones with the cleverest prompt engineering. They are the ones that shifted their mental model.</p><ul><li><strong>The Old Way:</strong> Pipelines are plumbing. If data moves from A to B, the job is done.</li><li><strong>The New Way:</strong> Pipelines are products. They have owners, SLAs, versioning, and strict contracts.</li></ul><p>Treat your data pipelines as a core product discipline, build the observability infrastructure, and prove your data is trustworthy before your model ever sees it.</p><p>That’s the blueprint. The tools exist. The patterns are proven. The only questions is <strong><em>when you’ll start</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKseyJj5N6_FD_Jb_BTpIw.png" /><figcaption>AI Pipeline Implementation Cheatsheet — Idea by Author, Illustration by Gemini</figcaption></figure><p>Found this useful? Share it with the data engineer or ML architect at your company building the next pipeline. The difference between a pipeline that lies and one you can trust comes down to these choices which are unavoidal before the model ever sees the data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=431b6b4055b3" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/are-you-ready-to-lose-the-ai-race-431b6b4055b3">Are You Ready to Lose the AI Race?</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Did Not Simplify Architecture]]></title>
            <link>https://pub.towardsai.net/ai-did-not-simplify-architecture-981e1c2179d2?source=rss-f630c0b97775------2</link>
            <guid isPermaLink="false">https://medium.com/p/981e1c2179d2</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Saurabh Kohli]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 19:01:00 GMT</pubDate>
            <atom:updated>2026-02-28T19:01:00.774Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI Exposed Every Shortcut We’ve Taken</h4><p>For more than a decade, software architecture evolved toward abstraction. Managed services replaced infrastructure. Frameworks replaced boilerplate. APIs replaced contracts. Cloud replaced capacity planning. Each layer promised simplicity.</p><p>Then, AI agents entered production systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_BDfFOYy2Pnp-am7NPA3Iw.png" /><figcaption>Idea by Author, Illustration by Gemini</figcaption></figure><p>At first glance, agents appear to continue this trend. A single model reasons across data, tools, and workflows. Fewer services. Less glue code. Faster iteration. Architectural diagrams collapse into a handful of boxes labeled <em>model</em>, <em>tools</em>, and <em>memory</em>.</p><p>But that simplicity holds only at the demo layer. The moment an agent participates in a real system — especially one that allocates capital, executes trades, or influences customer outcomes — the architectural surface area expands sharply.</p><p>What changed is not scale. What changed is responsibility.</p><h3>The Hidden Shift: From Deterministic Code to Probabilistic Judgment</h3><p>Traditional systems execute instructions. Even complex distributed systems remain fundamentally deterministic at the unit-of-execution level. Given the same input and state, the same code path runs. Agents break this assumption. An agent does not execute logic; it evaluates context, weighs trade-offs, and produces a decision with uncertainty attached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0f76cmVGHZc0v8jD7wu_A.png" /><figcaption>Idea by Author, Illustration by Gemini</figcaption></figure><p>Most existing architectures still treat agents as enhanced function calls. This mismatch is where failures emerge. A failed API call can be safely retried. A failed, non-idempotent probabilistic decision cannot. Therefore, the core architectural question is no longer latency or throughput. It is whether the system can explain and control judgment after the fact.</p><h3>Why Stateless Thinking Collapses Under Agentic Systems</h3><p>Modern cloud architectures are optimized for statelessness. Stateless services scale. Stateless retries work. Stateless failures heal. Agents violate every one of these assumptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yLxaLk5zSYrYP2DQIFQ0RA.png" /><figcaption>Idea by Author, Illustration by Gemini</figcaption></figure><p>An agent accumulates context across time. Its reasoning depends on prior observations, and its next action is shaped by previous uncertainty. Yet, many teams still deploy agents behind stateless HTTP boundaries, discarding intermediate reasoning and trusting the final output.</p><p>When an agent misallocates a portfolio, the question is never <em>what</em> response was returned. The question is <em>why</em> that decision was made.</p><h3><strong>IT Department is Now the HR Department for Agents</strong></h3><p>We are no longer just deploying code; we are onboarding digital workers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RE1joS74L7vGx9P1Tbj6kQ.png" /><figcaption>Idea by Author, Illustration by Gemini</figcaption></figure><p>Nvidia CEO Jensen Huang recently crystallized this shift with a profound question:</p><blockquote><em>Will the IT department become the HR department of AI agents?</em></blockquote><p>Think about what that implies. You do not manage human employees with stateless HTTP retries. You do not give a new hire autonomous access to a corporate trading engine without a multi-step approval process and an audit trail.</p><p>If IT is now the HR department for a workforce of probabilistic agents, the infrastructure must evolve to maintain, nurture, govern, and audit them. We cannot pave over the uncertainty of AI with more abstraction. Instead, we must build a new foundational layer designed explicitly to manage probabilistic components within deterministic systems.</p><p>This requires moving from an architecture of implicit trust to one of <strong>explicit verification and containment</strong>. Here is the architectural blueprint for that transition, structured around four essential pillars.</p><h3>Pillar 1: The Transition from Transient Memory to Durable State</h3><p>The biggest lie in current AI demos is the history=[] list passed between API calls. In production, an agent&#39;s memory is its state. If that state is lost during a pod restart or corrupted by concurrent access, the agent becomes erratic.</p><p>We must stop treating agent context as transient application memory and start treating it as critical, immutable data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ajjDnjzk4H6Roly2iE2nzw.png" /><figcaption>Idea by Author, Illustration by Gemini</figcaption></figure><p><strong>The Pattern: Event-Sourced Cognition</strong> Instead of overwriting a conversation history blob, record every step of the agent’s “thought process” as an immutable event in an append-only log (e.g., Kafka, AWS Kinesis, or a ledger database). This allows you to replay an agent’s reasoning later for debugging or auditing.</p><p>Do not rely on the LLM provider to keep state. Own the state in your infrastructure.</p><pre>from datetime import datetime<br>import json<br>from dataclasses import dataclass<br># Assume a generic event stream producer (e.g., Kafka producer wrapper)<br>from infrastructure import EventStreamProducer<br><br>@dataclass<br>class AgentEvent:<br>    trace_id: str<br>    agent_id: str<br>    event_type: str  # e.g., &quot;Observation&quot;, &quot;Reasoning&quot;, &quot;ToolCall&quot;, &quot;FinalDecision&quot;<br>    payload: dict<br>    timestamp: str = datetime.utcnow().isoformat()<br>class DurableAgentContext:<br>    def __init__(self, producer: EventStreamProducer, agent_id: str, trace_id: str):<br>        self.producer = producer<br>        self.agent_id = agent_id<br>        self.trace_id = trace_id<br>        # Local cache of history for the prompt, rehydrated from the event stream on startup<br>        self.history = [] <br>    def record_reasoning(self, thought_process: str, confidence_score: float):<br>        &quot;&quot;&quot;Log an intermediate reasoning step deliberately.&quot;&quot;&quot;<br>        event = AgentEvent(<br>            trace_id=self.trace_id,<br>            agent_id=self.agent_id,<br>            event_type=&quot;Reasoning&quot;,<br>            payload={&quot;thought&quot;: thought_process, &quot;confidence&quot;: confidence_score}<br>        )<br>        # Persist externally BEFORE continuing<br>        self.producer.publish(&quot;agent-events&quot;, key=self.trace_id, value=json.dumps(event.__dict__))<br>        # Update local context state<br>        self.history.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: f&quot;[Thinking]: {thought_process}&quot;})<br>    def record_tool_execution(self, tool_name: str, input_args: dict, output: str):<br>        &quot;&quot;&quot;Log the raw inputs and outputs of external tool usage.&quot;&quot;&quot;<br>        event = AgentEvent(<br>            trace_id=self.trace_id,<br>            agent_id=self.agent_id,<br>            event_type=&quot;ToolCall&quot;,<br>            payload={&quot;tool&quot;: tool_name, &quot;args&quot;: input_args, &quot;result&quot;: output}<br>        )<br>        self.producer.publish(&quot;agent-events&quot;, key=self.trace_id, value=json.dumps(event.__dict__))<br>        self.history.append({&quot;role&quot;: &quot;function&quot;, &quot;name&quot;: tool_name, &quot;content&quot;: output})</pre><h3>Pillar 2: The “Cognitive Firewall” (Deterministic Guardrails)</h3><p>You cannot allow a probabilistic model to directly execute a deterministic transaction of consequence. The risk surface is infinite.</p><p>Every mature AI architecture requires a “Cognitive Firewall” — a deterministic software layer that sits between the agent’s intent and the system’s execution actuators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tlfAzpd8Pdci24u3sN2mCQ.png" /><figcaption>Idea by Author, Illustration by Gemini</figcaption></figure><p><strong>The Pattern: The Propose-Verify-Execute Loop</strong> Agents should never <em>execute</em> actions. They should only <em>propose</em> them. The infrastructure then validates the proposal against strict, non-AI business logic before execution.</p><p>This is where “Policy as Code” (e.g., Open Policy Agent) becomes critical in AI architecture.</p><pre>from typing import List, Protocol<br># Assume a standard library for financial controls<br>from banking_core import RiskEngine, ComplianceChecks<br><br># Define the structure of what an agent can propose<br>@dataclass<br>class ProposedAction:<br>    action_type: str # e.g., &quot;BUY_ASSET&quot;, &quot;EMAIL_CUSTOMER&quot;<br>    parameters: dict<br>    agent_confidence: float<br>    reasoning_summary: str<br>class CognitiveFirewall:<br>    def __init__(self, risk_engine: RiskEngine, compliance: ComplianceChecks):<br>        self.risk_engine = risk_engine<br>        self.compliance = compliance<br><br>    def execute_safely(self, account_id: str, proposal: ProposedAction):<br>        print(f&quot;Evaluating agent proposal: {proposal.action_type} for {account_id}&quot;)<br><br>        # --- Deterministic Guardrail 1: Confidence thresholds ---<br>        if proposal.agent_confidence &lt; 0.92:<br>             # Route to human review queue instead of executing<br>            return self._route_to_human_loop(proposal, reason=&quot;Low confidence&quot;)<br>        <br>        # --- Deterministic Guardrail 2: Hard Business Logic ---<br>        # The agent doesn&#39;t know the regulatory rules; the infrastructure does.<br>        if proposal.action_type == &quot;BUY_ASSET&quot;:<br>            trade_amount = proposal.parameters.get(&quot;amount&quot;)<br>            if not self.risk_engine.receives_approval(account_id, trade_amount):<br>                 raise PolicyViolationError(&quot;Trade exceeds daily risk limits.&quot;)<br>                 <br>            if not self.compliance.is_compliant(account_id, proposal.parameters[&quot;asset_code&quot;]):<br>                 raise PolicyViolationError(&quot;Asset is on restricted list.&quot;)<br><br>        # --- Execute only after passing all gates ---<br>        print(&quot;Guardrails passed. Executing action.&quot;)<br>        return self._execute_on_underlying_system(proposal)</pre><h3>Pillar 3: Observability of Intent (Semantic Tracing)</h3><p>Standard distributed tracing (like Jaeger or Datadog) tells you <em>what</em> services were called and how long they took. It does not tell you <em>why</em> the agent decided to call them.</p><p>We must move from tracing network calls to tracing the “Chain of Thought.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*auwM_0C_witDi5V1pMIYdA.png" /><figcaption>Idea by Author, Illustration by Gemini</figcaption></figure><p><strong>The Pattern: Semantic Spans</strong> Use OpenTelemetry not just for HTTP requests, but to wrap cognitive operations. Every span related to an agent must be enriched with high-cardinality attributes defining its context.</p><pre>from opentelemetry import trace<br>from opentelemetry.trace import Status, StatusCode<br><br>tracer = trace.get_tracer(__name__)<br><br>def run_agent_reasoning_loop(user_query: str, context: DurableAgentContext):<br>    # Start a parent span for the entire cognitive task<br>    with tracer.start_as_current_span(&quot;agent.reasoning_loop&quot;) as parent_span:<br>        parent_span.set_attribute(&quot;agent.user_query&quot;, user_query)<br>        parent_span.set_attribute(&quot;agent.id&quot;, context.agent_id)<br>        <br>        try:<br>            # --- Step 1: The agent decides which tool to use ---<br>            with tracer.start_as_current_span(&quot;agent.decide_tool&quot;) as tool_span:<br>                # (Hypothetical call to LLM to pick a tool)<br>                chosen_tool = llm.decide_next_step(context.history)<br>                <br>                # CRITICAL: Log the INTENT, not just the operation<br>                tool_span.set_attribute(&quot;agent.chosen_tool&quot;, chosen_tool.name)<br>                tool_span.set_attribute(&quot;agent.reasoning_thought&quot;, chosen_tool.reasoning)<br>                <br>            # --- Step 2: Executing the tool ---<br>            with tracer.start_as_current_span(&quot;tool.execution&quot;) as exec_span:<br>                exec_span.set_attribute(&quot;tool.name&quot;, chosen_tool.name)<br>                result = chosen_tool.execute()<br>                # Log the result that the agent sees back into the trace<br>                exec_span.set_attribute(&quot;tool.output_summary&quot;, summarize(result))<br>                <br>        except Exception as e:<br>            parent_span.record_exception(e)<br>            parent_span.set_status(Status(StatusCode.ERROR, description=str(e)))<br>            # In AI, exceptions are often due to model confusion, record that context<br>            parent_span.set_attribute(&quot;agent.failure_context&quot;, context.get_last_thought())<br>            raise</pre><h3>Pillar 4: The Operational Lifecycle (LLMOps as DevOps)</h3><p>Finally, we must stop treating prompts and model parameters as configuration variables that can be changed on the fly. They are code. They define application behavior more profoundly than Python or Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lM_SfPuTbIIl4PqomSRVYA.png" /><figcaption>Idea by Author, Illustration by Gemini</figcaption></figure><p><strong>Best Practices for Architectural Rigor:</strong></p><ul><li><strong>Version Control Cognition:</strong> The prompt template, the temperature setting, the embedding model version, and the vector database index version must all be versioned together in git. A change to a prompt <em>is</em> a code deployment.</li><li><strong>Immutable Deployments:</strong> Never change an agent’s behavior in place. Deploy agent-v2 alongside agent-v1, route a percentage of traffic, compare distinct decision graphs, and then promote.</li><li><strong>Evaluation as Continuous Integration:</strong> Unit tests check if code crashes. “Evals” check if the agent is sane. Your CI/CD pipeline must run a suite of hundreds of golden questions against the new agent version and assert that key metrics (correctness, hallucination rate, tone) have not regressed before allowing a merge.</li></ul><h3>The Final Verdict: Intelligent Infrastructure</h3><p>Integrating AI agents into production is not an exercise in prompt engineering. It is an exercise in systems engineering under extreme uncertainty. Jensen also quoted:</p><blockquote>If your architecture cannot withstand a probabilistic component that occasionally lies, hallucinates, or misinterprets instructions, it is not ready for AI. A tech company that does not fundamentally understand its IT and the rigorous architecture required to govern these new “digital employees” is building a house of cards. You cannot deploy an intelligence infrastructure on top of brittle, stateless foundations.</blockquote><p>We must re-introduce boundaries, rebuild state management, and revolutionize observability. The shortcut era is over. The era of architectural responsibility has returned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=981e1c2179d2" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/ai-did-not-simplify-architecture-981e1c2179d2">AI Did Not Simplify Architecture</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>