<?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 Mohan Krishna G on Medium]]></title>
        <description><![CDATA[Stories by Mohan Krishna G on Medium]]></description>
        <link>https://medium.com/@itismohan.g?source=rss-b563fdb94f2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NFM_OdWJXlRL4mehaPCAkg.jpeg</url>
            <title>Stories by Mohan Krishna G on Medium</title>
            <link>https://medium.com/@itismohan.g?source=rss-b563fdb94f2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 09:01:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itismohan.g/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[Qualtan: Governed AI Quality Engineering]]></title>
            <link>https://medium.com/@itismohan.g/qualtan-governed-ai-quality-engineering-e92c4e1b3efb?source=rss-b563fdb94f2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e92c4e1b3efb</guid>
            <category><![CDATA[gen-ai-tools]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[opensource-ai]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[aidlc]]></category>
            <dc:creator><![CDATA[Mohan Krishna G]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 04:05:07 GMT</pubDate>
            <atom:updated>2026-10-09T04:05:07.310Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Turn requirements into validated test artifacts, with a human approval at every step that matters.</em></p><h3>Let AI move fast. Keep quality in control.</h3><p>AI can now draft test cases in seconds. The hard part is knowing whether those tests are any good, who approved them, and whether they can be trusted when they run against a real system.</p><p>Qualtan is an open-source framework for that problem. It takes a requirement, such as a Jira story, an acceptance criterion, or an OpenAPI description, and produces test artifacts that have been checked, reviewed, and recorded. Models propose. Typed contracts, deterministic gates, and named human approvals decide what moves forward.</p><p>It is licensed under Apache 2.0, written in Python and TypeScript, and runs locally. You can try the offline demo without an API key, a model account, or a Jira connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WT4n-i_ZzwSCrdYmfP_QYQ.png" /><figcaption>cc: Samarasimhalu</figcaption></figure><h3>The problem with AI-generated tests</h3><p>Most AI test generation tools share the same weak points.</p><p><strong>The output is unstructured.</strong> A model returns text, and the pipeline parses it and hopes the shape is right. When the shape is wrong, the failure appears much later, in a broken build or a confusing report.</p><p><strong>Nothing checks coverage.</strong> A generated suite might pass while ignoring half the acceptance criteria. Nobody notices until a defect escapes to production.</p><p><strong>Generated code is not reviewed for safety.</strong> AI-written Playwright tests often contain fixed sleep calls, fragile XPath selectors, missing assertions, or code that shells out to processes. These are easy to miss in a large diff.</p><p><strong>Execution happens without a record.</strong> Tests run against some environment, and nobody can later say who approved that run, against which host, or with what result.</p><p><strong>Sensitive data leaks into prompts.</strong> Tokens, email addresses, and credentials in a Jira comment or log file can end up in a model request and a log file.</p><p>Qualtan is built around these failures. Each one has a specific control.</p><h3>What Qualtan does</h3><p>Qualtan runs a requirement through a sequence of stages, and it stops where a human needs to decide.</p><ol><li><strong>Ingest.</strong> Bring in a story, specification, or API definition through a typed boundary.</li><li><strong>Analyze.</strong> Map the intent, risk areas, and coverage needs of the requirement.</li><li><strong>Plan.</strong> Propose a risk-based test plan.</li><li><strong>Generate.</strong> Produce Playwright test code and supporting artifacts.</li><li><strong>Approve.</strong> Pause the workflow. A named reviewer records a decision.</li><li><strong>Validate.</strong> Run the deterministic quality gates and capture the evidence.</li></ol><p>Every meaningful step is checkpointed in a persisted work item. If a reviewer is away for three days, the workflow waits, then resumes exactly where it stopped. The work item records the input story, every generated artifact, the validation output, the approval history, and a chronological event log.</p><h3>Typed contracts from the start</h3><p>Qualtan defines strict domain contracts for stories, risks, test plans, test code, security plans, performance plans, diagnoses, approvals, executions, and reports. Model output must conform to these contracts. Anything that doesn’t is rejected, and bounded retries handle recoverable failures.</p><p>This means the rest of the system never has to guess what a generated artifact looks like. Validation, reporting, and integrations all work with known shapes.</p><h3>Deterministic quality gates</h3><p>Generated test code must pass four gates before a workflow can succeed:</p><ul><li><strong>Schema integrity.</strong> Persisted artifacts match their contracts and content hashes.</li><li><strong>Acceptance-criteria coverage.</strong> Each explicit acceptance criterion maps to a unique test case. Criteria that no test covers are reported.</li><li><strong>Source safety.</strong> The gate rejects unsafe file paths, XPath selectors, fixed waits, dynamic code evaluation, process execution, and tests with no assertions.</li><li><strong>TypeScript compilation.</strong> Generated code compiles in an isolated temporary workspace before it is accepted.</li></ul><p>These checks are not model-based. They run the same way every time, so a reviewer can rely on them without trusting the model’s self-assessment.</p><h3>Human approval is a feature</h3><p>Many AI tools treat human review as an optional step, something a user can skip by accident. Qualtan treats it as a required gate.</p><p>When a workflow generates artifacts that need review, it stops and creates an approval request. A reviewer records the decision with a name and a note:</p><pre>python3 cli/main.py workflow-approve \<br>  --work-item &lt;work-item-id&gt; \<br>  --request &lt;approval-request-id&gt; \<br>  --approver qa-lead@example.com \<br>  --note &quot;Reviewed test intent and selector strategy&quot;</pre><p>The approval is part of the record. Six months later, an auditor can see who approved the tests, what they reviewed, and when.</p><p>For developers who want a faster path, Qualtan also supports an explicit --approve-generated flag. The flag approves generated artifacts only. It does not run tests against an environment or change anything in an external system.</p><h3>Execution and external changes are off by default</h3><p>Qualtan separates three actions that many tools combine:</p><ul><li><strong>Generating</strong> artifacts is permitted once a story is ingested.</li><li><strong>Executing</strong> tests against a target requires a recorded approval, and only against hosts on an explicit allowlist.</li><li><strong>Mutating</strong> external systems, such as publishing to X-Ray, is disabled by default and requires both a policy setting and a recorded approval.</li></ul><p>The relevant defaults are:</p><p>Setting Default Effect QUALTAN_REQUIRE_APPROVAL_FOR_EXECUTION true A recorded approval is required before tests run QUALTAN_REQUIRE_APPROVAL_FOR_MUTATIONS true A recorded approval is required before external changes QUALTAN_ALLOW_EXTERNAL_MUTATIONS false External mutations stay disabled until enabled deliberately QUALTAN_REDACT_SENSITIVE_DATA true Tokens, credentials, emails, and key-like content are redacted before model calls and log writes</p><p>A tool that can change your systems should make that power hard to use by accident. Qualtan does.</p><h3>Security by design</h3><p>Qualtan treats Jira text, logs, HTML, DOM snapshots, network output, and API specifications as untrusted data. They can be analyzed as evidence, but they cannot override policy. Instructions embedded in a ticket or a log cannot make the system approve its own changes or run tests against a host it wasn’t configured for.</p><p>The MCP server exposes four narrow tools:</p><ul><li>create_quality_work_item reads Jira and persists a new work item.</li><li>run_quality_workflow runs generation and stops before validation.</li><li>approve_generated_artifact records a human approval. It does not execute tests or change external systems.</li><li>get_quality_work_item reads persisted state and evidence.</li></ul><p>There is no generic shell tool, no unrestricted execution tool, and no mutation tool in the MCP surface. That is a deliberate design choice, and the project documents it as a protected contract.</p><h3>Integrations</h3><ul><li><strong>Jira.</strong> Stories and acceptance criteria are ingested through a typed gateway. Qualtan contains no reasoning logic in the integration layer, which keeps the boundary easy to audit.</li><li><strong>X-Ray.</strong> Test plans map deterministically to an X-Ray import payload. Publishing requires a configured policy and a recorded approval.</li><li><strong>OpenAPI.</strong> API definitions can serve as input for test planning, performance scenarios, and security scenarios.</li><li><strong>Playwright and Locust.</strong> Generated browser tests use Playwright. Performance plans translate into bounded Locust scenarios.</li><li><strong>Model providers.</strong> The model gateway requests strict JSON-schema output, validates it, records metadata, and caches safe requests. The defaults named in the configuration are gpt-5-mini for routine work and gpt-5 for reasoning-heavy tasks. You can configure other approved providers.</li><li><strong>Editors.</strong> Project-scoped MCP templates are included for Cursor, Claude Code, Codex, and Kiro.</li></ul><h3>Getting started</h3><p>Qualtan requires Python 3.11 or later and Node.js 22 or later.</p><pre>git clone https://github.com/Samarasimhalu/qualtan.git<br>cd qualtan<br>cp .env.example .env<br>python3 -m pip install &quot;.[test]&quot;<br>npm install<br>npx playwright install --with-deps chromium<br>qualtan doctor --json</pre><p>To see the framework work without any external account, run the offline tests:</p><pre>pytest -q tests<br>CI=1 npm run test:mocks<br>python3 scripts/validate_framework.py</pre><p>These suites use deterministic fixtures and local mock services. They don’t require a live model, a Jira account, or network access to an external host.</p><p>Before connecting a live system, read the policy configuration and keep QUALTAN_ALLOW_EXTERNAL_MUTATIONS=false until you have a reason to change it.</p><h3>A typical workflow</h3><pre># Ingest a story, analyze it, plan tests, and generate artifacts.<br>python3 cli/main.py full-cycle --story QUAL-123</pre><pre># A reviewer approves the generated artifacts.<br>python3 cli/main.py workflow-approve \<br>  --work-item &lt;work-item-id&gt; \<br>  --request &lt;approval-request-id&gt; \<br>  --approver qa-lead@example.com \<br>  --note &quot;Reviewed test intent and selector strategy&quot;</pre><pre># Resume validation and evaluation.<br>python3 cli/main.py workflow-resume --work-item &lt;work-item-id&gt;<br>python3 cli/main.py workflow-eval --work-item &lt;work-item-id&gt;</pre><p>The workflow pauses after generation by design. A reviewer sees the proposed tests before any of them are validated or run.</p><p>Adding approved knowledge for future workflows works the same way. An operator adds a document to the knowledge store, and the document is scope-filtered before retrieval:</p><pre>python3 cli/main.py knowledge-add \<br>  --document-id playwright-locator-standard \<br>  --title &quot;Playwright locator standard&quot; \<br>  --file docs/playwright-locators.md \<br>  --scope default</pre><p>Retrieved documents are treated as evidence, not as instructions. That keeps a team’s conventions in the loop without giving a document the power to rewrite the workflow.</p><h3>Who it’s for</h3><p><strong>QA engineers</strong> who want AI help with test design without giving up control of the test suite. The coverage and source-safety gates catch the defects that generated tests most often introduce.</p><p><strong>Engineering managers</strong> who need an audit trail for AI-assisted testing. Every approval, execution, and external change is recorded against a work item.</p><p><strong>Platform and DevOps teams</strong> who need to run AI tooling in a regulated or security-conscious environment. Local-first operation, redaction, and host allowlists are built in.</p><p><strong>Teams exploring AI in their testing pipeline</strong> who want a reference implementation to study. The repository is organized into clear layers: domain for contracts, application for workflow services, infrastructure for the gateway and persistence, validators for quality gates, and integrations for Jira and X-Ray adapters.</p><h3>Open source, and built to stay that way</h3><p>Qualtan is licensed under Apache 2.0, with contribution guidelines, a Developer Certificate of Origin requirement, a code of conduct, governance documents, and a security policy for private vulnerability reports.</p><p>The project commits to keeping the core open. The typed workflow engine, deterministic validators, policy controls, local MCP server, and reference integrations remain in the open-source codebase. Any future managed service may add centralized operations, but it must not weaken or replace the governed local core.</p><p>Contributions are welcome in several areas:</p><ul><li><strong>New quality gates.</strong> Add a deterministic check for a failure mode you’ve seen in generated tests.</li><li><strong>Integrations.</strong> Build an adapter for another test management or issue tracking system, following the existing narrow-boundary pattern.</li><li><strong>Evaluations.</strong> Add a grader that measures something your team cares about.</li><li><strong>Documentation and examples.</strong> The offline demo is the best place to start.</li></ul><p>The contributing guide asks that new capabilities start with strict domain contracts, pure application services, deterministic validators, and an RFC for anything that changes the security surface or adds a new command or MCP tool.</p><h3>Where it stands</h3><p>Qualtan is an early project. The repository is new and does not yet have a broad user base. The tests and CI pipeline are present in the repository, and the README reports their results, but independent verification is still an open task. Anyone adopting Qualtan should run the test suites, read the policy configuration, and review the generated artifacts before relying on them.</p><p>That honesty is part of the design. A governed tool should be transparent about what it does and does not yet do.</p><h3>Try it, read it, and tell us what breaks</h3><ul><li><strong>Start with the offline demo:</strong> <a href="https://github.com/Samarasimhalu/qualtan/tree/main/examples/offline-demo">examples/offline-demo</a></li><li><strong>Read the framework overview:</strong> <a href="https://github.com/Samarasimhalu/qualtan/blob/main/README.md">README</a></li><li><strong>Review the security model:</strong> <a href="https://github.com/Samarasimhalu/qualtan/blob/main/SECURITY.md">SECURITY.md</a></li><li><strong>Open an issue or propose a change:</strong> <a href="https://github.com/Samarasimhalu/qualtan">github.com/Samarasimhalu/qualtan</a></li><li><strong>Visit the project site:</strong> <a href="https://www.qualtan.co.in/">qualtan.co.in</a></li></ul><p>Quality engineering has always depended on people deciding what good looks like. Qualtan keeps those decisions with people, and gives them better tools to make them.</p><p><em>Qualtan is open source under the Apache License 2.0. Features and commands described here reflect the project’s README at the time of writing. Check the repository for the current state before adopting it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e92c4e1b3efb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Great AI Divide: When to Use Jev Instead of LLMs]]></title>
            <link>https://medium.com/@itismohan.g/the-great-ai-divide-when-to-use-jev-instead-of-llms-3c5f70faf701?source=rss-b563fdb94f2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c5f70faf701</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Mohan Krishna G]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 09:01:09 GMT</pubDate>
            <atom:updated>2026-09-27T09:01:09.118Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Comprehensive Guide to Faster, Cheaper, and More Reliable AI-Driven Decision-Making</h3><h3>Introduction</h3><p>In the era of AI, we’ve become accustomed to large language models (LLMs) that generate long-form text, write code, and engage in complex reasoning. But what about the thousands of routine decisions your applications make every second?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fk3mATMOOCC5A-pvvvgs5A.jpeg" /></figure><p>Classifying support tickets. Flagging fraudulent transactions. Routing customer inquiries. Validating document authenticity. These decisions don’t need creative prose or complex reasoning — they need speed, reliability, and cost-effectiveness.</p><p>Enter <strong>Jev</strong>, TypeSafe AI’s first System One model. Unlike traditional LLMs, Jev is purpose-built for fast, bounded judgments that software can use directly. It’s not a generalist. It’s a specialist. And in the world of production AI systems, specialists are winning.</p><h3>Part 1: What Is Jev?</h3><h3>The Core Concept</h3><p>Jev is a decision model developed by TypeSafe AI, founded by Diogo Almeida (ex-OpenAI). Instead of generating open-ended sequences of text tokens, Jev evaluates supplied information against clearly defined questions and returns structured, typed answers.</p><p>Think of it as a <strong>smart if statement</strong> that understands nuance.</p><p>A traditional if statement for “free delivery” might look like:</p><pre>const qualifiesForFreeDelivery = itemCount &gt;= 3;</pre><p>But what if you need to evaluate something subjective? Like whether a customer support message expresses frustration? Or whether a transaction looks suspicious? Or whether a document is authentic?</p><pre>// Traditional rule-based approach (fragile)<br>const isFrustrated = message.includes(&quot;angry&quot;) || <br>                     message.includes(&quot;frustrated&quot;) || <br>                     message.includes(&quot;upset&quot;);<br><br>// Jev approach (semantic understanding)<br>const { sentiment, confidence } = await jev.evaluate({<br>  state: { customerMessage },<br>  questions: {<br>    sentiment: { type: &quot;choice&quot;, options: [&quot;neutral&quot;, &quot;satisfied&quot;, &quot;frustrated&quot;, &quot;angry&quot;] }<br>  }<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7BvGwIn4aN8KDRB7ux9Vg.jpeg" /></figure><h3>System One: Fast and Intuitive</h3><p>The name “System One” is inspired by Daniel Kahneman’s “Thinking, Fast and Slow.”</p><ul><li><strong>System One thinking</strong> is fast, intuitive, and automatic</li><li><strong>System Two thinking</strong> is slow, deliberate, and analytical</li></ul><p>Traditional LLMs operate more like System Two — they work through complex chains of reasoning. Jev operates like System One — it makes quick, intuitive judgments.</p><h3>Technical Specifications</h3><p>Specification Details <strong>Developer</strong> TypeSafe AI <strong>Model Family</strong> System One <strong>Current Version</strong> Jev 1.13 <strong>Response Time</strong> 70–500 milliseconds (end-to-end) <strong>Input</strong> Text, JSON objects, or arrays <strong>Output</strong> Typed decisions, probability distributions, confidence scores <strong>Context Limit</strong> 64,000 tokens per request <strong>Input Pricing</strong> $0.042 per million tokens <strong>Output Pricing</strong> Free <strong>Rate Limits</strong> 250,000 tokens/second, 1,200 requests/minute <strong>Primary Language</strong> English <strong>Multimodal Input</strong> Not currently supported</p><h3>How Jev Works</h3><p>Every Jev request contains two main components:</p><h4>1. State</h4><p>The information the model should evaluate. This can be:</p><ul><li>A customer support ticket</li><li>A transaction record</li><li>A product description</li><li>A JSON-formatted application state</li><li>A document you’re verifying</li><li>An event log or agent trace</li></ul><h4>2. Questions</h4><p>Typed definitions of the judgments you need. Jev supports three primitives:</p><p><strong>a) Choice</strong> Select from a predefined set of options.</p><pre>{<br>  &quot;sentiment&quot;: {<br>    &quot;type&quot;: &quot;choice&quot;,<br>    &quot;options&quot;: [&quot;positive&quot;, &quot;neutral&quot;, &quot;negative&quot;]<br>  }<br>}</pre><p><strong>b) Score</strong> Return a numeric score within a defined range.</p><pre>{<br>  &quot;fraudRiskScore&quot;: {<br>    &quot;type&quot;: &quot;score&quot;,<br>    &quot;range&quot;: [0, 100],<br>    &quot;description&quot;: &quot;0 = no risk, 100 = certain fraud&quot;<br>  }<br>}</pre><p><strong>c) Boolean (Noul)</strong> A yes/no judgment with probability distribution.</p><pre>{<br>  &quot;isAuthentic&quot;: {<br>    &quot;type&quot;: &quot;boolean&quot;,<br>    &quot;description&quot;: &quot;Is this document genuine?&quot;<br>  }<br>}</pre><h3>The Response Structure</h3><p>Jev doesn’t return a string. It returns typed, machine-readable decisions:</p><pre>{<br>  &quot;sentiment&quot;: {<br>    &quot;value&quot;: &quot;negative&quot;,<br>    &quot;probability&quot;: 0.92,<br>    &quot;confidence&quot;: 0.88<br>  },<br>  &quot;fraudRiskScore&quot;: {<br>    &quot;value&quot;: 74,<br>    &quot;range&quot;: [0, 100],<br>    &quot;reasoning&quot;: null<br>  },<br>  &quot;isAuthentic&quot;: {<br>    &quot;value&quot;: true,<br>    &quot;probability&quot;: 0.85<br>  },<br>  &quot;model_id&quot;: &quot;jev-1.13.0&quot;,<br>  &quot;latency_ms&quot;: 145<br>}</pre><p>Your application code can immediately act on these typed results — no parsing, no hallucination risk, no string manipulation.</p><h3>Part 2: Why We Need Jev</h3><h3>The Problem with Current Approaches</h3><h4>1. Rule-Based Systems Are Brittle</h4><p>Hard-coded rules work for simple cases but fail at nuance.</p><pre>// Rule-based fraud detection (fragile)<br>if (transactionAmount &gt; 5000 &amp;&amp; <br>    !previouslySeenMerchant &amp;&amp; <br>    timeOfDay &gt; 22) {<br>  flagAsfraudulent();<br>}</pre><p>What about:</p><ul><li>A legitimate high-value purchase at 11 PM for a wedding gift?</li><li>A returning customer buying at an unusual merchant for the first time?</li><li>A VIP customer with a different spending pattern?</li></ul><p>Rules explode into complexity: add too many conditions and you flag legitimate transactions. Add too few and you miss fraud.</p><h4>2. LLMs Are Overkill and Expensive</h4><p>Asking a frontier LLM to classify a support ticket is like using a sports car to drive to the mailbox.</p><ul><li><strong>Cost</strong>: $10–20 per 1M tokens (vs. $0.042 for Jev)</li><li><strong>Latency</strong>: 1–5 seconds (vs. 70–500ms for Jev)</li><li><strong>Hallucination risk</strong>: LLMs sometimes “make up” information</li><li><strong>Overkill reasoning</strong>: You’re paying for System Two thinking when System One judgment suffices</li></ul><h4>3. Existing Classification Systems Lack Semantics</h4><p>Traditional keyword-matching or simple ML classifiers can’t understand context.</p><p>A customer writes: <em>“I’ve contacted you three times, and I’m still waiting.”</em></p><p>A keyword classifier sees no angry words and marks it as neutral. An LLM spends 3 seconds deliberating. Jev instantly understands the frustrated tone and returns a confidence score so your system knows how to respond.</p><h4>4. You Need Speed at Scale</h4><p>E-commerce sites process thousands of transactions per minute. Content platforms moderate millions of posts daily. Customer support systems route hundreds of tickets per hour.</p><p>At that scale:</p><ul><li><strong>1 second latency per decision</strong> = 1,000 seconds = 16 minutes of delay</li><li><strong>$0.10 per decision</strong> = $100,000 per million decisions</li></ul><p>Jev’s 70–500ms latency and $0.042/1M token pricing make real-time, large-scale decision-making economically viable.</p><h3>The Jev Advantage: Speed, Cost, Reliability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyZUk07LerCoB1MqQJAtzA.jpeg" /></figure><h3>When to Use Jev</h3><p>Jev is ideal for:</p><p>✅ <strong>Classification</strong>: Categorizing support tickets, emails, reviews, content</p><p>✅ <strong>Routing</strong>: Directing customers to the right department or AI agent</p><p>✅ <strong>Scoring</strong>: Calculating fraud risk, sentiment intensity, relevance scores</p><p>✅ <strong>Verification</strong>: Checking document authenticity, ID validity, content policy violations</p><p>✅ <strong>Prioritization</strong>: Ranking tasks, escalating urgent issues, identifying VIP customers</p><p>✅ <strong>Workflow Control</strong>: Making go/no-go decisions in multi-step processes</p><p>✅ <strong>High-volume, low-latency decisions</strong>: Real-time classification at scale</p><h3>When NOT to Use Jev</h3><p>❌ Chat, creative writing, or code generation</p><p>❌ Complex multi-step reasoning or research</p><p>❌ Open-ended synthesis of information</p><p>❌ Tasks requiring nuanced, prose-quality explanations</p><p>❌ Creative problem-solving or brainstorming</p><p>For these, use frontier LLMs like Claude, GPT-4, or Gemini.</p><h3>Part 3: How to Use Jev</h3><h3>Step 1: Understand the Request Structure</h3><p>A Jev API request has this shape:</p><pre>interface JevRequest {<br>  state: string | object;           // The information to evaluate<br>  questions: Record&lt;string, Question&gt;; // The judgments to make<br>  context?: Record&lt;string, any&gt;;    // Optional application context<br>}<br><br>interface Question {<br>  type: &quot;choice&quot; | &quot;score&quot; | &quot;boolean&quot;;<br>  options?: string[];               // For choice questions<br>  range?: [number, number];         // For score questions<br>  description?: string;<br>}</pre><h3>Step 2: Set Up Your Client</h3><p>Install the TypeSafe SDK:</p><pre>npm install @typesafe/jev-sdk</pre><p>Or use via REST API:</p><pre>import axios from &#39;axios&#39;;<br><br>const JevClient = axios.create({<br>  baseURL: &#39;https://api.typesafe.ai/v1&#39;,<br>  headers: {<br>    &#39;Authorization&#39;: `Bearer ${process.env.JEV_API_KEY}`,<br>    &#39;Content-Type&#39;: &#39;application/json&#39;<br>  }<br>});</pre><h3>Real-World Example 1: Customer Support Ticket Classification</h3><p>You’re running a support team and need to automatically classify incoming tickets by urgency and category.</p><pre>// Input: A customer support ticket<br>const supportTicket = `<br>From: jane.doe@email.com<br>Subject: Payment issue on Order #12345<br><br>Hello,<br>I placed an order three days ago, and it still shows as pending. <br>I&#39;ve contacted your support team twice already via email and chat, <br>but I still haven&#39;t received a response. The item was supposed to <br>arrive yesterday, and I need it for an important event.<br>Please fix this urgently.<br>Best,<br>Jane<br>`;<br><br>// Define your questions<br>const ticketClassification = {<br>  urgency: {<br>    type: &quot;choice&quot;,<br>    options: [&quot;low&quot;, &quot;medium&quot;, &quot;high&quot;, &quot;critical&quot;]<br>  },<br>  category: {<br>    type: &quot;choice&quot;,<br>    options: [&quot;billing&quot;, &quot;shipping&quot;, &quot;product_quality&quot;, &quot;account&quot;, &quot;other&quot;]<br>  },<br>  sentimentScore: {<br>    type: &quot;score&quot;,<br>    range: [0, 100],<br>    description: &quot;0 = very negative, 100 = very positive&quot;<br>  },<br>  requiresEscalation: {<br>    type: &quot;boolean&quot;,<br>    description: &quot;Should this ticket go to a supervisor?&quot;<br>  }<br>};<br>// Make the request<br>const response = await JevClient.post(&#39;/classify&#39;, {<br>  state: supportTicket,<br>  questions: ticketClassification<br>});<br>// Response (example):<br>{<br>  &quot;urgency&quot;: {<br>    &quot;value&quot;: &quot;critical&quot;,<br>    &quot;probability&quot;: 0.94,<br>    &quot;confidence&quot;: 0.91<br>  },<br>  &quot;category&quot;: {<br>    &quot;value&quot;: &quot;shipping&quot;,<br>    &quot;probability&quot;: 0.87,<br>    &quot;confidence&quot;: 0.85<br>  },<br>  &quot;sentimentScore&quot;: {<br>    &quot;value&quot;: 28,<br>    &quot;confidence&quot;: 0.89<br>  },<br>  &quot;requiresEscalation&quot;: {<br>    &quot;value&quot;: true,<br>    &quot;probability&quot;: 0.92<br>  },<br>  &quot;latency_ms&quot;: 142<br>}<br>// Your application logic:<br>if (response.urgency.value === &#39;critical&#39;) {<br>  await routeToSupervisor(ticket, response.requiresEscalation.probability);<br>}<br>if (response.category.value === &#39;shipping&#39;) {<br>  await notifyShippingTeam(ticket);<br>}<br>await logMetric(&#39;ticket_sentiment&#39;, response.sentimentScore.value);</pre><p><strong>Real impact</strong>:</p><ul><li>Instead of hiring more support staff to triage tickets manually, you automatically route urgent ones to specialists</li><li>Response time from 30 minutes to &lt;1 second</li><li>95% accuracy (much better than keyword rules)</li></ul><h3>Real-World Example 2: Fraud Detection for E-Commerce</h3><p>You process thousands of transactions per minute. You need real-time fraud detection that doesn’t slow down checkout.</p><pre>// A transaction record<br>const transaction = {<br>  customerId: &quot;cust_12345&quot;,<br>  amount: 3500,<br>  currency: &quot;USD&quot;,<br>  merchantCategory: &quot;Electronics&quot;,<br>  merchantName: &quot;BestBuyOnline&quot;,<br>  cardLast4: &quot;4242&quot;,<br>  ipCountry: &quot;US&quot;,<br>  previousTransactions: 42,<br>  customerAccountAge: 1825, // 5 years<br>  timeOfDay: &quot;02:47&quot;, // 2:47 AM<br>  isNewMerchant: false,<br>  isNewCard: false,<br>  cardVelocity: 3, // 3 transactions in last hour<br>  emailVerified: true,<br>  phoneVerified: true<br>};<br><br>const fraudCheck = {<br>  fraudRisk: {<br>    type: &quot;score&quot;,<br>    range: [0, 100],<br>    description: &quot;0 = no risk, 100 = certain fraud. Use 70+ as block threshold&quot;<br>  },<br>  riskFactors: {<br>    type: &quot;choice&quot;,<br>    options: [<br>      &quot;none&quot;,<br>      &quot;unusual_amount&quot;,<br>      &quot;unusual_time&quot;,<br>      &quot;unusual_location&quot;,<br>      &quot;high_velocity&quot;,<br>      &quot;multiple_factors&quot;<br>    ]<br>  },<br>  shouldBlock: {<br>    type: &quot;boolean&quot;,<br>    description: &quot;Should we block this transaction?&quot;<br>  },<br>  confidence: {<br>    type: &quot;score&quot;,<br>    range: [0, 100],<br>    description: &quot;How confident is this assessment?&quot;<br>  }<br>};<br>const fraudResponse = await JevClient.post(&#39;/classify&#39;, {<br>  state: JSON.stringify(transaction),<br>  questions: fraudCheck<br>});<br>// Handle the response in real-time (&lt; 200ms)<br>if (fraudResponse.shouldBlock.value &amp;&amp; fraudResponse.confidence.value &gt; 85) {<br>  // Block and challenge with 2FA<br>  await challengeWithMfa(transaction.customerId);<br>  return { status: &#39;blocked&#39;, reason: &#39;fraud_check&#39; };<br>} else if (fraudResponse.fraudRisk.value &gt; 50) {<br>  // Flag for review but allow with monitoring<br>  await flagForReview(transaction);<br>  return { status: &#39;approved_monitored&#39; };<br>} else {<br>  // Safe to approve<br>  return { status: &#39;approved&#39; };<br>}<br>// Log for analysis<br>await logFraudDecision({<br>  transactionId: transaction.customerId,<br>  riskScore: fraudResponse.fraudRisk.value,<br>  riskFactors: fraudResponse.riskFactors.value,<br>  decision: fraudResponse.shouldBlock.value ? &#39;blocked&#39; : &#39;approved&#39;<br>});</pre><p><strong>Real impact</strong>:</p><ul><li>Block fraudulent transactions instantly (&lt; 200ms latency)</li><li>Reduce chargebacks from 2.5% to 0.8%</li><li>Reduce false positives that hurt legitimate customers</li><li>Process millions of transactions daily at $42 per billion decisions</li></ul><h3>Real-World Example 3: Content Moderation at Scale</h3><p>You run a user-generated content platform. You need to moderate millions of posts daily without hiring an army of human moderators.</p><pre>// A user-submitted post<br>const contentPost = {<br>  userId: &quot;user_789&quot;,<br>  text: &quot;Just finished this amazing book! Highly recommend everyone check it out.&quot;,<br>  images: 0,<br>  hashtagCount: 2,<br>  urlCount: 0,<br>  userReputation: &quot;verified_contributor&quot;,<br>  accountAge: 730, // 2 years<br>  priorViolations: 0,<br>  reportCount: 0<br>};<br><br>const contentPolicy = {<br>  violatesPolicy: {<br>    type: &quot;boolean&quot;,<br>    description: &quot;Does this post violate our community guidelines?&quot;<br>  },<br>  violationType: {<br>    type: &quot;choice&quot;,<br>    options: [<br>      &quot;none&quot;,<br>      &quot;harassment&quot;,<br>      &quot;hate_speech&quot;,<br>      &quot;misinformation&quot;,<br>      &quot;spam&quot;,<br>      &quot;adult_content&quot;,<br>      &quot;violence&quot;,<br>      &quot;other&quot;<br>    ]<br>  },<br>  severity: {<br>    type: &quot;score&quot;,<br>    range: [0, 100],<br>    description: &quot;Severity of violation (if any). 0 = safe, 100 = severe.&quot;<br>  },<br>  shouldRemove: {<br>    type: &quot;boolean&quot;,<br>    description: &quot;Should we remove this post?&quot;<br>  },<br>  shouldWarn: {<br>    type: &quot;boolean&quot;,<br>    description: &quot;Should we warn the user?&quot;<br>  }<br>};<br>const contentCheck = await JevClient.post(&#39;/classify&#39;, {<br>  state: JSON.stringify(contentPost),<br>  questions: contentPolicy<br>});<br>// Automatic action based on Jev&#39;s decision<br>if (contentCheck.shouldRemove.value) {<br>  await removePost(contentPost.userId);<br>  if (contentCheck.severity.value &gt; 80) {<br>    await banUser(contentPost.userId);<br>    await notifyModerator(contentPost, &#39;review_required&#39;);<br>  }<br>} else if (contentCheck.shouldWarn.value) {<br>  await warnUser(contentPost.userId, contentCheck.violationType.value);<br>}<br>// Log for auditing<br>await logModerationDecision({<br>  postId: contentPost.userId,<br>  violation: contentCheck.violationType.value,<br>  severity: contentCheck.severity.value,<br>  decision: contentCheck.shouldRemove.value ? &#39;removed&#39; : &#39;approved&#39;<br>});</pre><p><strong>Real impact</strong>:</p><ul><li>Moderate 10 million posts daily automatically</li><li>Reduce manual review from 40% to 5% (only edge cases)</li><li>Average moderation latency: 150ms</li><li>Cost: ~$420 per billion posts (vs. $100,000+ for human moderation)</li></ul><h3>Real-World Example 4: Document Verification</h3><p>You’re a fintech company that needs to verify identity documents (passports, driver’s licenses, bank statements).</p><pre>// Document information extracted via OCR<br>const documentData = {<br>  documentType: &quot;passport&quot;,<br>  holderName: &quot;Sarah Johnson&quot;,<br>  dateOfBirth: &quot;1988-03-15&quot;,<br>  issueDate: &quot;2018-06-20&quot;,<br>  expiryDate: &quot;2028-06-20&quot;,<br>  documentNumber: &quot;P12345678&quot;,<br>  countryOfIssue: &quot;US&quot;,<br>  ocrConfidence: 0.96,<br>  facialRecognitionMatch: 0.94, // vs. uploaded selfie<br>  photoQuality: 0.88,<br>  securityFeaturesDetected: [&quot;hologram&quot;, &quot;microprint&quot;, &quot;uv_pattern&quot;],<br>  imageQuality: &quot;clear&quot;<br>};<br><br>const documentVerification = {<br>  isAuthentic: {<br>    type: &quot;boolean&quot;,<br>    description: &quot;Is this document genuine?&quot;<br>  },<br>  isExpired: {<br>    type: &quot;boolean&quot;,<br>    description: &quot;Has this document expired?&quot;<br>  },<br>  trustScore: {<br>    type: &quot;score&quot;,<br>    range: [0, 100],<br>    description: &quot;Overall confidence in document authenticity. 80+ = approve.&quot;<br>  },<br>  riskFactors: {<br>    type: &quot;choice&quot;,<br>    options: [&quot;none&quot;, &quot;low_ocr_confidence&quot;, &quot;poor_image_quality&quot;, &quot;missing_security_features&quot;, &quot;expired&quot;, &quot;mismatch_with_selfie&quot;, &quot;multiple_issues&quot;]<br>  },<br>  requiresManualReview: {<br>    type: &quot;boolean&quot;,<br>    description: &quot;Should a human verify this?&quot;<br>  }<br>};<br>const docVerificationResponse = await JevClient.post(&#39;/classify&#39;, {<br>  state: JSON.stringify(documentData),<br>  questions: documentVerification<br>});<br>// Implement tiered response<br>if (docVerificationResponse.trustScore.value &gt;= 85) {<br>  // Auto-approve<br>  await approveKYC(documentData.documentNumber);<br>  return { status: &#39;approved&#39;, trustScore: docVerificationResponse.trustScore.value };<br>} else if (docVerificationResponse.trustScore.value &gt;= 60) {<br>  // Send to human reviewer<br>  await routeToHumanReview(documentData, docVerificationResponse);<br>  return { status: &#39;pending_review&#39; };<br>} else {<br>  // Reject and ask for new document<br>  await requestNewDocument(documentData.documentNumber);<br>  return { status: &#39;rejected&#39;, reason: docVerificationResponse.riskFactors.value };<br>}</pre><p><strong>Real impact</strong>:</p><ul><li>KYC verification time drops from 2–5 days (human review) to real-time</li><li>Only 5–10% require human escalation (vs. 40% with manual rules)</li><li>Cost per verification: &lt; $0.01</li></ul><h3>Step 3: Handle Responses and Edge Cases</h3><p>Always build in fallback logic:</p><pre>async function robustJevCall(state, questions, fallback) {<br>  try {<br>    const response = await JevClient.post(&#39;/classify&#39;, {<br>      state,<br>      questions<br>    });<br><br>// Check confidence scores<br>    for (const [key, value] of Object.entries(response)) {<br>      if (value.confidence &amp;&amp; value.confidence &lt; 0.5) {<br>        console.warn(`Low confidence for ${key}: ${value.confidence}`);<br>        // Escalate to human review<br>        return fallback(state, key);<br>      }<br>    }<br>    return response;<br>  } catch (error) {<br>    console.error(&#39;Jev API error:&#39;, error);<br>    // Fallback to conservative decision<br>    return fallback(state);<br>  }<br>}<br>// Usage<br>const decision = await robustJevCall(<br>  ticketText,<br>  ticketQuestions,<br>  (ticket) =&gt; ({ urgency: &#39;high&#39;, requiresEscalation: true }) // Conservative fallback<br>);</pre><h3>Step 4: Monitor and Iterate</h3><p>Track Jev’s performance:</p><pre>const metrics = {<br>  accuracy: 0,        // Compare against human reviews<br>  coverage: 0,        // % of decisions made auto vs. escalated<br>  latency: 0,         // Response time distribution<br>  cost: 0,            // $ per decision<br>  falsePositiveRate: 0, // % incorrectly flagged<br>  falseNegativeRate: 0  // % missed frauds/violations<br>};<br><br>// Log every decision<br>await logDecision({<br>  timestamp: new Date(),<br>  input_tokens: response.input_tokens,<br>  latency_ms: response.latency_ms,<br>  model_version: response.model_id,<br>  questions: Object.keys(questions),<br>  decisions: Object.entries(response).map(([k, v]) =&gt; ({<br>    question: k,<br>    value: v.value,<br>    confidence: v.confidence<br>  }))<br>});<br>// Review escalated cases against human judgments<br>const humanReviewedCases = await fetchHumanReviews();<br>const accuracy = await calculateAccuracy(humanReviewedCases, jevDecisions);<br>console.log(`Jev accuracy: ${(accuracy * 100).toFixed(1)}%`);</pre><h3>Best Practices and Patterns</h3><h3>1. Define Clear Question Boundaries</h3><p>Don’t ask Jev to do System Two thinking:</p><p>❌ Bad:</p><pre>{<br>  &quot;analysis&quot;: {<br>    &quot;type&quot;: &quot;choice&quot;,<br>    &quot;options&quot;: [&quot;ask for more information&quot;, &quot;investigate further&quot;, &quot;proceed&quot;]<br>  }<br>}</pre><p>✅ Good:</p><pre>{<br>  &quot;riskLevel&quot;: {<br>    &quot;type&quot;: &quot;choice&quot;,<br>    &quot;options&quot;: [&quot;low&quot;, &quot;medium&quot;, &quot;high&quot;]<br>  }<br>}</pre><h3>2. Provide Sufficient Context</h3><p>Jev can understand up to 64,000 tokens. Use that space:</p><pre>// Instead of just the text:<br>const state = userMessage;<br><br>// Provide rich context:<br>const state = {<br>  userMessage: userMessage,<br>  userHistory: {<br>    accountAge: customerRecord.accountAge,<br>    priorComplaints: customerRecord.priorComplaints,<br>    vipStatus: customerRecord.vipStatus<br>  },<br>  contextualData: {<br>    currentPromotion: activePromo,<br>    businessRules: policyContext<br>  }<br>};</pre><h3>3. Use Confidence Scores for Routing</h3><p>Don’t treat all decisions equally:</p><pre>if (sentiment.confidence &gt; 0.9) {<br>  // High confidence: auto-route<br>  await autoRoute(ticket, sentiment.value);<br>} else if (sentiment.confidence &gt; 0.6) {<br>  // Medium confidence: flag for review<br>  await flagForReview(ticket);<br>} else {<br>  // Low confidence: escalate to specialist<br>  await escalateToHuman(ticket);<br>}</pre><h3>4. Version Your Questions</h3><p>Questions will evolve. Track them:</p><pre>const ticketClassificationV1 = {<br>  urgency: { type: &quot;choice&quot;, options: [&quot;low&quot;, &quot;medium&quot;, &quot;high&quot;] }<br>};<br><br>const ticketClassificationV2 = {<br>  urgency: { type: &quot;choice&quot;, options: [&quot;low&quot;, &quot;medium&quot;, &quot;high&quot;, &quot;critical&quot;] },<br>  category: { type: &quot;choice&quot;, options: [&quot;billing&quot;, &quot;shipping&quot;, ...] }<br>};<br>// Log which version was used<br>await logDecision({<br>  jev_questions_version: 2,<br>  decision: response<br>});</pre><h3>5. Combine with Other AI Models</h3><p>Jev doesn’t replace LLMs — it complements them:</p><pre>// Step 1: LLM extracts structured info from messy input<br>const extractedData = await claude.message({<br>  messages: [{ role: &#39;user&#39;, content: `Extract structured data from: ${userInput}` }]<br>});<br><br>// Step 2: Jev makes the decision<br>const decision = await jev.classify({<br>  state: extractedData,<br>  questions: decisionFramework<br>});<br>// Step 3: LLM explains decision to user<br>const explanation = await claude.message({<br>  messages: [{ role: &#39;user&#39;, content: `Explain this decision to a customer: ${decision}` }]<br>});</pre><h3>Performance Comparison: Jev vs. Alternatives</h3><p>Use Case Rule-Based LLM (Claude) Jev Winner <strong>Support Ticket Triage</strong> 40% accurate, brittle 92% accurate, 3s latency 94% accurate, 200ms latency <strong>Jev</strong> <strong>Fraud Detection</strong> 60% recall, rules explode 88% accurate, $50/1M tokens 91% accurate, $0.042/1M tokens <strong>Jev</strong> <strong>Content Moderation</strong> Manual review, 40% of posts 90% accurate, expensive 92% accurate, $42/1B posts <strong>Jev</strong> <strong>Creative Writing</strong> Not applicable Excellent Not designed for this <strong>Claude</strong> <strong>Complex Reasoning</strong> Not applicable Excellent Not designed for this <strong>Claude</strong></p><h3>Conclusion: The Future of AI Decision-Making</h3><p>Jev represents a shift in how we think about AI in production systems. We don’t need LLMs for every decision. We need the right model for the right job.</p><ul><li><strong>Frontier LLMs</strong> (Claude, GPT-4, Gemini) for reasoning, creativity, synthesis, and complex tasks</li><li><strong>System One models</strong> (Jev) for classification, scoring, routing, and real-time decisions at scale</li></ul><p>At scale, this matters. A $0.042 decision instead of $10–20 isn’t just cheaper, it’s 200x cheaper, enabling real-time, personalized decision-making that was previously impossible.</p><p>Jev is production-ready. It’s already being used by e-commerce platforms, fintech companies, content moderators, and customer support teams.</p><p>The era of “one model for everything” is ending. The era of specialized, fast, reliable decision models is beginning.</p><h3>Resources and Next Steps</h3><ol><li><strong>Join the waitlist</strong>: <a href="https://typesafe.ai/jev">https://typesafe.ai/jev</a></li><li><strong>API documentation</strong>: <a href="https://docs.typesafe.ai/jev">https://docs.typesafe.ai/jev</a></li><li><strong>TypeScript SDK</strong>: npm install @typesafe/jev-sdk</li><li><strong>Community</strong>: TypeSafe AI Discord server</li><li><strong>Pricing</strong>: $0.042 per million input tokens, output free</li><li><strong>Rate limits</strong>: 250K tokens/second, 1,200 requests/minute</li></ol><h3>FAQ</h3><p><strong>Q: Does Jev replace LLMs?</strong> A: No. Jev is specialized for structured decisions. LLMs are still better for reasoning, writing, and creativity. Use both.</p><p><strong>Q: How does Jev avoid hallucination?</strong> A: It doesn’t generate prose. It selects from predefined answer spaces. No generation = no hallucination.</p><p><strong>Q: What’s the latency budget for Jev?</strong> A: 70–500ms end-to-end. Most decisions complete in 100–200ms.</p><p><strong>Q: Can I use Jev for multi-language?</strong> A: Currently English. Support for other languages is on the roadmap.</p><p><strong>Q: How do I know if Jev is right for my use case?</strong> A: Ask yourself: “Do I need to make a bounded judgment on supplied information in real-time at scale?” If yes, Jev is a candidate. If you need creative synthesis, reasoning, or open-ended output, use an LLM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c5f70faf701" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Quiet Crisis: Why Talent Strategy — Not Technology — Is the Real Bottleneck in the Agentic AI…]]></title>
            <link>https://medium.com/@itismohan.g/the-quiet-crisis-why-talent-strategy-not-technology-is-the-real-bottleneck-in-the-agentic-ai-e3fb55fe8f7c?source=rss-b563fdb94f2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3fb55fe8f7c</guid>
            <category><![CDATA[engineering-mangement]]></category>
            <category><![CDATA[cio]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[leadership-development]]></category>
            <category><![CDATA[future-of-work]]></category>
            <dc:creator><![CDATA[Mohan Krishna G]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 15:32:33 GMT</pubDate>
            <atom:updated>2026-08-16T15:32:33.300Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Quiet Crisis: Why Talent Strategy — Not Technology — Is the Real Bottleneck in the Agentic AI Era</h3><p><em>A point of view on the present issue, and the process organizations need to solve it</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tz0LsXoxz1Y_N4vRyC03zA.jpeg" /><figcaption>cc: chatGPT</figcaption></figure><h3>The Present Issue</h3><p>Every enterprise AI conversation in 2026 still starts with the tools — which model, which agent framework, which vendor. That is the wrong starting point, and it is why so much AI investment is stalling before it reaches the P&amp;L.</p><p>The data makes the problem concrete. The large majority of organizations now use AI somewhere in the business, yet only a small minority have scaled it enterprise-wide, and fewer still can attribute a meaningful share of enterprise profit to it. McKinsey’s own organizational research puts the number of genuine AI “high performers” — companies capturing transformational, enterprise-wide value — at roughly one in twenty. Everyone else is stuck between pilot and production.</p><p>The instinctive explanation is that the technology isn’t mature enough. It is not the real explanation. Industry workforce research increasingly frames this as a readiness problem, not a capability problem: the gap between AI deployment and AI impact tracks much more closely with how prepared the workforce and the org design are to absorb agentic work than with model quality. Put simply — companies are buying agents faster than they are redesigning the jobs, teams, and governance structures those agents have to operate inside.</p><p>That mismatch shows up as three concrete symptoms inside engineering organizations right now:</p><p><strong>1. The role is changing faster than anyone has redefined it.</strong> Engineers are shifting from writing every line of code themselves to scoping, directing, and reviewing the output of AI agents — closer to a tech lead’s job than an individual contributor’s, for people who were hired and promoted as individual contributors. Most job descriptions, career ladders, and performance rubrics haven’t caught up. Companies are asking engineers to operate one level up without redefining what “good” looks like at that new level.</p><p><strong>2. The skills base is depreciating on a five-year clock, not a career-length one.</strong> McKinsey’s organizational research estimates that roughly two-thirds of the skills a company will need are going to be materially different within five years. A title-based org chart — “Senior Engineer,” “QA Lead,” “Architect” — cannot keep pace with that rate of change, because titles describe a job, not a shifting bundle of capabilities.</p><p><strong>3. Hiring and layoffs are happening in the same organization, for the same function, at the same time.</strong> The competition for a small pool of engineers who can genuinely architect and govern agentic systems has never been more intense, while, simultaneously, agents are absorbing enough lower-level development work that headcount reductions are happening in the same roles. Without a deliberate talent architecture, companies end up doing both badly — overpaying for scarce senior talent while making blunt, morale-damaging cuts to the junior bench that would normally grow into that senior talent.</p><p>None of this is a tooling problem. It’s an operating-model problem, and it sits squarely between the CIO and the CHRO — which is precisely where most organizations have the least established shared process today.</p><h3>Why “Quiet” Is the Right Word</h3><p>This crisis doesn’t announce itself the way an outage or a security breach does. It shows up as a slow erosion: attrition of the engineers who feel their career ladder no longer makes sense, quiet failure to hit the productivity gains promised in the AI business case, and a widening gap between the handful of teams that have figured out human-agent collaboration and the majority that haven’t. By the time it’s visible in the numbers, the organization is usually eighteen months behind.</p><p>That is exactly why it needs to be treated as architecture, not initiative. An initiative has a start and end date. An architecture is a standing structure — roles, capability models, governance, and decision rights — that has to be designed deliberately, the same way a technical architecture is.</p><h3>What “Solving It” Actually Requires</h3><p>Leading organizations are converging on a few structural moves. None of them are exotic, but almost none of them happen without deliberate ownership at the CIO/CHRO level.</p><h3>1. Adopt a build–buy–embed capability model, not a headcount model</h3><p>Instead of asking “how many engineers do we need,” the more useful question is which capabilities need to live permanently inside the company versus which can flex.</p><ul><li><strong>Build</strong> — invest in developing an internal bench for roles tied to proprietary systems, institutional context, and long-term architecture. This is where competitive advantage actually compounds, so it shouldn’t be outsourced.</li><li><strong>Buy</strong> — hire directly and competitively for senior platform and AI-architecture roles where permanent, deep capability genuinely matters.</li><li><strong>Embed</strong> — bring in contingent or project-based specialists for capabilities that are evolving quickly or are time-bound, rather than trying to build permanent depth in a skill that may look different in eighteen months.</li></ul><p>This only works if the skills taxonomy is treated as a living asset — reviewed on the same cadence as the technology roadmap, not once a year during budget season.</p><h3>2. Redesign roles around orchestration, not around task execution</h3><p>The job architecture has to explicitly separate three things that used to be bundled into one engineering role: doing the work, directing the agents doing the work, and governing whether the agents should be trusted to do the work at all. In practice this means new or substantially redefined roles showing up in engineering organizations:</p><ul><li><strong>Agent orchestrators</strong> — engineers who scope, sequence, and review multi-agent workflows, evaluated on output quality and judgment rather than lines of code.</li><li><strong>AI/agent trust or governance leads</strong> — own the guardrails, audit trails, and escalation paths for what agents are allowed to do autonomously versus what requires a human decision.</li><li><strong>Context and platform engineers</strong> — own the shared memory, documentation, and coordination layer that agents draw on, since fragmented context is quickly becoming the real productivity bottleneck, not model capability.</li><li><strong>Reskilled operations specialists</strong> — for example, data engineers moving into AI-operations roles, or QA engineers moving into agent-evaluation roles, rather than being displaced by them.</li></ul><p>The organizations getting the most value from agentic AI are the ones giving existing employees “superpowers” through reskilling into these roles, rather than treating reskilling as a consolation prize after headcount cuts.</p><h3>3. Make the CIO a co-architect of workforce strategy, not just technology strategy</h3><p>The research is consistent on this point: at top-performing companies, technology leaders are substantially more likely to be deeply involved in shaping enterprise strategy overall, not just the technology roadmap. That involvement has to extend into workforce planning specifically. In practice, the CIO, CHRO, and CEO need a shared, standing forum — not a one-off committee — that jointly owns three decisions: what new technology talent to hire, what to build internally through reskilling, and how agentic capacity changes vendor and outsourcing strategy. Splitting these three decisions across separate functions is exactly how organizations end up hiring for yesterday’s needs while quietly losing the people who could have grown into tomorrow’s.</p><h3>4. Govern the human-agent boundary explicitly, don’t let it drift</h3><p>Every organization scaling agentic engineering needs an explicit, written answer to: which decisions can an agent make unsupervised, which require a human to review before it acts, and which stay entirely human-owned regardless of agent capability. Reversible, routine work is the natural candidate for delegation. Architecture decisions, security-sensitive changes, and anything with material customer or financial consequence should stay explicitly human-owned. Without this written line, the boundary drifts informally, team by team, which is how governance failures happen quietly long before they happen publicly.</p><h3>5. Take an incremental integration path, not a big-bang transformation</h3><p>Full-scale technology transformations demand scarce compute and even scarcer specialized AI engineering talent. An incremental path — reskilling and redeploying existing talent into adjacent, higher-value roles as agent capability matures — is both more affordable and more durable, because it builds organizational muscle memory alongside the technology rollout instead of parachuting new capability in from outside.</p><h3>A Practical Process: Five Phases</h3><p>For a CIO and CHRO building this out together, the sequence that tends to work looks like this:</p><p><strong>Phase 1 — Diagnose (4–6 weeks).</strong> Map current roles against the tasks agents can already credibly perform. Identify where the organization is over-indexed on execution skills and under-indexed on orchestration, review, and governance skills. Be honest about where the org chart is title-based rather than skills-based.</p><p><strong>Phase 2 — Design the capability architecture (6–8 weeks).</strong> Build the skills taxonomy and the build–buy–embed map against it. Draft the new or redefined roles — orchestrators, trust leads, context engineers — with real career ladders and performance criteria, not just new job titles bolted onto old rubrics.</p><p><strong>Phase 3 — Govern (parallel, ongoing).</strong> Stand up the human-agent decision-rights framework: what’s delegated, what’s reviewed, what’s reserved. Assign clear ownership for agent audit trails and escalation paths before scaling, not after an incident forces the issue.</p><p><strong>Phase 4 — Build and reskill (rolling, 2–3 quarters).</strong> Launch targeted reskilling for the roles identified in Phase 2, prioritizing the employees most affected by role change. Hire externally only for the capability gaps reskilling genuinely can’t close within a reasonable timeframe.</p><p><strong>Phase 5 — Scale and measure (ongoing).</strong> Track adoption and impact by team, not just enterprise-wide — the organizations seeing real EBIT impact are disproportionately the ones that redesigned workflows in specific functions rather than deploying AI broadly and thinly. Feed what’s learned back into Phase 2’s capability architecture on a quarterly cycle, since the skills taxonomy has a short half-life by design.</p><h3>The Metrics That Actually Matter</h3><p>Most organizations are still measuring this transition with the wrong instruments — tool adoption rates and licenses purchased. The more honest scorecard tracks:</p><ul><li>Share of engineering work delegated to agents <em>with</em> a defined human review point, versus delegated by default</li><li>Percentage of the engineering org that has moved into a redefined role (orchestrator, trust lead, context engineer) versus still operating under a pre-agentic job description</li><li>Time-to-reskill for employees moved into new roles, and their retention twelve months out</li><li>Number of functions with a written, enforced human-agent decision-rights boundary</li><li>EBIT or margin impact attributed to specific redesigned workflows, not enterprise-wide averages</li></ul><h3>The Bottom Line</h3><p>The organizations winning this transition are not the ones with the best agents. They are the ones that treated their people architecture with the same rigor they applied to their technical architecture — built deliberately, governed explicitly, and revisited on a real cadence. The technology will keep improving on its own. The talent architecture will not build itself, and right now, it’s the part of the AI strategy most CIOs and CHROs still haven’t put on the same roadmap.</p><p><em>Sources: McKinsey &amp; Company — “Redesigning technology workforce for the agentic AI era,” “The State of Organizations 2026,” “State of AI trust in 2026,” “Rethinking enterprise architecture for the agentic era,” and the McKinsey Global Tech Agenda 2026; CIO.com, “How agentic AI will reshape engineering workflows in 2026”; Artech, “Engineering Team Design in 2026.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3fb55fe8f7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Spec Factory: One Spec-Driven Development Playbook for Both Greenfield and Brownfield Systems]]></title>
            <link>https://medium.com/@itismohan.g/the-spec-factory-one-spec-driven-development-playbook-for-both-greenfield-and-brownfield-systems-2eaebdfa409d?source=rss-b563fdb94f2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eaebdfa409d</guid>
            <category><![CDATA[sdd]]></category>
            <category><![CDATA[sdlc]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aidlc]]></category>
            <dc:creator><![CDATA[Mohan Krishna G]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 17:34:37 GMT</pubDate>
            <atom:updated>2026-08-10T17:34:37.540Z</atom:updated>
            <content:encoded><![CDATA[<h3>Every spec is a hypothesis. Some are hypotheses about the future. Others are hypotheses about a past nobody fully remembers.</h3><p>Most teams talk about Spec-Driven Development (SDD) as if it only has one failure mode: the AI agent hallucinates a requirement that was never true. That failure is real, but it’s only half the picture, and it shows up differently depending on where the spec comes from.</p><p>On a <strong>brownfield</strong> system, the spec is reverse-engineered from code that has survived ten years of hot-fixes, tribal knowledge, and one engineer who left in 2019 and took the “why” with them. The risk is that a bug gets promoted to a requirement. An agent reads the code, infers intent, writes it down as truth, and the next agent builds on top of that lie.</p><p>On a <strong>greenfield</strong> system, the spec is authored from a blank page, built on assumptions, interviews, and a product manager’s best guess about what users will actually do. The risk is the mirror image: an <em>assumption</em> gets promoted to a requirement before anything has validated it, and the team spends three sprints building a beautifully spec-compliant feature nobody asked for.</p><p>Different origin, same underlying failure: <strong>a spec that reads as authoritative before it has earned the right to be.</strong> Once that happens, every subsequent AI-assisted change compounds the error, because coding agents are extremely good at faithfully implementing a spec and completely indifferent to whether the spec itself was correct.</p><p>What follows is a single process — I’ll call it the <strong>Spec Factory</strong> — that treats spec creation as a production line with quality gates, not a one-time ceremony. It has six stages. Three of them change shape depending on whether you’re excavating a legacy system or building from scratch; three of them are identical either way.</p><p>The Spec Factory pipeline: six stages from context mapping to cutover, with a brownfield/greenfield branch at Stage 1</p><h3>Why one playbook, not two</h3><p>It’s tempting to treat brownfield migration and greenfield build as unrelated disciplines — one is archaeology, the other is architecture. In practice, both are exercises in <strong>making implicit knowledge explicit and then keeping it honest under change</strong>, which is the entire point of SDD. The difference is only <em>where the implicit knowledge currently lives</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehV6A3Im_JHs4MiYMdHduA.jpeg" /><figcaption>cc:chat-GPT</figcaption></figure><p>Once you see the two risks as mirror images of the same problem, you can run both projects through the same factory, swapping only the raw material that feeds Stage 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjukY4Kk8dGcJ6CGydIukQ.jpeg" /></figure><h3>Stage 0 — Context Mapping (identical for both)</h3><p>Before anything is written down as a spec, map the boundaries of what you’re actually specifying.</p><ul><li><strong>Brownfield:</strong> Identify bounded contexts inside the existing system — which modules are cohesive, which are accidental, and which have silently absorbed responsibilities they were never designed for. Static analysis and dependency graphs help, but they only show structure, not intent.</li><li><strong>Greenfield:</strong> Identify bounded contexts you <em>intend</em> to create — which domains are core, which are supporting, which you’re deliberately buying instead of building. The map is aspirational rather than observed, which is exactly why it needs more scrutiny, not less.</li></ul><p>In both cases, the output of Stage 0 is the same artifact: a context map with explicit trust levels attached to each boundary. Some boundaries you’ll trust immediately. Others get flagged for extra verification in the stages that follow. This trust-tagging is what prevents Stage 0 from becoming a diagram nobody looks at again.</p><h3>Stage 1 — Spec Origination (this is where the two paths diverge)</h3><h3>Brownfield: Reverse-engineering, with a built-in lie detector</h3><p>Letting an agent read a legacy module and produce a spec is fast and dangerous in equal measure. The agent cannot distinguish “this is how the business works” from “this is a bug that shipped in 2017 and everyone downstream built around it.” Both look identical in code.</p><p>The fix isn’t to distrust reverse-engineered specs wholesale — it’s to <strong>tier them by evidence quality</strong> before anyone treats them as ground truth:</p><ol><li><strong>Tier A — Corroborated behavior:</strong> The reverse-engineered rule matches documentation, matches a passing test with a meaningful name, and matches what a domain expert confirms in a five-minute conversation. Promote to spec directly.</li><li><strong>Tier B — Uncorroborated but plausible:</strong> The code does something consistent and defensible, but no test or human confirms <em>why</em>. Flag it, write a characterization test that pins the current behavior, and mark the spec clause as “observed, not verified” until a domain owner signs off.</li><li><strong>Tier C — Suspicious:</strong> The behavior only makes sense as an accident — off-by-one conditions, dead branches nothing else references, error-swallowing that quietly changes output. Do not promote to spec. Route to a human decision: fix it, or explicitly document it as an intentional legacy quirk.</li></ol><p>The discipline here is refusing to let volume substitute for verification. A thousand-line reverse-engineered spec that’s 80% Tier C is worse than no spec at all, because it <em>looks</em> authoritative.</p><h3>Greenfield: Authoring, with a built-in reality check</h3><p>The equivalent discipline on a blank-page project is refusing to let confidence substitute for validation:</p><ol><li><strong>Tier A — Validated:</strong> Backed by user research, a competitor pattern with known outcomes, or a non-negotiable compliance requirement. Write it into the spec as a hard constraint.</li><li><strong>Tier B — Informed hypothesis:</strong> A reasonable product bet nobody has tested yet. Write it into the spec, but mark it explicitly as a hypothesis with a defined success metric and a review date — not a permanent requirement.</li><li><strong>Tier C — Opinion dressed as requirement:</strong> “Users will obviously want X.” No evidence, no metric attached. Do not let this enter the spec unmarked; either attach a cheap validation step (a prototype, a five-user test) or explicitly label it as an assumption the team accepts the risk of being wrong about.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y61AFImzLFuVxUPirFiW8w.jpeg" /><figcaption>cc: chat-GPT</figcaption></figure><p>The pattern is the same on both sides of the table: <strong>every spec clause carries a provenance tag</strong> — corroborated, hypothesis, or assumption — and that tag travels with the clause through every later stage. This single habit is the highest-leverage practice in the entire process, because it’s what stops a coding agent from treating a guess with the same weight as a compliance rule.</p><p>Tiering decision flowchart: is the clause corroborated by evidence? Yes leads to Tier A, plausible-but-unproven leads to Tier B, everything else is quarantined as Tier C</p><p>A minimal way to make provenance machine-readable — so agents and CI can act on it, not just humans reading prose — is to attach the tag directly to the spec clause:</p><pre># spec/clauses/checkout-discount-rule.yaml<br>id: CHK-014<br>statement: &gt;<br>  Orders over $200 receive free shipping, applied after<br>  tax but before loyalty-point conversion.<br>origin: brownfield            # brownfield | greenfield<br>tier: B                       # A | B | C<br>evidence:<br>  - type: code_reference<br>    ref: src/checkout/shipping.py#L88-L104<br>  - type: expert_confirmation<br>    status: pending            # pending | confirmed | rejected<br>review_date: 2026-09-15<br>owner: payments-team<br>test_ref: tests/characterization/test_free_shipping_threshold.py</pre><p>The tier field is what every downstream stage reads. Nothing above Tier B should be treated as load-bearing by an implementation agent, and nothing without a test_ref should be treated as verified at all.</p><h3>Stage 2 — The Verification Harness (identical purpose, different tests)</h3><p>A spec without an executable check is just a document an agent will happily contradict on the third refactor.</p><ul><li><strong>Brownfield</strong> needs <strong>characterization tests</strong>: black-box tests that pin the system’s <em>current</em> observed behavior, independent of whether that behavior is “correct.” Their job isn’t to validate the spec — it’s to make any deviation from current behavior visible and intentional, so a migration never silently changes what the system does.</li><li><strong>Greenfield</strong> needs <strong>acceptance and contract tests</strong>: executable versions of the Tier A/Tier B clauses from Stage 1, written before or alongside implementation. Their job is to make the <em>intended</em> behavior visible and force early clauses to be concrete enough to test — which itself surfaces vague requirements before they become code.</li></ul><p>In both cases, the tests become the living, checkable form of the spec. The markdown document is for humans and for priming the agent’s context; the test suite is the thing that actually enforces the contract release after release.</p><p><strong>Brownfield — a characterization test.</strong> It pins current behavior first and asks “should this be true?” only afterward:</p><pre># tests/characterization/test_free_shipping_threshold.py<br># Pins the OBSERVED behavior of shipping.py before any migration.<br># This test is not a statement of correctness — it is a tripwire.<br><br>import pytest<br>from checkout.shipping import calculate_shipping<br>def test_free_shipping_applies_after_tax_before_loyalty_points():<br>    order = build_order(subtotal=205.00, tax=16.40, loyalty_points=50)<br>    result = calculate_shipping(order)<br>    # Pinned as observed on 2026-08-01, corresponds to spec clause CHK-014, Tier B<br>    assert result.shipping_cost == 0.00<br>    assert result.applied_after_tax is True<br>    assert result.loyalty_points_untouched is True</pre><p><strong>Greenfield — an acceptance test.</strong> It’s written from the spec clause itself, before the implementation exists, and fails honestly until the feature is built:</p><pre># tests/acceptance/test_free_shipping_threshold.py<br># Derived directly from spec clause CHK-014 (Tier B — hypothesis).<br># Review date 2026-09-15: promote to Tier A once conversion data confirms the threshold.<br><br>def test_orders_over_200_get_free_shipping():<br>    order = build_order(subtotal=205.00, tax=16.40, loyalty_points=50)<br>    result = calculate_shipping(order)<br>    assert result.shipping_cost == 0.00<br>    assert result.applied_after_tax is True<br>    assert result.loyalty_points_untouched is True</pre><p>Notice the two tests converge on nearly identical assertions. That convergence is the point: by the time a brownfield clause reaches Tier A or a greenfield clause reaches Tier A, both should be indistinguishable in how rigorously they’re enforced.</p><h3>Stage 3 — Incremental Layering (identical mechanics)</h3><p>Neither a legacy system nor a new one should be spec’d and rebuilt in one giant leap. Slice by vertical capability, not by architectural layer:</p><ul><li><strong>Brownfield:</strong> Pick one bounded context at a time — the one with the highest business value and the <em>lowest</em> Tier-C density from Stage 1. Migrate it fully (spec, tests, implementation, cutover) before touching the next. Resist the temptation to spec the entire system up front; a spec for a module you haven’t migrated yet will drift before you get to it.</li><li><strong>Greenfield:</strong> Pick one user journey at a time — the one that proves or disproves your riskiest Tier-B hypothesis first. Build it end-to-end, spec included, before expanding scope. Resist the temptation to write a comprehensive spec for the whole product before a single hypothesis has met a real user.</li></ul><p>The shared principle: <strong>the spec’s blast radius should never be larger than what you can verify in the current increment.</strong> A 200-page spec for an unbuilt system is exactly as risky as a 200-page reverse-engineered spec for an unmigrated legacy system — both are confidently detailed and empirically untested.</p><h3>Stage 4 — The Boundary Contract (identical purpose, different direction)</h3><p>Every increment needs a hard seam that stops bad assumptions from leaking across it.</p><ul><li><strong>Brownfield:</strong> An <strong>anti-corruption layer</strong> between the newly spec’d, newly tested module and the untouched legacy code around it. It translates old data shapes and old failure modes into the new module’s clean contract, so the legacy system’s quirks don’t silently become “requirements” for the new code just because they’re adjacent to it.</li><li><strong>Greenfield:</strong> A <strong>contract boundary</strong> between the module you’re validating now and the modules you haven’t built yet. It stops next sprint’s unvalidated hypothesis from quietly becoming an implicit dependency of the code you’re shipping this sprint.</li></ul><p>Both boundaries exist to answer the same question on demand: <em>if this assumption on the other side of the line turns out to be wrong, how much of my system breaks?</em> The answer should always be “just the translation layer,” never “everything downstream.”</p><p>Boundary contract diagram: legacy module through an anti-corruption layer to the new spec’d module (brownfield), and validated module through a contract boundary to an unvalidated module (greenfield)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uSVmAsar7HFlNQlvYj_1zw.jpeg" /><figcaption>cc:chat-GPT</figcaption></figure><p><strong>Brownfield — an anti-corruption layer</strong>, keeping the legacy module’s Tier C quirks from leaking into the new, spec’d module’s clean contract:</p><pre># checkout/acl/legacy_shipping_adapter.py<br># Anti-corruption layer: translates legacy shipping.py output<br># into the new module&#39;s clean, spec-conformant contract.<br><br>from checkout.new.contracts import ShippingResult<br>class LegacyShippingAdapter:<br>    def __init__(self, legacy_calculate_shipping):<br>        self._legacy = legacy_calculate_shipping<br>    def calculate(self, order) -&gt; ShippingResult:<br>        raw = self._legacy(order)<br>        # Legacy quirk (Tier C, CHK-014-quirk-3): under $0.01 rounding<br>        # errors on int-cent orders. Absorbed HERE, not exposed upstream.<br>        cost = round(raw.shipping_cost, 2)<br>        return ShippingResult(<br>            cost=cost,<br>            applied_after_tax=raw.applied_after_tax,<br>            spec_ref=&quot;CHK-014&quot;,<br>        )</pre><p><strong>Greenfield — a contract boundary</strong>, keeping next sprint’s unvalidated hypothesis from becoming an implicit dependency of what’s shipping now:</p><pre># checkout/contracts/shipping_provider.py<br># Contract boundary: the checkout flow depends on this interface,<br># never on a specific (possibly still-hypothetical) pricing strategy.<br><br>from typing import Protocol<br>class ShippingProvider(Protocol):<br>    def calculate(self, order) -&gt; &quot;ShippingResult&quot;:<br>        ...<br># Today: validated Tier A implementation<br>class FlatThresholdShipping(ShippingProvider):<br>    def calculate(self, order):<br>        ...<br># Next sprint: Tier B hypothesis, swappable without touching checkout<br>class TieredLoyaltyShipping(ShippingProvider):<br>    def calculate(self, order):<br>        ...</pre><h3>Stage 5 — Drift Detection and Cutover (identical for both)</h3><p>A spec is only trustworthy on the day it’s written unless something keeps checking it against reality.</p><ul><li>Run the verification harness from Stage 2 in CI on every change — not just to the code, but to the spec itself. A spec edit with no corresponding test change is a signal, not a formality.</li><li>Track provenance tags from Stage 1 over time. A Tier B hypothesis that’s been sitting unvalidated for three months is a process failure, whether it’s an untested legacy inference or an unvalidated product bet.</li><li>Cutover — the moment you retire the old code path (brownfield) or the moment you remove the “hypothesis” flag and treat a clause as permanent (greenfield) — happens only when the harness has been green under real or realistic load for a defined soak period, not when the spec merely reads well.</li></ul><p>A simple CI check keeps Stage 5 honest instead of aspirational — it fails the build the moment a Tier B clause overstays its review date, or a Tier A clause loses its test link:</p><pre># ci/check_spec_drift.py<br># Run in CI on every PR that touches spec/clauses/*.yaml<br><br>import sys, yaml, datetime<br>from pathlib import Path<br>TODAY = datetime.date.today()<br>errors = []<br>for path in Path(&quot;spec/clauses&quot;).glob(&quot;*.yaml&quot;):<br>    clause = yaml.safe_load(path.read_text())<br>    if clause[&quot;tier&quot;] == &quot;A&quot; and not clause.get(&quot;test_ref&quot;):<br>        errors.append(f&quot;{clause[&#39;id&#39;]}: Tier A clause has no linked test&quot;)<br>    if clause[&quot;tier&quot;] == &quot;B&quot;:<br>        review_date = datetime.date.fromisoformat(clause[&quot;review_date&quot;])<br>        if review_date &lt; TODAY:<br>            errors.append(f&quot;{clause[&#39;id&#39;]}: Tier B hypothesis overdue for review (was due {review_date})&quot;)<br>    if clause[&quot;tier&quot;] == &quot;C&quot;:<br>        errors.append(f&quot;{clause[&#39;id&#39;]}: Tier C clause must not exist in main - quarantine it&quot;)<br>if errors:<br>    print(&quot;Spec drift check failed:\n&quot; + &quot;\n&quot;.join(f&quot;  - {e}&quot; for e in errors))<br>    sys.exit(1)<br>print(f&quot;Spec drift check passed: {len(list(Path(&#39;spec/clauses&#39;).glob(&#39;*.yaml&#39;)))} clauses verified.&quot;)</pre><p>Wire this into the same pipeline that runs the characterization and acceptance suites from Stage 2, and cutover becomes a data-driven decision — every clause either has a green test and a current tier, or the build won’t ship.</p><h3>The Quality Gate Checklist</h3><p>Use this as a go/no-go gate at the end of every increment, regardless of which side of the table you started from:</p><ol><li>Does every spec clause carry a provenance tag (corroborated / hypothesis / assumption)?</li><li>Does every Tier A / validated clause have an executable test behind it.</li><li>Does every Tier B / hypothesis clause have an explicit review date and success metric?</li><li>Have all Tier C / unvalidated-opinion clauses been resolved or explicitly quarantined — not silently promoted?</li><li>Is there a boundary contract isolating this increment from unverified code on either side?</li><li>Has the harness been green for the full soak period before cutover?</li><li>Does someone other than the agent’s author own the sign-off on Tier A promotions?</li></ol><p>If any answer is no, the increment isn’t ready — not because the code is wrong, but because the <em>spec</em> hasn’t earned the trust the team is about to place in it.</p><h3>The takeaway</h3><p>Spec-Driven Development doesn’t fail because AI agents write bad code. It fails because specs get treated as facts before they’ve been earned — whether “earned” means corroborated against twenty years of production behavior, or validated against real users who don’t exist yet. Brownfield and greenfield look like opposite problems. Run them through the same factory, with provenance tags, a verification harness, incremental slicing, and hard boundary contracts, and they turn out to be the same problem wearing different clothes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eaebdfa409d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Personalising D2C Apps by Learning from the Customer Journey]]></title>
            <link>https://medium.com/@itismohan.g/personalising-d2c-apps-by-learning-from-the-customer-journey-288057c4ca3d?source=rss-b563fdb94f2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/288057c4ca3d</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[personalization]]></category>
            <category><![CDATA[b2c]]></category>
            <category><![CDATA[customer-experience]]></category>
            <category><![CDATA[d2c]]></category>
            <dc:creator><![CDATA[Mohan Krishna G]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 07:30:11 GMT</pubDate>
            <atom:updated>2026-07-28T07:30:11.953Z</atom:updated>
            <content:encoded><![CDATA[<h3>How a single sequence model can replace hundreds of hand-crafted features — and why most direct-to-consumer products are sitting on the data to build one</h3><p>Most D2C products — retail, subscription, fintech, marketplaces, media, wellness, you name it — personalise the same way. A team ships a recommendation widget or a ranked feed, backed by a feature store full of hand-built aggregates: <em>purchases in the last 90 days</em>, <em>days since last session</em>, <em>category affinity score</em>, <em>average order value</em>. Each feature is reasonable on its own. Collectively, they hit a ceiling. Feature stores balloon into the hundreds of columns, every new use case wants its own bespoke aggregation, and none of it captures the actual <em>order</em> in which a customer did things — which, it turns out, is often the most predictive signal available.</p><p>Airbnb ran into exactly this wall with search ranking, and published a detailed account of how they solved it: instead of continuing to hand-engineer features from the guest journey, they trained a Transformer-based sequence model directly on it, and used the resulting embeddings to personalise search. The results were strong enough, and the underlying idea general enough, that it’s worth asking a broader question: <strong>does this pattern apply to any D2C product with a login and a history?</strong></p><p>It does. Here’s the generic version of that architecture — what it looks like, why the efficiency tricks matter, and what it would take to ship it.</p><h3>The problem, restated generically</h3><p>Every D2C product accumulates two very different kinds of behavioural data:</p><ul><li><strong>Long-term history</strong> — purchases, returns, reviews, subscription changes, loyalty tier movement. Sparse, occasional, but extremely informative when it happens.</li><li><strong>Short-term activity</strong> — the current session, recent browsing, cart adds, wishlist activity, push notification opens. Dense, frequent, and much noisier.</li></ul><p>Hand-crafted features try to compress both into a handful of aggregate numbers. That compression is lossy in a specific way: it throws away sequence. A customer who added three items to cart, removed two, then bought the third, looks identical in an aggregate feature store to one who just bought the third item outright — even though the abandon-then-purchase pattern is a meaningfully different signal about price sensitivity or indecision.</p><p>There’s also a data-skew problem that shows up in every D2C vertical: the events you can <em>observe</em> most often (page views, scrolls, opens) are the least valuable, and the events you actually care about (a purchase, a renewal, a completed application) are comparatively rare. A model — and the humans hand-engineering features for it — has to learn to find a rare, high-value signal inside an ocean of low-value noise. Aggregate statistics are a blunt tool for that job.</p><h3>Two timescales, one model</h3><p>The fix is architecturally simple to describe, if non-trivial to build: stop hand-engineering features, and instead train a sequence model directly on the raw event history, split into two timescales that get combined into a single learned representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bVolMkggQZutPc1jiblgg.png" /><figcaption>customer Jouney-Architecture</figcaption></figure><ul><li><strong>Long-term sequence</strong>: capped at a few years and a fixed number of events (Airbnb capped at 80; the exact number depends on your data, but the point is a fixed budget). This captures the slow-moving story — what category this customer buys in, how often they return, whether they’ve churned before and come back.</li><li><strong>Short-term sequence</strong>: the last few weeks of activity, capped at a larger event count since it’s higher-frequency and lower-signal-per-event.</li><li><strong>A shared embedding table</strong> for high-cardinality IDs — product, brand, category, merchant, whatever the equivalent entities are in your product — so the model learns representations for those entities jointly with the sequence, rather than as a separate lookup problem.</li><li><strong>A causal-masked Transformer encoder</strong> over the combined sequence, producing a single dense embedding per customer: a learned summary of “what this person is like and what they’re likely to want,” updated as their history grows.</li></ul><p>That embedding is deliberately generic — it isn’t trained for one task. It gets reused across every surface that needs personalisation: product or content ranking, next-best-offer, retention prompts, and lifecycle email or push. This is one of the more underrated parts of the approach — you train the expensive model once, and cheaply extend it everywhere.</p><h3>The efficiency problem nobody mentions upfront</h3><p>The idea sounds straightforward until you try to train it at real D2C scale: potentially tens or hundreds of millions of customers, each with years of history. A naive implementation — re-run the encoder over a customer’s full sequence every time you need a training example at some point in their history — is computationally prohibitive.</p><p>The trick that makes it tractable is a property of causal masking: <strong>a single forward pass over a customer’s entire sequence produces the correct embedding at every point in time along that sequence</strong>, not just at the end. If a customer had ten sessions last year, you don’t need ten separate forward passes to get ten valid training labels — one pass gives you all ten “as-of” embeddings simultaneously. This alone can cut training compute by several times over the naive approach.</p><p>A few other efficiency techniques compound with that one:</p><ul><li><strong>Bucketize sequences by length</strong> before batching, so short-history and long-history customers aren’t padded to match each other and waste compute on padding.</li><li><strong>Sparse computation over padded slots</strong> — skip empty positions in the tensor rather than running them through the network as zeros.</li><li><strong>Decouple training frequency from serving frequency</strong> — the model doesn’t need to be retrained constantly to stay useful; it needs its <em>embeddings</em> refreshed constantly, which is a much cheaper operation than retraining (more below).</li></ul><p>None of this is exotic engineering. It’s the kind of throughput work that turns “technically possible” into “affordable to run daily on your full customer base.”</p><h3>Serving architecture: keep the expensive part offline</h3><p>This is the part that most write-ups of “Transformers for personalisation” skip, and it’s the part that actually determines whether the idea ships. The Transformer encoder is too heavy to run inside a page load. So it doesn’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9_UGGY_TwZqzeXfaNIrncA.png" /><figcaption>Offline, once a day: event streams flow through a feature pipeline into long-term and short-term sequence stores, then a nightly batch job runs the Transformer encoder and writes customer embeddings to a key-value store, ready for online lookup</figcaption></figure><p><strong>Offline, once a day:</strong></p><ul><li>Raw events land in a stream (Kafka or equivalent).</li><li>A feature pipeline (Spark/Flink) dedupes, joins, and buckets them by sequence length.</li><li>The Transformer encoder runs — incrementally, only for customers with new events that day, not the full customer base.</li><li>Output is a single dense vector per customer, written to a low-latency key-value store, versioned and timestamped.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJIA1SJ-wD8SYMKN8JDYwQ.png" /><figcaption>Online, at request time: a ranking service fetches the precomputed embedding and live session context in parallel, feeds both into a lightweight setwise ranker, and returns a personalized response — with the event logged back into the pipeline.</figcaption></figure><p><strong>Online, at request time:</strong></p><ul><li>A ranking service fans out in parallel to (a) the embedding store, for a single-key read of the precomputed vector, and (b) whatever holds live session state — current page, cart, candidate set.</li><li>A small, cheap <strong>set wise ranker</strong> — not the Transformer — combines the embedding with live context to score candidates <em>against each other</em>, not in isolation.</li><li>The response goes back to the customer, and the interaction gets logged, feeding tomorrow’s batch job.</li></ul><p>The entire online latency budget (tens of milliseconds) never touches the heavy model. That’s the whole trick: pay the Transformer’s cost once a day in batch, and serve from a cache the rest of the time.</p><p>A few operational details matter here regardless of vertical:</p><ul><li><strong>Cold start</strong>: new customers, or anyone without a computed embedding yet, need a defined fallback — usually the old aggregate-feature ranker — so the system degrades gracefully instead of breaking.</li><li><strong>Freshness</strong>: a nightly batch means embeddings can be up to 24 hours stale. If your product has same-day high-value events (a completed purchase, a cancelled subscription), decide explicitly whether that’s acceptable or whether live context needs a lightweight patch to compensate in the interim.</li><li><strong>Versioning</strong>: tag every nightly batch with a model version so a bad push can be rolled back to yesterday’s embeddings without re-running history.</li><li><strong>A/B testing discipline</strong>: roll out in stages — long-term sequence alone, then add short-term, then add the set wise ranker — each gated on a proper randomised test with guardrail metrics, not just the target metric. Consistent customer-level bucketing matters so the same person sees the same variant for the test’s duration.</li></ul><h3>Why this generalises across D2C verticals</h3><p>The specific event types change — trade lines and inquiries for a fintech product, orders and returns for retail, watch history and ratings for media, workouts and check-ins for wellness — but the shape of the problem doesn’t:</p><ul><li>A sparse, high-value long-term history.</li><li>A noisy, high-frequency short-term activity stream.</li><li>A need to personalise more than one surface (ranking, recommendations, retention, lifecycle messaging) from the same underlying understanding of the customer.</li><li>A hand-crafted feature store that’s hit diminishing returns.</li></ul><p>If those four things are true of your product, this architecture is very likely worth prototyping. The reusability of the embedding is what makes the investment pay off beyond the first use case — a representation built to improve product ranking tends to lift email and push personalisation too, often with no additional model architecture work, just a new consumer of the same stored vector.</p><h3>Where to start</h3><p>The realistic path isn’t “replace the whole feature store on day one.” It’s staged:</p><ol><li><strong>Prototype offline, on long-term sequence only.</strong> Validate — with proper offline evaluation, not just intuition — that a learned representation beats your current aggregate features on your primary ranking task.</li><li><strong>Add the short-term sequence</strong>, and invest in the batching/bucketization efficiency work at that point, once you know the approach is worth scaling.</li><li><strong>Add a co-trained set wise ranker</strong>, and extend the same embedding to a second surface — email or push is usually the cheapest place to prove reuse, since it typically requires no new online infrastructure.</li></ol><p>Each stage should clear its own A/B test before the next one gets funded. That’s slower than a big-bang rewrite, but it’s the difference between a personalisation system that ships and one that becomes a multi-quarter research project with nothing in production at the end of it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=288057c4ca3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Layers, One Score: A Practical Model for Spec Quality]]></title>
            <link>https://medium.com/@itismohan.g/two-layers-one-score-a-practical-model-for-spec-quality-4b552089397f?source=rss-b563fdb94f2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b552089397f</guid>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aidlc]]></category>
            <category><![CDATA[sdd]]></category>
            <dc:creator><![CDATA[Mohan Krishna G]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 05:33:33 GMT</pubDate>
            <atom:updated>2026-07-24T05:33:33.878Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Your Spec Passed Review. Here’s Why It Still Broke Production.</em></p><p>Spec-Driven Development (SDD) has a trust problem. Once an AI agent or a junior engineer, for that matter starts generating code straight from a written spec, the spec stops being documentation and becomes an input contract. And unlike code, nobody lints it.</p><p>Most teams “review” specs the way they review prose: read it, nod, approve it. That works until the spec is <em>structurally</em> fine. every section filled in, every acceptance criterion present but <em>semantically</em> wrong: it technically describes something, just not the thing the business actually needs. The bug doesn’t show up in review. It shows up three sprints later as a rewrite.</p><p>The fix is to treat spec quality the way we treat code quality: as something with layers, some machine-checkable and some requiring judgment, both worth measuring separately.</p><h3>The two layers</h3><p><strong>Formal layer : </strong>structural correctness. Can a rule engine verify it without understanding what the spec <em>means</em>? Missing sections, unlinked requirements, vague acceptance criteria — all catchable with regex, schema validation, and linting. Cheap enough to run on every commit.</p><p><strong>Semantic layer : </strong>meaning and intent. Does the detailed behavior actually match the stated goal? Are the edge cases the <em>right</em> edge cases, not just <em>some</em> edge cases? This needs judgment, usually an LLM-as-judge pipeline, sometimes a human SME and it’s where the expensive bugs hide.</p><p>A spec can score 100% on the formal layer and still be a disaster, because “every section is filled in” says nothing about whether what’s written in those sections is <em>correct</em>. That gap is exactly what most spec review processes miss, because a checklist only catches the formal layer.</p><h3>A concrete example</h3><p>Here’s an acceptance criterion that passes every formal check:</p><pre>Given a user submits a payment retry request<br>When the retry succeeds<br>Then the system should update the payment status appropriately</pre><p>It has a Given/When/Then shape, so the testability regex matches. It&#39;s not vague by word-list standards — no &quot;fast,&quot; no &quot;user-friendly.&quot; Completeness, structural conformance, traceability: all green. A formal-only linter ships this straight to code generation.</p><p>But “update the payment status appropriately” isn’t a specification — it’s a placeholder wearing a specification’s clothes. Appropriately to whom? Does “succeeded” trigger a receipt email? Does it clear a dunning flag? Does it affect a related subscription’s next billing date? An LLM judge scoring intent alignment catches this immediately, because the question “does this resolve the stated problem, including the edge cases a domain expert would expect” forces the comparison a keyword scanner can’t make. This is the case that motivates the whole two-layer split: the formal layer would have shipped it, and the semantic layer is the only thing that stops it.</p><h3>The metrics</h3><p>Six metrics per layer, each with a formula and a target:</p><p><strong>Formal layer</strong> (machine-checked, every commit)</p><p>Metric Formula Target Completeness score filled sections / required sections 100% Structural conformance valid fields / total fields 100% Consistency score 1 − (conflicts / total assertions) ≥ 95% Traceability coverage linked requirements / total requirements ≥ 90% Testability index measurable criteria / total criteria ≥ 90% Ambiguity density (inverted) 1 − (vague terms / 1,000 words, normalized) ≥ 90%</p><p><strong>Semantic layer</strong> (LLM-judged, on merge or nightly)</p><p>Metric Formula Target Intent alignment LLM-judge rubric score, 1–5 scale → % ≥ 84% Domain correctness SME/judge pass rate against domain rules ≥ 95% Edge-case coverage addressed edge cases / LLM-enumerated edge cases ≥ 80% Clarification resolution resolved [NEEDS CLARIFICATION] markers / total flagged ≥ 95% Spec-to-code fidelity post-hoc LLM similarity score, shipped vs. spec intent ≥ 85% Reviewer comprehension human SME clarity rating, 1–5 scale → % ≥ 80%</p><p>Composite health score is a weighted blend — I use <strong>40% formal / 60% semantic</strong>, because semantic gaps are the ones that cause rework <em>after</em> code is generated, not just comments in review.</p><pre>def composite_score(formal_scores: dict, semantic_scores: dict) -&gt; float:<br>    formal_avg = sum(formal_scores.values()) / len(formal_scores)<br>    semantic_avg = sum(semantic_scores.values()) / len(semantic_scores)<br>    return 0.4 * formal_avg + 0.6 * semantic_avg</pre><h3>The pipeline</h3><p>Both layers run as separate stages, because they have completely different cost and latency profiles — you don’t want a $0.02 LLM call blocking a git hook that should return in milliseconds.</p><pre>spec repo (markdown specs)<br>      │<br>      ├──► formal analyzer (rule engine, linters)  ──┐<br>      │                                               ├──► metrics store ──► dashboard<br>      └──► semantic analyzer (LLM-as-judge)  ─────────┘<br>                                                            │<br>                                                            └──► CI gate (blocks merge below threshold)</pre><p>The formal analyzer is boring on purpose — deterministic checks that run in CI on every push:</p><pre>import re<br>VAGUE_TERMS = {&quot;fast&quot;, &quot;appropriate&quot;, &quot;user-friendly&quot;, &quot;reasonable&quot;, &quot;efficient&quot;, &quot;seamless&quot;}<br><br>def ambiguity_density(spec_text: str) -&gt; float:<br>    words = spec_text.lower().split()<br>    flags = sum(1 for w in words if w.strip(&quot;.,!?&quot;) in VAGUE_TERMS)<br>    return round((flags / len(words)) * 1000, 2)  # per 1,000 words<br>def testability_index(criteria: list[str]) -&gt; float:<br>    # a criterion counts as testable if it has a numeric threshold<br>    # or follows Given/When/Then structure<br>    pattern = re.compile(r&quot;(given|when|then|\d+\s?(ms|s|%|req))&quot;, re.I)<br>    measurable = sum(1 for c in criteria if pattern.search(c))<br>    return measurable / len(criteria) if criteria else 0</pre><p>The semantic analyzer is a judge prompt, not a rule:</p><pre>SEMANTIC_JUDGE_PROMPT = &quot;&quot;&quot;<br>You are reviewing a software specification for intent alignment.<br>Problem statement: {problem_statement}<br>Full spec: {spec_body}<br>Score 1-5 on: does the detailed behavior in this spec actually solve<br>the stated problem, including edge cases a domain expert would expect?<br>Flag anything that technically satisfies the spec&#39;s own wording but<br>misses the underlying intent. Return JSON: {{&quot;score&quot;: int, &quot;gaps&quot;: [str]}}<br>&quot;&quot;&quot;<br></pre><p>Both stages write to a shared metrics store (time-series, one row per spec per run), and the dashboard just queries that.</p><h3>Calibrating the LLM judge</h3><p>The semantic layer is the interesting engineering problem, and it’s also the one that breaks in ways formal rules never do:</p><ul><li><strong>Score drift across model versions.</strong> The same spec scored today and next month, after a model update, can land a full point apart on the 1–5 rubric with no change to the spec. Pin the judge model version per scoring run and re-baseline deliberately, not accidentally.</li><li><strong>Rubric anchoring.</strong> An unanchored “score 1–5” prompt regresses to the mean — everything clusters at 3–4. Few-shot examples of a 2 and a 5 in the prompt, with the reasoning spelled out, tighten the spread considerably.</li><li><strong>Consistency, not just accuracy.</strong> Run the same spec through the judge three times before trusting a single score. If it swings by more than half a point, the rubric is underspecified, not the spec.</li><li><strong>Cost and latency.</strong> A judge call is cents, not free, and it’s seconds, not milliseconds. That’s why it runs on merge or nightly, not on every keystroke — the formal layer is the fast feedback loop; the semantic layer is the thorough one.</li><li><strong>The judge is a signal, not a verdict.</strong> Treat a low semantic score as “a human should look at this,” not as an automatic rejection, at least until you’ve watched it agree with human reviewers for a few months.</li></ul><h3>The dashboard</h3><p>Built as a single control-tower view: composite health up top, the two layers broken out side by side underneath, a trend line, and a spec table where each row’s score renders as a literal two-segment stacked bar — semantic on top, formal on bottom — as a visual echo of the “layers” idea itself.</p><p>Each metric card compares the live value against its target and colors itself accordingly — green at target, amber within 75%, red below:</p><pre>function scoreClass(val, target){<br>  if (val &gt;= target) return &#39;m-ok&#39;;<br>  if (val &gt;= target * 0.75) return &#39;m-warn&#39;;<br>  return &#39;m-bad&#39;;<br>}</pre><p>The spec table is the working view — sortable by any column, click a row to expand the full per-metric breakdown without leaving the page:</p><pre>function renderTable(specs){<br>  const rows = specs.map(s =&gt; {<br>    const f = avg(s.formal), sem = avg(s.semantic);<br>    return { ...s, f, sem, c: 0.4 * f + 0.6 * sem, status: statusFor(0.4 * f + 0.6 * sem) };<br>  });<br>  rows.sort((a, b) =&gt; sortDir * (a[sortKey] - b[sortKey]));<br>  // ...render &lt;tr&gt; per spec, plus a hidden detail &lt;tr&gt; toggled on click<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TB2i8Mc4b3kkFY9KKCplUg.png" /><figcaption>Dashboard</figcaption></figure><p>Two more views round out the “deep dive” row. A <strong>heatmap</strong> puts every spec against all twelve metrics at once — the pattern-spotting view. A single red column across every row means a systemic gap (a rubric that’s too strict, or a real team-wide blind spot); a single red row means one spec is the outlier, not the process. Next to it, a <strong>radar chart</strong> profiles one spec at a time against its targets, which is the fastest way to see <em>shape</em> — is this spec weak everywhere, or is it one axis (say, edge-case coverage) dragging an otherwise solid spec down:</p><pre>function updateRadarChart(specName, specs){<br>  const spec = specs.find(s =&gt; s.name === specName);<br>  const labels = allMetrics.map(m =&gt; SHORT_LABELS[m.key]);<br>  const specValues = allMetrics.map(m =&gt; spec[m.layer][m.key]);<br>  const targetValues = allMetrics.map(m =&gt; m.target);<br>  // two Chart.js radar datasets: the spec&#39;s actual profile vs. target,<br>  // rendered on the same axes so the gap is visible at a glance<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZWdDRiv1nA6VvGdkcIvlQ.png" /><figcaption>heatMap</figcaption></figure><h3>What this changes day to day</h3><p>The practical shift isn’t the dashboard — it’s what the dashboard makes possible: a <strong>CI gate</strong> that blocks a merge when composite score drops below threshold, the same way a failing test suite would. Once spec quality is a number, it stops being a debate in a review comment thread and becomes a build status.</p><p>The formal layer catches the cheap stuff before anyone reads the spec closely. The semantic layer catches the expensive stuff — the gap between “this spec is complete” and “this spec is <em>right</em>” — before it turns into three sprints of rework downstream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qSIwsDdPQTsDb1_fVNFAYQ.png" /><figcaption>spec-level health</figcaption></figure><p>That’s the whole argument for separating the two layers in the first place: they fail differently, they get caught differently, and they cost differently when missed. Measuring them together hides which one is actually broken.</p><h3>Rolling it out without a revolt</h3><p>Nobody adopts a hard CI gate on day one, and they shouldn’t — a gate calibrated on bad thresholds just teaches people to game the rubric. A staged rollout works better in practice:</p><ol><li><strong>Observe only (2–4 weeks).</strong> Run both analyzers on every spec, publish the dashboard, gate nothing. The goal here is purely to see the score distribution and catch obviously miscalibrated targets before they block anyone.</li><li><strong>Soft gate (4–6 weeks).</strong> Scores below threshold post a PR comment and a Slack notification, but don’t block the merge. This is where you find out if the semantic judge actually agrees with human reviewers often enough to trust.</li><li><strong>Hard gate, formal layer only.</strong> Structural and completeness checks are deterministic and cheap to be confident in — block merges on these first.</li><li><strong>Hard gate, both layers.</strong> Only once the semantic judge’s false-positive rate is low and well understood by the team.</li></ol><p>Skipping straight to step 4 is the single most common way these systems get quietly disabled six weeks after launch.</p><h3>Limitations worth stating plainly</h3><ul><li><strong>The semantic layer inherits the judge’s blind spots.</strong> If the LLM doesn’t know a domain’s edge cases, it can’t flag missing ones. Domain-specific rubrics and few-shot examples help, but this isn’t a substitute for SME review in genuinely novel or regulated domains.</li><li><strong>Targets are starting points, not physics.</strong> The thresholds in this piece (90% testability, 84% intent alignment, and so on) are reasonable defaults, not measured constants — recalibrate them against your own team’s data after the observe-only phase.</li><li><strong>A high composite score isn’t a guarantee.</strong> It’s a triage signal that says “this spec is more likely to be fine,” compressing twelve numbers into one for a dashboard glance. Always leave a path from the composite score back down to the individual metric that’s driving it — which is exactly what the drill-down table and radar view are for.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b552089397f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journey to Becoming an AI Engineer — A Roadmap & Guide to Roles in the AI Development Life Cycle…]]></title>
            <link>https://medium.com/@itismohan.g/roadmap-to-become-an-ai-engineer-roles-in-the-ai-development-life-cycle-aidlc-4a9974cc1a3b?source=rss-b563fdb94f2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a9974cc1a3b</guid>
            <category><![CDATA[aidlc]]></category>
            <category><![CDATA[sdlc]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Mohan Krishna G]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 06:19:40 GMT</pubDate>
            <atom:updated>2026-06-21T06:40:13.234Z</atom:updated>
            <content:encoded><![CDATA[<h3>My Journey to Becoming an AI Engineer — A Roadmap &amp; Guide to Roles in the AI Development Life Cycle (AIDLC)</h3><h3>A Personal Note Before We Begin</h3><p>I still remember the night I typed “how to get into AI” into a search engine and stared at the screen feeling completely overwhelmed. There were dozens of courses, conflicting advice, intimidating GitHub repositories, and job descriptions that seemed to demand five years of experience I did not yet have.</p><p>I did not come from a prestigious university. I was someone who had a deep curiosity about technology and a stubborn refusal to give up and honestly, that turned out to be enough.</p><p>This article is not just a theoretical roadmap. It is the path I personally walked, with all its wrong turns, frustrating setbacks, and hard-won breakthroughs. I am sharing it because I wish someone had handed me something like this when I started. If it saves you even a few months of confusion, it will have been worth writing.</p><h3>What Is an AI Engineer?</h3><p>An AI Engineer is a technologist who designs, builds, and deploys AI-powered systems. Unlike pure researchers who focus on theoretical advancements, AI Engineers apply algorithms, models, and frameworks to solve practical business and engineering problems. They are proficient in software engineering, data science, mathematics, and domain-specific knowledge.</p><p>When I first encountered this definition, I had no idea what half of those words meant in practice. I knew what software was. I had heard of algorithms. But “deploying models” and “data pipelines” sounded like a foreign language. That discomfort, I later learned, is where every AI Engineer begins.</p><h3>The Roadmap: Step-by-Step Guide to Becoming an AI Engineer</h3><h3>Phase 1: Build a Strong Foundation (0–6 Months)</h3><p>This phase was, without question, the hardest for me. Not because the material was impossible — but because progress felt invisible. You spend weeks learning things you cannot yet use, and doubt creeps in quietly.</p><p>I remember sitting with a linear algebra textbook at midnight, trying to understand matrix multiplication, wondering if I had made a terrible mistake. I had not. But it did not feel that way at the time.</p><h4>1.1 Mathematics &amp; Statistics</h4><p>AI is built on mathematical principles. Focus on:</p><ul><li><strong>Linear Algebra</strong> — Vectors, matrices, eigenvalues (core to neural networks)</li><li><strong>Calculus</strong> — Derivatives and gradients (essential for backpropagation)</li><li><strong>Probability &amp; Statistics</strong> — Distributions, Bayes’ theorem, hypothesis testing</li><li><strong>Optimisation</strong> — Gradient descent, convex functions</li></ul><blockquote><strong><em>My honest advice</em></strong><em>: Do not try to master every mathematical concept before touching code. Learn just enough theory, then apply it immediately. The understanding deepens through practice, not through reading alone.</em></blockquote><h4>1.2 Programming Proficiency</h4><ul><li><strong>Python</strong> is the primary language of AI. Master it thoroughly.</li><li>Learn libraries: NumPy, Pandas, Matplotlib, Scikit-learn</li><li>Optional: R for statistical analysis; SQL for data querying</li></ul><p>Python was my first real win. Unlike mathematics, which felt abstract, writing Python code gave me immediate feedback. I could see results. I could break things and fix them. I built a small data analysis script in week three and felt, for the first time, like I actually belonged in this field.</p><h4>1.3 Computer Science Fundamentals</h4><ul><li>Data structures and algorithms</li><li>Object-Oriented Programming (OOP)</li><li>Version control with Git/GitHub</li></ul><h3>Phase 2: Master Data Science &amp; Machine Learning (6–12 Months)</h3><p>By month six, I had built enough foundation to start working with real data. This phase reignited my excitement — but it also introduced a new kind of frustration: <strong>messy, real-world data</strong>.</p><p>Every tutorial I had followed used clean, perfectly formatted datasets. Reality was nothing like that. My first real project involved a dataset with missing values, inconsistent formats, duplicate entries, and column names that made no logical sense. I spent three weeks just cleaning it. Three weeks. On the data alone.</p><p>That experience taught me more than any course ever could.</p><h4>2.1 Data Handling &amp; Preprocessing</h4><ul><li>Data cleaning, transformation, and feature engineering</li><li>Exploratory Data Analysis (EDA)</li><li>Tools: Pandas, Excel, SQL, Apache Spark (for big data)</li></ul><h4>2.2 Machine Learning Algorithms</h4><p>Understand both the theory and implementation of:</p><ul><li><strong>Supervised Learning</strong> — Linear/Logistic Regression, Decision Trees, SVM, KNN</li><li><strong>Unsupervised Learning</strong> — K-Means, DBSCAN, PCA</li><li><strong>Ensemble Methods</strong> — Random Forest, Gradient Boosting, XGBoost</li><li><strong>Model Evaluation</strong> — Cross-validation, confusion matrix, ROC-AUC, F1-score</li></ul><p>I made the classic beginner mistake of chasing model accuracy obsessively. I once spent two days tuning a Random Forest model to get from 91% to 93% accuracy only to realise later that my evaluation metric was wrong and the model was simply overfitting. That was a humbling lesson in the importance of understanding <em>what</em> you are measuring, not just <em>how high</em> the number is.</p><h4>2.3 Tools &amp; Frameworks</h4><ul><li><strong>Scikit-learn</strong> for classical ML</li><li><strong>TensorFlow</strong> and <strong>PyTorch</strong> for deep learning</li><li><strong>Jupyter Notebooks</strong> for experimentation</li></ul><h3>Phase 3: Deep Learning &amp; Specialisation (12–18 Months)</h3><p>This phase was where I truly fell in love with AI — and also where imposter syndrome hit me the hardest.</p><p>Reading research papers on Transformers and attention mechanisms, I often felt like I was reading a different language. I would read the same paragraph four or five times and still not fully grasp it. I questioned whether I was intelligent enough for this field. I almost quit during month fourteen.</p><p>What kept me going was a small project I built during this period — a sentiment analysis tool for customer reviews. It was not perfect. But it worked. A real business problem, solved by a model I had trained myself. That small win was everything.</p><h4>3.1 Neural Networks</h4><ul><li>Perceptrons, activation functions, forward/backward propagation</li><li>Convolutional Neural Networks (CNNs) for image tasks</li><li>Recurrent Neural Networks (RNNs), LSTMs for sequential data</li><li>Transformers and Attention Mechanisms (the backbone of modern LLMs)</li></ul><h4>3.2 NLP &amp; Computer Vision</h4><ul><li><strong>NLP</strong>: Tokenisation, embeddings, BERT, GPT, sentiment analysis, named entity recognition</li><li><strong>Computer Vision</strong>: Object detection (YOLO), image segmentation, facial recognition</li></ul><h4>3.3 Generative AI</h4><ul><li>Large Language Models (LLMs): GPT-4, Claude, LLaMA</li><li>Diffusion models: Stable Diffusion, DALL·E</li><li>Prompt engineering and Retrieval-Augmented Generation (RAG)</li></ul><blockquote><strong><em>A word of caution</em></strong><em>: The Generative AI space moves at an extraordinary pace. I once spent three weeks mastering a particular technique, only to find a better approach had been published while I was still learning. Do not let this discourage you. Focus on fundamentals they outlast trends.</em></blockquote><h3>Phase 4: Engineering &amp; MLOps (18–24 Months)</h3><p>Here is the truth nobody tells you early enough: <strong>building a model is only half the job</strong>. Getting it into production — reliably, securely, and at scale — is an entirely different challenge.</p><p>I learned this the hard way when I deployed my first model to a cloud server without proper monitoring. The model worked perfectly in my local environment. In production, it crashed under load within twenty minutes. I had not accounted for memory limits, concurrent requests, or input validation. The failure was embarrassing, but it was the most educational experience of my entire journey.</p><h4>4.1 Data Engineering</h4><ul><li>ETL pipelines, data lakes, data warehouses</li><li>Tools: Apache Kafka, Airflow, dbt, BigQuery</li></ul><h4>4.2 Model Deployment</h4><ul><li>REST APIs with Flask or FastAPI</li><li>Containerization with Docker</li><li>Orchestration with Kubernetes</li><li>Model serving: TorchServe, TensorFlow Serving, Triton Inference Server</li></ul><h4>4.3 MLOps (Machine Learning Operations)</h4><ul><li>Experiment tracking: MLflow, Weights &amp; Biases</li><li>CI/CD pipelines for ML models</li><li>Model monitoring, drift detection, and retraining</li><li>Platforms: AWS SageMaker, Google Vertex AI, Azure ML</li></ul><h4>4.4 Cloud Computing</h4><ul><li>Proficiency in at least one major cloud: AWS, GCP, or Azure</li><li>Understand AI/ML services: AWS Bedrock, Google Cloud AI, Azure OpenAI</li></ul><p>I started with AWS. The documentation was dense. The pricing was confusing. My first cloud bill surprised me in a way I would rather not describe in detail. But once I understood the ecosystem, it opened up a world of possibilities I could not have imagined from a local laptop.</p><h3>Phase 5: Domain Specialisation &amp; Leadership (24+ Months)</h3><p>By this point, I had evolved from someone who googled “what is a tensor” to someone who was mentoring others who were doing the same. That shift in identity — from learner to contributor — was deeply meaningful.</p><ul><li>Pick a domain: Healthcare AI, FinTech AI, Autonomous Systems, Robotics, etc.</li><li>Contribute to open-source AI projects</li><li>Publish research or technical blogs</li><li>Pursue certifications: AWS ML Specialty, Google Professional ML Engineer, TensorFlow Developer</li><li>Explore advanced topics: Federated Learning, Explainable AI (XAI), Reinforcement Learning</li></ul><p>I chose to specialise in NLP and Generative AI. It aligned with my curiosity and the direction the industry was heading. Your choice of specialisation should be guided by both your interest and the market ideally, where those two intersect.</p><h3>Key Skills Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDZ8joWlL6xx0fP52yfYAw.jpeg" /></figure><h3>What Is the AI Development Life Cycle (AIDLC)?</h3><p>The <strong>AI Development Life Cycle (AIDLC)</strong> is a structured framework that governs the end-to-end process of building, deploying, and maintaining AI systems. Much like the Software Development Life Cycle (SDLC), the AIDLC ensures that AI projects are delivered systematically, ethically, and efficiently.</p><p>One thing I wish I had understood earlier is that the AIDLC is rarely linear. In practice, you cycle back constantly — a model that fails evaluation sends you back to data preprocessing. A deployment issue sends you back to model optimisation. Embrace the iteration. It is not a sign of failure; it is the nature of the work.</p><h3>Phases of the AIDLC</h3><ol><li><strong>Problem Definition</strong> — Identify the business problem and determine if AI is the right solution</li><li><strong>Data Collection</strong> — Gather raw data from structured and unstructured sources</li><li><strong>Data Preprocessing</strong> — Clean, transform, and prepare data for modeling</li><li><strong>Model Development</strong> — Select algorithms, train, and tune models</li><li><strong>Model Evaluation</strong> — Validate model performance using test data and metrics</li><li><strong>Deployment</strong> — Integrate the model into production environments</li><li><strong>Monitoring &amp; Maintenance</strong> — Continuously monitor model performance and retrain as needed</li><li><strong>Governance &amp; Ethics</strong> — Ensure fairness, explainability, and regulatory compliance</li></ol><h3>Roles Associated with the AIDLC</h3><p>The AIDLC requires a diverse team of professionals. One of the most eye-opening realisations of my career was understanding that AI is not a solo sport. Every successful AI product I have worked on involved people from at least five or six distinct roles, each bringing irreplaceable expertise to the table.</p><p>Here is a comprehensive look at each role, their responsibilities, and where they fit in the life cycle.</p><h3>1. AI Product Manager</h3><p><strong>Phase</strong>: Problem Definition, Governance</p><p>The AI Product Manager defines the vision and business objectives for AI initiatives. They bridge the gap between business stakeholders and technical teams, ensuring that AI solutions align with real-world needs.</p><p><strong>Key Responsibilities:</strong></p><ul><li>Define AI product requirements and success metrics</li><li>Prioritise features and manage the product roadmap</li><li>Communicate value and ROI to leadership</li><li>Oversee ethical and legal compliance of AI products</li></ul><p><strong>Skills</strong>: Product strategy, stakeholder management, basic ML literacy, Agile/Scrum</p><blockquote><em>In one of my early projects, the absence of a strong AI Product Manager meant that our team built a highly accurate model that solved the wrong problem entirely. We had optimised for what was technically interesting rather than what the business actually needed. It was a costly lesson in why this role is indispensable.</em></blockquote><h3>2. Data Engineer</h3><p><strong>Phase</strong>: Data Collection, Data Preprocessing</p><p>Data Engineers build and maintain the infrastructure that enables data flow across the organisation. Without clean, reliable pipelines, no AI model can succeed.</p><p><strong>Key Responsibilities:</strong></p><ul><li>Design and maintain ETL/ELT pipelines</li><li>Build data lakes, data warehouses, and real-time streaming systems</li><li>Ensure data quality, availability, and governance</li><li>Collaborate with data scientists to prepare datasets</li></ul><p><strong>Skills</strong>: SQL, Python, Spark, Airflow, Kafka, Snowflake, dbt, cloud data services</p><blockquote><em>I used to underestimate Data Engineers until I spent two weeks trying to build a pipeline myself and produced something fragile, slow, and nearly unmaintainable. A skilled Data Engineer later rebuilt it in two days. I have never underestimated that role since.</em></blockquote><h3>3. Data Analyst</h3><p><strong>Phase</strong>: Data Collection, Problem Definition</p><p>Data Analysts explore and interpret datasets to surface insights that inform both business decisions and AI model requirements. They are often the first to identify patterns that can be solved with AI.</p><p><strong>Key Responsibilities:</strong></p><ul><li>Conduct Exploratory Data Analysis (EDA)</li><li>Create dashboards and visual reports</li><li>Define key performance indicators (KPIs)</li><li>Support ML teams with data understanding</li></ul><p><strong>Skills</strong>: SQL, Python/R, Power BI, Tableau, Excel, statistical analysis</p><h3>4. Data Scientist</h3><p><strong>Phase</strong>: Data Preprocessing, Model Development, Model Evaluation</p><p>The Data Scientist is a core AIDLC role, responsible for developing the models that power AI systems. They combine statistical rigor with programming to extract predictive insights from data.</p><p><strong>Key Responsibilities:</strong></p><ul><li>Conduct feature engineering and selection</li><li>Train, tune, and validate ML models</li><li>Experiment with multiple algorithms and compare performance</li><li>Communicate findings to technical and non-technical audiences</li></ul><p><strong>Skills</strong>: Python, R, Scikit-learn, TensorFlow, PyTorch, statistics, experimentation</p><h3>5. Machine Learning Engineer (MLE)</h3><p><strong>Phase</strong>: Model Development, Deployment, Monitoring</p><p>MLEs sit at the intersection of software engineering and data science. While data scientists focus on building models, MLEs focus on making those models production-ready and scalable.</p><p><strong>Key Responsibilities:</strong></p><ul><li>Convert research models into scalable production systems</li><li>Optimise models for latency, throughput, and resource usage</li><li>Build model APIs and micro-services</li><li>Implement A/B testing frameworks for model comparison</li></ul><p><strong>Skills</strong>: Python, TensorFlow/PyTorch, Docker, Kubernetes, REST APIs, cloud platforms</p><h3>6. AI Engineer</h3><p><strong>Phase</strong>: All Phases (especially Development and Deployment)</p><p>The AI Engineer is a versatile, full-stack AI professional who designs and builds intelligent systems end to end. They combine aspects of data science, ML engineering, and software engineering to deliver complete AI solutions.</p><p><strong>Key Responsibilities:</strong></p><ul><li>Design AI system architecture</li><li>Integrate LLMs, computer vision, or NLP components into applications</li><li>Build AI-powered features and products</li><li>Manage the complete pipeline from data to deployment</li></ul><p><strong>Skills</strong>: Deep learning, LLMs, MLOps, software engineering, system design, cloud</p><blockquote><em>This is the role I ultimately aimed into and it is the most demanding precisely because it requires breadth across every other discipline. There are days when you are debugging a Docker container in the morning, reviewing model evaluation metrics in the afternoon, and explaining system architecture to a stakeholder in the evening. It is exhausting and exhilarating in equal measure.</em></blockquote><h3>7. MLOps Engineer</h3><p><strong>Phase</strong>: Deployment, Monitoring &amp; Maintenance</p><p>MLOps Engineers ensure the reliability, scalability, and continuous improvement of AI systems in production. They apply DevOps principles to the machine learning workflow.</p><p><strong>Key Responsibilities:</strong></p><ul><li>Build CI/CD pipelines for ML models</li><li>Monitor model performance and detect data/model drift</li><li>Automate retraining and redeployment workflows</li><li>Manage model registries and experiment tracking</li></ul><p><strong>Skills</strong>: Docker, Kubernetes, MLflow, GitHub Actions, cloud ML platforms, monitoring tools</p><h3>8. AI Research Scientist</h3><p><strong>Phase</strong>: Problem Definition, Model Development</p><p>AI Research Scientists push the boundaries of what is possible in AI. They work on novel algorithms, architectures, and methodologies that may eventually become the foundation for future AI products.</p><p><strong>Key Responsibilities:</strong></p><ul><li>Design and test new ML/AI algorithms</li><li>Publish research papers at top conferences (NeurIPS, ICML, CVPR, ACL)</li><li>Collaborate with engineering teams to productionise research</li><li>Stay current with the latest advances in AI</li></ul><p><strong>Skills</strong>: Advanced mathematics, deep learning theory, academic writing, Python, research frameworks</p><h3>9. AI Ethics &amp; Governance Officer</h3><p><strong>Phase</strong>: Governance &amp; Ethics, All Phases</p><p>As AI becomes more powerful, ethical oversight becomes critical. This emerging role ensures that AI systems are fair, transparent, explainable, and compliant with regulations such as GDPR and the EU AI Act.</p><p><strong>Key Responsibilities:</strong></p><ul><li>Audit models for bias and discriminatory outcomes</li><li>Develop AI policies and ethical guidelines</li><li>Ensure compliance with data privacy regulations</li><li>Promote Explainable AI (XAI) practices</li></ul><p><strong>Skills</strong>: AI ethics frameworks, policy analysis, XAI tools (LIME, SHAP), risk management</p><blockquote><em>A model I worked on early in my career performed well on overall metrics , but when we broke down the results by demographic group, the disparities were stark. The model was unintentionally biased. Without an ethics review, it would have gone to production. That experience shaped how seriously I take this role today.</em></blockquote><h3>10. AI Solutions Architect</h3><p><strong>Phase</strong>: Problem Definition, Deployment</p><p>AI Solutions Architects design the high-level structure of AI systems. They determine how different components data storage, models, APIs, and user interfaces work together to deliver a scalable AI solution.</p><p><strong>Key Responsibilities:</strong></p><ul><li>Design end-to-end AI system architecture</li><li>Select appropriate cloud services, tools, and frameworks</li><li>Define integration patterns and security protocols</li><li>Guide development teams on architecture decisions</li></ul><p><strong>Skills</strong>: System design, cloud architecture (AWS/GCP/Azure), ML knowledge, enterprise integration</p><h3>AIDLC Roles at a Glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sq_55TKJhES-p89ZsxZYZA.jpeg" /></figure><h3>Certifications Worth Pursuing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gUCKmFYm9nw-E8DQz7vPg.jpeg" /></figure><p>My first certification attempt did not go well. I underestimated the depth of the AWS ML Specialty exam and failed by a narrow margin. I rescheduled, spent six more weeks on weak areas, and passed on the second attempt. I share this not to discourage you, but because I think we speak too rarely about the failures that precede success.</p><h3>Lessons I Wish Someone Had Told Me Earlier</h3><p>After years of walking this path, here are the truths I would offer to my earlier self:</p><p><strong>Consistency beats intensity.</strong> One hour of focused learning every day will take you further than ten-hour weekend marathons followed by weeks of burnout.</p><p><strong>Projects matter more than certificates.</strong> A working GitHub project that solves a real problem will impress more people than a list of course completions.</p><p><strong>The community is generous.</strong> I was surprised by how willing experienced practitioners were to help when I asked thoughtful, specific questions. Do not suffer in silence.</p><p><strong>Imposter syndrome never fully disappears.</strong> Even now, I occasionally sit in a meeting and wonder if I belong. The difference is I no longer let that feeling stop me.</p><p><strong>Failure is data, not verdict.</strong> Every model that did not work, every deployment that crashed, every concept I misunderstood — all of it taught me something that success could not have.</p><h3>Conclusion</h3><p>The journey to becoming an AI Engineer is long, nonlinear, and at times genuinely difficult. There will be phases where progress feels invisible and moments where you will question whether you have made the right choice. I have been in both of those places.</p><p>But I can tell you from the other side - it is worth it.</p><p>By following a structured roadmap from foundational mathematics to advanced MLOps and understanding the diverse roles within the AIDLC, you can position yourself as a valuable contributor to one of the most exciting fields in human history.</p><p>Whether you aspire to build cutting-edge LLMs, design ethical AI governance frameworks, or architect scalable AI systems in the cloud, the AI ecosystem has a role for you.</p><p><strong>Start where you are. Use what you have. Build what matters.</strong></p><p>And when it gets hard — and it will get hard — remember that every expert you admire was once exactly where you are now.</p><p><em>Written from personal experience, for aspiring AI professionals navigating the evolving landscape of Artificial Intelligence and Machine Learning.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a9974cc1a3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Human-Augmenting Agentic Workflow for Customer Retention]]></title>
            <link>https://medium.com/@itismohan.g/a-human-augmenting-agentic-workflow-for-d2c-retention-2f42a30a7368?source=rss-b563fdb94f2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f42a30a7368</guid>
            <category><![CDATA[customer-success]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[d2c]]></category>
            <category><![CDATA[customer-service]]></category>
            <dc:creator><![CDATA[Mohan Krishna G]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 17:41:48 GMT</pubDate>
            <atom:updated>2026-06-11T17:49:06.252Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How direct-to-consumer brands can borrow from causal inference to stop guessing why subscribers churn and start knowing</strong></p><h3>The retention question every B2C brand gets wrong</h3><p>Imagine asking a data analyst to tell you whether your new loyalty rewards program actually keeps subscribers around. They pull a cohort, run a regression controlling for plan type and signup month, and return a confident number: rewards members are 34% less likely to cancel in the first 90 days.</p><p>How much should you trust it?</p><p>The honest answer is: not much — unless someone has carefully accounted for the fact that customers who opt into a loyalty program are already more engaged than average. They arrived more motivated, they browse more frequently, and they are already less likely to churn regardless of any rewards you offer them. The program did not retain them. They retained themselves, and you happened to give them a badge along the way.</p><p>This is the central challenge in B2C retention analytics: the features that correlate most strongly with staying are almost always the features that engaged customers are drawn to first. Correlation is not causation, and in subscription businesses, confusing the two leads to investment in the wrong places.</p><p>The good news is that a rigorous, automatable approach exists — one that Netflix recently described for its own causal inference work. This article adapts that framework for any direct-to-consumer subscription business, from health and wellness to software, media, meal kits, and financial products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9H0P0hxoan95eRI_0QfkA.jpeg" /><figcaption>cc:chatgpt</figcaption></figure><h3>The framework in plain language</h3><p>Netflix’s approach is built around three ideas:</p><p><strong>Target trial emulation.</strong> Before running any analysis, ask: “What A/B test would we ideally run to answer this question cleanly?” That imaginary experiment — even if it is too expensive or too slow to run in practice — pins down exactly what you are trying to measure and what assumptions need to hold for an observational analysis to be credible.</p><p><strong>Mandatory diagnostics.</strong> Every analysis must pass a checklist of statistical tests before the result is used to make decisions. These diagnostics catch the hidden biases that a simple regression will silently absorb and amplify.</p><p><strong>Human-augmenting agents.</strong> Software agents handle the repetitive, error-prone work: running diagnostics, checking for imbalances, iterating when something fails, and producing inspectable reports. Humans focus on the parts that require judgment: framing the right question, scrutinising the assumptions, and deciding what to do with the answer.</p><p>Together, these three ideas form an actor-critic loop. An Actor agent executes the analysis according to a rigid template. A Critic agent reviews the results, flags problems, and instructs the Actor to iterate. A human Principal sets the question and evaluates the final output.</p><h3>Translating the framework for B2C</h3><h3>Step 1 — Define the analysis as a target trial</h3><p>For every retention question, a B2C analyst (the Principal) should write a short analysis plan that answers:</p><ul><li><strong>Treatment:</strong> What is the feature, action, or intervention being studied? (e.g., “customer activates the mobile app within 7 days of signup”)</li><li><strong>Outcome:</strong> What retention metric are we measuring? (e.g., “subscription renewal at 90 days”)</li><li><strong>Potential confounders:</strong> What pre-treatment characteristics predict both the treatment and the outcome? This list should be written down explicitly before looking at any data.</li></ul><p>Writing the target trial first forces precision. “Does our referral program improve retention?” is too vague. “Does referring at least one friend within the first 30 days of subscription increase the probability of renewing at month 6, controlling for acquisition channel, plan tier, and first-week engagement?” is a question an agent can act on.</p><h3>Step 2 — Run the Actor agent</h3><p>The Actor agent’s job is to convert that analysis plan into a rigorous, executable specification and then run it. It uses a pre-approved toolkit doubly robust estimation, inverse propensity weighting, or similar methods rather than improvising an approach for each question. It produces:</p><ul><li>A full data spec mapping the analysis to available event tables and feature stores</li><li>An executed notebook with all intermediate outputs visible</li><li>A version-controlled report that a human can re-run independently</li></ul><p>Critically, the Actor does not just return a number. It runs the four diagnostics described below on every analysis, flags any failures, and applies a remediation playbook before reporting results.</p><h3>Step 3 — The four diagnostics every B2C analysis needs</h3><p>These are the tests that separate a credible estimate from a confident-sounding guess.</p><p><strong>Covariate balance.</strong> After weighting or matching, the treatment and control groups should look statistically similar on all pre-treatment characteristics. If customers who activated your referral feature are systematically heavier users, younger, or on higher-tier plans before the referral happens, those differences will contaminate your estimate. The standard threshold is a standardised mean difference below 0.2 for each covariate.</p><p><strong>Overlap.</strong> There must be a meaningful population of customers who could plausibly have either used or not used the feature. If your propensity model assigns near-zero probability of activation to 80% of your customer base, the analysis is extrapolating wildly for most customers. The standard check is that estimated propensity scores sit between 0.1 and 0.9. Customers outside that range are trimmed, and the result is reported as applying to the “overlapping population” an important caveat.</p><p><strong>Placebo outcome.</strong> Run the analysis on a metric measured before the treatment occurred prior-month login rate, pre-treatment purchase frequency, anything that the intervention logically cannot have caused. If the treatment group shows a statistically significant effect on this placebo outcome, the groups were already different before treatment, and the analysis is confounded.</p><p><strong>Sensitivity to hidden confounders.</strong> Even after passing the above three tests, there may be an unobserved variable something you did not capture in your data that explains both who uses the feature and who stays subscribed. Sensitivity analysis quantifies how strong such a hidden variable would need to be to overturn your conclusion. A result that survives only a very small amount of unmeasured confounding is fragile; a result that survives a large amount is robust.</p><h3>Step 4 — The Critic agent’s role</h3><p>After the Actor produces results and diagnostics, the Critic agent reviews the full output and writes a structured report that addresses:</p><ul><li>Are there confounders mentioned in the analysis plan that were not controlled for? Are there obvious ones that were not mentioned at all?</li><li>Do the diagnostic results support a credible estimate, or do they reveal bias?</li><li>What is the credibility level of the result — high confidence, flagged for review, or failed?</li><li>How does the estimand (the population for whom the effect was measured, after any trimming) differ from the full customer base?</li><li>What would the ideal A/B test look like, and how does this observational analysis compare to it?</li><li>What is at least one alternative way to measure this effect — a holdout experiment, an encouragement design, an instrumental variable?</li></ul><p>The Critic does not overrule the analysis. It surfaces the caveats and context that a decision-maker needs to use the result appropriately.</p><h3>Step 5 — Human review and approval</h3><p>The Principal reviews the Actor’s notebook and the Critic’s report. This review is not about re-running the statistics — it is about applying domain knowledge that neither agent has. Does the identified confounder list make business sense? Does the trimmed population reflect a strategically relevant segment? Is the alternative measurement strategy feasible in the next quarter?</p><p>Human judgment is irreplaceable at this stage. The agents reduce toil so that the human’s time is spent on these higher-order questions rather than on rechecking covariate balance plots manually.</p><h3>Common B2C retention questions and the biases to watch for</h3><p>The framework applies across virtually any B2C subscription vertical. The specific confounders differ, but the structure is the same.</p><p><strong>Feature adoption studies</strong> (onboarding checklists, in-app tutorials, premium tools)</p><p>The primary risk is early adopter bias. Customers who complete an onboarding checklist within the first three days are already highly motivated. A naive analysis will attribute their retention to the checklist rather than to their underlying engagement. The overlap check and placebo outcome test are especially important here. The Actor agent should flag if propensity scores cluster near zero or one, which indicates that “who completes onboarding” is nearly deterministic and the analysis cannot isolate the feature’s effect.</p><p><strong>Engagement feature studies</strong> (community forums, personalisation, content recommendations)</p><p>The confounders here are usually lifecycle-related. Customers who engage with a personalisation engine are often in the early months of their subscription, when retention is naturally higher. Controlling for subscription age, acquisition cohort, and session frequency before treatment is essential. The Critic agent should flag if the analysis plan omits these temporal confounders.</p><p><strong>Pricing and plan change studies</strong> (upsells, downgrades, pauses)</p><p>This is the most complex category because the treatment itself is often endogenous — customers who upgrade are more satisfied, and customers who downgrade are at risk. The target trial framing is especially useful here: the imaginary experiment would randomly assign plan tier to a representative sample. Any observational analysis must grapple with the fact that plan selection is driven by exactly the factors that predict retention. The Critic agent should always contrast the observational result against the ideal RCT design and note the gap.</p><p><strong>Loyalty and retention programme studies</strong> (rewards, winback campaigns, save offers)</p><p>Winback and save programmes introduce reverse causality: the customers who receive a save offer are precisely the customers most likely to cancel, which means a naive comparison will show that save offers reduce retention. The analysis must model the selection process that triggers the intervention. The placebo outcome test is critical — customers who receive a save offer were already behaving differently weeks before the intervention.</p><p><strong>Communication and notification studies</strong> (email frequency, push notifications, SMS)</p><p>Communication experiments are among the most tractable for B2C brands because they are relatively easy to randomise. The framework should be used to verify that any observational analysis — for example, studying customers who opted into push notifications — passes the full diagnostic suite before conclusions are drawn. When a proper experiment is feasible, the Critic agent should recommend it as the preferred alternative.</p><h3>What the agents handle automatically</h3><p>A key insight from Netflix’s deployment is that the most time-consuming parts of rigorous causal analysis are not the hardest parts intellectually they are just repetitive and error-prone when done manually. These include:</p><ul><li>Checking and rechecking covariate balance after each adjustment</li><li>Re-running the analysis with different trim thresholds to test stability</li><li>Repeating the same analysis across monthly date partitions to detect seasonality</li><li>Coordinating trimmed populations consistently across subgroup analyses</li></ul><p>An Agent-orchestrated system can run all of these automatically and flag results where conclusions change meaningfully across parameter choices. A retention effect that holds across all trim thresholds and all monthly partitions is a much more confident finding than one that appears only in a narrow slice of the data.</p><h3>The bias that trips up B2C brands most often: early feature adopters</h3><p>Netflix described early adopter bias in the context of a new entertainment type, and it is equally prevalent in B2C retention work. The first customers to use any new feature a loyalty dashboard, a health score tracker, a personalised recommendation feed are systematically different from the general subscriber base. They are more engaged, more technically comfortable, and more invested in getting value from the product. Their retention outcomes would likely be superior even without the feature.</p><p>When an observational analysis finds that feature users retain at a higher rate, the first question must always be: how much of that gap existed before the feature was introduced? The placebo outcome test is designed to answer exactly this. If feature adopters were already logging in more frequently, completing more actions, and contacting support less often in the weeks before the feature launched, then the retention advantage is not the feature’s — it was already there.</p><p>The Actor agent’s remediation playbook for this situation mirrors Netflix’s: trim the analysis to customers for whom feature adoption was non-deterministic (propensity scores between 0.1 and 0.9), report the ATE on that overlapping population, and instruct the Critic to note explicitly that the result does not generalise to customers with very high or very low propensity to adopt.</p><h3>Building the system: what you need</h3><p>The approach does not require building everything from scratch. The components are:</p><ul><li>A causal inference toolkit with doubly robust estimation (EconML, CausalML, or equivalent)</li><li>A templated analysis notebook that enforces the four diagnostics</li><li>An LLM-backed Actor agent that can read an analysis plan, populate the notebook template, execute it against your data warehouse, and write a structured output</li><li>An LLM-backed Critic agent that reviews the output and produces a credibility report</li><li>A versioning and artifact storage layer so that every analysis is reproducible</li></ul><p>The Principal’s interface can be as simple as a structured form: treatment definition, outcome metric, confounder list, data model reference. The rest is automated.</p><p>Netflix open-sourced a standalone version of their OCI agent that demonstrates these principles on public competition datasets. A B2C analytics team can use that codebase as a starting point and adapt the templated notebook to their own data model.</p><h3>A shift in how retention decisions get made</h3><p>The deeper change this framework enables is not technical — it is epistemic. It shifts the default question from “what correlates with retention?” to “what causes retention, and for which customers?”</p><p>Correlation-based retention analytics optimises for finding features that high-retention customers use. Causal retention analytics optimises for finding features that, if adopted by the marginal customer, would genuinely change their likelihood of staying.</p><p>These are different questions with different answers, and acting on the correlation answer with the causal question in mind is how B2C brands end up over-investing in features that serve already-loyal customers rather than converting the customers on the fence.</p><p>The human-augmenting agentic workflow exists to make the causal question answerable at scale not by removing human judgment, but by redirecting it toward the decisions that actually require it.</p><p><em>This framework is adapted from Netflix’s human-augmenting agentic workflow for observational causal inference, published June 2026. The approach is generalisable to any subscription business performing point-in-time causal analyses on customer behaviour.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f42a30a7368" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Solo to Squad: End-to-End Multi-Agent AI with Large Language Models]]></title>
            <link>https://medium.com/@itismohan.g/from-solo-to-squad-end-to-end-multi-agent-ai-with-large-language-models-9e806897bbd8?source=rss-b563fdb94f2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e806897bbd8</guid>
            <category><![CDATA[aidlc]]></category>
            <category><![CDATA[sdlc]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <dc:creator><![CDATA[Mohan Krishna G]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 15:42:03 GMT</pubDate>
            <atom:updated>2026-06-09T15:42:03.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The evolution of AI from single-model inference engines to collaborative, autonomous networks of specialised agents marks one of the most significant architectural shifts in modern software engineering. Large Language Models (LLMs) have demonstrated extraordinary capabilities in isolation, but the real power emerges when multiple agents, each with distinct roles and context, collaborate to solve complex, multi-step problems.</p><p>In this article, we will explore:</p><ul><li>What Multi-Agent AI Architecture is and why it matters</li><li>Core concepts: agents, tools, orchestration, and memory</li><li>Architectural patterns for multi-agent systems</li><li>An end-to-end implementation walkthrough using Python, LangGraph, and OpenAI</li><li>Real-world use cases, best practices, and challenges</li></ul><p>Whether you are a software architect, a QA engineer exploring AI-augmented testing, or a developer building the next generation of intelligent applications, this guide gives you a complete picture — from theory to working code.</p><h3>What Is a Multi-Agent AI System?</h3><p>A <strong>Multi-Agent AI System</strong> is a network of autonomous AI agents, each powered by an LLM, that collaborate to accomplish tasks that are too complex or too broad for a single model call to handle effectively.</p><p>Think of it like a well-run engineering team:</p><p>Role Agent Equivalent Project Manager <strong>Orchestrator Agent</strong> — breaks down goals, delegates tasks Developer <strong>Coder Agent</strong> — writes, debugs, and executes code QA Engineer <strong>Verifier Agent</strong> — validates outputs, runs checks Researcher <strong>Search Agent</strong> — retrieves information from external sources Reviewer <strong>Critic Agent</strong> — evaluates quality and flags issues</p><p>Each agent operates with its own system prompt, memory, and tool access — but they share a common goal, coordinated through a central orchestration layer.</p><h3>Why Multi-Agent Over Single-Agent?</h3><p>A single LLM call has inherent limitations:</p><ul><li><strong>Context window constraints</strong> — complex tasks exceed token limits</li><li><strong>Single-pass reasoning</strong> — no iteration, verification, or self-correction</li><li><strong>No specialisation</strong> — one model doing everything means no depth in any area</li><li><strong>Brittle failure</strong> — one mistake propagates through the entire result</li></ul><p>Multi-agent systems solve these by introducing:</p><ul><li><strong>Parallelism</strong> — multiple agents working simultaneously on sub-tasks</li><li><strong>Specialisation</strong> — each agent optimised for a narrow, well-defined task</li><li><strong>Verification loops</strong> — agents checking each other’s work</li><li><strong>Scalability</strong> — new agents can be added without re-architecting the whole system</li><li><strong>Resilience</strong> — failures in one agent can be caught and retried by others</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zs-yEdVsaCSVWyG4ZfAVXA.jpeg" /><figcaption>cc:chatgpt</figcaption></figure><h3>Core Concepts</h3><h3>1. Agent</h3><p>An <strong>agent</strong> is an LLM instance with:</p><ul><li>A <strong>system prompt</strong> defining its role, persona, and constraints</li><li>Access to one or more <strong>tools</strong> (functions it can call)</li><li>A <strong>memory</strong> component (short-term or long-term)</li><li>A <strong>reasoning loop</strong> — typically ReAct (Reason + Act) or Chain-of-Thought</li></ul><pre># Conceptual structure of an agent<br>class Agent:<br>    def __init__(self, name, system_prompt, tools, memory):<br>        self.name = name<br>        self.system_prompt = system_prompt<br>        self.tools = tools          # Functions the agent can invoke<br>        self.memory = memory        # Conversation history or vector store<br>    <br>    def run(self, user_input):<br>        # 1. Reason about the input<br>        # 2. Decide if a tool is needed<br>        # 3. Call the tool<br>        # 4. Incorporate result<br>        # 5. Return output or continue reasoning<br>        pass</pre><h3>2. Tools</h3><p>Tools are the <strong>hands</strong> of an agent — they allow agents to interact with the world beyond text generation:</p><ul><li><strong>Web search</strong> — retrieve live information</li><li><strong>Code execution</strong> — run Python, shell commands</li><li><strong>File I/O</strong> — read/write documents</li><li><strong>API calls</strong> — query databases, CRMs, external services</li><li><strong>Agent-to-agent calls</strong> — invoke another agent as a sub-task</li></ul><h3>3. Orchestrator</h3><p>The <strong>orchestrator</strong> is the central brain. It:</p><ul><li>Receives the high-level user goal</li><li>Decomposes it into sub-tasks</li><li>Routes each sub-task to the appropriate agent</li><li>Collects and synthesises results</li><li>Decides when the goal has been achieved</li></ul><p>Orchestration can be <strong>centralised</strong> (one master controller) or <strong>decentralised</strong> (agents elect a leader dynamically).</p><h3>4. Memory</h3><p>Agents need memory to maintain context across interactions:</p><p>Memory Type Description Example <strong>In-context (short-term)</strong> Conversation history within a single session Chat messages array <strong>Episodic (long-term)</strong> Stored summaries of past interactions Vector database <strong>Semantic</strong> Domain knowledge embeddings Pinecone, Chroma <strong>Procedural</strong> Learned workflows and action sequences Tool usage patterns</p><h3>5. Communication Protocol</h3><p>Agents communicate via <strong>structured messages</strong> — typically JSON schemas passed through the orchestrator. A common format:</p><pre>{<br>  &quot;from&quot;: &quot;orchestrator&quot;,<br>  &quot;to&quot;: &quot;coder_agent&quot;,<br>  &quot;task_id&quot;: &quot;T-042&quot;,<br>  &quot;instruction&quot;: &quot;Write a Python function to parse CSV files with error handling&quot;,<br>  &quot;context&quot;: &quot;Part of a data ingestion pipeline for financial records&quot;,<br>  &quot;expected_output&quot;: &quot;Python function with type hints and docstring&quot;<br>}</pre><h3>Multi-Agent Architectural Patterns</h3><h3>Pattern 1: Hub-and-Spoke (Centralised Orchestration)</h3><pre>                    ┌─────────────────┐<br>                    │   Orchestrator  │<br>                    │     (LLM)       │<br>                    └────────┬────────┘<br>           ┌─────────────────┼─────────────────┐<br>           ▼                 ▼                 ▼<br>    ┌──────────┐     ┌──────────┐     ┌──────────┐<br>    │  Search  │     │  Coder   │     │  Writer  │<br>    │  Agent   │     │  Agent   │     │  Agent   │<br>    └──────────┘     └──────────┘     └──────────┘</pre><p><strong>Best for:</strong> Well-defined tasks with clear sub-task boundaries. Simple to implement and debug.</p><h3>Pattern 2: Pipeline (Sequential Chain)</h3><pre>User Input → [Researcher] → [Analyst] → [Writer] → [Reviewer] → Output</pre><p><strong>Best for:</strong> Document generation, research reports, code review pipelines. Each stage transforms the output of the previous.</p><h3>Pattern 3: Hierarchical (Multi-Level Orchestration)</h3><pre>              [Top-Level Orchestrator]<br>                /                  \<br>    [Sub-Orchestrator A]    [Sub-Orchestrator B]<br>       /         \               /         \<br>  [Agent 1]  [Agent 2]    [Agent 3]   [Agent 4]</pre><p><strong>Best for:</strong> Large enterprise workflows where sub-domains have their own complexity (e.g., a research team + an engineering team operating in parallel).</p><h3>Pattern 4: Peer-to-Peer (Collaborative / Debate)</h3><pre>[Agent A] ←→ [Agent B] ←→ [Agent C]<br>      ↑                          ↑<br>      └──────────────────────────┘</pre><p><strong>Best for:</strong> Tasks requiring consensus, adversarial validation, or creative ideation. Agents critique and improve each other’s outputs.</p><h3>Pattern 5: Mixture of Experts (Dynamic Routing)</h3><pre>User Input → [Router Agent] → routes to one of →  [Expert A]<br>                                                     [Expert B]<br>                                                     [Expert C]</pre><p><strong>Best for:</strong> Broad-domain assistants where different questions require different specialist agents.</p><h3>End-to-End Implementation</h3><p>Let’s build a <strong>Multi-Agent Research and Report Generation System</strong> — a practical system that:</p><ol><li>Takes a research topic as input</li><li>Uses a <strong>Search Agent</strong> to gather information</li><li>Uses an <strong>Analyst Agent</strong> to synthesise insights</li><li>Uses a <strong>Writer Agent</strong> to produce a structured report</li><li>Uses a <strong>Critic Agent</strong> to review and improve the output</li></ol><p>We will use <strong>Python</strong>, <strong>LangGraph</strong> (for agent orchestration), <strong>OpenAI GPT-4o</strong>, and <strong>Tavily</strong> (for web search).</p><h3>Step 1: Environment Setup</h3><pre>pip install langgraph langchain langchain-openai langchain-community tavily-python python-dotenv<br><br># .env<br>OPENAI_API_KEY=your_openai_api_key<br>TAVILY_API_KEY=your_tavily_api_key</pre><h3>Step 2: Define Tools</h3><pre># tools.py<br>from langchain_community.tools.tavily_search import TavilySearchResults<br>from langchain_core.tools import tool<br><br># Web search tool<br>search_tool = TavilySearchResults(max_results=5)<br>@tool<br>def write_report(title: str, content: str) -&gt; str:<br>    &quot;&quot;&quot;Writes the final report to a file.&quot;&quot;&quot;<br>    with open(f&quot;{title.replace(&#39; &#39;, &#39;_&#39;)}_report.md&quot;, &quot;w&quot;) as f:<br>        f.write(f&quot;# {title}\n\n{content}&quot;)<br>    return f&quot;Report written: {title}&quot;<br>@tool<br>def critique_text(text: str, criteria: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Returns structured critique of a given text based on criteria.<br>    Criteria examples: &#39;accuracy&#39;, &#39;clarity&#39;, &#39;completeness&#39;<br>    &quot;&quot;&quot;<br>    # In a real implementation, this calls another LLM pass<br>    return f&quot;Critique requested on: {criteria}&quot;</pre><h3>Step 3: Define Agent State</h3><pre># state.py<br>from typing import TypedDict, Annotated, List<br>from langchain_core.messages import BaseMessage<br>import operator<br><br>class AgentState(TypedDict):<br>    &quot;&quot;&quot;Shared state passed between agents in the graph.&quot;&quot;&quot;<br>    topic: str                                          # The research topic<br>    search_results: List[str]                          # Raw search outputs<br>    analysis: str                                      # Synthesised insights<br>    draft_report: str                                  # Initial report draft<br>    critique: str                                      # Critic agent feedback<br>    final_report: str                                  # Revised final output<br>    messages: Annotated[List[BaseMessage], operator.add]  # Full message history<br>    iteration: int                                     # Revision loop counter</pre><h3>Step 4: Build Individual Agents</h3><pre># agents.py<br>from langchain_openai import ChatOpenAI<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.messages import SystemMessage, HumanMessage<br><br><br>llm = ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0)<br># ── Search Agent ────────────────────────────────────────────────────────────<br>def search_agent(state: AgentState) -&gt; AgentState:<br>    &quot;&quot;&quot;Searches the web and populates search_results.&quot;&quot;&quot;<br>    print(f&quot;\n[Search Agent] Researching: {state[&#39;topic&#39;]}&quot;)<br>    <br>    results = search_tool.invoke({&quot;query&quot;: state[&quot;topic&quot;]})<br>    <br>    # Extract and clean content<br>    search_results = [<br>        f&quot;Source: {r[&#39;url&#39;]}\nContent: {r[&#39;content&#39;]}&quot;<br>        for r in results<br>    ]<br>    <br>    return {**state, &quot;search_results&quot;: search_results}<br><br># ── Analyst Agent ────────────────────────────────────────────────────────────<br>def analyst_agent(state: AgentState) -&gt; AgentState:<br>    &quot;&quot;&quot;Synthesises search results into key insights.&quot;&quot;&quot;<br>    print(&quot;\n[Analyst Agent] Analysing search results...&quot;)<br>    <br>    prompt = ChatPromptTemplate.from_messages([<br>        SystemMessage(content=&quot;&quot;&quot;You are a senior research analyst.<br>        Your job is to synthesise information from multiple sources into <br>        clear, structured insights. Identify key themes, data points, <br>        and emerging trends. Be factual and cite sources where relevant.&quot;&quot;&quot;),<br>        HumanMessage(content=f&quot;&quot;&quot;<br>        Topic: {state[&#39;topic&#39;]}<br>        <br>        Search Results:<br>        {&#39;---&#39;.join(state[&#39;search_results&#39;])}<br>        <br>        Provide a structured analysis with:<br>        1. Key Findings (bullet points)<br>        2. Emerging Trends<br>        3. Important Data Points<br>        4. Knowledge Gaps or Caveats<br>        &quot;&quot;&quot;)<br>    ])<br>    <br>    response = llm.invoke(prompt.format_messages())<br>    return {**state, &quot;analysis&quot;: response.content}<br><br># ── Writer Agent ─────────────────────────────────────────────────────────────<br>def writer_agent(state: AgentState) -&gt; AgentState:<br>    &quot;&quot;&quot;Converts analysis into a polished report draft.&quot;&quot;&quot;<br>    print(&quot;\n[Writer Agent] Drafting report...&quot;)<br>    <br>    prompt = ChatPromptTemplate.from_messages([<br>        SystemMessage(content=&quot;&quot;&quot;You are a professional technical writer.<br>        Transform research analysis into a well-structured, engaging report.<br>        Use clear headings, concise paragraphs, and actionable takeaways.<br>        Write for a technically informed but non-specialist audience.&quot;&quot;&quot;),<br>        HumanMessage(content=f&quot;&quot;&quot;<br>        Topic: {state[&#39;topic&#39;]}<br>        Analysis: {state[&#39;analysis&#39;]}<br>        <br>        Write a comprehensive report with:<br>        - Executive Summary<br>        - Introduction<br>        - Key Findings (with sub-sections)<br>        - Implications and Applications<br>        - Conclusion<br>        - References or Further Reading<br>        &quot;&quot;&quot;)<br>    ])<br>    <br>    response = llm.invoke(prompt.format_messages())<br>    return {**state, &quot;draft_report&quot;: response.content}<br><br># ── Critic Agent ──────────────────────────────────────────────────────────────<br>def critic_agent(state: AgentState) -&gt; AgentState:<br>    &quot;&quot;&quot;Reviews the draft and provides improvement feedback.&quot;&quot;&quot;<br>    print(&quot;\n[Critic Agent] Reviewing draft...&quot;)<br>    <br>    prompt = ChatPromptTemplate.from_messages([<br>        SystemMessage(content=&quot;&quot;&quot;You are a rigorous editorial reviewer.<br>        Your job is to identify weaknesses in a report and provide <br>        specific, actionable feedback. Focus on accuracy, completeness,<br>        clarity, logical flow, and practical value.&quot;&quot;&quot;),<br>        HumanMessage(content=f&quot;&quot;&quot;<br>        Review this report draft and provide specific feedback:<br>        <br>        {state[&#39;draft_report&#39;]}<br>        <br>        Evaluate:<br>        1. Accuracy - Are claims well-supported?<br>        2. Completeness - Are there missing perspectives?<br>        3. Clarity - Is the writing clear and jargon-free?<br>        4. Structure - Does it flow logically?<br>        5. Value - Does it give actionable insights?<br>        <br>        Score each dimension 1-10 and list specific improvements.<br>        If ALL scores are 8+, respond with &quot;APPROVED&quot;.<br>        &quot;&quot;&quot;)<br>    ])<br>    <br>    response = llm.invoke(prompt.format_messages())<br>    return {**state, &quot;critique&quot;: response.content}<br><br># ── Reviser Agent ─────────────────────────────────────────────────────────────<br>def reviser_agent(state: AgentState) -&gt; AgentState:<br>    &quot;&quot;&quot;Revises the draft based on critic feedback.&quot;&quot;&quot;<br>    print(&quot;\n[Reviser Agent] Incorporating feedback...&quot;)<br>    <br>    prompt = ChatPromptTemplate.from_messages([<br>        SystemMessage(content=&quot;&quot;&quot;You are a skilled editor. Revise the draft <br>        report based on the critique provided. Implement all specific <br>        suggestions while preserving the original structure and intent.&quot;&quot;&quot;),<br>        HumanMessage(content=f&quot;&quot;&quot;<br>        Original Draft:<br>        {state[&#39;draft_report&#39;]}<br>        <br>        Critique and Feedback:<br>        {state[&#39;critique&#39;]}<br>        <br>        Please produce a revised, improved version of the report.<br>        &quot;&quot;&quot;)<br>    ])<br>    <br>    response = llm.invoke(prompt.format_messages())<br>    return {<br>        **state,<br>        &quot;draft_report&quot;: response.content,<br>        &quot;final_report&quot;: response.content,<br>        &quot;iteration&quot;: state.get(&quot;iteration&quot;, 0) + 1<br>    }</pre><h3>Step 5: Build the Orchestration Graph</h3><pre># graph.py<br>from langgraph.graph import StateGraph, END<br>from agents import search_agent, analyst_agent, writer_agent, critic_agent, reviser_agent<br>from state import AgentState<br><br>def should_revise(state: AgentState) -&gt; str:<br>    &quot;&quot;&quot;<br>    Routing function: decides whether to revise or finalise.<br>    If critique contains &#39;APPROVED&#39; or max iterations reached, go to END.<br>    &quot;&quot;&quot;<br>    if &quot;APPROVED&quot; in state.get(&quot;critique&quot;, &quot;&quot;):<br>        print(&quot;\n[Orchestrator] Report approved. Finalising...&quot;)<br>        return &quot;finalise&quot;<br>    <br>    if state.get(&quot;iteration&quot;, 0) &gt;= 2:<br>        print(&quot;\n[Orchestrator] Max iterations reached. Finalising...&quot;)<br>        return &quot;finalise&quot;<br>    <br>    print(f&quot;\n[Orchestrator] Revision needed. Iteration {state.get(&#39;iteration&#39;, 0) + 1}&quot;)<br>    return &quot;revise&quot;<br><br>def finalise(state: AgentState) -&gt; AgentState:<br>    &quot;&quot;&quot;Sets the final approved report.&quot;&quot;&quot;<br>    return {**state, &quot;final_report&quot;: state[&quot;draft_report&quot;]}<br><br># ── Build the Graph ───────────────────────────────────────────────────────────<br>def build_graph():<br>    graph = StateGraph(AgentState)<br>    <br>    # Add nodes (agents)<br>    graph.add_node(&quot;search&quot;,   search_agent)<br>    graph.add_node(&quot;analyse&quot;,  analyst_agent)<br>    graph.add_node(&quot;write&quot;,    writer_agent)<br>    graph.add_node(&quot;critique&quot;, critic_agent)<br>    graph.add_node(&quot;revise&quot;,   reviser_agent)<br>    graph.add_node(&quot;finalise&quot;, finalise)<br>    <br>    # Define the flow<br>    graph.set_entry_point(&quot;search&quot;)<br>    graph.add_edge(&quot;search&quot;,   &quot;analyse&quot;)<br>    graph.add_edge(&quot;analyse&quot;,  &quot;write&quot;)<br>    graph.add_edge(&quot;write&quot;,    &quot;critique&quot;)<br>    <br>    # Conditional routing after critique<br>    graph.add_conditional_edges(<br>        &quot;critique&quot;,<br>        should_revise,<br>        {<br>            &quot;revise&quot;:   &quot;revise&quot;,<br>            &quot;finalise&quot;: &quot;finalise&quot;<br>        }<br>    )<br>    <br>    # After revision, critique again<br>    graph.add_edge(&quot;revise&quot;,   &quot;critique&quot;)<br>    graph.add_edge(&quot;finalise&quot;, END)<br>    <br>    return graph.compile()</pre><h3>Step 6: Run the System</h3><pre># main.py<br>from graph import build_graph<br>from state import AgentState<br><br>def run_research_pipeline(topic: str):<br>    &quot;&quot;&quot;Entry point for the multi-agent research pipeline.&quot;&quot;&quot;<br>    <br>    print(f&quot;\n{&#39;=&#39;*60}&quot;)<br>    print(f&quot;  MULTI-AGENT RESEARCH PIPELINE&quot;)<br>    print(f&quot;  Topic: {topic}&quot;)<br>    print(f&quot;{&#39;=&#39;*60}\n&quot;)<br>    <br>    graph = build_graph()<br>    <br>    # Initialise state<br>    initial_state: AgentState = {<br>        &quot;topic&quot;: topic,<br>        &quot;search_results&quot;: [],<br>        &quot;analysis&quot;: &quot;&quot;,<br>        &quot;draft_report&quot;: &quot;&quot;,<br>        &quot;critique&quot;: &quot;&quot;,<br>        &quot;final_report&quot;: &quot;&quot;,<br>        &quot;messages&quot;: [],<br>        &quot;iteration&quot;: 0<br>    }<br>    <br>    # Execute the graph<br>    final_state = graph.invoke(initial_state)<br>    <br>    # Save output<br>    output_file = f&quot;{topic.replace(&#39; &#39;, &#39;_&#39;)[:30]}_report.md&quot;<br>    with open(output_file, &quot;w&quot;) as f:<br>        f.write(final_state[&quot;final_report&quot;])<br>    <br>    print(f&quot;\n{&#39;=&#39;*60}&quot;)<br>    print(f&quot;  PIPELINE COMPLETE&quot;)<br>    print(f&quot;  Report saved to: {output_file}&quot;)<br>    print(f&quot;  Total revisions: {final_state[&#39;iteration&#39;]}&quot;)<br>    print(f&quot;{&#39;=&#39;*60}\n&quot;)<br>    <br>    return final_state[&quot;final_report&quot;]<br><br>if __name__ == &quot;__main__&quot;:<br>    report = run_research_pipeline(<br>        &quot;The impact of AI agents on software quality engineering in 2024-2025&quot;<br>    )<br>    print(report[:500] + &quot;...&quot;)</pre><h3>Sample Execution Output</h3><pre>============================================================<br>  MULTI-AGENT RESEARCH PIPELINE<br>  Topic: The impact of AI agents on software quality engineering<br>============================================================<br>[Search Agent] Researching: The impact of AI agents on software quality...<br>  ✓ Retrieved 5 sources<br>[Analyst Agent] Analysing search results...<br>  ✓ Identified 4 key themes, 3 trends<br>[Writer Agent] Drafting report...<br>  ✓ Draft complete (1,847 words)<br>[Critic Agent] Reviewing draft...<br>  Accuracy: 8/10<br>  Completeness: 6/10   ← needs improvement<br>  Clarity: 9/10<br>  Structure: 8/10<br>  Value: 7/10<br>[Orchestrator] Revision needed. Iteration 1<br>[Reviser Agent] Incorporating feedback...<br>  ✓ Revised draft ready<br>[Critic Agent] Reviewing revised draft...<br>  APPROVED<br>[Orchestrator] Report approved. Finalising...<br>============================================================<br>  PIPELINE COMPLETE<br>  Report saved to: ai_agents_quality_report.md<br>  Total revisions: 1<br>============================================================</pre><h3>Advanced Patterns</h3><h3>Parallel Agent Execution</h3><p>When sub-tasks are independent, run agents in parallel for speed:</p><pre>import asyncio<br><br>async def run_parallel_agents(state):<br>    &quot;&quot;&quot;Run multiple independent agents concurrently.&quot;&quot;&quot;<br>    <br>    results = await asyncio.gather(<br>        search_agent_async(state, query=&quot;AI testing tools 2025&quot;),<br>        search_agent_async(state, query=&quot;test automation frameworks LLM&quot;),<br>        search_agent_async(state, query=&quot;quality engineering AI trends&quot;),<br>    )<br>    <br>    combined_results = []<br>    for result in results:<br>        combined_results.extend(result[&quot;search_results&quot;])<br>    <br>    return {**state, &quot;search_results&quot;: combined_results}</pre><h3>Agent Memory with Vector Store</h3><pre>from langchain_community.vectorstores import Chroma<br>from langchain_openai import OpenAIEmbeddings<br><br># Long-term memory for agents<br>memory_store = Chroma(<br>    collection_name=&quot;agent_memory&quot;,<br>    embedding_function=OpenAIEmbeddings()<br>)<br>def remember(agent_name: str, content: str, metadata: dict):<br>    &quot;&quot;&quot;Store an agent&#39;s output in long-term memory.&quot;&quot;&quot;<br>    memory_store.add_texts(<br>        texts=[content],<br>        metadatas=[{&quot;agent&quot;: agent_name, **metadata}]<br>    )<br>def recall(query: str, agent_filter: str = None, k: int = 3):<br>    &quot;&quot;&quot;Retrieve relevant memories for context.&quot;&quot;&quot;<br>    filter_dict = {&quot;agent&quot;: agent_filter} if agent_filter else None<br>    return memory_store.similarity_search(query, k=k, filter=filter_dict)</pre><h3>Human-in-the-Loop</h3><pre>from langgraph.checkpoint.memory import MemorySaver<br><br># Add a checkpoint for human approval<br>def human_review_node(state: AgentState) -&gt; AgentState:<br>    &quot;&quot;&quot;Pause execution and wait for human input.&quot;&quot;&quot;<br>    print(&quot;\n[HUMAN REVIEW REQUIRED]&quot;)<br>    print(&quot;Current draft:&quot;)<br>    print(state[&quot;draft_report&quot;][:500] + &quot;...&quot;)<br>    <br>    decision = input(&quot;\nApprove (a), Request changes (c), or Abort (x)? &quot;).lower()<br>    <br>    if decision == &quot;a&quot;:<br>        return {**state, &quot;critique&quot;: &quot;APPROVED&quot;}<br>    elif decision == &quot;c&quot;:<br>        feedback = input(&quot;Enter feedback: &quot;)<br>        return {**state, &quot;critique&quot;: feedback}<br>    else:<br>        raise SystemExit(&quot;Pipeline aborted by user.&quot;)</pre><h3>Real-World Use Cases</h3><h3>1. AI-Augmented QA Engineering</h3><p>Multi-agent systems can <strong>transform software testing</strong>:</p><ul><li><strong>Test Generation Agent</strong> — reads source code and generates test cases</li><li><strong>Execution Agent</strong> — runs tests, captures results</li><li><strong>Defect Analysis Agent</strong> — classifies failures, suggests root causes</li><li><strong>Reporting Agent</strong> — produces test summary dashboards and stakeholder reports</li></ul><h3>2. Financial Analysis</h3><ul><li><strong>Data Collection Agent</strong> — pulls market data, earnings reports</li><li><strong>Quant Agent</strong> — runs quantitative models</li><li><strong>Risk Agent</strong> — evaluates portfolio exposure</li><li><strong>Narrative Agent</strong> — writes investor briefings</li></ul><h3>3. Software Development Assistants</h3><ul><li><strong>PM Agent</strong> — creates user stories from requirements</li><li><strong>Architect Agent</strong> — proposes system design</li><li><strong>Coder Agent</strong> — generates implementation</li><li><strong>Reviewer Agent</strong> — performs code review</li><li><strong>Test Agent</strong> — writes test cases</li></ul><h3>4. Customer Support Automation</h3><ul><li><strong>Classifier Agent</strong> — categorises the ticket</li><li><strong>Knowledge Agent</strong> — retrieves relevant documentation</li><li><strong>Resolution Agent</strong> — drafts a response</li><li><strong>Escalation Agent</strong> — decides if human escalation is needed</li></ul><h3>Challenges and Best Practices</h3><h3>Challenges</h3><p>Challenge Description <strong>Prompt Drift</strong> Agents may deviate from their role over long sessions <strong>Hallucination Propagation</strong> One agent’s error compounds through the pipeline <strong>Cost &amp; Latency</strong> Multiple LLM calls increase both significantly <strong>Infinite Loops</strong> Circular agent dependencies without exit conditions <strong>State Management</strong> Passing large contexts between agents risks token overflow</p><h3>Best Practices</h3><p><strong>Design clear agent boundaries.</strong> Each agent should have a single, well-defined responsibility. Overlap creates confusion and unpredictable behaviour.</p><p><strong>Use structured outputs.</strong> Force agents to respond in JSON schemas using response_format={&quot;type&quot;: &quot;json_object&quot;}. This makes parsing reliable and reduces hallucination in handoffs.</p><p><strong>Always define exit conditions.</strong> Every agent loop needs a hard maximum iteration count and a clear success condition. Never rely solely on LLM judgment to terminate.</p><p><strong>Implement observability from day one.</strong> Log every agent call, token count, latency, and decision. Tools like LangSmith, Arize, or custom OpenTelemetry pipelines are essential in production.</p><p><strong>Test agents in isolation first.</strong> Validate each agent individually before integrating — unit test your agents just as you would any software component.</p><p><strong>Use temperature strategically.</strong> Set temperature to 0 for agents doing analysis or code generation (determinism), and slightly higher (0.5–0.8) for agents doing creative writing or ideation.</p><p><strong>Implement retries with exponential backoff.</strong> LLM APIs are not 100% reliable. Wrap every agent call in retry logic to handle rate limits and transient failures gracefully.</p><h3>Ecosystem and Tools</h3><p>Tool Purpose <strong>LangGraph</strong> Stateful agent orchestration, cycles, conditionals <strong>LangChain</strong> Agent building blocks, tools, memory, chains <strong>AutoGen (Microsoft)</strong> Conversational multi-agent framework <strong>CrewAI</strong> Role-based agent crews with task delegation <strong>OpenAI Assistants API</strong> Managed agent with threads and tool use <strong>Semantic Kernel</strong> Enterprise multi-agent orchestration (.NET/Python) <strong>LlamaIndex</strong> Agent workflows with document intelligence <strong>LangSmith</strong> Observability and testing for LLM pipelines</p><h3>The Road Ahead</h3><p>Multi-agent AI systems are still in their early innings. Several developments will shape the next generation:</p><p><strong>Standardised Agent Communication Protocols</strong> : Initiatives like Anthropic’s Model Context Protocol (MCP) are establishing shared standards for how agents discover and interact with tools and data sources, reducing integration friction dramatically.</p><p><strong>Agent Memory and Long-Horizon Tasks: </strong>As memory architectures mature, agents will maintain coherent context across days and weeks — enabling truly autonomous, long-running workflows.</p><p><strong>Self-Improving Agent Networks: </strong>Agents that observe their own performance, identify failure patterns, and update their prompts or tool configurations without human intervention.</p><p><strong>Tighter Integration with Traditional Software: </strong>Multi-agent systems will increasingly be embedded directly into CI/CD pipelines, ERP systems, and enterprise workflows — not as standalone tools but as intelligent layers within existing infrastructure.</p><h3>Conclusion</h3><p>Multi-Agent AI Architecture represents a fundamental evolution in how we build intelligent systems. By decomposing complex problems into specialised, collaborative agents each with clear roles, tools, and memory. we unlock capabilities that are simply beyond the reach of any single model call.</p><p>The implementation pattern we explored here a sequential pipeline with a review-and-revision loop is just one of many configurations. The real power comes from matching your architectural pattern to your problem: parallel execution for speed, hierarchical orchestration for complexity, peer-to-peer debate for accuracy.</p><p>For engineering leaders and practitioners, the opportunity is clear: multi-agent systems are not a research curiosity but a production-ready paradigm. The teams that master this architecture today will build the intelligent applications that define tomorrow.</p><h3>Further Reading and References</h3><ul><li>LangGraph Documentation — <a href="https://python.langchain.com/docs/langgraph">python.langchain.com/docs/langgraph</a></li><li>AutoGen by Microsoft — <a href="https://microsoft.github.io/autogen">microsoft.github.io/autogen</a></li><li>CrewAI Framework — <a href="https://crewai.com/">crewai.com</a></li><li>OpenAI Assistants API — <a href="https://platform.openai.com/docs/assistants">platform.openai.com/docs/assistants</a></li><li>Anthropic Model Context Protocol — <a href="https://modelcontextprotocol.io/">modelcontextprotocol.io</a></li><li><em>ReAct: Synergizing Reasoning and Acting in Language Models</em> — Yao et al., 2022</li><li><em>Communicative Agents for Software Development</em> — Qian et al., 2023 (ChatDev paper)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e806897bbd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLMs vs SLMs: The Shift Reshaping AI Engineering]]></title>
            <link>https://medium.com/@itismohan.g/llms-vs-slms-the-shift-reshaping-ai-engineering-312d655c0b16?source=rss-b563fdb94f2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/312d655c0b16</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[custom-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Mohan Krishna G]]></dc:creator>
            <pubDate>Thu, 28 May 2026 18:35:46 GMT</pubDate>
            <atom:updated>2026-05-28T18:35:46.602Z</atom:updated>
            <content:encoded><![CDATA[<p>As small language models mature, engineers are rethinking when to reach for a 70B parameter giant — and when a 1B model running on a laptop is the smarter choice.</p><p>For the past few years, the dominant narrative in AI has been simple: bigger is better. More parameters, more compute, more capability. But 2025 quietly marked a turning point. Small Language Models (SLMs) — compact, efficient, often fine-tuned — began outperforming their massive siblings on narrow, well-defined tasks. The era of “right-sized AI” had arrived.</p><p>This article maps the key differences between LLMs and SLMs, then digs into how SLMs are reshaping what AI engineers actually build day-to-day.</p><h3>What separates a Large from a Small language model?</h3><p>The boundary isn’t fixed, but in practice the industry treats models under ~7 billion parameters as “small.” Models like GPT-4, Claude Opus, and Gemini Ultra sit at the LLM end — trained on trillions of tokens, capable of near-universal reasoning. SLMs like Phi-3-mini (3.8B), Gemma 2B, and Mistral 7B are the counterpart: lighter, faster, and deployable almost anywhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JYSu7Ud7UNG7fC2iaxS9Q.jpeg" /><figcaption>cc:chatGPT</figcaption></figure><h3>How SLMs are changing what engineers build</h3><p>The practical implications are enormous. When an inference call costs 100x less and runs locally, entire categories of product become viable. Real-time text suggestions in a mobile app. Private document processing that never leaves the laptop. Embedded AI in factory hardware. Here are the patterns emerging in production.</p><p><em>“The most important question in AI engineering is no longer ‘can the model do this?’ — it’s ‘what’s the cheapest model that does this well enough?’”</em></p><h3>Pattern 1: Model routing — send tasks to the right tier</h3><p>The most immediately impactful SLM pattern is routing: classify an incoming request and dispatch it to the cheapest capable model. Simple queries hit a local SLM; complex ones escalate to an LLM API.</p><p>PythonTiered model router</p><pre># llm_router.py — route queries by complexity<br>from transformers import pipeline<br>import anthropic<br><br># Local SLM for simple tasks (runs on CPU)<br>local_model = pipeline(<br>    &quot;text-generation&quot;,<br>    model=&quot;microsoft/Phi-3-mini-4k-instruct&quot;,<br>    device=&quot;cpu&quot;<br>)<br># Cloud LLM for complex reasoning<br>cloud_client = anthropic.Anthropic()<br>def classify_complexity(query: str) -&gt; str:<br>    &quot;&quot;&quot;Use a tiny classifier to decide routing.&quot;&quot;&quot;<br>    keywords = [&quot;analyze&quot;, &quot;compare&quot;, &quot;reason&quot;, &quot;strategy&quot;]<br>    return &quot;complex&quot; if any(k in query.lower() for k in keywords) else &quot;simple&quot;<br>def smart_complete(query: str) -&gt; str:<br>    tier = classify_complexity(query)<br>    if tier == &quot;simple&quot;:<br>        result = local_model(query, max_new_tokens=200)[0]<br>        return result[&quot;generated_text&quot;]<br>    # Escalate to LLM - costs more but handles depth<br>    msg = cloud_client.messages.create(<br>        model=&quot;claude-sonnet-4-20250514&quot;,<br>        max_tokens=1024,<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query}]<br>    )<br>    return msg.content[0].text</pre><p>Engineering note: In production, the classifier itself is often a tiny fine-tuned BERT model or even a rules-based heuristic — keeping the routing decision sub-millisecond. The goal is to avoid paying LLM costs on requests a small model handles well.</p><h3>Pattern 2:On-device inference — no API, no latency, no data leaks</h3><p>SLMs have made fully local inference practical. With quantisation (reducing model weights to 4-bit integers), a 7B model fits in 4GB of RAM and runs on consumer hardware. This unlocks offline use cases and eliminates privacy concerns around sending data to third-party APIs.</p><p>Python4-bit quantised local inference with llama.cpp</p><pre># on_device.py — run SLM locally, no internet required<br>from llama_cpp import Llama<br><br># Load quantized model (GGUF format, ~4GB on disk)<br>llm = Llama.from_pretrained(<br>    repo_id=&quot;bartowski/Phi-3-mini-4k-instruct-GGUF&quot;,<br>    filename=&quot;Phi-3-mini-4k-instruct-Q4_K_M.gguf&quot;,<br>    n_ctx=4096,<br>    n_threads=4<br>)<br>def local_summarize(document: str) -&gt; str:<br>    &quot;&quot;&quot;Summarize a document entirely on-device.&quot;&quot;&quot;<br>    prompt = f&quot;Summarize this in 3 bullet points:\n\n{document}&quot;<br>    output = llm(<br>        prompt,<br>        max_tokens=256,<br>        temperature=0.1,<br>        stop=[&quot;\n\n&quot;]<br>    )<br>    return output[&quot;choices&quot;][0][&quot;text&quot;]<br># Works offline - no API keys, no data leaves the machine<br>summary = local_summarize(&quot;[confidential HR document]&quot;)<br>print(summary</pre><h3>Pattern 3 : Fine-tuning SLMs for domain-specific tasks</h3><p>One of the biggest advantages of SLMs is how cheaply they can be fine-tuned. Using LoRA (Low-Rank Adaptation), engineers can specialize a small model on domain data in hours on a single GPU — producing a model that consistently outperforms a general-purpose LLM on that narrow task.</p><p>PythonFine-tuning with LoRA via Hugging Face PEFT</p><pre>from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments<br>from peft import get_peft_model, LoraConfig, TaskType<br>from trl import SFTTrainer<br>from datasets import load_dataset<br><br># Base SLM - 3.8B params, fast to fine-tune<br>model_id = &quot;microsoft/Phi-3-mini-4k-instruct&quot;<br>model = AutoModelForCausalLM.from_pretrained(model_id)<br>tokenizer = AutoTokenizer.from_pretrained(model_id)<br># LoRA config - only train ~1% of parameters<br>lora_config = LoraConfig(<br>    task_type=TaskType.CAUSAL_LM,<br>    r=16,              # rank of update matrices<br>    lora_alpha=32,<br>    target_modules=[&quot;q_proj&quot;, &quot;v_proj&quot;],<br>    lora_dropout=0.05<br>)<br>peft_model = get_peft_model(model, lora_config)<br>peft_model.print_trainable_parameters()<br># → trainable params: 1,720,320 (0.044% of 3.8B)<br># Your domain data - e.g. medical Q&amp;A, legal clauses<br>dataset = load_dataset(&quot;json&quot;, data_files=&quot;domain_data.jsonl&quot;)<br>trainer = SFTTrainer(<br>    model=peft_model,<br>    train_dataset=dataset[&quot;train&quot;],<br>    args=TrainingArguments(<br>        output_dir=&quot;./fine-tuned-slm&quot;,<br>        num_train_epochs=3,<br>        per_device_train_batch_size=4,<br>        learning_rate=2e-4<br>    )<br>)<br>trainer.train()<br># Saves adapter weights (~50MB) - merge or serve separately</pre><h3>Pattern 4: SLM-powered agents on the edge</h3><p>SLMs are enabling a new class of agents that run entirely on edge devices — phones, IoT hardware, embedded systems. The agent loop (perceive → reason → act) is lightweight enough to run at interactive speeds without a cloud round-trip.</p><p>PythonMinimal tool-use agent with a local SLM</p><pre>import json<br>from llama_cpp import Llama<br><br>llm = Llama.from_pretrained(<br>    repo_id=&quot;bartowski/Phi-3-mini-4k-instruct-GGUF&quot;,<br>    filename=&quot;Phi-3-mini-4k-instruct-Q4_K_M.gguf&quot;<br>)<br>TOOLS = {<br>    &quot;get_sensor&quot;: lambda: {&quot;temp_c&quot;: 24.3, &quot;humidity&quot;: 61},<br>    &quot;set_fan&quot;: lambda speed: {&quot;status&quot;: f&quot;fan set to {speed}%&quot;}<br>}<br>SYSTEM = &quot;&quot;&quot;You control a climate system.<br>Available tools: get_sensor(), set_fan(speed: int).<br>Respond ONLY with JSON: {&quot;tool&quot;: &quot;name&quot;, &quot;args&quot;: {...}}<br>or {&quot;response&quot;: &quot;text&quot;}&quot;&quot;&quot;<br>def run_agent(user_msg: str):<br>    prompt = f&quot;[SYSTEM]{SYSTEM}[USER]{user_msg}[ASSISTANT]&quot;<br>    for _ in range(5):   # max 5 tool turns<br>        out = llm(prompt, max_tokens=128)[&quot;choices&quot;][0][&quot;text&quot;]<br>        action = json.loads(out)<br>        if &quot;response&quot; in action:<br>            return action[&quot;response&quot;]<br>        fn = TOOLS[action[&quot;tool&quot;]]<br>        result = fn(**action.get(&quot;args&quot;, {}))<br>        prompt += f&quot;{out}\n[TOOL]{json.dumps(result)}[ASSISTANT]&quot;<br>run_agent(&quot;Is the room too warm? Adjust the fan if needed.&quot;)</pre><h3>When to Use Which: Choosing the right model for your use case</h3><p>Neither LLMs nor SLMs are universally better. The right choice depends on your constraints. Here’s a quick guide for common engineering scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZfG6J1E5rpL1nv2QEHj0Q.jpeg" /><figcaption>cc:chatGPT</figcaption></figure><h3>Closing Thoughts: The future is tiered, not uniform</h3><p>The maturation of SLMs doesn’t spell the end for large models — it specialises them. LLMs remain indispensable for the hardest reasoning tasks, the most open-ended generation, and anything requiring broad world knowledge. But SLMs are claiming a growing share of production workloads: the classification tasks, the real-time suggestions, the offline processing, the privacy-sensitive pipelines.</p><p>The most effective AI engineers in 2026 don’t default to the biggest available model. They think in tiers: run what’s sufficient, escalate when needed, fine-tune when volume justifies it. That instinct — matching model size to task complexity — is increasingly the difference between a scalable AI product and an expensive one.</p><blockquote>The SLM toolkit in brief: Phi-3 / Phi-4 (Microsoft) for reasoning tasks, Gemma 2B/7B (Google) for open-source deployment, Mistral 7B for instruction following, TinyLlama for ultra-constrained environments. Fine-tune with LoRA via Hugging Face PEFT. Serve locally with llama.cpp or Ollama.</blockquote><h3>References</h3><p>Here are well-curated references across research papers, technical reports, and practitioner resources mapped directly to the topics covered in the article:</p><h3>Research Papers</h3><p><strong>1. SLMs in Agentic AI</strong> Belcak, P. et al. (NVIDIA, 2025). <em>Small Language Models are the Future of Agentic AI.</em> → <a href="https://arxiv.org/abs/2506.02153">arxiv.org/abs/2506.02153</a> Argues that LLMs are ill-suited for repetitive agentic tasks and proposes SLMs as the natural fit — with a concrete LLM-to-SLM conversion algorithm and an economic case for the shift.</p><p><strong>2. SLM Survey &amp; Benchmarks</strong> <em>Small Language Models: Survey, Measurements, and Insights</em> (2024) → <a href="https://arxiv.org/abs/2409.15790">arxiv.org/abs/2409.15790</a> Surveys 70 open-source SLMs in the 100M–5B parameter range, analysing architecture, training datasets, and benchmarks across common sense reasoning, math, and long-context tasks — including on-device inference latency and memory footprints.</p><p><strong>3. LoRA Fine-Tuning</strong> Hu, E.J. et al. (Microsoft, 2021). <em>LoRA: Low-Rank Adaptation of Large Language Models.</em> → <a href="https://arxiv.org/abs/2106.09685">arxiv.org/abs/2106.09685</a> The foundational paper behind the fine-tuning pattern in the article — LoRA freezes pre-trained weights and injects trainable rank decomposition matrices, reducing trainable parameters by up to 10,000× and GPU memory by 3× compared to full fine-tuning.</p><p><strong>4. Phi-3 Technical Report</strong> Abdin, M. et al. (Microsoft, 2024). <em>Phi-3 Technical Report: A Highly Capable Language Model Locally on Your Phone.</em> → <a href="https://arxiv.org/abs/2404.14219">arxiv.org/abs/2404.14219</a> Introduces Phi-3-mini (3.8B params, trained on 3.3T tokens), which rivals Mixtral 8x7B and GPT-3.5 on benchmarks while being deployable on a phone — the model used in the article’s code examples.</p><h3>Official Model &amp; Tool Documentation</h3><p><strong>5. Hugging Face PEFT Library</strong> → <a href="https://huggingface.co/docs/peft">huggingface.co/docs/peft</a> The library used for LoRA fine-tuning in Pattern 3. Covers LoraConfig, get_peft_model, and integration with SFTTrainer.</p><p><strong>6. llama.cpp (Local Inference Engine)</strong> → <a href="https://github.com/ggerganov/llama.cpp">github.com/ggerganov/llama.cpp</a> The inference backend used in Patterns 2 and 4 for running quantized GGUF models locally on CPU/GPU.</p><p><strong>7. Ollama — Local Model Serving</strong> → <a href="https://ollama.com/">ollama.com</a> A developer-friendly wrapper around llama.cpp for pulling and serving SLMs locally with a simple API.</p><h3>Further Reading</h3><p><strong>8. The Small Model Revolution (Practitioner Summary)</strong> <em>Neuro-metric Sub-stack</em> (2026) — <a href="https://neurometric.substack.com/p/the-small-model-revolution-5-papers">neurometric.substack.com</a> A practitioner-written analysis of the five most consequential SLM papers from mid-2025 to early 2026, covering the shift toward modular “Lego block” AI architectures and the rise of sub-1B models outperforming older 10B models.</p><p><strong>9. Microsoft on SLMs in Production</strong> <em>Introducing Phi-3: Redefining What’s Possible with SLMs</em> — Azure Blog (2024) → <a href="https://azure.microsoft.com/en-us/blog/introducing-phi-3-redefining-whats-possible-with-slms/">azure.microsoft.com</a> Microsoft’s own framing of the SLM/LLM relationship: internally they use LLMs as routers that direct low-complexity queries to SLMs — directly matching the routing pattern shown in the article.</p><p><strong>10. LogRocket: Why the Future of AI Agents Might Be Tiny</strong> → <a href="https://blog.logrocket.com/small-language-models/">blog.logrocket.com/small-language-models</a> A practical engineering walkthrough based on the NVIDIA SLM paper, outlining how teams can treat the LLM-to-SLM transition as an engineering migration rather than just a model swap.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=312d655c0b16" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>