<?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 Clearwater Analytics Engineering on Medium]]></title>
        <description><![CDATA[Stories by Clearwater Analytics Engineering on Medium]]></description>
        <link>https://medium.com/@clearwateranalyticsengineering?source=rss-6fb0d6055766------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-ELQ7N0y9an6xrmA6juBFw.png</url>
            <title>Stories by Clearwater Analytics Engineering on Medium</title>
            <link>https://medium.com/@clearwateranalyticsengineering?source=rss-6fb0d6055766------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:30:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@clearwateranalyticsengineering/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Turn any Repository into a Senior AI-Powered Development Environment]]></title>
            <link>https://medium.com/cwan-engineering/how-to-turn-any-repository-into-a-senior-ai-powered-development-environment-fe9ad4f616d6?source=rss-6fb0d6055766------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe9ad4f616d6</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[ai-coding]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Clearwater Analytics Engineering]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 02:26:12 GMT</pubDate>
            <atom:updated>2026-07-24T02:26:56.562Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YmIJJyRE9gkg3ox292vHAw.png" /></figure><h3>The Problem I Kept Running Into</h3><p>Every time I started a new AI session, I found myself doing the same thing: re-explaining the project, re-describing the architecture, re-telling the AI what we were working on. Sometimes it would take 10–15 minutes just to get the AI to the point where it could actually help. And the next day? Same thing. Start over.</p><p>I was using Claude Code and Windsurf heavily on the CWAN API Service project, our API gateway platform here at Clearwater Analytics. Over 18 months of daily iteration on a production platform with 1,200+ API endpoints, our team built something that worked really well. The AI knew the codebase. It knew the architecture. It picked up where we left off every single session. The workspace grew to 93 workflows, 14 specialized agents, and 79 slash commands, and the team was genuinely operating at a different level than teams that were just using “AI chat.”</p><p>The question I kept asking myself was what exactly made it work? And could I package that so any team, on any codebase, could have the same thing?</p><p>That question led to the Agentic-Repos framework.</p><h3>What Makes an “Agentic Repository” Different</h3><p>A standard repository contains code. An agentic repository contains code plus a complete AI knowledge layer. The difference is significant.</p><p>The way I describe it, a standard repo is an empty apartment. The walls are the same, the plumbing is the same, but one is ready to live in. An agentic repository is furnished. When you open it in Claude Code or Windsurf, the AI already knows:</p><ul><li>What the project does</li><li>What tech stack it uses</li><li>What the current priorities are</li><li>What was accomplished in the last session</li><li>Where to find any specific piece of information</li></ul><p>It does not ask you to explain the project. It does not start from scratch. It picks up where you left off.</p><p>The way this works is not magic. It is a set of files that load automatically when the AI session starts, a structured knowledge base it can navigate efficiently, and specialized agents tailored to the specific tech stack.</p><h3>The Six Principles I Extracted from the CWAN API Service</h3><p>After 18 months of running this in production, I distilled the approach into six principles. Every one of them is non-negotiable.</p><ol><li><strong>Evidence-Based Only.</strong> Every AI claim cites a source: file path and line number, or a URL. “I think” and “probably” are not acceptable in an engineering environment.</li><li><strong>Zero Hallucination.</strong> When the AI is uncertain, it says so explicitly with confidence levels: HIGH, MEDIUM, or LOW. No invented endpoints, no made-up configurations.</li><li><strong>Single Source of Truth.</strong> Agent prompts live in one location. Every wrapper and slash command is a thin pointer. When you update an agent, you update it once. On CWAN API I now maintain 93 workflows, 14 specialized agents, and 79 slash commands. Without single source of truth, keeping that many agents in sync would be impossible.</li><li><strong>Session Continuity.</strong> Every session starts by reading the project context and a progress tracker. The AI never asks “what are we working on?” It reads the tracker and continues. This single pattern changed how my team interacted with AI more than any other.</li><li><strong>Knowledge Graph Navigation.</strong> Knowledge is organized in a structured graph with tiers of authority. The AI navigates it in constant-time lookups instead of grepping through the filesystem.</li><li><strong>Generated Artifacts Standard.</strong> All AI-produced content goes to a Generated/ directory. Knowledge is read-only. Source of Truth is immutable. Mixing AI output with authoritative knowledge corrupts the knowledge base.</li></ol><p>The reason these work together is that they address the three biggest failure modes I kept seeing in teams using AI for development. The AI makes things up, the AI repeats itself because it has no memory, and the AI produces content that nobody can find or trust.</p><h3>The Architecture</h3><p>Here is what the AI knowledge layer looks like inside a repository after you run the conversion:</p><pre>your-repo/<br>├── CLAUDE.md                    AI rules tailored to your tech stack<br>├── AGENTS.md                    Claude Code workspace instructions<br>├── START_HERE.md                Entry point for every AI session<br>├── Knowledge/<br>│   ├── KNOWLEDGE_GRAPH.md       Navigation map linking all knowledge<br>│   ├── Source of Truth/         Authoritative references (read-only)<br>│   └── DOCUMENT_INDEX.md        Topic-based quick lookup<br>├── Generated/                   Everything AI produces lands here<br>├── prompts/templates/AI Agents/ Full agent definitions<br>└── .claude/<br>    ├── agents/                  Role-specific Claude Code agents<br>    └── commands/                Slash commands for common workflows</pre><p>Each piece solves a specific problem:</p><p>CLAUDE.md loads automatically when you open the project in Claude Code. It tells the AI the rules it must follow, the commands available, and the structure of the project. This is not a generic set of instructions. It is tailored to the detected tech stack. AGENTS.md does the same for Claude Code&#39;s workspace context.</p><p><strong>START_HERE.md</strong> is what the AI reads at the beginning of every session. It contains the current project context, what the team is working on, and the priorities. This is the file that eliminates the “let me understand your project” conversation that wastes the first 10 minutes of every AI session.</p><p><strong>The Knowledge Graph</strong> is the piece most people overlook, and it is the piece that makes the biggest difference. Instead of the AI searching blindly through files, it uses a structured graph with authority tiers, concept clusters, and a search index. Tier 1 is Source of Truth — documents that only humans can modify. When two documents conflict, the higher tier wins.</p><p><strong>The Generated/ directory</strong> keeps AI output separate from human-authored knowledge. This seems like a small detail, but it is critical for trust. If everything in Knowledge/Source of Truth/ was verified by a human, and everything in Generated/ was produced by AI, you always know what to trust.</p><h3>One Command to Convert Any Repository</h3><p>The reason I built this as a framework rather than just documenting the CWAN API Service setup is that I wanted any team to be able to apply it to any codebase. The result is a single command:</p><pre>/project:convert-repo-to-agentic &lt;repo-path-or-url&gt;</pre><p>You provide a repository URL or a local path. The framework:</p><ol><li>Clones the repo if needed</li><li>Detects the tech stack by examining the actual files (Spring Boot, FastAPI, Express, Terraform, and more)</li><li>Counts endpoints, analyzes authentication patterns, finds tests and CI/CD config</li><li>Generates CLAUDE.md with rules tailored to the detected stack</li><li>Creates the full Knowledge/ structure</li><li>Generates three specialized agents: a developer agent, a researcher agent, and a code reviewer agent</li><li>Creates slash commands for code review, session context, and repo analysis</li><li>Builds a Progress Tracker so the next session picks up where this one left off</li></ol><p>The entire thing is evidence-based. Nothing is invented. The agent reads actual files before making any claim about the repo. If you use Windsurf instead of Claude Code, the equivalent /convert-repo-to-agentic workflow is included as well.</p><h3>How the Detection Works</h3><p>One thing I spent real time on was making the tech stack detection reliable. The agent does not assume. It runs detection commands:</p><pre># Build system detection<br>ls pom.xml build.gradle package.json requirements.txt go.mod 2&gt;/dev/null<br><br># Framework detection<br>grep -rl &quot;springframework&quot; src/ --include=&quot;*.java&quot; --include=&quot;*.kt&quot;<br>grep -rl &quot;fastapi\|flask\|django&quot; . --include=&quot;*.py&quot;<br>grep -rl &quot;express\|nestjs&quot; src/ --include=&quot;*.ts&quot;</pre><p>Then it adapts what it generates based on what it actually finds. A Spring Boot repo gets a CLAUDE.md with Maven commands and Spring-specific patterns. A FastAPI repo gets pytest patterns and uvicorn startup commands. A Terraform repo gets HCL syntax guidance and resource patterns.</p><p>The generated agents are also adapted. A developer agent for a Spring Boot service knows about annotations, Maven lifecycle, and Spring idioms. A developer agent for a FastAPI service knows about async patterns, Pydantic models, and pytest fixtures.</p><h3>Session Continuity: The Piece That Changes Everything</h3><p>I want to be specific about session continuity because this is the part that has the biggest practical impact.</p><p>In a standard AI workflow, every session starts from scratch. You explain the project, you explain what you are working on, you explain what you tried last time. This wastes time and leads to repetition.</p><p>In an agentic repo, the first thing the AI does in every session is run three reads:</p><ol><li>START_HERE.md -- current project context</li><li>Knowledge/KNOWLEDGE_GRAPH.md -- navigation map</li><li>Generated/PROGRESS_TRACKER.md -- where we left off</li></ol><p>The Progress Tracker is updated at the end of every session using /project:generate-session-context. It captures what was accomplished, what is in progress, what decisions were made, and what the next three priorities are. The next session starts by reading it and continuing directly.</p><p>The difference in experience is significant. Teams that use this stop re-explaining their projects to AI. They start treating AI sessions the way they treat a colleague who was in the last meeting: you do not re-introduce the project, you just continue.</p><h3>How I Built This Over 18 Months</h3><p>This did not start as a framework. It started as a messy collection of markdown files in one repository.</p><ol><li>I wrote the first CLAUDE.md file and a handful of workflow scripts. The AI stopped making certain categories of mistakes because it had explicit rules to follow. But there was no structure, and every new repository required manual setup.</li><li>I added the Knowledge Graph pattern after realizing that flat folder structures do not scale. The AI was spending too much time searching for information. The graph gave it a navigation map with O(1) lookups instead of O(n) grep searches. I also introduced the Source of Truth tier: documents that only humans can modify, which the AI must defer to when conflicts arise.</li><li>I built specialized agents for different roles: developer, code reviewer, researcher, architect, scrum master. Each agent had its own context and instructions. The single source of truth pattern for agents became necessary when the number of agents grew, because duplicate content was already drifting.</li><li>I introduced session continuity with the progress tracker. Before this, every AI session started from scratch. After this, the AI read what happened in the last session and continued directly. I also started building the Markdown Knowledge Base system that became the foundation of the knowledge layer.</li><li>I generalized everything into the Agentic-Repos framework. The conversion command was built so that any repository, regardless of tech stack, could get the full agentic layer with a single command. The detection system reads the actual files (pom.xml, build.gradle.kts, package.json, requirements.txt, go.mod) and adapts everything it generates.</li><li>The pattern is now becoming part of the CI/CD pipeline. New repositories get the agentic layer as part of their initial scaffolding. The Knowledge Graph is maintained as a living document that gets updated when architecture decisions are made, not as an afterthought at the end of a sprint. I published the enterprise implementation on our <a href="https://medium.com/cwan-engineering/building-an-ai-powered-markdown-knowledge-base-system-for-your-engineering-team-4bccea3cdbfe">CWAN Engineering Blog</a>.</li></ol><h3>The Scale Today</h3><p>The CWAN API Service workspace that this framework was extracted from now has:</p><ul><li><strong>93 workflows</strong> covering everything from sprint planning to code review to service onboarding</li><li><strong>14 specialized AI agents</strong> (developer, architect, security engineer, QA, DevOps, product manager, scrum master, and domain-specific agents)</li><li><strong>79 slash commands</strong> for common development operations</li><li><strong>Knowledge Graphs</strong> across multiple repositories, each with authority tiers, concept clusters, and search indexes</li><li><strong>Automated repo conversion</strong> that detects tech stack and generates tailored agents</li></ul><p>The measurable impact was that new developer onboarding dropped from weeks to about a day. An engineer joins the team, opens the repository, and the AI agent walks them through the architecture, the current priorities, and the conventions. The knowledge is in the graph, not in someone’s head.</p><h3>Three Agents That Show What “Specialized” Actually Means</h3><p>When I say the framework produces specialized agents, I do not mean agents with different names that do the same thing. I mean agents with fundamentally different initialization sequences, different knowledge loaded, and different operational modes. Here are three from the CWAN API Service that illustrate the range.</p><h3>The Sprint Planning Agent</h3><p>This agent acts as an AI-powered scrum master. When activated, it does not ask “what sprint are you on?” It runs a sequence: it reads the project onboarding file, loads the Knowledge Graph, pulls the latest state of the API gateway to count how many services are onboarded (a key metric the team tracks against a quarterly scorecard), then syncs the current sprint from the project management system. It compares the live ticket statuses against the last known state and only updates files if something changed. If nothing changed, it skips the rewrite entirely and reports “no changes since last sync.”</p><p>The result is that when an engineer or a manager opens a session, the agent greets them with a context-aware summary: how many services are live, what the sprint backlog looks like, which tickets are blocked, and what the velocity trend is. The entire initialization takes a few seconds. Without this agent, assembling the same picture from the ticketing system, the deployment state, and the sprint board would take 15–20 minutes of manual navigation.</p><p>The reason this works is that the agent has explicit rules for each step: where to read credentials, what commands to run, how to detect whether the data is stale, and what format to use for the greeting. None of this is left to the AI’s judgment. The judgment is encoded in the workflow.</p><h3>The Domain Intelligence Agent</h3><p>This is the agent I use for cross-domain reasoning across the entire platform. The CWAN API Service spans multiple service domains: security infrastructure, client management, reporting, fund accounting, and more. Each domain has its own repository, its own Knowledge Graph, and its own specialized agents. But sometimes you need to answer a question that spans domains: “If we change the authentication pattern on the gateway, which downstream services are affected?” or “What is the current integration status between our API platform and the frontend application layer?”</p><p>The domain intelligence agent loads knowledge files from multiple domains at initialization: the architecture blueprint, the verified system numbers, the integration strategy documents, and the service-level Knowledge Graphs from each domain it needs to reason about. It can trace a question from the gateway configuration through the authentication layer to the backend service and back to the frontend, citing specific documents at each step.</p><p>Without this agent, answering cross-domain questions required scheduling a meeting with engineers from each team. With it, the answer comes back in seconds, with citations to the source documents so you can verify every claim.</p><h3>The Gateway Infrastructure Agent</h3><p>This is the most technically specialized of the three. It understands the API gateway infrastructure: Terraform configurations, OpenAPI specifications, Nginx routing rules, service onboarding procedures, and the Lambda-based authentication system. When activated, it reads the gateway repository’s onboarding file, loads the gateway-specific Knowledge Graph, and presents a set of demo questions showing what it can answer.</p><p>The value of this agent is in what it prevents. Before it existed, onboarding a new backend service to the API gateway required reading multiple Terraform files, understanding the routing conventions, and manually verifying that the OpenAPI spec matched the backend’s actual endpoints. An engineer unfamiliar with the gateway could spend days on their first onboarding. With the agent, the process is guided: it knows the steps, the conventions, the common mistakes, and it can generate the configuration files based on the backend service’s actual endpoints.</p><p>This is what I mean when I say the agentic repo pattern produces senior-level agents. Each of these agents has deep domain knowledge that would take a human weeks to accumulate. The knowledge is not in the AI’s training data. It is in the Knowledge Graph, the architecture documents, and the rules files that the framework creates and maintains.</p><h3>What Comes Next</h3><p>The direction I am working toward is making the agentic layer a standard part of repository scaffolding, the same way a README, a .gitignore, and a CI/CD config are standard today. When you create a new repository, it should come with a Knowledge Graph, a set of AI agents tailored to the tech stack, and the rules that make those agents reliable.</p><p>The gap between teams that use AI as a chat interface and teams that build structured knowledge environments for their AI agents is already significant. It will only grow. Rolling this out across CWAN is how we make our whole SDLC smarter.</p><h3>References</h3><ul><li><a href="https://medium.com/cwan-engineering/building-an-ai-powered-markdown-knowledge-base-system-for-your-engineering-team-4bccea3cdbfe">Building an AI-Powered Markdown Knowledge Base System for Your Engineering Team</a> — CWAN Engineering Blog</li><li><a href="https://www.linkedin.com/pulse/agentic-repos-framework-turns-any-repository-senior-rany-ilsyc">Agentic Repos: The Framework That Turns Any Repository into a Senior AI Development Environment</a> — the public LinkedIn companion to this article</li></ul><h3>About the Author</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*A_rwD3IoyU8zIfuA.png" /></figure><p>Rany ElHousieny is an Engineering Leader at Clearwater Analytics with over 30 years of experience in software development, machine learning, and artificial intelligence. He has held leadership roles at Microsoft for two decades, where he led the NLP team at Microsoft Research and Azure AI, contributing to advancements in AI technologies. At Clearwater, Rany continues to leverage his extensive background to drive innovation in AI, helping teams solve complex challenges while maintaining a collaborative approach to leadership and problem-solving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe9ad4f616d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cwan-engineering/how-to-turn-any-repository-into-a-senior-ai-powered-development-environment-fe9ad4f616d6">How to Turn any Repository into a Senior AI-Powered Development Environment</a> was originally published in <a href="https://medium.com/cwan-engineering">cwan-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI-Powered Markdown Knowledge Base System for Your Engineering Team]]></title>
            <link>https://medium.com/cwan-engineering/building-an-ai-powered-markdown-knowledge-base-system-for-your-engineering-team-4bccea3cdbfe?source=rss-6fb0d6055766------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bccea3cdbfe</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-knowledge-graphs]]></category>
            <category><![CDATA[knowledge-management]]></category>
            <dc:creator><![CDATA[Clearwater Analytics Engineering]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 17:37:33 GMT</pubDate>
            <atom:updated>2026-04-24T17:38:35.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*O68QHf16ac81vJQFmDC2Qg.png" /></figure><h3>Why I Built This System</h3><p>After managing a team building a complex API Gateway and Developer Portal (1,200+ APIs across 6 acquired tech stacks), I ran into a problem that I suspect every engineering manager faces: institutional knowledge was scattered everywhere. Meeting notes in one place, architecture decisions in another, sprint data in JIRA, credential docs in a wiki, and the real decisions lived in people’s heads.</p><p>When a new developer joined the team, onboarding took weeks. When I needed to answer a leadership question about our progress, I had to dig through 10 different sources. When the AI coding assistant tried to help, it hallucinated because it had no grounded context.</p><p>So I built a system that solved all three problems at once. This article walks you through how I did it and how you can do the same for your team.</p><h3>The Architecture: Three Layers</h3><p>The system has three layers that build on each other:</p><p><strong>Layer 1: Knowledge Repository</strong> — A structured directory of markdown files organized by authority level and topic.</p><p><strong>Layer 2: Markdown Knowledge Base</strong> — A single markdown file that maps relationships between all documents, making the entire knowledge base navigable by both humans and AI agents.</p><p><strong>Layer 3: AI Agents</strong> — Specialized agents that consume the knowledge base and perform domain-specific tasks with grounded, evidence-based responses.</p><p>Let me walk through each layer with real examples from the system I built.</p><h3>Layer 1: The Knowledge Repository</h3><h3>Directory Structure</h3><p>The foundation is a well-organized directory of markdown files. Here is the structure I use:</p><pre>project-root/<br>|-- START_HERE.md              # Onboarding entry point<br>|-- AGENTS.md                  # Instructions for AI agents<br>|-- CLAUDE.md                  # Project rules for Claude<br>|-- Knowledge/<br>|   |-- KNOWLEDGE_BASE.md     # The Knowledge Base map (Layer 2)<br>|   |-- Source of Truth/       # Tier 1: Leadership-approved docs<br>|   |-- 00_project_context.md  # Tier 2: Core knowledge files<br>|   |-- 01_component_a.md<br>|   |-- 02_component_b.md<br>|   |-- meetings/              # Meeting notes<br>|   |-- TEAM/                  # Team profiles<br>|   |-- Public_API_Standards/  # Domain-specific knowledge<br>|   |-- archive/               # Historical docs (not authoritative)<br>|-- Planning/<br>|   |-- Q2_Sprint_1/           # Sprint planning files<br>|   |-- Q2_Sprint_2/<br>|-- Generated/                 # AI-generated artifacts<br>|-- prompts/<br>|   |-- templates/<br>|       |-- AI Agents/         # Agent prompt definitions<br>|-- .claude/<br>|   |-- commands/              # Slash commands<br>|   |-- skills/                # Auto-activating skills</pre><h3>The Document Authority Hierarchy</h3><p>Not all documents are equal. I organize them into tiers:</p><p><strong>Tier 1: Source of Truth</strong> — Leadership-approved documents that define the project’s direction. These are read-only for AI agents. Examples: team kickoff notes, scorecards, VP directives, architecture decisions. If an AI agent contradicts a Tier 1 document, the agent is wrong.</p><p>Enforcement happens at three points: (1) each agent’s session initialization forces it to read Source of Truth files first, (2) the rules file (CLAUDE.md) instructs agents to cite Tier 1 files with file:line evidence for any authoritative claim, and (3) the user verifies answers by clicking through to the citation. When cited evidence doesn&#39;t support the claim — or when it contradicts a Tier 1 file the user knows — the user catches it. The tier system converts <em>silent hallucination</em> into a <em>visible, citable mismatch</em> that a reviewer can spot.</p><p><strong>Tier 2: Core Knowledge</strong> — Foundational technical documents that explain the system’s components. Examples: API gateway strategy, identity layer design, MCP server architecture. These are the “textbook” for your project.</p><p><strong>Tier 3: Implementation &amp; Analysis</strong> — Sprint planning files, meeting notes, generated reports. These are working documents that change frequently.</p><p><strong>Tier 4: Historical/Archive</strong> — Old documents kept for reference. Explicitly marked as non-authoritative to prevent AI agents from citing outdated information.</p><h3>Practical Tips for Layer 1</h3><p>1. <strong>Use numbered prefixes</strong> for core knowledge files (00_, 01_, 02_). This gives a natural reading order for new team members.</p><p>2. <strong>Always include a</strong> START_HERE.md at the root. This is the single entry point for both humans and AI agents. It should contain: project overview, team roster, current sprint, critical context, and pointers to deeper documents.</p><p>3. <strong>Store meeting notes in</strong> meetings/ with date prefixes like 2026-03-15_Topic_Summary.md. This makes them searchable and chronological.</p><p>4. <strong>Never delete outdated documents — archive them, and update the Knowledge Base.</strong> Move superseded docs to archive/, add a one-line banner at the top marking them non-authoritative, and remove their entries from active concept clusters in the Knowledge Base. Because agents read the Knowledge Base first and only follow its links, archived files become invisible to them. Build this archive step into your post-meeting and post-decision workflows from day one — a stale knowledge layer is worse than no layer at all, because it masquerades as ground truth.</p><p>5. <strong>Keep everything in markdown.</strong> It is version-controlled, diff-friendly, AI-readable, and renders well in GitLab/GitHub.</p><h3>Layer 2: The Markdown Knowledge Base</h3><p>This is the part that ties everything together. The Knowledge Base is a single markdown file (Knowledge/KNOWLEDGE_BASE.md) that maps relationships between all documents in the knowledge base.</p><h3>What the Knowledge Base Contains</h3><p>1. <strong>Document hierarchy</strong> — Which files exist at each tier, with one-line descriptions</p><p>2. <strong>Relationship mappings</strong> — How documents connect to each other (e.g., “gateway strategy depends on IAM design”)</p><p>3. <strong>Concept clusters</strong> — Groups of documents around specific topics (e.g., “Authentication &amp; Credentials” cluster includes 6 files across 3 directories)</p><p>4. <strong>Evidence trails</strong> — Where specific claims or decisions are documented</p><p>5. <strong>Navigation paths</strong> — Suggested reading order for different use cases (onboarding, deep-dive, decision-making)</p><p>6. <strong>Mermaid diagrams</strong> — Visual representation of document relationships</p><h3>Example Knowledge Base Structure</h3><pre># Project Knowledge Base<br><br>## Document Hierarchy &amp; Authority<br><br>### Tier 1: Source of Truth (READ ONLY)<br>Source of Truth/<br>|-- team_kickoff.md          [PRIMARY - Vision, roadmap, team structure]<br>|-- scorecard.md             [CRITICAL - Success metrics &amp; milestones]<br>|-- vp_directive.md          [CRITICAL - Priorities &amp; ownership]<br><br>### Tier 2: Core Knowledge<br>00_project_context.md        [Foundation - Start here]<br>01_api_gateway.md            [Component - Gateway strategy]<br>02_identity_layer.md         [Component - Identity &amp; auth]<br>03_mcp_servers.md            [Component - MCP integration]<br><br>## Concept Clusters<br><br>### Authentication &amp; Credentials<br>- START_HERE.md &gt; &quot;Developer Auth&quot; section<br>- 02_identity_layer.md &gt; full IAM design<br>- 15_auth_standard.md &gt; implementation spec<br>- Environment variables file &gt; token storage (NEVER commit)<br><br>### Sprint Planning<br>- Planning/Q2_Sprint_1/ &gt; current sprint<br>- Generated/PROGRESS_TRACKER.md &gt; status<br>- Knowledge/21_quality_standards.md &gt; story requirements<br><br>## Relationship Map (Mermaid)<br>(mermaid diagram showing document connections)</pre><h3>How AI Agents Use the Knowledge Base</h3><p>When an AI agent receives a question like “What is our authentication strategy?”, it:</p><p>1. Reads the Knowledge Base first</p><p>2. Finds the “Authentication &amp; Credentials” concept cluster</p><p>3. Reads the listed files in priority order (Tier 1 first)</p><p>4. Answers with citations to specific files and line numbers</p><p>Without the Knowledge Base, the AI agent would have to search every file in the repo, likely miss important context, and potentially hallucinate based on outdated files in the archive.</p><h3>Maintaining the Knowledge Base</h3><p>The Knowledge Base needs to stay current. I use two mechanisms:</p><p>1. <strong>Automatic maintenance triggers</strong> — After meetings, run a workflow that updates the Knowledge Base. After adding new documents, update the entry. The file AI_KNOWLEDGE_BASE_MAINTENANCE.md defines the rules for AI agents.</p><p>2. <strong>Post-meeting update workflow</strong> — After any significant meeting or decision, run a workflow that updates the Knowledge Base, START_HERE.md, and relevant agent prompts. This keeps the entire system in sync.</p><h3>Layer 3: AI Agents</h3><p>This is where the system becomes powerful. Each AI agent is a specialized prompt that consumes the Knowledge Base and performs domain-specific work.</p><h3>Agent Architecture</h3><p>I follow a single source of truth architecture for agents:</p><pre>prompts/templates/AI Agents/    # Source prompts (full definitions)<br>.claude/commands/&lt;name&gt;.md      # Thin wrappers (invoke via /slash-command)<br>.claude/skills/&lt;name&gt;/          # Skill definitions (auto-activating)</pre><p>The rule is simple: <strong>only edit the source prompts.</strong> The workflow wrappers and skills are thin pointers. This prevents content drift between multiple copies of agent instructions.</p><h3>Anatomy of an Agent Prompt</h3><p>Every agent prompt follows this structure:</p><pre># Agent Name<br><br>## Role<br>One paragraph defining what this agent does.<br><br>## Session Initialization (MANDATORY)<br>1. Read START_HERE.md<br>2. Read Knowledge/KNOWLEDGE_BASE.md<br>3. Check Generated/PROGRESS_TRACKER.md<br>4. Read relevant Source of Truth files<br><br>## Core Capabilities<br>- Capability 1 with specific instructions<br>- Capability 2 with specific instructions<br><br>## Rules<br>- Evidence-based responses only (cite file:line)<br>- Mark confidence levels (HIGH/MEDIUM/LOW)<br>- Never speculate about system behavior<br>- Follow the authority hierarchy (Tier 1 overrides Tier 2)<br><br>## Knowledge Sources<br>(list of files this agent should read)<br><br>## Tools Available<br>(list of tools/scripts this agent can use)</pre><h3>Example Agents I Built</h3><p>Here are some of the agents in the system and what they do:</p><p><strong>Developer Agent</strong> — Writes code, implements features, follows the project’s coding standards. Knows the repo structure, CI/CD pipeline, and testing patterns.</p><p><strong>Scrum Master Agent</strong> — Manages sprint ceremonies, creates JIRA tickets, tracks velocity, generates sprint review decks. Fetches live data from JIRA APIs.</p><p><strong>Security Engineer Agent</strong> — Reviews code for security issues, knows the IAM integration patterns, validates authentication flows.</p><p><strong>Gateway Expert Agent</strong> — Deep specialist in the API Gateway infrastructure. Knows Terraform configs, Nginx routing rules, OpenAPI specs, and service onboarding procedures.</p><p><strong>Service Learning Agent</strong> — Onboards new service domains. Clones a repo, analyzes it, generates a Knowledge Base and an AI Agent for that service.</p><h3>Workflows: Making Agents Actionable</h3><p>Agents become truly useful when wrapped in workflows that developers can invoke with slash commands:</p><pre>---<br>description: Generate sprint review slides from JIRA data<br>---<br><br># /sprint-review-slides<br><br>## Step 1: Fetch data from JIRA<br>(automated script that pulls velocity, tickets, accomplishments)<br><br>## Step 2: Update the generator script<br>(copy from previous sprint, update SPRINT dictionary)<br><br>## Step 3: Generate the deck<br>python3 Planning/Q2_Sprint_N/generate_sprint_review.py<br><br>## Step 4: Verify output<br>(check the generated .pptx file)</pre><p>A developer types /sprint-review-slides and the agent handles everything: fetching JIRA data, generating PowerPoint slides, and saving the output.</p><h3>Key Workflows I Use Daily</h3><ul><li>/sprint-review-slides - Generates sprint review decks from live JIRA data</li><li>/review-sprint-before-start - Analyzes velocity trends before committing to a sprint</li><li>/sprint-planning-complete - Creates epics, stories, assigns points, syncs to JIRA</li><li>/code-review - Reviews merge requests with architecture context</li><li>/create-feature-branch - Creates branches from JIRA tickets with proper naming</li><li>/commit-push-create-mr - Commits, pushes, and creates GitLab merge requests</li></ul><h3>How to Build This for Your Team</h3><h3>Step 1: Start with START_HERE.md</h3><p>Create a single entry point file that answers these questions:</p><ul><li>What is this project?</li><li>Who is on the team?</li><li>What sprint are we in?</li><li>What are the key architecture decisions?</li><li>Where do I find credentials and access?</li></ul><p>This file should be readable in under 5 minutes and give someone enough context to start contributing.</p><h3>Step 2: Organize Your Knowledge</h3><p>Take your existing documents (wiki pages, design docs, meeting notes) and organize them into the tiered structure:</p><pre>mkdir -p Knowledge/Source\ of\ Truth<br>mkdir -p Knowledge/meetings<br>mkdir -p Knowledge/TEAM<br>mkdir -p Knowledge/archive<br>mkdir -p Planning<br>mkdir -p Generated<br>mkdir -p prompts/templates/AI\ Agents</pre><p>Move your most important documents into Source of Truth/. Convert wiki pages to markdown. Date-prefix your meeting notes.</p><h3>Step 3: Build the Knowledge Base</h3><p>Create Knowledge/KNOWLEDGE_BASE.md with:</p><p>1. A list of every document organized by tier</p><p>2. One-line descriptions for each file</p><p>3. Concept clusters grouping related files</p><p>4. A Mermaid diagram showing relationships</p><p>Start simple. You do not need to map every relationship on day one. The Knowledge Base grows organically as you add documents and discover connections.</p><h3>Step 4: Create Your First Agent</h3><p>Pick the task your team does most often (probably sprint planning or code review) and create an agent for it:</p><p>1. Write the agent prompt in prompts/templates/AI Agents/MY_AGENT.md</p><p>2. Create a slash command in .claude/commands/my-agent.md</p><p>3. Test it by invoking the slash command</p><p>4. Iterate based on what the agent gets wrong</p><h3>Step 5: Add Rules</h3><p>Create CLAUDE.md (or .claude/rules.md, or the equivalent rules file for your AI tool) with rules like:</p><ul><li>Always read the Knowledge Base before answering questions</li><li>Cite sources with file:line format</li><li>Never contradict Source of Truth documents</li><li>Mark confidence levels on claims</li><li>Do not hallucinate — say “I don’t know” when unsure</li></ul><p>Rules are what turn a generic AI assistant into a grounded team member.</p><h3>Step 6: Automate Maintenance</h3><p>Create workflows for keeping the system current:</p><ul><li><strong>Post-meeting workflow</strong> — After meetings, update Knowledge Base and START_HERE</li><li><strong>Sprint planning workflow</strong> — Creates tickets, assigns points, syncs to JIRA</li><li><strong>Session context workflow</strong> — Logs what was accomplished for continuity across sessions</li></ul><h3>Real Results</h3><p>After running this system for several months with a team of 5 developers:</p><p><strong>Onboarding time dropped from weeks to hours.</strong> New developers read START_HERE.md and the Knowledge Base, then the agent answers their questions with cited sources.</p><p><strong>Sprint review prep went from 2 hours to 5 minutes.</strong> The /sprint-review-slides workflow pulls live data from JIRA and generates the entire PowerPoint deck.</p><p><strong>Decision traceability improved dramatically.</strong> Every architecture decision is documented, cited in the Knowledge Base, and available to every agent. No more “I think we decided X in that meeting last month.”</p><p><strong>AI agent accuracy improved significantly.</strong> With the Knowledge Base providing grounded context, agents stopped hallucinating about system behavior and started citing real evidence.</p><h3>Common Mistakes to Avoid</h3><p>1. <strong>Do not try to document everything at once.</strong> Start with Source of Truth and the 5 most important knowledge files. Grow from there.</p><p>2. <strong>Do not skip the authority hierarchy.</strong> Without tiers, AI agents treat a random meeting note with the same weight as a VP directive. That leads to bad answers.</p><p>3. <strong>Do not let the Knowledge Base go stale.</strong> Build the maintenance habit into your workflows. If the Knowledge Base is outdated, AI agents make outdated recommendations.</p><p>4. <strong>Do not duplicate content across agent prompts.</strong> Use a single source of truth for each agent definition. Wrappers should be thin pointers, not copies.</p><p>5. <strong>Do not forget the rules file.</strong> Without rules, AI agents default to generic behavior. Rules are what make them follow your team’s standards.</p><h3>Getting Started Today</h3><p>The simplest starting point is three files:</p><p>1. START_HERE.md - Your project&#39;s entry point</p><p>2. Knowledge/KNOWLEDGE_BASE.md - Document map with tiers and relationships</p><p>3. AGENTS.md - Instructions for AI agents entering your workspace</p><p>From there, add knowledge files as you go, build agents for repetitive tasks, and create workflows for your most common operations. The system compounds over time — every document you add makes every agent smarter.</p><h3>References:</h3><p><a href="https://medium.com/gitconnected/the-complete-guide-to-building-hallucination-free-ai-systems-from-prompts-to-knowledge-graphs-a8f04b912d17">https://medium.com/gitconnected/the-complete-guide-to-building-hallucination-free-ai-systems-from-prompts-to-knowledge-graphs-a8f04b912d17</a></p><p><a href="https://www.linkedin.com/pulse/copy-how-knowledge-graphs-transform-genai-code-from-rany-jml7c">https://www.linkedin.com/pulse/copy-how-knowledge-graphs-transform-genai-code-from-rany-jml7c</a></p><p><a href="https://www.linkedin.com/pulse/from-knowledge-graphs-smart-search-making-ai-actually-rany-lniec">From Knowledge Graphs to Smart Search: Making AI Assistants Actually Fast</a></p><h3>About the Author</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*t91mo8E3htk3ZId6fVEJTg.png" /></figure><p>Rany ElHousieny is an Engineering Leader at Clearwater Analytics with over 30 years of experience in software development, machine learning, and artificial intelligence. He has held leadership roles at Microsoft for two decades, where he led the NLP team at Microsoft Research and Azure AI, contributing to advancements in AI technologies. At Clearwater, Rany continues to leverage his extensive background to drive innovation in AI, helping teams solve complex challenges while maintaining a collaborative approach to leadership and problem-solving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bccea3cdbfe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cwan-engineering/building-an-ai-powered-markdown-knowledge-base-system-for-your-engineering-team-4bccea3cdbfe">Building an AI-Powered Markdown Knowledge Base System for Your Engineering Team</a> was originally published in <a href="https://medium.com/cwan-engineering">cwan-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Architecture Diagramming with Parallel Agents and Feedback-Driven Prompting]]></title>
            <link>https://medium.com/cwan-engineering/scaling-architecture-diagramming-with-parallel-agents-and-feedback-driven-prompting-717c61aaa1b3?source=rss-6fb0d6055766------2</link>
            <guid isPermaLink="false">https://medium.com/p/717c61aaa1b3</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Clearwater Analytics Engineering]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 18:29:44 GMT</pubDate>
            <atom:updated>2026-03-13T18:30:23.017Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDNgLlIs3rpvOCMcK68cGw.jpeg" /></figure><h3>Introduction</h3><p>Diagramming applications is one of the most effective ways to know your domain, but the sheer volume of applications a team can own makes the task of diagramming all of them impossible to do individually and extremely daunting.</p><p>With the recent marriage of generative AI tools and software development, tasks that required significant manual effort are increasingly automated — enabling teams to shift their focus from repetitive implementation to higher-order design, architecture, and innovation. In practice, the hard part isn’t generating output; Instead, it’s orchestrating agents to optimize concurrency, while continuously improving prompts to accommodate a diverse range of applications.</p><p>The idea started here: come up with a way to run multiple agents at the same time, to reduce the time and effort it would take to diagram a team’s entire system.</p><h3>Summary</h3><p>I developed a parallelized agentic script that analyzes all source code and IaC for a group of related microservices and automatically generates architecture diagrams for each. Finally, it diagrams the whole system of applications and how they relate to each other.</p><p><strong>Are the diagrams comprehensive?</strong> Not always. As AI is used to generate them, they need refinement to ensure accuracy and usefulness, but they provide a useful starting point for understanding complex system architectures.</p><p><strong>Was this fun and interesting?</strong> Absolutely. What began as a diagramming project evolved into something far more compelling. As the experiment progressed, I found myself increasingly captivated by optimizing the agentic workflow itself rather than perfecting the diagrams. The real innovation emerged organically: a self-improving feedback loop where agents continuously version and refine their own prompts. Similar to the concept within systems/controls engineering, this mechanism allows the system to evolve autonomously as it encounters diverse applications across our company’s ecosystem, learning from each analysis to improve future runs.</p><h3>An Iterative Approach</h3><p>Having no real end goal except “have the AIs completely diagram our entire system architecture” and no set design, this experiment evolved significantly as it progressed and new technologies became available.</p><h3>Phase 1: Proof of Concept</h3><p>To start, all the code needed to be accessible on a local disk for the agent runner to inspect and process. This would provide the majority of information needed to diagram our applications. From here a two-part plan was put into motion:</p><p>1. Individually analyze all the applications within the group<br>2. Combine / synthesize a full picture view of the system</p><p>These two parts were the genesis of the Individual Analysis Agent and the Synthesis Agent.</p><p>Early instructions directed the Individual Analysis Agents to only look at applications that they could identify the IaC repos for. Unfortunately, the project structure for pairing application repos and IaC repos together varied from team-to-team so, after a few attempted runs, it became obvious that the complexity of identifying the pairs was too much for the agent whose responsibility was supposed to be diagramming individual applications. This led to the creation of the Discovery Agent.</p><h3>Phase 2: Attempting to Parallelize Agents in the IDE</h3><p>At the time this portion of the experiment was performed, the ability of chat agents to launch their own subagents had not been released to the IDE being used for development. This made concurrency a bit difficult. Since one of the main goals of this exploration was to get multiple Individual Analysis Agents running at the same time processing these applications, all the development through this point was merely opening different chat windows within the IDE and pasting in prompts developed between the “Planning Agent” and I.</p><p>At this point 4 separate agents prompts were used to split up the work of establishing relationships between repositories, diagramming/analyzing applications, generating a full system diagram of all the applications, and coordinating/troubleshooting/improving the entire process:</p><p>1. <strong>Discovery Agent</strong> — Responsible for discovering the relationships between our application repositories. It produces a list of applications that the Individual Analysis Agents would need to go through, where the entries looked like this:</p><pre>### 11. nova-dashboard<br>- **App Repo:** `/Users/kyle-barnett/dev/AstroOps/nova-dashboard`<br>- **IAC Repo:** `/Users/kyle-barnett/dev/AstroOps/nova-dashboard-iac`<br>- **Match Type:** Exact name match<br>- **IAC Location:** Separate repository<br>- **🆕 Deployment Type:** EKS with Fleet<br>- **🆕 Namespace:** nova-dashboard<br>- **🆕 Team:** AstroOps<br>- **🆕 Environments:** testing, staging, production<br>- **🆕 Jenkins:** ✅ Found<br>- **🆕 Priority:** P0 - High (actively deployed)<br>- **Status:** ✅ Ready for analysis</pre><p>2. <strong>Individual Analysis Agent</strong> — The diagrammer and analyzer. It would use information made by the Discovery Agent to locate all of the information about an application. Creating this agent was the most exciting one, because it offered the most opportunities for parallelization.</p><p>3. <strong>Synthesis Agent</strong> — This was the end goal for the whole project. Once we had all the smaller diagrams and application relationships on an individual level, one last agent would go through all of them and piece them together into a set of diagrams that captured the complexities of the entire system.</p><p>4. <strong>Meta-Coordinator / Planning Agent</strong> — At this point in the development process, this agent was responsible for helping improve the prompts created for each agent. As each agent finished running, it would be asked for improvements surrounding its prompt and then this agent would update the prompt for the agent giving the feedback.</p><p>5. <strong>(Honorable Mention) Monitoring Agent</strong> — This agent was supposed to monitor the task queue and report real-time analytics on the state of the process. A python script quickly seemed like a more appropriate solution to monitoring.</p><p>Issues did arise, which helped clarify the scope of applications to be diagrammed. By establishing a clear definition of the intended applications for inclusion, we ensured that repositories such as shared libraries, testing and lower environment applications, and legacy systems were appropriately managed within the process. This led to the inclusion of additional repos for our environmental deployments and the Discovery Agent coming up with its own priority classification system for applications with the highest priority being a production deployed.</p><p>Originally, the chat window used for overall planning and conversation was referred to as the “Planning Agent” but as time went on, human error crept in and chat windows were mixed up with each other. Prompts were given to it that weren’t meant for it, and its role/responsibilities overlapped with the Meta-Coordinator Agent. Both agents ended up existing as two separate but similar prompts that were tough to distinguish from one another.</p><p>Overall, two Individual Analysis agents were able to run at the same time and got a pretty good albeit manually managed flow of analysis going.</p><h3>Phase 3: Experimenting with Devin CLI</h3><p>After reading about <a href="https://devin.ai/">Devin CLI</a>, many pain-points around parallelization became easier to manage. There was no need any longer to manage four different chat windows at the same time, constantly trying to organize them in a way that allowed for easy recognition of what agent lived where and with what context. Now the same could be done with terminal windows!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHn8R6N3YucmBJ1WTmcy6A.png" /></figure><p>Working with this new technology, the main constraint on productivity became unfamiliarity with permission settings. While working in “Normal” permission mode, every terminal command the CLI wanted to perform needed confirmation from the user before running it.</p><p>At this point, each agent’s invocation was translated into its own task within a file-based task queue. Agents would then create a task-queue.lock file before claiming tasks in an attempt to prevent concurrency issues within the queue file.</p><h3>Phase 4: Near Autonomous Parallelization</h3><p>The current version of this project has been reduced to running as a singular python script. The script kicks off a Startup Agent that assists the user in cloning all the repositories for the microservices. Upon exiting the Devin CLI agent, an orchestrator class manages headless versions of the rest of the agent types while maintaining the file-based task queue and kicking off the associated agent for each task (discovery, analysis, synthesis, and feedback). Each agent was launched with a combined prompt + task created by the orchestrator depending on what is available in the queue.</p><p>The following diagram is a self-analysis of the project, performed by feeding a prompt into the Startup Agent where it was instructed to analyze its own codebase by creating a symlink to the project root instead of cloning external repositories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TGTMmpijqRZ3d8brpEqFg.png" /></figure><h3>Parallelizing Agent Work</h3><p>The key advantage of the parallelization became apparent during <strong>Phase 3</strong> while adopting Devin CLI instead of conversing with multiple chat windows. The work/task queue that was developed allowed for a flow where any amount of Individual Analysis agents could be spun up as workers, processing applications from the queue. Here are some stats from a four-agent limited run against a group of 35 applications:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ejJU2fZDiBQpxZw8mpXXA.png" /></figure><ul><li>The Individual Analysis phase completion time was 2–3 times higher than all other phases</li><li>Other phases were relatively comparable to each other</li></ul><p>The script was run a second time against the same collection of applications with an increased maximum of concurrent agents to compare runtime (note: since feedback from the first run would have already been incorporated into the agent prompts, the second run potentially skews the results to be higher than they should be). A 2:1 ratio of applications to max Individual Analysis agents (20 overall) was used for the analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpUZvSJZBV7APzM4TqPp4g.png" /></figure><ul><li>The Individual Analysis phase is much more comparable to the other phases during the second run reducing from 46.6% of the total run to 18.5%</li><li>The overall run time was reduced by 28.5%</li><li>Interestingly the Synthesis phase took twice as long for the second run, exposing portion of the process that may need some improvement</li></ul><h3>Feedback-Driven Prompting</h3><p>Feedback-driven prompting involves asking an agent for improvements to its original prompt based on the outcome of the task it was asked to perform. That feedback is then incorporated into that prompt for the next time it is utilized for a similar task.</p><p>One of the most interesting features implemented early on was a feedback loop between the agents and me. During <strong>Phase 2</strong>, while working in multiple chat sessions in the IDE, every conversation with a chat agent started to naturally end with the question:</p><p>Do you have any feedback that could be used to improve your original prompt?</p><p>After memories had been created for each of the agents, all agents had knowledge of each other’s existence and the final chat command degraded to “any feedback for the planning agent?”. Nonetheless, each agent would come up with improvements to its prompting as different applications were analyzed. Their feedback was then dropped into the Meta-Coordinator agent’s chat window. On its own, the agent even started versioning each of the agent’s prompts.</p><p>Eventually, constantly asking agents for their feedback and adapting their prompts became a chore. This responsibility was subsequently delegated to the agents themselves. The Meta-Coordinator agent would now adapt the prompts of each of the individual agents, and the final assignment of every prompt was to output feedback on how well the prompt addressed the task assigned. Here is an example prompt snippet:</p><pre>## POST-TASK SELF-REFLECTION (REQUIRED)<br>**Before exiting, you MUST write a feedback entry to the feedback queue file.** Do NOT output any summary to the user before writing feedback.</pre><p>With the incorporation of the task-queue into the design, it also felt natural to start a “feedback-queue” as well. Analyzing feedback added to this queue was also updated to be a task at the end of the run. Further refinement and splitting up of agent responsibilities led to the establishment of a Feedback Agent. The Feedback Agent’s sole purpose was to process agent feedback and update their respective prompts (this also led to the deprecation the meta-coordinator / planning agent).</p><p>This process was initially developed against different systems of StellarOps applications, which are architecturally similar to one another. Feedback from the agents tended to be minimal at times. However, after running the script against the AstroOps team’s applications, the volume and specificity of the feedback exploded due to the architectural differences from a vastly different application stack. The result was the 11-minute runtime listed above, making up 19.3% of the total runtime. Here is an analysis of the feedback-queues leftover from the StellarOps vs AstroOps run:</p><p>StellarOps feedback was largely self-congratulatory because the prompts already fit the TFC-only, EKS/EC2-homogeneous codebase well. AstroOps feedback was genuinely constructive because the codebase exposed real prompt blind spots (Lambda, desktop apps, MCP, multi-database patterns). The time estimate data was useful in both, but AstroOps’ prompt gap identification drove meaningful prompt evolution.</p><p>After rerunning the script against the AstroOps group a second time the following was recorded:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZWNFVVig23qxCuk0-wRp_g.png" /></figure><p>At first glance the second run is shockingly worse. Confused, I ran an analysis:</p><p>Summary</p><p>The feedback DID help — for the 26 apps that both runs analyzed, AstroOps_2 was 298s (5 min) faster cumulatively, averaging 11.5s/app improvement. The per-app speedups are real: interstellar-mail-relay -60s, nebula-gateway -41s, asteroid-dodge-lambda -111s. AstroOps_2 was slower overall because of three compounding factors:</p><p>1. The v4.2 discovery found more (and harder) apps</p><p>The improved discovery prompt found 37 apps vs 35. The v4.1 discovery found several trivial/deprecated apps (mission-proto, stellar-commons, asteroid-identifier-iac) while v4.2 found more complex ones (quasar-engine, cosmos-db-ws, warp-drive-simulator-iac).</p><p>2. One outlier task dominated the analysis wall-clock</p><p>analysis-quasar-engine took 459s (7.6 min) — nearly 3x the average. It was the last analysis task to finish and extended the wall-clock by ~4.5 minutes. This single task that didn’t exist in AstroOps_1 accounts for almost the entire wall-clock difference. Without it, AstroOps_2 analysis wall-clock would have been ~26 min — the same as AstroOps_1.</p><p>3. The v4.2 prompts are 66% larger</p><p>The analysis prompt grew from 503 to 813 lines (19.5KB to 32.4KB). Every one of the 37 agents had to ingest ~13KB more prompt text. This adds a small per-task overhead that compounds across all tasks. The discovery prompt grew 39% too, adding ~1 min to that phase.</p><p>4. Feedback phase was actually much faster (-3.8 min)</p><p>The v4.2 feedback processing was 3.8 min faster than v4.1 (7.2m vs 11.0m), likely because the prompts were already better-tuned and there was less corrective work to do.</p><p>Net: The feedback made each individual analysis faster, but the improved discovery found harder apps and a single<br> outlier task blew out the wall-clock.</p><p>So similar to early POCs, multiple iterations are needed between full runs to adapt to unencountered patterns and correctly identify applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-R83tKm78O5XVPoL5NBxQ.png" /><figcaption>AstroOps System Overview</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gzNn4mh4_E2DoqFYmGAKA.png" /><figcaption>Zoomed in Mission Control Core Diagram</figcaption></figure><h3>Future Improvements</h3><p>The actual diagrams for each of the applications, as well as the system-wide diagrams, definitely need some work. Looking back at the initial agent chat history, there was a conversation about what the best diagramming method would be for an agent to analyze an application and its dependencies. It responded with Mermaid and described different application diagram types. The latter part of the response was forgotten, the answer to the question eventually becoming only “Mermaid diagrams.” Incorporating different diagram types to eliminate some of the noisiness on the diagrams, and then eventually splitting the analysis of an application from the creation of multiple types of diagrams would probably be a meaningful improvement.</p><p>Additionally, more work can be done to break down some of the agent prompts to help parallelize the process further. Breaking up the responsibilities of the Synthesis and Discovery agents could help bring to light an effective weay to run multiple of them at the same time. The discovery process already works with a list of repositories, so splitting identification work should be relatively easy and reduce the consistent 9–10 minutes for that phase. The bigger problem to tackle would be how to run multiple Synthesis agents. Since that task is cumulative in nature, a lot more thought may be needed to break it down into smaller chunks. The Individual Analysis agents can also be broken down further to more effectively specialize their analysis between application types.</p><p>Once the process has been refined further, it would be worth exploring how feasible it would be to run it against the organization’s full application portfolio — and how quickly it could complete.</p><h3>Conclusion</h3><p>Incorporating feedback-driven prompting into an agentic ecosystem is a must for creating an adaptive, increasingly autonomous system. As prompts grow and agents start taking on overly broad tasks, taking a step back and breaking down their responsibilities allows for opportunities for additional concurrency. Traditional software development principles still apply when developing agentic software!</p><h3>Resources</h3><p>· <a href="https://cursor.com/blog/scaling-agents">Cursor’s blog on scaling long-running autonomous coding</a> was significant source of inspiration for this experiment.</p><h3>About the Author</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*DO4Tnf8C7zw8lzsL1kdO0Q.jpeg" /></figure><p>Kyle Barnett has been a Software Development Engineer at CWAN since May 2022. Pivoting from his Chemical Engineering undergraduate degree, Kyle decided to chase the passion he discovered in software development. Beyond the realm of coding, Kyle enjoys skiing, golfing, playing with his dog, maintaining an active lifestyle, and University of Washington football. Go dawgs!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=717c61aaa1b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cwan-engineering/scaling-architecture-diagramming-with-parallel-agents-and-feedback-driven-prompting-717c61aaa1b3">Scaling Architecture Diagramming with Parallel Agents and Feedback-Driven Prompting</a> was originally published in <a href="https://medium.com/cwan-engineering">cwan-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Tech Debt — Wrapper Types]]></title>
            <link>https://medium.com/cwan-engineering/managing-tech-debt-wrapper-types-8829a462b9c3?source=rss-6fb0d6055766------2</link>
            <guid isPermaLink="false">https://medium.com/p/8829a462b9c3</guid>
            <category><![CDATA[tech-debt]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Clearwater Analytics Engineering]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 07:16:07 GMT</pubDate>
            <atom:updated>2026-02-02T17:40:35.862Z</atom:updated>
            <content:encoded><![CDATA[<h3>Managing Tech Debt — Wrapper Types</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*rlVlueTRNG16fqY7ZfNN_w.png" /></figure><p>Your company relies on dozens of different API integrations to build your software. Cloud integrations, 3rd party libraries, metrics repositories — the works. What happens when one of those APIs changes how it works or needs to be replaced?</p><p>If you’re unlucky, the answer isn’t good. Developers scrambling to update hundreds of files, multiple teams sequestered, weeks of testing, potential downtime and so on.</p><p>As with all software design, there are dozens of approaches that can make the process better. This blog focuses on a specific one that was popularized by Google in their Tech on the Toilet blog called “<a href="https://testing.googleblog.com/2020/12/testing-on-toilet-separation-of.html">wrapper types</a>” (also known as <a href="https://refactoring.guru/design-patterns/facade">the façade pattern</a>). To quote their blog and sum up the idea here:</p><blockquote><strong>Wrapping an external API follows the </strong><a href="https://en.wikipedia.org/wiki/Separation_of_concerns"><strong>Separation of Concerns</strong></a> principle, since the logic for how the API is called is separated from the domain logic. This has many benefits, including:</blockquote><blockquote>- If the way the API is used changes, encapsulating the API in a wrapper insulates how far those changes can propagate across your codebase.</blockquote><blockquote>- You can modify the interface or the implementation of types you own, but you can’t for API types</blockquote><blockquote>- It is easier to switch or add another API, since they can still be represented by the introduced types…</blockquote><blockquote>- Readability can improve as you don’t need to sift through API code to understand core logic.</blockquote><p>Interestingly, a lot of technologies exist that make some of the above points seem somewhat moot.</p><ul><li>“Encapsulating the API in a wrapper insulates how far those changes can propagate”? Use <a href="https://docs.openrewrite.org/">Open Rewrite</a> to propagate those changes en masse.</li><li>“It is easier to switch or add another API”? Let <a href="https://aws.amazon.com/transform/custom/">AWS Transform (Custom)</a> handle the migration.</li><li>“Readability can improve”? Your favorite AI agent can summarize the documentation for you… if it exists.</li></ul><p>Hypothetically though, what if the API is pervasively used throughout your application so any changes would touch hundreds of files? How would that code review go? Would you or anyone on your team be willing to go through it well enough to:</p><ul><li>Make sure no mistakes were made?</li><li>Confirm the tests were updated appropriately?</li><li>Ensure <a href="https://www.justice.gov/opa/pr/chinese-national-who-deployed-kill-switch-code-employers-network-sentenced-four-years-prison#:~:text=For%20Immediate%20Release,engaging%20in%20similar%20unlawful%20activities.">nothing malicious was introduced</a>?</li></ul><p>These are all situations where wrapper types can help. The following will cover a few of the ways we have utilized wrapper types at CWAN, admittedly pre-AI, which smoothed out our on-prem to cloud migration, reduced overall system maintenance, and help to encapsulate API requirements in a maintainable way.</p><h3>CWCU</h3><p>We’ll start with how we smoothed out our cloud migration with a more controversial wrapper: CWCU. CWCU is our internal HTTP client wrapper library. Literally, an abstraction of an HTTP client that just delegates off to a real, 3rd party HTTP client for requests. Why, you might ask? Because getting HTTP right can be tricky. You typically need to create the Client once, then need to make sure the right settings are set for optimal execution in your environment, and have some variety of resilience patterns that need followed to ensure a certain level of stability, among other concerns.</p><p>Even utilizing the API of some HTTP clients can be confusing. Apache 4.5 (what was current back in the day) for instance, has <a href="https://hc.apache.org/httpcomponents-client-4.5.x/current/httpclient/apidocs/org/apache/http/client/HttpClient.html">8 different execute() methods</a>! OkHttp reduces that to one but then retrieving a response’s content can be done <a href="https://square.github.io/okhttp/3.x/okhttp/okhttp3/ResponseBody.html">5 different ways</a>. If you try searching the internet for examples on how to use these, each “answer” is likely to have a different example of how to use them. Further, as developers on a project come and go, team decisions on how to “properly” (consistently) do things will be forgotten and eventually all variants of the API might be used. This might not be a bad thing though; it should only make refactors/migrations more cumbersome but can also lead newer developers to question what the right way to do things is. To add to the problem, developers need not be the cause of inconsistent API usage as AI will happily play the part of utilizing all the examples from the internet unless you <a href="https://medium.com/cwan-engineering/vibe-check-software-engineering-with-ai-41d9808b802c#af79">give it solid coding standards to work with</a>.</p><p>How does CWCU help us then?</p><h3>API Simplification</h3><p>First, it simplifies the overall API used to make HTTP requests. In fact, there are 3 ways of executing a request <em>and</em> handling the response (example interface):</p><pre>interface Http {<br>    /**<br>     * Executes a request and immediately closes it without returning a response. This is useful for requests where you don&#39;t expect anything in the response<br>     * body. E.g. a fire-and-forget POST.<br>     */<br>    void execute();<br><br>    /**<br>     * Executes the request and stream the response to {@code out}.<br>     *<br>     * &lt;p&gt;&lt;b&gt;Note&lt;/b&gt;: If you are executing a non-GET request and do not intend to do anything with the data that is returned, see: {@link #execute()}.<br>     *<br>     * @param out Where to stream the response of the request to<br>     */<br>    void executeRequest(OutputStream out);<br><br>    /**<br>     * Executes the request and returns a stream of the response.  {@link HttpInputStream} gives you a stream with access to the response headers and other properties.<br>     *<br>     * &lt;p&gt;&lt;b&gt;MAKE SURE&lt;/b&gt; you call {@link HttpInputStream#close() close()} on the stream! Otherwise, you could leak HTTP connections.<br>     *<br>     * @return A stream of the response from the HTTP request<br>     */<br>    HttpInputStream executeRequestAsStream();<br>}</pre><p>Is this perfect for all scenarios? No. Will you need the other methods eventually? Maybe. But, for basic CRUD/REST requests, it covers a vast majority of the use cases we’ve come across.</p><h3>Migration Insulation</h3><p>Second, it has helped us to introduce HTTP/2 support — via an underlying HTTP client change — across a swath of our apps with a very simple migration. The process is:</p><ol><li>Update the app’s Maven pom to use the new library version.</li><li>Fix imports, because the packaging changed for backwards compatibility.</li><li>Remove deprecated methods that were removed.</li><li>Test.</li></ol><p>Due to the repackaging, the code reviews can still be a bit tedious. But, making sure nothing below your import lines has changed is far easier than making sure API nuances aren’t going to cause problems. This is all thanks to the fact that the HTTP wrapper is thoroughly tested to ensure all public/promised functionality behaves as expected even after the radical, internal change to the wrapper.</p><h3>Environment Configuration</h3><p>Lastly, it helped our cloud migration. A big design feature of this wrapper was that every “host” (target domain) be abstracted out into a `<strong><em>ServerConfiguration</em></strong>` Object (that contained a few extra properties too, e.g. port, HTTP scheme) which could be shared/injected in various places as needed to control what end-server we ultimately issued requests to. The `<strong><em>ServerConfiguration</em></strong>` further enforced that all hosts have a defined `<strong><em>SystemProperty</em></strong>` that could be used to override what domain a host ultimately mapped to at runtime which is similar in concept to functionality that systems like <a href="https://developer.hashicorp.com/consul">Consul</a> and <a href="https://aws.amazon.com/cloud-map/">AWS Cloud Map</a> can offer but done prior to the existence of such technology (spoiler: environment variable support could be easily added with minimal change for better EKS support too).</p><p>When it came time to migrate from on-prem to the cloud, we had a problem with respect to testing that DNS, another viable alternative, couldn’t easily resolve but the use of a `<strong><em>SystemProperty</em></strong>` made trivial: how do we keep our on-prem servers pointed to on-prem environments while simultaneously testing the new cloud environment for stability before switching over? The apps that used CWCU simply had to deploy the app with different configurations in the different environments and were immediately able to get to testing. The ones that didn’t, however, needed to make a significant number of small changes (again, pre-AI) to make their host names configurable and thus delayed their migration.</p><h3>Tangent: Separation of Concerns (SoC)</h3><p>When working with data persistence layers, especially in Java, it is easy to be reminded about DAOs (<a href="https://en.wikipedia.org/wiki/Data_access_object">Data Access Objects</a>). Generally, these are used for wrapping JDBC, ORM, or similar framework, code into a consolidated, easy to test, easy to mock Object that can be reused and grant access to data in a Database or other forms of data storage.</p><p>Often, working with HTTP, it is easy to forget that SoC <em>should</em> apply there too. As a result, HTTP requests get directly embedded in code that needs data and results in a complicated, hard to test system. When possible, don’t forget to create a “<strong><em>Client</em></strong>” class (same as a DAO with a semantically different name) to encapsulate your HTTP requests. This is a much more direct approach to a “wrapper type” than something like CWCU. It helps keep important logic consolidated, testable, mockable, and migratable. Be sure to remind your AI assistant to do the same.</p><h3>Brave (Openzipkin)</h3><p>Ref: <a href="https://github.com/openzipkin/brave">https://github.com/openzipkin/brave</a></p><blockquote>Brave is a distributed tracing instrumentation library [for Java].</blockquote><p>At the time we were working on integrating with it, Brave went from version 3 to version 5. It was a very active project with a TON of (breaking) API changes. Incorporating Brave into all our projects and maintaining the massive amount of churn it was going through was untenable. So, we made a wrapper type for it.</p><p>It’s not that the API was particularly simple and easy to wrap, it is because the concepts we needed to utilize were. Through some sample implementations we realized there wasn’t much in terms of “public” functionality that we needed to capture. If you’re familiar with <a href="https://opentelemetry.io/docs/concepts/signals/traces/">distributed tracing</a>, our foundational requirements were to:</p><ul><li>Open/close spans.</li><li>Inject/extract span information across thread/network boundaries.</li><li>Annotate spans with relevant metadata.</li></ul><p>Ultimately, this resulted in us creating:</p><ul><li>A `<strong><em>Trace</em></strong>` class to help with overall orchestration of trace data.</li><li>A `<strong><em>Span</em></strong>` class for opening, closing, annotating, etc.</li><li>A `<strong><em>Propagator</em></strong>` class for injection/extraction.</li><li>A ton of other internal classes for making it all work.</li></ul><p>3 public classes though? It was so easy to maintain that we survived 3 major version upgrades of Brave, one of which was a significant rewrite, with zero public API changes.</p><h3>AWS SDK</h3><p>Whether you use AWS or not, you likely know of its API. Love it or hate it, the AWS SDK is a <em>vast</em> API that lets you control virtually everything residing in AWS. The vastness of it alone makes it easy to consider it complex without even getting into the nitty-gritty of each API, cost implications, etc.</p><p>For instance, let’s focus on <a href="https://aws.amazon.com/sns/">SNS</a> for a moment. The <a href="https://docs.aws.amazon.com/sns/latest/api/API_PublishBatch.html">Publish Batch API docs</a> make it explicit that it comes with limitations:</p><ul><li>10 messages per-batch.</li><li>256 KB <strong>total</strong> payload size.</li></ul><p>Assuming you’ve followed good SoC concepts, you’ll likely have a Client/DAO of some kind for sending messages to SNS. But, do you really want to remember these limitations in <em>every</em> Client that sends messages? What about response handling? Can you ensure that all SNS usages will handle responses correctly; specifically checking for which messages succeeded vs. failed, retrying failures where appropriate, or even not allowing inputs that are known to cause failures?</p><p>That is what highlights a deficiency with the best aspect of the AWS SDK: it is too low-level. AWS themselves even seemed to recognize this and created their own wrapper type for SNS (and SQS in tandem): the <a href="https://docs.aws.amazon.com/sns/latest/dg/large-message-payloads.html">extended client for handling large messages</a> that offloads payloads to S3 transparently.</p><p>Creating higher-level wrapper types that can isolate the low-level requirements of an API into one maintainable spot helps scale the usage of the API within your app while shielding newer developers from the need to read all the docs and consider all the edge cases before accidentally introducing bugs, performance issues, or worse, high-cost usages of an API as a result of innocent ignorance.</p><p>An example wrapper would look like:</p><pre>public class SNSPublisher {<br>    private static final int SNS_MAX_BATCH_SIZE = Integer.parseInt(System.getProperty(&quot;SNS_MAX_BATCH_SIZE&quot;, &quot;10&quot;));<br>    /** 262,143 == 256kb - 1 (subtracting one just in case) */<br>    private static final int SNS_MAX_PAYLOAD_BYTES = Integer.parseInt(System.getProperty(&quot;SNS_MAX_PAYLOAD_BYTES&quot;, &quot;262143&quot;));<br><br>    private final SnsClient client;<br>    private final String topicArn;<br><br>    public SNSPublisher(SnsClient client, String topicArn) {<br>        this.client = client;<br>        this.topicArn = topicArn;<br>    }<br><br>    /**<br>     * Publishes a single messages to SNS.<br>     *<br>     * @see #publish(java.util.Collection)<br>     */<br>    public SNSPublishResult publish(PublishBatchRequestEntry message) {<br>        return publish(List.of(message)).get(0);<br>    }<br><br>    /**<br>     * The {@code messages} will be published in batches due to SNS API limits. If any batch fails due to an Exception then publishing will stop. Prior messages<br>     * may have still sent. Be sure to check the returned result for details on what succeeded.<br>     */<br>    public SNSPublishResult publish(Collection&lt;PublishBatchRequestEntry&gt; messages) {<br>        // 1. Parition `messages` into SNS_MAX_BATCH_SIZE batches that also do not exceed SNS_MAX_PAYLOAD_BYTES payload size.<br>        //    - This is where the real value add is; implement to match AWS&#39;s definition of a &quot;payload.&quot;<br>        // 2. Attempt to publish each batch individually.<br>        //    - Catch any errors and handle appropriately.<br>        // 4. Consolidate all PublishBatchResponses into a custom `SNSPublishResult` that contains the relevant response information.<br>        return result;<br>    }<br>}</pre><h3>Arguments Against Wrappers</h3><p>For completeness, it is worth calling out some reasons to not use wrapper types. Like every other hammer in your toolbox, they are not ideal for every situation.</p><p>First, consider ramp-up time for new developers to learn to use the wrapper type. Unlike public libraries, an internal type doesn’t have StackOverflow as a utility for answering questions about how to use it. If you have <a href="https://stackoverflow.co/internal/">Stack Internal</a>, great! But that leaves out Google, Reddit, and other useful Q&amp;A utilities.</p><p>Second, ironically because of the prior issue, AI is also going to have issues helping with usage of the library. It will be bound by whatever you put in the docs, other AI-specific rules files, or examples in the code you have checked out at the time. So, remember to document your libraries well even if you practice self-documenting code.</p><p>Lastly, your wrapper type could be too restrictive for general utility. Be very cognizant of this at design time and try to find the right balance between:</p><ul><li>Over-engineering — thus making it as complicated as a low-level API.</li><li>Under-engineering — resulting in excuses to not use it which can cause inconsistent, harder to maintain apps. Or worse, “debates” about what to use/when that are backed strictly by opinions instead of facts.</li></ul><h3>Summary</h3><p>In the age of AI, it is easy to let design patterns fall by the wayside. Like Superman, AI can read, write, and modify code “faster than a speeding bullet.” Even as humans get involved and are modifying code, a lack of standards can lead to hard to manage code. The “time suck” can be especially prevalent at code review time. Investing in good design up-front can reduce the rate at which interest on tech debt is accrued.</p><p>Wrapper types are one mechanism for reducing overall debt and also:</p><ul><li>Exercise the SoC concept and can minimize scope of code changes.</li><li>May distill complex APIs into simpler, domain-focused interfaces.</li><li>Can be used early in development to guard against future, mass refactors.</li><li>Help define org-wide standards for API usage.</li><li>May add features and/or functionality to existing APIs.</li><li>Are not a hammer for every nail and should be used judiciously.</li></ul><h3>About the Author</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*NNFeE4WxN4QjdinD.jpeg" /></figure><p>Craig Hecock is a Principal Engineer at Clearwater Analytics with over 15 years of experience in software development. With a comprehensive background spanning front-end, back-end, and working on both SQL/NoSQL databases, he has a proven track record in triaging and debugging complex issues. Craig is passionate about leveraging technology to solve complex problems and improve user experiences. Aside from working on code, Craig is a strong advocate for team growth, enjoys mentoring others and helping them develop their skills as developers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8829a462b9c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cwan-engineering/managing-tech-debt-wrapper-types-8829a462b9c3">Managing Tech Debt — Wrapper Types</a> was originally published in <a href="https://medium.com/cwan-engineering">cwan-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Vibe Coding: Software Engineering with AI in Practice]]></title>
            <link>https://medium.com/cwan-engineering/beyond-vibe-coding-software-engineering-with-ai-in-practice-29075461a527?source=rss-6fb0d6055766------2</link>
            <guid isPermaLink="false">https://medium.com/p/29075461a527</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Clearwater Analytics Engineering]]></dc:creator>
            <pubDate>Fri, 12 Dec 2025 21:21:51 GMT</pubDate>
            <atom:updated>2025-12-12T21:26:14.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IvJPNh363imPDayvgzj63A.png" /></figure><h3>Introduction</h3><p>In the<a href="https://medium.com/cwan-engineering/vibe-check-software-engineering-with-ai-41d9808b802c"> first post of this series</a>, we looked at why naive “just ask the AI to code” approaches feel unpredictable, and how clear collaboration rules and coding standards make AI behave more like a reliable junior developer than a creative guesser.</p><p>This post goes <strong>beyond vibe coding</strong> and shows practical ways to work with AI coding agents to produce better-engineered software products in real projects.</p><p>As a senior engineer, you still own design, requirements, and architectural decisions. AI is most effective when you use chat to explore design options and clarify incomplete requirements, then capture the agreed plan in markdown. From there, you validate each step with incremental changes and tests to prevent regressions so progress stays both transparent and correct. The practical question becomes:</p><p>How do you make AI’s plan visible, keep it aligned with your design, and ensure tests and documentation stay integrated into your day-to-day workflow?</p><p>We’ll focus on three levers you control directly:</p><p>· <strong>Markdown feature files and TODOs</strong> as your steering wheel for AI execution.<br>· <strong>Testing guardrails</strong> that keep AI writing tests that actually protect your system.<br>· <strong>Design artifacts and tool memory</strong> that help you and AI stay aligned on architecture over time.</p><p>By the end, you’ll have a practical playbook for working with AI coding agents: how to turn vague tickets into clear feature definitions and visible markdown TODO lists, structure work as small reviewed commits, and use testing-as-you-go to prevent regressions. You’ll also see how to visualize architecture with lightweight diagrams so design, implementation, and tests stay aligned as the codebase evolves.</p><h3>1. The Transparency Problem</h3><p>Most AI coding tools do a surprising amount of planning that you never see.</p><p>They break problems into subtasks, choose an order of operations, and quietly maintain their own internal “todo list” as they work. Even when they show you a few bullet points in the chat window, that’s only a thin slice of the actual reasoning happening in the background.</p><p>That creates three problems:</p><p>· <strong>Hidden internal planning</strong> — You can’t inspect or edit the real plan the AI is following.<br>· <strong>Partial visibility</strong> — When the AI shows todos, you don’t know what it left out or silently changed.<br>· <strong>Session isolation</strong> — Whatever plan did exist evaporates as soon as the tab closes or the context window resets.</p><p>If you’ve ever had an AI “helpfully” tweak a few extra lines of code or string content you didn’t mention, you’ve already met this hidden plan. Somewhere, a little invisible project manager decided those changes were part of the sprint — it just forgot to loop you in.</p><p><strong>Claude Code’s Plan Mode</strong></p><p>Anthropic’s Claude Code agent exposes this hidden planning explicitly through an optional <em>plan mode</em> for larger tasks. Instead of diving straight into edits, it first generates a step-by-step plan you can review and adjust, then executes against that plan.</p><p>If you’re using Claude Code, it’s worth experimenting with plan mode whenever you ask for non-trivial changes (new features, refactors, multi-file edits). You still want the final plan written into your feature markdown file, but plan mode can give you a clearer starting point and make it easier to catch misunderstandings before code changes happen.</p><p>For humans, keeping the whole plan in your head leads to forgotten requirements and missed steps. AI runs into the same problem when the real plan only lives in its own working memory or a single session — you have less opportunity to review or correct it before code changes start.</p><p>The fix is <strong>moving the plan out of the AI’s head and into shared, persistent artifacts</strong> — markdown files, checklists, and test plans that live next to your code.</p><h3>2. Team Project Management vs Personal TODOs</h3><p>Team project management tools already do their job well.</p><p>· Jira, Linear, Azure DevOps, and similar tools handle priorities, dependencies, and releases.<br>· They often hold the <strong>official requirements</strong>, but those requirements aren’t engineering plans- they describe what to build, not how to build it.<br>· Product and project leaders use them to track what should happen <em>across</em> the team and when.</p><p>What they don’t give you is a <strong>step-by-step execution plan</strong> for how one engineer and one AI assistant will actually build a specific feature.</p><p>That’s where personal TODOs come in.</p><p>· <strong>Team tools</strong> answer: <em>What work exists? What’s the status?<br></em>· <strong>Personal TODOs</strong> answer: <em>What’s the implementation plan? What are the concrete steps that I want AI to execute. These are generally in a specific order and can be as detailed as pseudo code.</em></p><p>When you drop a Jira story directly into an AI chat and say “implement this,” you’re asking the AI to invent that execution plan in its own private memory. Instead, you want to:</p><p>· Translate the story into a <strong>sequence of small, explicit steps</strong>.<br>· Make that sequence visible in a markdown file that both you and the AI can see.<br>· Treat that list as the steering wheel: you decide what’s on it and in what order; the AI helps you execute.</p><p><strong>Using AI to Refine Requirements</strong></p><p>When you paste a ticket’s requirements into an AI coding agent, don’t stop at “understood.” Ask it to identify what’s unclear, list assumptions it would otherwise make, and propose follow-up questions. Iterate on that dialog until you both have a shared, concrete understanding. From there, you can work together to turn the clarified requirements into a step-by-step plan in a feature markdown file.</p><p>You don’t stop using Jira or your existing processes. You add a layer underneath them: <strong>per-feature TODOs and checklists</strong> that make the AI’s plan transparent and controllable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*gf_E8Hq0KwQTbG24yyhm0A.png" /></figure><p>The key insight: you and AI work together to turn requirements into an explicit implementation plan. That plan becomes the shared artifact you both execute against.</p><p>In the next section, we’ll put those TODOs into feature markdown files so both you and the AI are always working from the same shared plan.</p><h3>3. Practical Feature Markdown Planning</h3><p>Once you’ve used chat to clarify the requirements for a feature, you need a place to capture:</p><p>· Refined requirements<br>· Clarified questions and answers<br>· Step-by-step instructions (TODOs)<br>· Test plans and checkpoints<br>· Design notes and diagrams</p><p>A <strong>feature markdown file</strong> is the natural home for all of that.</p><h3>3.1 From Jira Story to Feature File</h3><p>A typical flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ANnc0CU9EcCxcteV--GPTw.png" /></figure><p>1. Start from a Jira (or Linear/Azure DevOps) story.<br>2. Create a feature file in your repo, for example:<br> · <em>docs/features/feature-101.md</em><br>3. Paste the story into the top of the file under a ## Requirements section.<br>4. Use a short series of interactive prompts with the AI to:<br> · Surface questions about unclear requirements and capture your answers in the feature file.<br> · Propose an initial implementation plan as a checklist of TODOs, then refine and reorder it based on your feedback.<br> · Recommend early validation and testing checkpoints, and update them as the design becomes clearer.</p><p>Here’s the kind of prompt you might give the AI:</p><pre>Create a feature file `docs/features/feature-101.md` for this feature.<br> <br> Here&#39;s the Jira story to seed your understanding:<br> [paste story details]<br> <br> Structure the file with these sections:<br> 1. **Requirements** - restate the story in your own words and list open questions.<br> 2. **Implementation Plan** - `[ ]` checkbox TODOs for tracking progress.<br> 3. **Implementation Workflow** - the steps you should follow for each TODO (for example: show which files you plan to change, explain your approach, wait for my approval, then run or update tests).<br> 4. **Checkpoints** - where we should pause and validate behavior.<br> 5. **Test Plan** - initial list of tests we&#39;ll need (we&#39;ll refine using TEST-PATTERNS.md later).<br> <br> This will be an interactive process: start by asking what requirements need clarification, then iterate as you propose and refine the TODO list and testing checkpoints based on my answers.</pre><p>You’re not asking the AI to disappear and “handle it.” You’re asking it to <strong>build the working surface you’ll both use</strong>.</p><h3>3.2 Treating the Checklist as the Steering Wheel</h3><p>Once you have the feature file and initial TODOs:</p><p>· You review and edit the TODO list.<br>· You explicitly choose which [ ] item to work on next.<br>· You ask the AI to focus on <strong>one checkbox at a time</strong>.</p><p>For example:</p><blockquote>“Let’s work on the next TODO in docs/features/feature-101.md.”</blockquote><p>As you and the AI complete work:</p><p>· The AI updates [ ] → [x] in the feature file.<br>· You both see the live progress and remaining scope.<br>· The plan survives beyond a single chat session because it lives in versioned markdown.</p><p>There’s also a small but real benefit: humans get the satisfaction of checking boxes, and AI tools get a clearer definition of “done” than a vague “keep going” in chat.</p><p><strong>Commit Progress Frequently</strong></p><p>Consider committing code after each meaningful TODO is completed. Small, reviewed commits make it easier to see exactly what the AI changed, spot unintended edits, and connect each change back to a specific checkbox in your feature file.</p><p>In the rest of this post, we’ll keep using this feature-file idea as the hub. We’ll plug in:</p><p>· A feature-level test plan section inside <em>docs/features/feature-101.md </em>that lists the concrete tests for this change.<br>· Team-wide testing guardrails from <em>TEST-PATTERNS.md</em> so every feature uses the same testing philosophy.<br>· Design and architecture diagrams via Mermaid.<br>· Tool memory as a helper around these markdown artifacts.</p><p>Transparent incremental steps lead to less developer frustration and more architecturally sound, testable code.</p><h3>4. Markdown as the Language of Design and Tests</h3><p>If feature files are the hub, markdown is the road surface everything runs on. Markdown hits a sweet spot:</p><p>· <strong>Human-readable</strong> — easy for engineers to review and edit.<br>· <strong>Machine-friendly</strong> — easy for AI to parse and for tools to transform.<br>· <strong>Flexible</strong> — supports text, checklists, code snippets, and diagrams in one place.</p><p>In practice, a feature file might include:</p><pre>· ## Requirements - restated story, edge cases, and clarifications.<br>· ## Implementation Plan - the checkbox TODOs you and the AI are working through.<br>· ## Implementation Workflow - agreed steps the AI should follow for each TODO.<br>· ## Test Plan - initial unit, integration, and E2E test ideas.<br>· ## Design &amp; Diagrams - Mermaid diagrams for flow, architecture, or sequences.<br>· ## Decisions - tradeoffs you made and why.<br>· ## Open Questions - unresolved items to revisit.</pre><p>Over time, this file becomes the <strong>single story of the feature</strong> — from problem to design to tests and implementation. AI isn’t just responding to whatever you said in the last prompt; it’s working inside a stable context that you can edit and refine.</p><pre># Feature 101 - Short, descriptive title<br> <br> ## Requirements<br> - Restated story in your own words<br> - Edge cases and constraints<br> - Open questions to resolve<br> <br> ## Implementation Plan<br> - [ ] Step 1 - small, concrete change<br> - [ ] Step 2 - next change<br> - [ ] Step 3 - follow-up work<br> <br> ## Implementation Workflow<br> For each TODO above, the AI should:<br> 1. Show which files it plans to change.<br> 2. Explain the approach.<br> 3. Wait for approval.<br> 4. Apply the change.<br> 5. Run or update tests.<br> <br> ## Test Plan<br> - Unit tests: what behaviors will be covered<br> - Integration/E2E tests: which workflows should be verified<br> <br> ## Design &amp; Diagrams<br> - Mermaid diagrams for data flow, component relationships, or sequences<br> <br> ## Decisions<br> - Key tradeoffs and why they were chosen<br> <br> ## Open Questions<br> - Items that still need clarification or follow-up</pre><p>In the <a href="https://medium.com/cwan-engineering/vibe-check-software-engineering-with-ai-41d9808b802c">previous Blog</a>, we said: <em>“Markdown is the language AI speaks.”</em> In this post, we’re putting that into practice. You’re not just pasting prompts into chat; you’re curating a set of markdown documents — feature files, coding standards, testing patterns — that define how AI collaborates with your team.</p><p><strong>From Feature File to Merge Request</strong></p><p>Because the feature file captures requirements, TODOs, test plans, and decisions, AI can also use it to draft merge request descriptions. Instead of trying to remember everything that changed, you can ask the AI to summarize<em> docs/features/feature-101.md</em> into a concise GitLab MR description that explains the intent, key changes, tests added or updated, and any known follow-ups.</p><h3>5. Test Patterns: TEST-PATTERNS.md</h3><p>Your feature file’s test plan describes <strong>what</strong> you’ll test for a specific change. A <em>TEST-PATTERNS.md</em> document describes <strong>how</strong> your team writes tests in general: mocking strategy, file and naming patterns, unit vs integration strategy, coverage expectations, and any tool- or framework-specific guidance (for example, that you use Jest or prefer MSW for API mocking).</p><p>Without this kind of shared reference, AI focuses on test metrics instead of writing high-value tests that protect customer experience. It’s easy for it to generate:</p><p>· Large numbers of shallow tests.<br>· Over-mocked tests that assert implementation details.<br>· Tests that pass even when user-facing behavior is broken.</p><p>The metrics can say 100% code coverage while your gut says 0% confidence that the code actually works.</p><p>A <em>TEST-PATTERNS.md</em> document gives AI a <strong>testing knowledge base</strong> it can use to build consistent test scaffolding:</p><p>· Where different types of tests live and how they’re named.<br>· What to mock and what to test for real.<br>· How to focus on externally visible behavior.<br>· What makes a test meaningful rather than just more coverage.</p><h3>5.1 Test Organization — Structure Tests Predictably</h3><p>AI needs clear rules about where tests go and how to organize them. Without this, tests end up scattered and inconsistent.</p><pre>## Test Organization Guidelines<br> - **Unit tests** - test individual components/functions in isolation.<br> - **Integration tests** - test how components work together.<br> - **Test location** - say whether tests live side-by-side with code or in a `__tests__` directory.<br> -- e.g., `Component.tsx` and `Component.test.tsx` in the same folder.<br> - **File naming** - define consistent patterns that make tests easy to find.<br> - **Test grouping** - keep related tests organized together logically.</pre><p>You don’t have to adopt a particular layout, but you should give AI clear project-level patterns so tests stay consistent and easy to discover for both humans and tools.</p><p><strong>Example file structure (one possible pattern):</strong></p><pre>src/components/ComponentName/<br> ├── Component.tsx<br> ├── Component.test.tsx # Unit tests with mocked dependencies<br> └── Component.msw.test.tsx # Integration tests with MSW (if you use it)</pre><p>One powerful way to do this is to include <strong>project-level code patterns</strong> directly in <em>TEST-PATTERNS.md</em> so AI can copy them when generating new tests.</p><p><strong>Example integration test with MSW (if your project uses it):</strong></p><pre>describe(&#39;Component with API&#39;, () =&gt; {<br>  beforeAll(() =&gt; server.listen())<br>  afterEach(() =&gt; server.resetHandlers())<br>  afterAll(() =&gt; server.close())<br> <br> it(&#39;loads and displays data&#39;, async () =&gt; {<br>   render(&lt;Component /&gt;)<br>   await screen.findByText(&#39;loaded data&#39;)<br>   })<br> })</pre><p>By giving AI a concrete pattern like this, you’re not just telling it “use MSW” — you’re showing exactly how MSW tests should look in your project so it can generate consistent scaffolding.</p><p>Using consistent structure and examples keeps tests uniform and cohesive across the project. It gives AI (and humans) a better chance of understanding existing patterns, finding tests that already exist, and implementing new tests in the right place.</p><h3>5.2 Mocking Philosophy — Test the Right Level</h3><p>Most AI coding tools learn how to write tests by analyzing your existing code and documentation. They infer patterns: where tests live, how they’re named, what they assert. A <em>TEST-PATTERNS.md</em> file makes it much more likely that those inferred patterns match what you actually want.</p><p>Out of the box, many tools can generate unit, functional, and basic regression tests on their own. Where they often need more guidance is <strong>choosing the right boundaries</strong> for API and integration testing. AI thrives on structured tasks and defined success criteria; without that structure, it’s easy for it to treat “more coverage” as the primary goal instead of writing tests that exercise meaningful behavior.</p><p>A mocking philosophy section in <em>TEST-PATTERNS.md</em> gives the AI a concrete target:</p><pre>## Mocking Guidelines<br> - **Mock external dependencies** - APIs, third‑party services, file system, database.<br> - **Don&#39;t mock what you&#39;re validating** - keep the component or function under test real.<br> - **Mock at the boundary** - intercept network calls and infrastructure, not domain logic.<br> - **Keep mocks simple** - return predictable data; avoid re‑implementing business rules in mocks.<br> - **Test behavior, not implementation** - assert outcomes that matter to users or callers.</pre><p>Instead of inventing its own approach, the assistant can align test generation with these rules.</p><pre>// ✅ DO: Mock external API hooks or clients<br> jest.mock(&#39;@services/api&#39;, () =&gt; ({<br>   useGetDataQuery: jest.fn(),<br>   useUpdateDataMutation: jest.fn(),<br> }))<br> <br> // ❌ DON&#39;T: Mock the code you&#39;re trying to validate<br>   jest.mock(&#39;./Component&#39;, () =&gt; ({<br>   internalHelper: jest.fn(),<br> }))</pre><p>In your feature file or prompts, you can tie this together:</p><blockquote>“When adding or updating tests for this feature, follow the Mocking Guidelines section in docs/TEST-PATTERNS.md.</blockquote><blockquote>Mock only external boundaries like network calls or storage; keep the component or function under test real, and focus assertions on observable behavior.”</blockquote><p>That combination — clear test patterns plus explicit prompts — helps the AI aim coverage at the layers you care about instead of just increasing the number of tests.</p><h3>5.3 Testing Approach — Test What Matters</h3><p>Given just a codebase, many AI tools will happily generate more tests. What they don’t automatically know is <strong>which behaviors actually matter</strong>: which flows are riskier, which edge cases are important, and which parts of the system are already covered.</p><p>A Testing Approach section in <em>TEST-PATTERNS.md</em> gives the assistant a checklist for <strong>where to look</strong> and <strong>what to prioritize</strong> when proposing or adding tests:</p><pre>## Testing Approach<br> <br> - **Start from behavior** - derive tests from user stories, feature files, and public APIs.<br> - **Test public interfaces** - functions, components, and endpoints that external callers use.<br> - **Test expected outcomes** - returned values, state changes, rendered output, or side effects that matter.<br> - **Cover edge cases** - invalid inputs, error conditions, and boundary scenarios called out in requirements.<br> - **Avoid implementation testing** - don&#39;t assert on private helpers, internal state, or specific hook usage.<br> - **Prefer fewer, meaningful tests** - focus on scenarios that would hurt users if they broke.</pre><p>You can then point the AI at both your feature file and this section when asking for tests:</p><blockquote>“For this feature, read <em>docs/features/feature-101.md</em> and the Testing Approach section in<em> </em>docs/TEST-PATTERNS.md.</blockquote><blockquote>Propose tests that cover the main workflows and edge cases described there, focusing on public interfaces and observable behavior.”</blockquote><p><strong>Example:</strong></p><pre>// ✅ DO: Test behavior and outcomes<br> it(&#39;shows a loading indicator while data is fetching&#39;, () =&gt; {<br>   mockQuery.mockReturnValue({ isLoading: true, data: null, error: null })<br>   render(&lt;ReportPage /&gt;)<br>   expect(screen.getByTestId(&#39;loading-spinner&#39;)).toBeInTheDocument()<br> })<br> <br> // ❌ DON&#39;T: Test internal implementation details<br> it(&#39;calls useReportQuery hook three times&#39;, () =&gt; {<br>   const spy = jest.spyOn(apiHooks, &#39;useReportQuery&#39;)<br>   render(&lt;ReportPage /&gt;)<br>   expect(spy).toHaveBeenCalledTimes(3) // fragile and tied to implementation<br> })</pre><p>By combining:</p><p>· <strong>Feature files</strong> (what this change is supposed to do), and<br>· <strong>Testing approach guidelines</strong> (how your team prefers to validate behavior),</p><p>you give the AI a much clearer target, so its proposed tests are more likely to follow your intended patterns and focus on behavior that matters.</p><h3>5.4 Quality Standards — Make Tests Meaningful</h3><p>The same software engineering principles that guide your coding standards should also guide your tests. Clear intent, single responsibility, and reliable behavior matter just as much in the test suite as they do in production code.</p><p>You can capture those expectations directly in <em>TEST-PATTERNS.md</em> so they become part of the context AI sees when it generates or updates tests:</p><pre>## Quality Standards<br> - **Clear test names** - describe the behavior being verified in plain language.<br> - **Single responsibility** - each test should verify one specific behavior or scenario.<br> - **Reliable assertions** - tests should fail when behavior breaks, and pass when it works.<br> - **Independent tests** - avoid coupling tests to each other or to run order.<br> - **Quality threshold** - define a minimum standard (for example, coverage or critical paths) so tests focus on the areas that matter most.</pre><p>Providing these test pattern prompts will give context to the AI to follow in how to write the tests:</p><blockquote>“When adding or updating tests, follow the Quality Standards section in docs/TEST-PATTERNS.md. Favor clear names, single responsibility, reliable assertions, and independence between tests.”</blockquote><p>That way, the assistant is working from the same quality bar you would apply if you were writing the tests by hand.</p><h3>6. Tool Memory and Persistent Context</h3><p>Modern AI tools often include some form of <strong>memory</strong> — a way to remember preferences, patterns, or past work across sessions. In Windsurf, for example, memories persist within a workspace and can be created automatically by the assistant or explicitly by the user.</p><p>That’s powerful, but there are important limits: in current tools, memories are usually tied to a single developer and workspace or project, they only capture slices of past context, and they can drift out of sync with the real codebase over time.</p><h3>6.1 What Tool Memory Is Good At</h3><p>Within a single developer’s workspace, memory can help with:</p><p>· Remembering your <strong>personal workflow patterns</strong> (how you like components structured, your preferred libraries).<br>· Recalling frequently used <strong>prompts or coding patterns</strong>.<br>· Keeping track of <strong>small preferences</strong> that don’t belong in team-wide docs.</p><p>Under the hood, tools usually:</p><p>· <strong>Store short text snippets or files</strong> as memories that describe preferences, patterns, or project-specific notes.<br>· <strong>Select a few relevant memories</strong> for each request based on simple heuristics or search, then include them alongside your prompt.<br>· <strong>Use those memories as extra context</strong>, not as a guarantee — if a memory is missing, vague, or outdated, the tool will still respond, just with less accurate guidance.</p><h3>6.2 Why Memory Isn’t Enough for Teams</h3><p>For team collaboration, memory has real limitations:</p><p>· <strong>Individual vs team context</strong> — your memories aren’t shared with teammates.<br>· <strong>Staleness</strong> — memories can become outdated as the codebase and practices evolve.<br>· <strong>Opacity</strong> — others can’t see or review what’s stored in your personal memory.</p><p>That’s why the core, team-wide rules still belong in <strong>versioned markdown documents in the repo</strong>, such as:</p><p>· <em>WORKING-TOGETHER.md</em> — collaboration rules for humans and AI.<br>·<strong><em> </em></strong><em>CODING-STANDARDS.md</em> — principle priorities, formatting guidance, patterns.<br>· <em>TEST-PATTERNS.md</em> — everything from the previous section.<br>· Feature files like <em>docs/features/feature-101.md</em>.<br>· Project-level rules files (for example, <em>.windsurf/rules or CLAUDE.md</em>).</p><h3>6.3 Tool Examples: Windsurf and Claude Code</h3><p>Both Windsurf and Claude Code support persistent context, but they do it in different ways.</p><p><strong>Windsurf (Cascade Memories and Rules)</strong></p><p>· <strong>Auto and explicit memories</strong> — Cascade can auto-generate memories during a conversation, or you can explicitly ask it to create one.<br>· <strong>Workspace-scoped</strong> — memories are tied to a specific workspace; they’re not shared across workspaces or between teammates by default.<br>· <strong>UI-managed</strong> — you can browse, edit, and delete memories in the Memories &amp; Rules panel.<br>· <strong>Complemented by rules files</strong> — global and workspace-level markdown rules (<em>global_rules.md, .windsurf/rules</em>) give Cascade project-wide behavior that lives in versioned files.</p><p><strong>Claude Code (File-Based Project Memories)</strong></p><p>· <strong>Markdown-first memory</strong> — Claude Code loads memory files (such as <em>CLAUDE.md</em> and any imported markdown) automatically into the project’s context when the workspace starts.<br>· <strong>Hierarchical loading</strong> — files higher in the directory tree are loaded first, with more specific files overriding or extending them.<br>· <strong>Versioned with code</strong> — these memory files live alongside your source, can be code-reviewed, and evolve through normal git workflows.<br>· <strong>Quick additions with #</strong> — inside Claude Code, you can press <em>#</em>, type a short note, and hit Enter to append that memory into the appropriate <em>CLAUDE.md</em> file so it’s available in future sessions.</p><p>Both approaches reinforce the same theme: use the tool’s memory features as a convenience layer, but keep the durable rules and patterns in <strong>human-readable, versioned markdown</strong> that your team controls.</p><h3>6.4 Best Practices for Memory and Markdown</h3><p>Tool memories are great at accumulating <strong>fragments of recent work</strong> — what you’ve been doing in this workspace or project — but they don’t automatically give you a complete architectural picture.</p><p>A practical split looks like this:</p><p><strong>Use tool memory for</strong>:<br> · Iterative, task-level context (recent features, commands, and patterns the agent keeps revisiting).<br> · Personal workflow preferences and frequently repeated snippets that help you move faster.</p><p><strong>Use markdown for</strong>:<br> · Team decisions and architectural patterns that should outlive any single session.<br> · Project-wide coding standards and testing practices.<br> · Feature design documents that capture requirements, TODOs, and design notes while a change is in progress.</p><p>Many teams find it useful to add an <em>ARCHITECTURE.md</em> at the root of the repo to capture high-level system design, key flows, and major dependencies in one place that both humans and AI can reference.</p><p>And in daily work:</p><p>· Explicitly <strong>point the AI to the right markdown docs</strong> at the start of a session.<br>· Periodically <strong>clean up memories</strong> so stale entries don’t interfere with actual code changes that happened between sessions.<br>· Consider adding a project-level rules file (like <em>.windsurf/rules</em> in Windsurf or <em>CLAUDE.md</em> in Claude Code) that tells the tool where to find <em>WORKING-TOGETHER.md, CODING-STANDARDS.md, TEST-PATTERNS.md</em>, and your feature files.</p><p>Feature requirements docs don’t have to be permanent artifacts; many teams keep them in lowercase files scoped to a single feature or ticket and clean them up once the work is complete.</p><p>When you describe patterns, processes, designs, and feature requirements in markdown, you give AI a consistent, shareable context that works across tools and across the whole team — not just within one person’s memory for a single session.</p><h3>7. Visual Design with Mermaid and AI</h3><p>Architecture diagrams are one of the fastest ways to align humans and AI on how a system works — or how it should work.</p><p>The good news is that AI is surprisingly good at <strong>turning code into diagrams and using diagrams as design input to guide code changes</strong>. Once again, markdown is the medium.</p><h3>7.1 Code to Diagrams — Understand Existing Systems</h3><p>When you point AI at a feature or subsystem and ask for diagrams, you’re asking it to:</p><p>· Analyze the code.<br>· Identify key components and relationships.<br>· Present that structure visually.</p><p>Helpful prompts include:</p><p>· “Document the current [feature] architecture.”<br>· “Create a Mermaid diagram showing component relationships for the reporting module.”<br>· “What are the responsibilities of each component in this flow?”<br>· “Show the data flow through this system from API to UI.”</p><p>The assistant can respond with Mermaid diagrams like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*9ZuLg3dozDAlLAlUsJ6Mhw.png" /></figure><p>Use cases:</p><p>· <strong>Onboarding</strong> new developers.<br>· Understanding <strong>legacy systems</strong> you didn’t build.<br>· Documenting previously <strong>undocumented code</strong>.<br>· Preparing for <strong>refactoring</strong> work.<br>· Preparing for <strong>larger code reviews</strong>.</p><p>If you’re using VS Code, installing a markdown preview extension that supports Mermaid (such as <em>Markdown Preview Enhanced</em>) lets you render these diagrams directly from your feature files.</p><h3>7.2 Diagrams to Better Code — Design Enhancement</h3><p>Diagrams also help before and during implementation:</p><p>· <strong>For new features</strong> — create diagrams before coding to validate the approach.<br>· <strong>For code reviews</strong> — generate architecture docs to explain complex changes.<br>· <strong>For refactors</strong> — visualize current vs target state to identify improvement opportunities.</p><p>You might ask:</p><p>· “Propose a high-level architecture diagram for adding CSV export to the reporting page.”</p><p>· “Show a sequence diagram for our new authentication flow, based on this feature file.”</p><p>· “Compare the current dependency graph to the proposed one and highlight risk areas.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*qQ0ygAzNIqjWHCipqXu_HQ.png" /></figure><p>Fifteen minutes of diagramming with AI — grounded in your code and feature files — can save hours of review time and misunderstandings later.</p><h3>8. Putting It All Together</h3><p>In the first post of this series, we focused on <strong>why</strong> naive AI usage fails and <strong>how</strong> to reset expectations by treating AI as a junior developer operating inside clear working agreements and coding standards.</p><p>In this post, we turned that philosophy into a concrete workflow for senior engineers:</p><p>· <strong>Make AI’s plan visible</strong> — use feature markdown files and checkbox TODOs to keep the execution plan out of the AI’s head and in your repo.<br>· <strong>Give AI testing guardrails</strong> — use <em>TEST-PATTERNS.md</em> to define where tests live, what to mock, what to test, and what “good” looks like.<br>· <strong>Anchor work in markdown</strong> — make sure key requirements, designs, tests, and decisions live in docs your team can see. Short‑lived TODOs can stay in feature requirements docs or personal lists; long‑lived features get shared, versioned docs.<br>· <strong>Use tool memory wisely</strong> — lean on it for personal preferences, but put team rules and feature context in shared documents.<br>· <strong>Visualize architecture with AI</strong> — generate and refine Mermaid diagrams to understand existing systems and design new ones.</p><p>A chat‑only workflow makes every feature feel like a new conversation; a markdown‑anchored workflow makes it feel like you and the AI are picking up the same notebook every time.</p><p>A simple end-to-end flow might look like this:</p><p>1. A Jira ticket is created for adding CSV export to a reporting page.<br>2. You create <em>docs/features/reporting-csv-export.md</em> and paste the story into a ## Requirements section.<br>3. With AI, you build a checklist of TODOs and a preliminary test plan in that file.<br>4. You link in <em>WORKING-TOGETHER.md, CODING-STANDARDS.md, and TEST-PATTERNS.md</em> so the assistant knows how to behave.<br>5. You work through TODOs one at a time, updating tests according to <em>TEST-PATTERNS.md</em>.<br>6. You ask AI to generate a sequence diagram to document the new data flow.<br>7. When the feature ships, you can either keep the feature requirements doc as a record, or fold its outcomes into longer-lived design docs (for example, updating<em> ARCHITECTURE.md</em> or a module-level design document).</p><p>These techniques optimize AI collaboration across the complete development lifecycle — architecture design, implementation, testing, documentation, and workflow optimization — while keeping you in the senior engineer role. Markdown is the language AI speaks; using it intentionally turns AI from an unpredictable partner into a reliable implementer working inside your standards and design.</p><p>The difference is simple: less vibe, more engineering.</p><h3>About the Author</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*XoEyBoQl43Qa4WK5Ti3tJA.jpeg" /></figure><p>Eric Christianson is a Staff Software Engineer at Clearwater Analytics with over 30 years of experience developing innovative technology solutions for leading companies. He focuses on creating user-friendly experiences and fostering collaboration across teams to solve complex challenges. Eric is currently leading efforts to build customer-facing applications developed with AI coding agents and providing AI-assisted workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29075461a527" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cwan-engineering/beyond-vibe-coding-software-engineering-with-ai-in-practice-29075461a527">Beyond Vibe Coding: Software Engineering with AI in Practice</a> was originally published in <a href="https://medium.com/cwan-engineering">cwan-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Check: Software Engineering with AI]]></title>
            <link>https://medium.com/cwan-engineering/vibe-check-software-engineering-with-ai-41d9808b802c?source=rss-6fb0d6055766------2</link>
            <guid isPermaLink="false">https://medium.com/p/41d9808b802c</guid>
            <category><![CDATA[ai-coding]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Clearwater Analytics Engineering]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 22:30:32 GMT</pubDate>
            <atom:updated>2026-01-04T22:19:04.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2G_bRFSN20rS623pTm9fUQ.png" /></figure><p>Software engineering is changing fast in the age of AI, and the way we design, build, and ship software is evolving with it. This multi-part series dives into practical techniques for using AI to boost productivity, keep code quality high, and help your teams move faster — without losing control of your architecture or standards.</p><h3><strong>Introduction</strong></h3><p>Teams are already using AI to build real features in real codebases, not just experiments or demos. The open question is how to make that work <strong>predictable and sustainable</strong> as systems grow more complex.</p><p>This post focuses on three things:</p><ul><li><strong>The vision</strong>: a development cycle where AI can carry a business requirement all the way to production-ready code.</li><li><strong>The transition phase we’re in now</strong>: AI as a powerful assistant that still needs structure, context, and guardrails.</li><li><strong>The practical foundation</strong>: treating AI as a junior developer, and capturing how we work together in a few small but important documents.</li></ul><p>By the end, you should have a clear mental model for AI’s role on the team and a concrete starting point for WORKING-TOGETHER.md and CODING-STANDARDS.md in your own coding project.</p><h3><strong>The Vision: From Requirements to Production-Ready Code</strong></h3><p>The industry’s ambitious goal is clear: <strong>transform a business requirement into production-ready code through AI automation</strong> — a development cycle where AI carries work from idea to implementation with minimal human intervention.</p><p>But there’s a critical insight that unlocks this vision: <strong>the same principles that make human developers successful apply to AI systems</strong>.</p><p>Just as vague requirements lead to failed projects and overly verbose specifications cause confusion, AI coding assistants need well-crafted context to deliver reliable results. The breakthrough isn’t in the AI’s capabilities alone, but in learning how to communicate requirements with the right balance of clarity and detail.</p><p>When we provide AI with well-structured context — clear objectives, specific constraints, relevant examples, and architectural guidance — we dramatically reduce guesswork and hallucination. Instead of improvising, the AI follows a clear path from business need to deployable feature.</p><p>The future of development isn’t just about smarter AI; it’s about <strong>becoming better requirement architects</strong> who can design the right inputs for automated code generation.</p><h3><strong>AI-Assisted Software Engineering: Beyond Vibe Coding</strong></h3><p>Until that vision is realized, humans are still responsible for building and maintaining high-quality software assets. The question becomes: <strong>how do we work with today’s AI tools in a way that is reliable, repeatable, and worth the investment?</strong></p><p>The difference between effective AI assistance and “vibe coding” lies in having a systematic approach rather than letting the AI rely on intuitive guessing.</p><p>When developers provide AI with:</p><ul><li>Access to technical documentation and requirements.</li><li>Clear examples of existing code patterns.</li><li>Explicit architectural constraints and boundaries.</li></ul><p>…the AI becomes a <strong>reliable implementer</strong> instead of a creative guesser.</p><p>This is where the mental model of AI as a <strong>junior developer</strong> is powerful. In this model:</p><ul><li>The AI excels at execution, reading documentation, following established patterns, and implementing solutions precisely.</li><li>The human acts as senior architect, making design decisions, clarifying requirements, and reviewing outcomes.</li></ul><p>Crucially, the AI <strong>should not</strong>:</p><ul><li>Make architectural decisions on its own.</li><li>Fill in missing requirements with assumptions.</li><li>Redesign systems because it “seems cleaner” without explicit direction.</li></ul><p>Thinking of the current phase as a <strong>transition period</strong> helps:</p><ul><li>Acknowledge the gap between our long-term vision and today’s reality.</li><li>Connect solid software design principles directly into AI-assisted code creation.</li><li>Frame AI as an effective tool that, with proper guidance and review, can significantly improve feature velocity.</li></ul><p>The rest of this post focuses on the practical pieces you can put in place now — project-level collaboration rules and coding standards — that make this AI-as-junior-developer model work in real codebases.</p><blockquote><strong>Markdown is the language AI speaks.</strong><br> It’s easy for humans to read and easy for AI to parse. Think of your markdown files as the instruction manual that tells AI how to behave in your project.</blockquote><h3><strong>Project-Level AI Collaboration Rules</strong></h3><p>Most teams have coding standards. Very few have <strong>explicit collaboration rules</strong> for how they’ll work with AI.</p><p>Without those rules written down, you get the worst of both worlds:</p><ul><li>AI improvises when it should ask questions.</li><li>Engineers get surprised by changes they didn’t intend.</li><li>Everyone spends more time managing miscommunication than building features.</li></ul><p>The fix is to treat these rules as a small, versioned artifact in your project — written in markdown — so both humans and AI can see and follow them. You might keep them in a dedicated file (such as WORKING-TOGETHER.md), or you might embed them into a tool-specific configuration file (like CLAUDE.md or a rules file). The filename is flexible; the <strong>content</strong> is what matters.</p><p>Four parts go a long way.</p><h4><strong>1. Clear Roles — You’re the Architect, AI Is the Coder</strong></h4><p>You’re the architect, AI is the coder. AI doesn’t get to make design decisions or guess what you want. It asks questions and implements what you tell it to do.</p><p>Here’s one way to express that as a markdown prompt block for your AI tool:</p><pre># Our Pair Programming Team<br>1. **You are the senior architect** - provide guidance, control commits, make decisions.<br>2. **I am the implementer** - follow your guidance, ensure architectural alignment.<br>3. **We use git** - you control all commits, I implement and explain changes.<br>4. **Incremental development** - you request features step-by-step, I implement exactly what&#39;s asked.<br>5. **One step at a time** - I won&#39;t do more than requested.<br>6. **Report discoveries** - if directions are unclear or I find issues, I report and wait for input.<br>7. **Present decision points** - I show options and wait for your decision.</pre><p>You can also experiment with a more concise variant:</p><p><strong>Alternative concise rule:</strong><br> <em>“AI generates code and suggestions, but humans own commits and architecture decisions. AI should not introduce new frameworks, services, or patterns without an explicit request.”</em></p><p>Both formats communicate the same idea; some tools respond better to a short, high-signal rule, others to a more explicit list.</p><h4><strong>2. Structured Communication — No More Guessing Games</strong></h4><p>AI works best when it knows how you expect it to communicate. Instead of ad hoc back-and-forth, give it a script you can paste directly into your rules file.</p><p>For example:</p><pre>## Communication Rules<br>- **STOP** when stuck, confused, or discovering issues.<br>- **REPORT** findings with full context and options.<br>- **WAIT** for your input before proceeding.<br>- **DOCUMENT** everything for transparency.</pre><p>You can extend that with more explicit analysis steps:</p><pre>- **ANALYZE** - restate the problem and evidence.<br>- **EXPLAIN** - outline what you plan to change and why.<br>- **GET APPROVAL** - wait for an explicit &quot;go ahead&quot; before larger changes.<br>- **ASK, don&#39;t assume** - when something is unclear, ask targeted questions instead of guessing.</pre><p><strong>Alternative concise rule:</strong><br><em>“For any non-trivial change, AI must restate the problem, propose an approach, and wait for confirmation before editing files.”</em></p><p>This turns AI from a black box into a collaborator who talks through the plan instead of silently changing things.</p><h4><strong>3. Validation Checkpoints — Catch Problems Early</strong></h4><p>Small course corrections beat large surprises. A few simple checkpoints keep you in control of what AI is doing.</p><p>You can express your implementation flow as a prompt like this:</p><pre>## Implementation Flow<br>1. **Before** - confirm understanding, verify architecture fit, get approval.<br>2. **During** - one step at a time, report issues immediately, document changes.<br>3. **After** - summarize what was done, explain integration, report next TODOs.</pre><p><strong>Alternative concise rule:</strong><br><em>“At the end of each step, AI summarizes the files changed, the behavior modified, and any follow-up TODOs before we move on.”</em></p><p>These checkpoints are cheap, and they prevent the “I have no idea what just changed” feeling that kills trust.</p><h4><strong>4. Quality Standards — Follow the Playbook</strong></h4><p>Finally, you can set expectations for code quality so AI doesn’t “cut corners” in ways your team wouldn’t.</p><p>For example, your high-level prompt might look like:</p><pre>## Code Quality Standards<br>- **Maintain consistency** - use established project patterns and conventions.<br>- **Quality first** - clean, readable code that follows team standards.<br>- **Link to coding standards** - follow the rules described in our coding standards document.</pre><p><strong><em>An example on how to link another document in a prompt:</em></strong></p><pre>- **Coding Standards** - see `docs/CODING-STANDARDS.md` patterns</pre><p>You can extend that with more detailed DO/DON’T guidance in the same markdown rules file or in a separate coding standards doc that you link to:</p><pre>- **DO** follow patterns in the repo and respect existing architecture and module boundaries.<br>- **DO** add or update tests when changing behavior.<br>- **DO** update relevant docs when introducing new patterns.<br>- **DON&#39;T** modify unrelated code &quot;for cleanliness&quot; without explicit agreement.<br>- **DON&#39;T** introduce new architectural patterns without discussion.<br>- **DON&#39;T** skip explanations for non-trivial changes.</pre><p><strong>Alternative concise rule:</strong><br><em>“Any change to business logic must include at least one test update (unit or integration) and a brief explanation of the behavior change.”</em></p><p>Writing these rules in markdown gives you a concrete contract for how you’ll collaborate. You can paste them into a collaboration rules file or integrate them into whatever AI tooling your team uses.</p><h3><strong>Coding Standards as the Team Playbook</strong></h3><p>If collaboration rules describe <em>how</em> you and AI work together, coding standards describe <em>how the code itself should look and behave</em>.</p><p>AI is extremely sensitive to examples. If your codebase is inconsistent, your prompts are vague, and your standards are scattered across Confluence, you’ll get equally inconsistent results from AI. A single, markdown-based coding standards document gives AI a concrete playbook to follow.</p><p>Before diving into specifics, it helps to name the key concepts your coding standards should cover:</p><ul><li><strong>Principle priorities</strong> — a clear hierarchy when DRY, SOLID, KISS, and YAGNI conflict (no guessing which matters more).</li><li><strong>Formatting rules</strong> — pointers to config files (Prettier, ESLint, TypeScript) instead of hardcoded, stale docs.</li><li><strong>Architectural patterns</strong> — component structure, naming conventions, file organization; follow existing patterns, don’t invent new ones.</li><li><strong>Quality gates</strong> — testing requirements, error handling, documentation standards; non-negotiable minimums.</li></ul><p>The following sections show how to turn each of these areas into markdown prompts that AI can follow.</p><h4><strong>1. Core Principles</strong></h4><p>Start by making your core principles explicit. This gives AI a shared vocabulary with the team.</p><pre>## Core Principles<br>- **DRY** - extract shared utilities, components, and constants.<br>- **SOLID** - single responsibility, focused interfaces, dependency injection.<br>- **KISS** - simple, readable code with clear names.<br>- **YAGNI** - only implement what&#39;s needed now.</pre><p>This mirrors what you’d expect from human engineers and gives AI a list of principles to reference when making tradeoffs.</p><h4><strong>2. Principle Conflict Resolution → Stop AI From Overthinking</strong></h4><p>When coding principles conflict, AI needs to know which one wins. Otherwise it can spend a lot of effort trying to satisfy everything perfectly.</p><p>You can encode your priorities like this:</p><pre>## Principle Conflict Resolution<br>**Priority Order**: YAGNI &gt; KISS &gt; SOLID &gt; DRY<br>- **Early Development**: YAGNI &gt; DRY (avoid premature abstraction).<br>- **Complex Features**: KISS &gt; SOLID (favor simple, understandable designs).<br>- **Mature Code**: SOLID &gt; DRY (good design over aggressive deduplication).<br>**Apply DRY only when**: 3+ instances AND stable requirements.</pre><p><strong>Optional Concise principle priority rule:</strong><br><em> “When DRY, SOLID, KISS, and YAGNI conflict, prioritize YAGNI &gt; KISS &gt; SOLID &gt; DRY. Apply DRY only after 3+ stable repetitions, and favor simple, well-factored code over perfect abstraction.”</em></p><h4><strong>3. Code Formatting → Point to Truth Sources</strong></h4><p>Formatting rules in documentation go stale quickly. Instead of duplicating them, point AI to the actual config files that your tooling already uses.</p><pre>## Code Formatting<br>- **Prettier** - see `.prettierrc` for current rules (`npm run prettier:fix`).<br>- **ESLint** - auto-fix on save, organize imports (see `.vscode/settings.json`).<br>- **TypeScript** - strict mode, path aliases (see `tsconfig.json` paths).</pre><p>This keeps the markdown light while still giving AI the right pointers into your real sources of truth.</p><h4><strong>4. Component Structure → Follow the Pattern</strong></h4><p>For UI work especially, structure matters. Show AI exactly how components should look and ask it to copy that pattern instead of inventing its own.</p><pre>## Component Structure<br>```typescript<br>interface ComponentProps {<br>// Props interface first<br>}<br>export const Component: React.FC&lt;ComponentProps&gt; = ({ prop1, prop2 }) =&gt; {<br>// Hooks at the top<br>const [state, setState] = useState()<br>const { data } = useQuery()<br>// Event handlers with useCallback<br>const handleClick = useCallback(() =&gt; {<br>// Implementation<br>}, [dependencies])<br>// Early returns for loading/error states<br>if (loading) return &lt;Spinner /&gt;<br>if (error) return &lt;ErrorMessage /&gt;<br>// Main render<br>return &lt;div&gt;{/* JSX */}&lt;/div&gt;<br>}</pre><p>Over time, this makes AI-generated components blend into the surrounding codebase instead of feeling like they came from a different project.</p><h4><strong>5. Testing and Quality Gates</strong></h4><p>Finally, set clear expectations for tests, error handling, and documentation. These are your quality gates — what must be true before code is considered ready.</p><pre>## Testing and Quality Gates<br>- **Testing patterns** - Link to testing patterns<br>- **Coverage** - use Jest (`npm test`), aim for meaningful tests over raw coverage metrics.<br>- **Separate concerns** - keep data fetching separate from presentation.<br>- **Focused interfaces** - prefer small, specific prop interfaces.<br>- **Clear naming** - use descriptive variables and function names.<br>- **Error handling** - provide graceful fallbacks and user-friendly messages.<br>- **Approriate Logging** – have log levels and actionable messages/data for triage.<br>- **Reuse existing patterns** - follow established project conventions.</pre><p><strong><em>An example on how to link another document in a prompt</em></strong></p><pre>- **Testing patterns** - see `docs/TEST-PATTERNS.md` for mocking, MSW integration, and component testing.</pre><p>Together, these prompts give AI a concrete sense of your coding style, structure, and quality expectations. Like your collaboration rules, you can evolve this document as your codebase and practices mature.</p><h3><strong>Tool Callout: Where These Prompts Live</strong></h3><p>So far, we’ve treated collaboration rules and coding standards as markdown text. Different tools have different ways to load that text and turn it into behavior, but the pattern is the same: write the rules once, let the tool read them automatically.</p><ul><li><strong>Claude Code (Anthropic)</strong> — uses CLAUDE.md files as instructions. A .claude.md file at the project root can include your collaboration rules and coding standards for the entire project. Additional CLAUDE.md files in subdirectories can scope rules to specific areas (for example, frontend/CLAUDE.md or services/payments/CLAUDE.md). A personal CLAUDE.md in your home directory can capture individual preferences.</li><li><strong>Windsurf</strong> — uses a project-specific rules configuration to define how AI behaves in that workspace. You can include your markdown prompts for collaboration and coding standards there so the assistant reads them automatically whenever you work in that project.</li><li><strong>OpenHands</strong> — uses policies and configuration to define what the agent is allowed to do and how it should behave. The same markdown rules can be translated into OpenHands policies, guiding its actions and guardrails instead of relying on ad hoc prompts.</li></ul><p>In each case, the goal is the same: move expectations out of one-off conversations and into versioned markdown that lives with your code.</p><h3><strong>Looking Ahead: Practical tool applications, managing feature additions, Markdown, and Design</strong></h3><p>In this post, we focused on <strong>why</strong> naive AI usage fails and <strong>how</strong> to reset expectations by treating AI as a junior developer operating inside clear working agreements and coding standards.</p><p>That’s the foundation. But once you put AI into your daily workflow, a new set of questions appears:</p><ul><li>How do you keep the AI’s plan visible instead of buried in a chat history?</li><li>How do you use markdown TODOs and feature requirement files to direct AI step-by-step instead of giving it huge, ambiguous tasks?</li><li>Does AI coding agent memory management matter?</li><li>How do you standardize test patterns so AI writes valuable tests instead of just more tests?</li><li>How do you use markdown and lightweight design artifacts to keep humans and AI aligned on architecture?</li></ul><p>Those are the problems the second part of this series will tackle. <a href="https://medium.com/cwan-engineering/beyond-vibe-coding-software-engineering-with-ai-in-practice-29075461a527">This link</a> will take you to part two.</p><h3><strong>About the Author</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*XoEyBoQl43Qa4WK5Ti3tJA.jpeg" /></figure><p>Eric Christianson is a Staff Software Engineer at Clearwater Analytics (CWAN) with over 30 years of experience developing innovative technology solutions for leading companies. He focuses on creating user-friendly experiences and fostering collaboration across teams to solve complex challenges. Eric is currently leading efforts to build customer-facing applications developed with AI coding agents and providing AI-assisted workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41d9808b802c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cwan-engineering/vibe-check-software-engineering-with-ai-41d9808b802c">Vibe Check: Software Engineering with AI</a> was originally published in <a href="https://medium.com/cwan-engineering">cwan-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Chaos to Clarity: Managing Dependencies and Environments in Python REST APIs Development]]></title>
            <link>https://medium.com/cwan-engineering/from-chaos-to-clarity-managing-dependencies-and-environments-in-python-rest-apis-development-7aff1d144148?source=rss-6fb0d6055766------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aff1d144148</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dependencies]]></category>
            <dc:creator><![CDATA[Clearwater Analytics Engineering]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 20:19:52 GMT</pubDate>
            <atom:updated>2025-07-25T20:19:52.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWdGXN3PU81nxdv-AFWPCQ.png" /></figure><p>Building REST APIs with Python is one of the quickest ways to deliver robust backends — until you need to get your code running consistently for every developer and across every system. Have you spent hours wrangling dependencies or trying to figure out why it breaks on your laptop, but not on someone else’s? You’re not alone!</p><p>In this blog, I’ll walk you through the biggest challenges I’ve faced (and seen others face) in streamlining Python REST API development, along with proven solutions to each centered on dependency management, environment consistency, onboarding, and debugging.</p><h3>Challenge 1: Dependency Confusion &amp; Version Hell</h3><p><strong>“It works on my machine, but not on deployment or my colleague’s!”</strong></p><h4>The Problem</h4><p>Python projects often depend on dozens of libraries, each with its own set of sub-dependencies. If your team isn’t careful, small differences in dependency versions can lead to hard-to-diagnose bugs or even total failure to start the app.</p><h4>Solutions</h4><p><strong>Option 1: </strong><a href="https://pip.pypa.io/en/stable/reference/requirements-file-format/"><strong>requirements.txt</strong></a></p><pre>fastapi==0.95.2<br>uvicorn==0.21.1<br>requests==2.31.0</pre><p><strong>Install with:</strong></p><pre>pip install -r requirements.txt</pre><p><strong>Pros:<br></strong>· Simple and universal<br>· Great for legacy or quick-and-dirty projects</p><p><strong>Cons:<br></strong>· No guarantee of exact versions for sub-dependencies<br>· No built-in separation for dev/prod dependencies</p><p><strong>Option 2: </strong><a href="https://python-poetry.org/"><strong>Poetry</strong></a></p><pre>pip install poetry<br>poetry init # guides you through pyproject.toml creation<br>poetry add fastapi uvicorn<br>poetry install</pre><p>· Generates both pyproject.toml and poetry.lock, which <em>lock all versions exactly</em> (including sub-dependencies), ensuring everyone gets the same environment.</p><p><strong>Pros:<br></strong>· Consistent installs everywhere — great for teams and CI/CD<br>· Handles dependency conflicts, dev/prod separation, and upgrades more gracefully</p><p><strong>Cons:<br></strong>· New tool for those used to requirements.txt (but worth the small learning curve)</p><p><strong>Quick Recommendation:</strong><br> If onboarding, reproducibility, or collaboration are priorities — use Poetry. For tiny or legacy projects, requirements.txt might suffice.</p><h3>Challenge 2: The “Works on My OS” Problem</h3><p><strong>“Why does the app run fine on Linux, but fail for Windows or Mac users?”</strong></p><h4>The Problem</h4><p>Even with consistent dependencies, differences in operating systems and local environments trip up lots of Python devs. OS-specific bugs, missing system libraries, or conflicting Python versions cause headaches and slow onboarding.</p><h4>Solution: <a href="https://www.docker.com/">Docker</a> &amp; <a href="https://docs.docker.com/compose/">Docker Compose</a></h4><p><strong>Dockerfile Example:</strong></p><pre>FROM python:3.12-slim <br>WORKDIR /app <br>COPY pyproject.toml poetry.lock ./<br>RUN pip install poetry &amp;&amp; poetry install --no-root<br> <br>COPY . .<br>EXPOSE 8000<br> <br>CMD [“poetry”, “run”, “uvicorn”, “main:app”, “--host”, “0.0.0.0”, “--port”, “8000”]</pre><p><strong>Run your project in a container:</strong></p><pre>docker build -t rest-api-app .<br>docker run -p 8000:8000 rest-api-app</pre><p>Now everyone on your team uses the <em>same</em> environment — no matter their OS.</p><p><strong>Scaling up? Use Docker Compose:</strong></p><p>docker-compose.yml</p><pre>services:<br> api:<br>   build: .<br>   ports:<br>    - “8000:8000”<br>   depends_on:<br>    - db<br> db:<br>   image: postgres:15<br>   environment:<br>     POSTGRES_DB: mydb<br>     POSTGRES_USER: myuser<br>     POSTGRES_PASSWORD: mypass</pre><p><strong>Spin up the entire stack:</strong></p><pre>docker-compose up --build</pre><p><strong>Benefits:</strong></p><p>· No more “it works on my machine” woes<br>· Super simple onboarding: just install Docker &amp; go</p><h3>Challenge 3: Onboarding New &amp; Junior Developers</h3><p><strong>“The project README is 20 steps long. Where do I start?!”</strong></p><h4>The Problem</h4><p>Complex setup instructions overwhelm new team members, leading to mistakes and hours wasted on setup instead of coding.</p><h4>Solution: Makefile (or Taskfile)</h4><p>A Makefile lets you hide all those tedious commands behind simple, memorable shortcuts.</p><p><strong>Example Makefile:</strong></p><pre>run:<br> poetry run uvicorn main:app --host 0.0.0.0 --port 8000<br> <br>docker-build:<br> docker build -t rest-api-app .<br> <br>docker-run:<br> docker run -p 8000:8000 rest-api-app<br> <br>compose-up:<br> docker-compose up --build</pre><p><strong>Now, onboarding = just one command:</strong></p><pre>make run # Start the server (local)<br>make docker-build<br>make compose-up # Start the entire stack</pre><p>No more long copy-paste commands. Less room for error. Faster time-to-productivity.</p><h3>Challenge 4: Debugging Inside Containers</h3><p><strong>“I can’t set breakpoints in my code — how do I debug in Docker?”</strong></p><h4>The Problem</h4><p>By default, debugging tools like breakpoints don’t work inside containers, and print statements only get you so far.</p><h4>Solution: debugpy + Your IDE</h4><ol><li><strong>Add debugpy</strong> as a dev dependency:</li></ol><pre>poetry add --dev debugpy</pre><p>2. <strong>Update Docker Compose:</strong></p><pre>services:<br> api:<br>   build: .<br>   ports:<br>     - “8000:8000”<br>     - “5678:5678” # For debugger<br>   volumes:<br>     - .:/app # Live-code reload<br>   command: &gt; <br>    poetry run python -m debugpy --listen 0.0.0.0:5678 --wait-for-client<br>   -m uvicorn main:app --host 0.0.0.0 --port 8000 --reload</pre><p><strong>3.</strong> <strong>In VS Code or PyCharm:<br> </strong>a. Attach your debugger to localhost:5678<br> b. Now, breakpoints and variable inspection work as expected — <em>inside</em> the container.</p><p>Debugging can once again be as smooth as local development.</p><h3>Challenge 5: “Do I Really Need All These Tools?”</h3><p><strong>“It feels overwhelming — what’s the minimum setup I can get away with?”</strong></p><h4>The Problem</h4><p>Using every tool, everywhere, can be overkill. Not every team or project has the same needs.</p><h4>Solution: Find Your Team’s “Just Right” Stack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vovUqvq-dRa6H9_aI8oKg.png" /></figure><p><strong>Takeaway:</strong><br> Pick the tools that solve <em>your</em> problems — no more, no less.</p><h3>Conclusion</h3><p>Streamlining REST API development in Python isn’t about using every new tool — but about picking the ones that directly eliminate common pain points: dependency hell, OS inconsistency, onboarding delays, and debugging headaches.</p><p>With Poetry (or requirements.txt), Docker, a simple Makefile, and debugpy for debugging, you’ll spend less time fighting setups and more time writing features. Start simple and add tools as your project (or team) grows. Your future self — and your teammates — will thank you!</p><h3>About the Author</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*Bd-Hm8rbF_Q_Tpt7nB-oSA.jpeg" /></figure><p>Mani Shankar Kumar is a Senior Software Engineer at Clearwater Analytics with over 11 years of hands-on experience in full-stack software development, cloud architecture, and AI-driven innovation. At Clearwater, he has been instrumental in leading the development of GenAI solutions, including the internal AI assistant Crystal, which significantly streamlined data access across the organization. Mani brings deep technical expertise across Java, Python, and Kotlin, combined with modern cloud ecosystems such as AWS and Azure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aff1d144148" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cwan-engineering/from-chaos-to-clarity-managing-dependencies-and-environments-in-python-rest-apis-development-7aff1d144148">From Chaos to Clarity: Managing Dependencies and Environments in Python REST APIs Development</a> was originally published in <a href="https://medium.com/cwan-engineering">cwan-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Multi-Agent Systems with LangGraph]]></title>
            <link>https://medium.com/cwan-engineering/building-multi-agent-systems-with-langgraph-04f90f312b8e?source=rss-6fb0d6055766------2</link>
            <guid isPermaLink="false">https://medium.com/p/04f90f312b8e</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Clearwater Analytics Engineering]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 15:16:41 GMT</pubDate>
            <atom:updated>2025-06-09T15:16:41.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LM9P6rwfquUTuuxEifIaWQ.png" /></figure><h3>Introduction to LangGraph</h3><p>In the previous <a href="https://medium.com/cwan-engineering/multi-agent-systems-and-cwic-flow-pioneering-ai-orchestration-5867ac9c0a34">article</a>, we explored the concept of multi-agent systems and how Clearwater Analytics pioneered this approach with CWIC Flow. We also demonstrated how to build a simple multi-agent system without specialized frameworks. Now, let’s explore LangGraph, a powerful library that provides structured workflows for building sophisticated multi-agent systems.</p><p>LangGraph is a library built on top of LangChain that allows you to create stateful, multi-agent applications with Large Language Models (LLMs). It provides a structured way to compose chains into graphs, manage state across multiple LLM calls, and build complex workflows with conditional routing.</p><h3>Understanding the Basics of LangGraph</h3><p>Before diving into implementation, let’s understand some key concepts in LangGraph:</p><ul><li><strong>State</strong>: The information that persists between different steps of your graph</li><li><strong>Nodes</strong>: Functions that process the state and return a new state</li><li><strong>Edges</strong>: Define how the state flows between nodes</li><li><strong>Graph</strong>: The overall workflow that connects nodes via edges</li></ul><p>This structured approach allows for more complex interactions between agents, including conditional routing, feedback loops, and persistent memory.</p><h3>Visual LangGraph Workflow</h3><p>Let’s visualize how a basic LangGraph works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*7MGmm56dYkhEvEwkbD3ACQ.png" /></figure><p>This diagram illustrates the key concepts:</p><ul><li><strong>State</strong> (blue boxes): Contains data that flows through the graph</li><li><strong>Nodes</strong> (purple boxes): Functions that process state and produce new state</li><li><strong>Edges</strong> (arrows): Define the flow from one node to the next</li><li><strong>Entry/Exit Points</strong> (green ovals): Where the workflow begins and ends</li></ul><h3>Environment Setup</h3><p>First, let’s make sure we have all the necessary packages installed. If you’re running this code for the first time, you’ll need to install the required packages.</p><h3>Install required packages</h3><pre># Install required packages with latest versions<br>!pip install langchain langchain-openai langgraph python-dotenv</pre><p>Now, let’s set up our environment variables. We’ll need an API key for OpenAI to use their models. Create a .env file in the same directory as this notebook with your OpenAI API key:</p><pre>OPENAI_API_KEY=your_api_key_here</pre><pre># Load environment variables from .env file<br>import os<br>from dotenv import load_dotenv<br>load_dotenv()  # Load API keys from .env file<br># Verify that the API key is loaded<br>if os.getenv(&quot;OPENAI_API_KEY&quot;) is None:<br>    print(&quot;Warning: OPENAI_API_KEY not found in environment variables.&quot;)<br>else:<br>    print(&quot;OPENAI_API_KEY found in environment variables.&quot;)</pre><h3>Importing Required Libraries</h3><p>Now, let’s import the libraries we’ll need for our multi-agent system:</p><pre># Import necessary libraries<br>from typing import Dict, List, TypedDict, Annotated, Sequence, Any, Optional, Literal, Union<br>import json<br># Modern imports for langchain and langgraph<br>from langchain_core.messages import HumanMessage, AIMessage, SystemMessage, BaseMessage<br>from langchain_openai import ChatOpenAI<br>from langgraph.graph import StateGraph, END</pre><h3>Creating a Simple LLM Helper Function</h3><p>Before we dive into multi-agent systems, let’s create a simple helper function to interact with an LLM. This will help us understand the basic building blocks of LangGraph.</p><pre>def ask_llm(prompt, model=&quot;gpt-4o&quot;, temperature=0.7):<br>    &quot;&quot;&quot;A simple function to get a response from an LLM.&quot;&quot;&quot;<br>    # Create a ChatOpenAI instance<br>    llm = ChatOpenAI(model=model, temperature=temperature)<br>    # Create a message with the prompt<br>    messages = [HumanMessage(content=prompt)]<br>    # Get a response from the LLM<br>    response = llm.invoke(messages)<br>    # Return the content of the response<br>    return response.content<br># Let&#39;s test our function<br>response = ask_llm(&quot;What is LangGraph and how does it relate to LangChain?&quot;)<br>print(response)</pre><p>Response output:</p><blockquote>LangGraph is an open-source library designed for building and managing complex applications that use large language models (LLMs). It is a framework that offers tools and components to create, customize, and execute workflows involving LLMs, making it easier to integrate these models into various applications. LangGraph is closely related to LangChain, as it can be thought of as an extension or complementary toolset to LangChain. LangChain is another framework specifically aimed at developing applications with LLMs, focusing on chaining together different components or tasks to create more complex workflows. LangGraph builds upon the principles of LangChain by providing additional functionalities and a more structured way to define and manage LLM-based applications. In essence, while LangChain focuses on the chaining of language model-powered tasks, LangGraph provides a more comprehensive framework that includes graph-based execution flows, enhanced control over tasks, and improved management of the interactions between different components. Together, these tools can be used to streamline the development and deployment of sophisticated applications leveraging the capabilities of LLMs.</blockquote><p>Let’s create a very simple graph with just one agent to understand these concepts:</p><pre># Define the state type<br>class SimpleState(TypedDict):<br>    messages: List[BaseMessage]  # The conversation history<br>    next: str  # Where to go next in the graph<br># Define a simple agent node<br>def simple_agent(state: SimpleState) -&gt; SimpleState:<br>    &quot;&quot;&quot;A simple agent that responds to the last message.&quot;&quot;&quot;<br>    messages = state[&quot;messages&quot;]<br>    llm = ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0.7)<br>    response = llm.invoke(messages)<br>    return {&quot;messages&quot;: messages + [response], &quot;next&quot;: &quot;output&quot;}<br># Define an output node<br>def output(state: SimpleState):<br>    &quot;&quot;&quot;Return the final state. This marks the end of the workflow.&quot;&quot;&quot;<br>    return {&quot;messages&quot;: state[&quot;messages&quot;], &quot;next&quot;: END}<br># Build the graph<br>def build_simple_graph():<br>    &quot;&quot;&quot;Build a simple LangGraph workflow.&quot;&quot;&quot;<br>    # Create a new graph<br>    workflow = StateGraph(SimpleState)<br>    # Add nodes<br>    workflow.add_node(&quot;agent&quot;, simple_agent)<br>    workflow.add_node(&quot;output&quot;, output)<br>    # Add edges<br>    workflow.add_edge(&quot;agent&quot;, &quot;output&quot;)<br>    # Set the entry point<br>    workflow.set_entry_point(&quot;agent&quot;)<br>    # Compile the graph<br>    return workflow.compile()</pre><p>Now, let’s run our simple graph:</p><pre># Create the graph<br>simple_graph = build_simple_graph()<br># Initialize the state with a test message<br>initial_state = {<br>    &quot;messages&quot;: [HumanMessage(content=&quot;Explain what a multi-agent system is in simple terms.&quot;)],<br>    &quot;next&quot;: &quot;&quot;<br>}<br># Run the graph<br>result = simple_graph.invoke(initial_state)<br># Print the conversation<br>for message in result[&quot;messages&quot;]:<br>    if isinstance(message, HumanMessage):<br>        print(f&quot;Human: {message.content}&quot;)<br>    elif isinstance(message, AIMessage):<br>        print(f&quot;AI: {message.content}&quot;)</pre><p>Output:</p><blockquote>Human: Explain what a multi-agent system is in simple terms.<br>AI: A multi-agent system is a collection of independent “agents” that interact with each other. Think of each agent as an individual with its own ability to make decisions, similar to how people can think and act on their own. These agents work together or compete to achieve specific goals or complete tasks.<br>In simple terms, imagine a group of robots that clean your house. Each robot is an agent. One might vacuum the floors, another might dust the furniture, and another might take out the trash. They all work independently but communicate and coordinate with each other to make sure the entire house is cleaned efficiently. This is the essence of a multi-agent system: multiple entities working together, often in a coordinated manner, to perform complex tasks or solve problems.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hNF0R3qW5OEmhTW60ZOkg.png" /></figure><p>This diagram shows:</p><ol><li>The overall flow from Start → Agent → Output → End</li><li>The Agent Process subgraph showing the internal steps of the simple_agent function</li><li>The State subgraph showing the components of the SimpleState TypedDict</li><li>Color-coded nodes to distinguish different types of components</li></ol><p>The workflow starts with an initial state containing messages and next fields, processes it through the Agent node which adds a response using the LLM, then passes it to the Output node which returns the final state, ending the workflow.</p><p>Now, let’s understand what just happened:</p><ol><li>We defined a state schema (SimpleState) with the fields we want to track.</li><li>We created nodes for the agent and output functions.</li><li>We connected these nodes with edges to define the flow of information.</li><li>We set up an entry point and compiled the graph.</li><li>We initialized the state with a human message and ran the graph.</li></ol><p>This simple example illustrates the basic concepts of LangGraph. In real-world scenarios, you can create much more complex graphs with multiple nodes and conditional edges.</p><h3>What’s Next</h3><p>In the next step, we’ll build our first specialized agent: the researcher agent. We’ll dive deeper into agent design patterns, learn how to define agent roles and capabilities, and see how to make the agent perform research tasks effectively.</p><h3>Creating a Specialized Researcher Agent</h3><p>In the previous step, we set up our environment and created a simple graph with a single agent. Now, we’ll build our first specialized agent for our collaborative research assistant system: the researcher agent.</p><p>In this step, we’ll focus on building the Researcher Agent — the component responsible for gathering and analyzing information.</p><h3>What is a Researcher Agent?</h3><p>A Researcher Agent is an AI system designed to thoroughly investigate topics and provide comprehensive, well-structured information. It serves as the information-gathering component in our multi-agent system with capabilities to:</p><ol><li>Understand research queries deeply</li><li>Collect relevant information comprehensively</li><li>Organize findings in a structured, accessible format</li><li>Present information objectively and accurately</li><li>Identify limitations and gaps in available information</li></ol><h3>Building a Modern Researcher Agent with LangGraph</h3><p>The latest versions of LangGraph and LangChain offer improved approaches to building agents. Let’s explore how to create a Researcher Agent using these modern tools.</p><h4>Step 1: Setting Up the Environment</h4><p>First, we need to import the necessary libraries. Note the modern import paths for LangChain and LangGraph:</p><pre>from typing import Dict, List, TypedDict, Any, Optional<br>import json<br>import os<br>from dotenv import load_dotenv<br># Modern imports for langchain and langgraph<br>from langchain_core.messages import HumanMessage, AIMessage, SystemMessage, BaseMessage<br>from langchain_openai import ChatOpenAI<br>from langgraph.graph import StateGraph, END<br># Load environment variables<br>load_dotenv()</pre><h4>Step 2: Defining the Researcher’s Role</h4><p>A clear system prompt is crucial for shaping the agent’s behavior:</p><pre>RESEARCHER_SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are a skilled research agent tasked with gathering comprehensive information on a given topic. <br>Your responsibilities include:<br>1. Analyzing the research query to understand what information is needed<br>2. Conducting thorough research to collect relevant facts, data, and perspectives<br>3. Organizing information in a clear, structured format<br>4. Ensuring accuracy and objectivity in your findings<br>5. Citing sources or noting where information might need verification<br>6. Identifying potential gaps in the information<br>Present your findings in a well-structured format with clear sections and bullet points where appropriate.<br>Your goal is to provide comprehensive, accurate, and useful information that fully addresses the research query.<br>&quot;&quot;&quot;</pre><h4>Step 3: Creating the Researcher Function</h4><p>Now we’ll implement the researcher agent as a function:</p><pre>def create_researcher_agent(model=&quot;gpt-4o&quot;, temperature=0.7):<br>    &quot;&quot;&quot;Create a researcher agent using the specified LLM.&quot;&quot;&quot;<br>    # Initialize the model<br>    llm = ChatOpenAI(model=model, temperature=temperature)<br>    def researcher_function(messages):<br>        &quot;&quot;&quot;Function that processes messages and returns a response from the researcher agent.&quot;&quot;&quot;<br>        # Add the system prompt if it&#39;s not already there<br>        if not messages or not isinstance(messages[0], SystemMessage) or messages[0].content != RESEARCHER_SYSTEM_PROMPT:<br>            messages = [SystemMessage(content=RESEARCHER_SYSTEM_PROMPT)] + (messages if isinstance(messages, list) else [])<br>        # Get response from the LLM<br>        response = llm.invoke(messages)<br>        return response<br>    return researcher_function</pre><h3>Integrating with LangGraph: The Modern Approach</h3><p>The latest version of LangGraph uses TypedDict for state management, providing better type safety and clearer state structure:</p><pre># Define the state type for our research workflow<br>class ResearchState(TypedDict):<br>    &quot;&quot;&quot;Type definition for our research workflow state.&quot;&quot;&quot;<br>    messages: List[BaseMessage]  # The conversation history<br>    query: str  # The research query<br>    research: Optional[str]  # The research findings<br>    next: Optional[str]  # Where to go next in the graph</pre><h4>Creating a Researcher Node</h4><p>Next, we implement a node for our LangGraph workflow:</p><pre>def researcher_node(state: ResearchState) -&gt; ResearchState:<br>    &quot;&quot;&quot;A node in our graph that performs research on the query.&quot;&quot;&quot;<br>    # Get the query from the state<br>    query = state[&quot;query&quot;]<br>    # Create a message specifically for the researcher<br>    research_message = HumanMessage(content=f&quot;Please research the following topic thoroughly: {query}&quot;)<br>    # Get the researcher agent<br>    researcher = create_researcher_agent()<br>    # Get response from the researcher agent<br>    response = researcher([research_message])<br>    # Update the state with the research findings<br>    new_messages = state[&quot;messages&quot;] + [research_message, response]<br>    # Return the updated state<br>    return {<br>        **state,<br>        &quot;messages&quot;: new_messages,<br>        &quot;research&quot;: response.content,<br>        &quot;next&quot;: &quot;output&quot;  # In a multi-agent system, this would go to the next agent<br>    }</pre><h4>Building the Research Workflow</h4><p>Now we can build a complete LangGraph workflow:</p><pre>def build_research_graph():<br>    &quot;&quot;&quot;Build a simple research workflow using LangGraph.&quot;&quot;&quot;<br>    # Create a new graph with our state type<br>    workflow = StateGraph(ResearchState)<br>    # Add nodes<br>    workflow.add_node(&quot;researcher&quot;, researcher_node)<br>    workflow.add_node(&quot;output&quot;, output_node)<br>    # Add edges<br>    workflow.add_edge(&quot;researcher&quot;, &quot;output&quot;)<br>    # Set the entry point<br>    workflow.set_entry_point(&quot;researcher&quot;)<br>    # Compile the graph<br>    return workflow.compile()</pre><p>Here’s a visual representation of our workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*bbX9Dh-rzTvIx5234CP2vw.png" /></figure><h4>Enhancing the Researcher Agent with Structured Output</h4><p>For better integration with other agents, we can enhance our researcher to provide structured output:</p><pre>ENHANCED_RESEARCHER_PROMPT = &quot;&quot;&quot;<br>You are a skilled research agent tasked with gathering comprehensive information on a given topic. <br>Your responsibilities include:<br>1. Analyzing the research query to understand what information is needed<br>2. Conducting thorough research to collect relevant facts, data, and perspectives<br>3. Organizing information in a clear, structured format<br>4. Ensuring accuracy and objectivity in your findings<br>5. Citing sources or noting where information might need verification<br>6. Identifying potential gaps in the information<br>Present your findings in the following structured format:<br>SUMMARY: A brief overview of your findings (2-3 sentences)<br>KEY POINTS:<br>- Point 1<br>- Point 2<br>- Point 3<br>DETAILED FINDINGS:<br>1. [Topic Area 1]<br>   - Details and explanations<br>   - Supporting evidence<br>   - Different perspectives if applicable<br>2. [Topic Area 2]<br>   - Details and explanations<br>   - Supporting evidence<br>   - Different perspectives if applicable<br>GAPS AND LIMITATIONS:<br>- Identify any areas where information might be incomplete<br>- Note any contradictions or areas of debate<br>- Suggest additional research that might be needed<br>Your goal is to provide comprehensive, accurate, and useful information that fully addresses the research query.<br>&quot;&quot;&quot;</pre><p>This structured format makes it easier for subsequent agents (like critics and writers) to process and build upon the researcher’s findings.</p><h4>A More Robust Research Workflow</h4><p>With our enhanced researcher agent, we can create a more robust workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*_BBfeYZv5rHm0GUPGoGftw.png" /></figure><p>We implement this workflow with a specialized state type:</p><pre>class EnhancedResearchState(TypedDict):<br>    &quot;&quot;&quot;Enhanced type definition for our research workflow state.&quot;&quot;&quot;<br>    messages: List[BaseMessage]<br>    query: str<br>    structured_research: Optional[str]<br>    next: Optional[str]</pre><h4>Researcher Agent in Action: An Example Query</h4><p>Let’s see how our enhanced researcher agent handles a complex query:</p><p>Query: “What are the latest advancements in renewable energy technologies?”</p><p>Response (structured format):</p><blockquote>SUMMARY: Recent advancements in renewable energy technologies include significant improvements in solar cell efficiency, innovative wind turbine designs, enhanced energy storage solutions, breakthroughs in green hydrogen production, and developments in advanced biofuels.<br>KEY POINTS:<br>- Solar PV technology has achieved record efficiency levels with perovskite-silicon tandem cells exceeding 30% efficiency<br>- Floating offshore wind turbines are expanding deployment possibilities in deeper waters<br>- Grid-scale battery storage costs have declined dramatically while energy density has increased<br>- Green hydrogen production via electrolysis has become more efficient and economically viable<br>- Advanced biofuels from non-food biomass sources are approaching commercial viability<br>DETAILED FINDINGS:<br>1. Solar Energy Advancements<br> — Perovskite solar cells have rapidly improved, with lab efficiencies exceeding 25%<br> — Perovskite-silicon tandem cells have reached 31.25% efficiency, approaching the theoretical limit<br> — Bifacial solar panels that capture light from both sides increase energy yield by 5–30%<br> — Building-integrated photovoltaics (BIPV) have advanced with transparent solar cells for windows<br> — Agrivoltaics systems that combine farming with solar production have shown promising results<br>2. Wind Energy Innovations<br> — Larger turbines with blades exceeding 100 meters in length have increased capacity factors<br> — Floating offshore wind platforms enable deployment in waters 60+ meters deep<br> — Airborne wind energy systems (kite and drone-based) are in advanced testing<br> — Bladeless wind turbines using oscillation technology reduce wildlife impacts and maintenance costs<br> — Digital twin technology and AI improving predictive maintenance and output optimization<br>[additional sections omitted for brevity]<br>GAPS AND LIMITATIONS:<br>- Long-duration energy storage (10+ hours) remains a significant challenge despite advancements<br>- Most breakthrough technologies mentioned are still scaling from lab to commercial deployment<br>- Cost comparisons between emerging technologies often lack standardized metrics<br>- Environmental impacts of some newer technologies (like certain rare earth mining for magnets) need further study<br>- Regional differences in technology adoption and policy support create uneven advancement landscapes</blockquote><h4>Benefits of the Modern Approach</h4><p>The modern approach to building researcher agents with LangGraph offers several advantages:</p><ol><li><strong>Type Safety</strong>: TypedDict provides better type checking and documentation</li><li><strong>Structured State</strong>: Clearly defined state structure improves maintainability</li><li><strong>Modular Design</strong>: Functions and components can be easily reused and tested</li><li><strong>Modern APIs</strong>: Using the latest LangChain and LangGraph APIs ensures compatibility</li></ol><h3>Next Steps: Building a Complete Multi-Agent System</h3><p>The researcher agent is just the first step in building a comprehensive multi-agent system. In future articles, we’ll explore:</p><ol><li>Building a Critic Agent to evaluate and challenge the researcher’s findings</li><li>Creating a Writer Agent to synthesize information into cohesive content</li><li>Implementing a Coordinator Agent to manage workflow between agents</li><li>Developing advanced routing logic for more dynamic agent interactions</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*-kzDbJv1M6-34cNBE6X56A.png" /></figure><p>Building a modern researcher agent with LangGraph provides a powerful foundation for multi-agent systems. By leveraging the latest APIs and structured approaches to agent development, we can create more effective, maintainable, and powerful AI systems that collaborate to solve complex problems.</p><p>The researcher agent we’ve built demonstrates how specialized agents can be designed to fulfill specific roles within a larger system — gathering and organizing information that can then be evaluated, refined, and presented by other agents in the workflow.</p><p>As we continue to explore multi-agent systems, we’ll see how these specialized components can work together to create AI solutions that surpass what any single model could accomplish alone.</p><h3>Adding a Critic Agent</h3><p>In the previous steps, we set up our environment and created a researcher agent. Now, we’ll add a second specialized agent to our collaborative research assistant system: the critic agent.</p><h4>The Concept of a Critic Agent</h4><p>A Critic Agent is designed to evaluate, challenge, and improve the work of other agents. Just as human work benefits from peer review and constructive criticism, AI outputs can be significantly enhanced by dedicated evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*XYW9QOhEaqxTfaZnDPp_YQ.png" /></figure><p>The Critic Agent serves critical functions in a multi-agent workflow:</p><ol><li><strong>Quality Assurance</strong>: Identifies inaccuracies, gaps, or flaws in the research</li><li><strong>Bias Detection</strong>: Highlights potential biases in the provided information</li><li><strong>Completeness Check</strong>: Ensures all aspects of a topic are adequately covered</li><li><strong>Alternative Perspectives</strong>: Introduces different viewpoints or interpretations</li><li><strong>Constructive Feedback</strong>: Provides actionable suggestions for improvement</li></ol><h4>Modern Implementation with LangGraph</h4><p>The latest versions of LangGraph and LangChain provide powerful tools for building more robust and maintainable multi-agent systems. Let’s explore how to implement a Critic Agent using these modern frameworks.</p><h4>Core Components</h4><p>Our implementation focuses on three key elements:</p><ol><li><strong>Type Safety</strong>: Using TypedDict for state management</li><li><strong>Structured Output</strong>: Enhancing the critic with structured JSON feedback</li><li><strong>Modular Design</strong>: Creating reusable agent functions</li></ol><h4>The Critic’s System Prompt</h4><p>The foundation of our Critic Agent is a well-crafted system prompt that establishes its role and responsibilities:</p><pre>CRITIC_SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are a Critic Agent, part of a collaborative research assistant system. Your role is to evaluate <br>and challenge information provided by the Researcher Agent to ensure accuracy, completeness, and objectivity.<br>Your responsibilities include:<br>1. Analyzing research findings for accuracy, completeness, and potential biases<br>2. Identifying gaps in the information or logical inconsistencies<br>3. Asking important questions that might have been overlooked<br>4. Suggesting improvements or alternative perspectives<br>5. Ensuring that the final information is balanced and well-rounded<br>Be constructive in your criticism. Your goal is not to dismiss the researcher&#39;s work, but to strengthen it.<br>Format your feedback in a clear, organized manner, highlighting specific points that need attention.<br>Remember, your ultimate goal is to ensure that the final research output is of the highest quality possible.<br>&quot;&quot;&quot;</pre><h4>Modern State Management</h4><p>A significant improvement in recent versions of LangGraph is better state management through TypedDict:</p><pre>class CollaborativeResearchState(TypedDict):<br>    &quot;&quot;&quot;State type for our collaborative research assistant.&quot;&quot;&quot;<br>    messages: List[BaseMessage]  # The conversation history<br>    next: Optional[str]  # Where to go next in the graph</pre><p>This approach provides clear type hints and makes the code more maintainable.</p><h4>The Workflow: Researcher → Critic</h4><p>Let’s visualize the basic flow of information between our Researcher and Critic agents:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccAacO6uD7TLEGQrYakbnA.png" /></figure><p>Our LangGraph implementation defines this workflow with modern syntax:</p><pre>def build_collaborative_research_assistant():<br>    &quot;&quot;&quot;Build a collaborative research assistant with researcher and critic agents.&quot;&quot;&quot;<br>    # Create a new graph with our state type<br>    workflow = StateGraph(CollaborativeResearchState)<br>    # Add nodes<br>    workflow.add_node(&quot;researcher&quot;, researcher_node)<br>    workflow.add_node(&quot;critic&quot;, critic_node)<br>    workflow.add_node(&quot;output&quot;, output_node)<br>    # Add edges<br>    workflow.add_edge(&quot;researcher&quot;, &quot;critic&quot;)<br>    workflow.add_edge(&quot;critic&quot;, &quot;output&quot;)<br>    # Set the entry point<br>    workflow.set_entry_point(&quot;researcher&quot;)<br>    # Compile the graph<br>    return workflow.compile()</pre><h4>Enhancing the Critic with Structured Output</h4><p>To make our Critic Agent more useful for downstream processes, we can enhance it to provide structured feedback in JSON format. This makes it easier for other agents (like a Writer Agent) to process and incorporate the criticism.</p><p>Here’s how we implement structured critique:</p><pre>class CriticEvaluation(BaseModel):<br>    &quot;&quot;&quot;Structured format for critic evaluations.&quot;&quot;&quot;<br>    quality_score: int = Field(description=&quot;Overall quality score from 1-10&quot;)<br>    strengths: List[str] = Field(description=&quot;Key strengths of the research&quot;)<br>    areas_for_improvement: List[str] = Field(description=&quot;Areas that need improvement&quot;)<br>    missing_information: List[str] = Field(description=&quot;Important information that was not included&quot;)<br>    bias_assessment: str = Field(description=&quot;Assessment of potential biases in the research&quot;)<br>    additional_questions: List[str] = Field(description=&quot;Questions that should be addressed&quot;)</pre><p>This structured approach allows us to build a more robust workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1kO3LM0Z1q9ySPykmNuWg.png" /></figure><h4>The Complete Multi-Agent Research Process</h4><p>When we put it all together, our multi-agent system follows this process:</p><ol><li><strong>User Input</strong>: The user submits a research question</li><li><strong>Research Phase</strong>: The Researcher Agent gathers and organizes information</li><li><strong>Critique Phase</strong>: The Critic Agent evaluates the research for quality and completeness</li><li><strong>Structured Feedback</strong>: The system provides organized, actionable criticism</li><li><strong>Final Output</strong>: The combined research and critique provide a comprehensive response</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33XvhQtkJ3irrgW68J2VxQ.png" /></figure><h4>Benefits of the Modern Approach</h4><p>The modern implementation using the latest LangGraph and LangChain APIs offers several advantages:</p><ol><li><strong>Type Safety</strong>: Properly typed states reduce errors and improve code maintainability</li><li><strong>Structured Output</strong>: JSON-formatted criticism enables easier integration with other components</li><li><strong>Better Maintainability</strong>: Clear separation of concerns with modular agent design</li><li><strong>Visualization Support</strong>: Built-in tools for workflow visualization and understanding</li></ol><p>By adding a Critic Agent to our multi-agent system, we create a powerful check-and-balance mechanism that improves the quality, accuracy, and completeness of our AI-generated research. This approach mimics human collaborative processes, where peer review and constructive criticism lead to better outcomes.</p><p>The structured criticism approach also provides a foundation for the next step in our multi-agent journey: adding a Writer Agent that can synthesize the research and critique into a coherent, well-crafted final response.</p><p>In our next section, we’ll explore how to build this Writer Agent and complete our multi-agent research assistant system.</p><h3>The Writer Agent</h3><p>In the previous steps of this article, we explored how to build a collaborative research assistant with specialized agents: a researcher agent to gather information and a critic agent to evaluate and challenge that information. Now, it’s time to add the third essential component: a writer agent that will synthesize this information into a coherent, well-written response. This section explores how to implement a Writer Agent that synthesizes information and produces coherent, comprehensive outputs — creating a complete collaborative research workflow that mirrors human teams of researchers, editors, and writers.</p><h4>The Concept of a Writer Agent</h4><p>A Writer Agent serves as the final communicator in a multi-agent system, transforming raw research and critical analysis into polished, coherent content optimized for human consumption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*aRDOSBEv05WKNAsM2HmQ_Q.png" /></figure><p>The Writer Agent fulfills several crucial functions in the workflow:</p><ol><li><strong>Information Synthesis</strong>: Combines insights from both the researcher’s findings and the critic’s evaluation</li><li><strong>Organization</strong>: Structures information in a logical, accessible way for the end user</li><li><strong>Style Adaptation</strong>: Presents information in clear, engaging language appropriate to the context</li><li><strong>Perspective Integration</strong>: Balances different viewpoints to create a comprehensive response</li><li><strong>Clarity Enhancement</strong>: Simplifies complex concepts without sacrificing accuracy</li></ol><h4>Modern Implementation with LangGraph</h4><p>The latest versions of LangGraph and LangChain provide sophisticated tools for building integrated multi-agent systems. Let’s explore how to implement a Writer Agent using these modern frameworks.</p><h4>The Writer’s System Prompt</h4><p>The foundation of our Writer Agent is a carefully designed system prompt:</p><pre>WRITER_SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are a Writer Agent, part of a collaborative research assistant system. Your role is to synthesize <br>information from the Researcher Agent and feedback from the Critic Agent into a coherent, well-written response.<br>Your responsibilities include:<br>1. Analyzing the information provided by the researcher and the feedback from the critic<br>2. Organizing the information in a logical, easy-to-understand structure<br>3. Presenting the information in a clear, engaging writing style<br>4. Balancing different perspectives and ensuring objectivity<br>5. Creating a final response that is comprehensive, accurate, and well-written<br>Format your response in a clear, organized manner with appropriate headings, paragraphs, and bullet points.<br>Use simple language to explain complex concepts, and provide examples where helpful.<br>Remember, your goal is to create a final response that effectively communicates the information to the user.<br>&quot;&quot;&quot;</pre><h4>Modern State Management and Node Implementation</h4><p>One of the key improvements in recent versions of LangGraph is the use of TypedDict for state management, providing better code organization and type safety:</p><pre>class CollaborativeResearchState(TypedDict):<br>    &quot;&quot;&quot;State type for our collaborative research assistant.&quot;&quot;&quot;<br>    messages: List[BaseMessage]  # The conversation history<br>    next: Optional[str]  # Where to go next in the graph</pre><p>The Writer node implementation follows a clean, functional approach:</p><pre>def writer_node(state: CollaborativeResearchState) -&gt; CollaborativeResearchState:<br>    &quot;&quot;&quot;Node function for the writer agent.&quot;&quot;&quot;<br>    # Extract messages from the state<br>    messages = state[&quot;messages&quot;]<br>    # Create writer messages with the system prompt<br>    writer_messages = [SystemMessage(content=WRITER_SYSTEM_PROMPT)] + messages<br>    # Initialize the LLM with a balance of creativity and accuracy<br>    llm = ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0.6)<br>    # Get the writer&#39;s response<br>    response = llm.invoke(writer_messages)<br>    # Return the updated state<br>    return {<br>        &quot;messages&quot;: messages + [response],<br>        &quot;next&quot;: &quot;output&quot;<br>    }</pre><h4>The Complete Multi-Agent Workflow</h4><p>When we integrate the Writer Agent with our Researcher and Critic Agents, we create a sophisticated workflow that mimics a professional research and writing team:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JjW1QrsxfTuMQkMco9_Juw.png" /></figure><p>The implementation of this workflow in LangGraph is clean and maintainable:</p><pre>def build_complete_research_assistant():<br>    &quot;&quot;&quot;Build a complete research assistant with researcher, critic, and writer agents.&quot;&quot;&quot;<br>    # Create a new graph with our state type<br>    workflow = StateGraph(CollaborativeResearchState)<br>    # Add nodes<br>    workflow.add_node(&quot;researcher&quot;, researcher_node)<br>    workflow.add_node(&quot;critic&quot;, critic_node)<br>    workflow.add_node(&quot;writer&quot;, writer_node)<br>    workflow.add_node(&quot;output&quot;, output_node)<br>    # Add edges<br>    workflow.add_edge(&quot;researcher&quot;, &quot;critic&quot;)<br>    workflow.add_edge(&quot;critic&quot;, &quot;writer&quot;)<br>    workflow.add_edge(&quot;writer&quot;, &quot;output&quot;)<br>    # Set the entry point<br>    workflow.set_entry_point(&quot;researcher&quot;)<br>    # Compile the graph<br>    return workflow.compile()</pre><h4>Enhanced Features for Advanced Applications</h4><p>For more complex applications, we can enhance our Writer Agent and overall workflow with advanced features:</p><h4>Rich Metadata Tracking</h4><p>We can create an enhanced state type that tracks metadata about each agent’s contribution:</p><pre>class EnhancedResearchState(TypedDict):<br>    &quot;&quot;&quot;Enhanced state type with metadata for the research process.&quot;&quot;&quot;<br>    messages: List[BaseMessage]  # The conversation history<br>    metadata: Dict[str, Any]  # Metadata about each step in the process<br>    next: Optional[str]  # Where to go next in the graph</pre><p>This allows us to capture information like processing time, token counts, and model parameters, which is valuable for analysis and optimization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*CgcOK_SBM-_ow7STYkBHCw.png" /></figure><h4>Flexible Architecture Patterns</h4><p>The three-agent structure we’ve built (Researcher → Critic → Writer) can be adapted to various application needs:</p><p><strong>1. Hierarchical Organization</strong>:</p><ul><li>Research Team (Multiple specialized researchers) → Editor → Writer</li></ul><p><strong>2. Parallel Processing</strong>:</p><ul><li>Multiple researchers working on different aspects → Critics evaluating each part → Writer synthesizing everything</li></ul><p><strong>3. Hybrid Structures</strong>:</p><ul><li>Some agents working sequentially, others in parallel, based on the task</li></ul><h4>Benefits of the Writer Agent</h4><p>Adding a Writer Agent to your multi-agent system provides several key benefits:</p><ol><li><strong>Improved Communication</strong>: Content is presented in a way that’s optimized for human understanding</li><li><strong>Consistency</strong>: The writing style and structure remain consistent, even when research covers diverse topics</li><li><strong>Integration</strong>: Various perspectives and pieces of information are woven together cohesively</li><li><strong>Efficiency</strong>: The final output is ready to use without additional editing or reformatting</li><li><strong>Adaptability</strong>: The Writer Agent can adjust its style and structure based on the context and audience</li></ol><p>By adding a Writer Agent to our system, we’ve completed a powerful collaborative workflow that mirrors how humans work together on complex information tasks. Each agent in our system has a specialized role:</p><ul><li>The <strong>Researcher Agent</strong> gathers comprehensive information</li><li>The <strong>Critic Agent</strong> evaluates and ensures quality</li><li>The <strong>Writer Agent</strong> communicates effectively to the end user</li></ul><p>This separation of concerns allows each agent to excel at its specific task while contributing to a cohesive whole. Using modern LangGraph and LangChain features like TypedDict for state management, we’ve built a system that’s not only powerful but also maintainable and extensible.</p><p>Multi-agent systems represent a significant advancement in AI application design, moving beyond the limitations of single-agent approaches to create more robust, balanced, and effective solutions.</p><h3>The Coordinator Agent</h3><p>In our journey to build sophisticated multi-agent systems with LangGraph, we’ve explored specialized agents for research, criticism, and writing. Now, let’s focus on the critical component that transforms a fixed, sequential workflow into a truly dynamic, intelligent solution: the coordinator agent.</p><h4>The Need for Coordination in Multi-Agent Systems</h4><p>As multi-agent systems grow in complexity, coordinating the interactions between agents becomes increasingly important. A well-designed coordinator can:</p><ul><li>Analyze user queries to determine the optimal workflow</li><li>Skip unnecessary steps for simple requests</li><li>Initiate additional research cycles when needed</li><li>Ensure all relevant specialists contribute appropriately</li><li>Adapt the workflow based on intermediate results</li></ul><h4>The Coordinator Agent Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*YET9UFxBxSFi9lwBoN3uCQ.png" /></figure><p>The diagram above illustrates our dynamic multi-agent architecture. Unlike previous implementations where agents operated in a fixed sequence, this system uses a Coordinator Agent to determine the optimal path at each stage. For simple queries, it can bypass research altogether, while for complex ones, it orchestrates the full research cycle.</p><h4>Building the Coordinator in Modern LangGraph</h4><p>Modern LangGraph provides powerful tools for implementing this dynamic architecture:</p><pre>def coordinator_node(state: ResearchState) -&gt; ResearchState:<br>    &quot;&quot;&quot;Coordinator node that decides the workflow path.&quot;&quot;&quot;<br>    # Extract messages from the state<br>    messages = state[&quot;messages&quot;]<br>    # Create coordinator messages with the system prompt<br>    coordinator_messages = [SystemMessage(content=COORDINATOR_SYSTEM_PROMPT)] + messages<br>    # Initialize the LLM with a lower temperature for consistent decision-making<br>    llm = ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0.2)<br>    # Get the coordinator&#39;s response<br>    response = llm.invoke(coordinator_messages)<br>    # Parse the JSON response to determine next steps<br>    try:<br>        decision = json.loads(response.content)<br>        next_step = decision.get(&quot;next&quot;, &quot;researcher&quot;)  # Default to researcher if not specified<br>    except Exception:<br>        # If there&#39;s an error parsing the JSON, default to the researcher<br>        next_step = &quot;researcher&quot;<br>    # Return the updated state<br>    return {&quot;messages&quot;: messages, &quot;next&quot;: next_step}</pre><p>The key improvement in our implementation is the use of conditional edges in the workflow graph:</p><pre># Add conditional edges from the coordinator<br>workflow.add_conditional_edges(<br>    &quot;coordinator&quot;,<br>    lambda state: state[&quot;next&quot;],<br>    {<br>        &quot;researcher&quot;: &quot;researcher&quot;,<br>        &quot;done&quot;: &quot;output&quot;<br>    }<br>)</pre><h4>Dynamic Decision Making in Action</h4><p>Let’s examine how our Coordinator Agent’s decision-making process works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yI74XkFTDB4GDC5PYlb-pA.png" /></figure><p>For simple factual queries, the Coordinator can provide a direct answer, avoiding unnecessary work. For complex topics requiring expertise, it orchestrates a full research cycle involving all specialized agents.</p><h4>Comparison: Static vs. Dynamic Workflows</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*CMB9TLkVRUf-btdbY-OYDg.png" /></figure><p>The comparison above highlights the key difference between static and dynamic workflows. The dynamic approach with a Coordinator Agent offers:</p><ul><li><strong>Efficiency</strong>: Simple queries get immediate responses</li><li><strong>Adaptability</strong>: Workflow changes based on query complexity</li><li><strong>Intelligence</strong>: Decision-making at key junctures</li><li><strong>Recursion</strong>: Ability to loop back for further research when needed</li></ul><h4>Technical Implementation Details</h4><p>Our implementation leverages several modern LangGraph features:</p><ol><li><strong>TypedDict for State Management</strong>: Using ResearchState with proper typing</li><li><strong>Conditional Edges</strong>: Dynamic routing based on agent decisions</li><li><strong>Structured Output</strong>: JSON formatting with reasoning and next steps</li><li><strong>Error Handling</strong>: Robust parsing with fallbacks</li><li><strong>LLM Integration</strong>: I am using GPT-4o through those examples.</li></ol><p>This approach provides a clean, maintainable, and extensible architecture that can be adapted for various applications.</p><h4>Extending the Coordinator Pattern</h4><p>The Coordinator pattern can be extended in several ways:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6VBuG0goWkLAlfm1wx7jQ.png" /></figure><h4>Building a Dynamic Multi-Agent System</h4><p>With our coordinator agent implemented, we can now transform our system from a fixed, sequential workflow to a dynamic one where the coordinator decides which path to take:</p><pre>def build_dynamic_research_assistant():<br>    &quot;&quot;&quot;Build a dynamic research assistant with a coordinator agent managing the workflow.&quot;&quot;&quot;<br>    # Create a new graph<br>    workflow = Graph()<br>     <br>    # Add nodes<br>    workflow.add_node(&quot;coordinator&quot;, coordinator_agent)<br>    workflow.add_node(&quot;researcher&quot;, researcher_agent)<br>    workflow.add_node(&quot;critic&quot;, critic_agent)<br>    workflow.add_node(&quot;writer&quot;, writer_agent)<br>    workflow.add_node(&quot;output&quot;, output)<br>     <br>    # Add conditional edges from the coordinator<br>    workflow.add_conditional_edges(<br>        &quot;coordinator&quot;,<br>        lambda state: state[&quot;next&quot;],<br>        {<br>            &quot;researcher&quot;: &quot;researcher&quot;,<br>            &quot;done&quot;: &quot;output&quot;<br>        }<br>    )<br>     <br>    # Add the rest of the edges<br>    workflow.add_edge(&quot;researcher&quot;, &quot;critic&quot;)<br>    workflow.add_edge(&quot;critic&quot;, &quot;writer&quot;)<br>    workflow.add_edge(&quot;writer&quot;, &quot;coordinator&quot;)<br>    workflow.add_edge(&quot;output&quot;, END)<br>     <br>    # Set the entry point<br>    workflow.set_entry_point(&quot;coordinator&quot;)<br>     <br>    # Compile the graph<br>    return workflow.compile()</pre><p>This graph creates a dynamic workflow where:</p><ol><li>The coordinator agent analyzes the user’s query and decides whether to engage the research team or provide a direct response</li><li>If research is needed, the query flows through our specialized agents: researcher → critic → writer</li><li>After the writer completes its work, control returns to the coordinator, which can either send the response to the user or initiate additional research</li><li>This creates a loop where complex queries can be refined through multiple iterations of research, critique, and writing</li></ol><h3>Visual Workflow Diagrams</h3><h4>Dynamic Multi-Agent System Architecture</h4><p>Here’s a visual representation of our dynamic multi-agent system with the coordinator agent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yE2lfGqEp53jCmuktaDUlw.png" /></figure><p>The diagram illustrates the dynamic nature of our system:</p><ol><li>The coordinator agent receives all user queries first</li><li>For simple queries, the coordinator can provide responses directly</li><li>For complex queries, the coordinator routes them through our specialist agents</li><li>After the writer agent produces a response, the coordinator reviews it</li><li>The coordinator can either deliver the final response or request additional research</li><li>This creates a feedback loop that can handle complex, multi-step queries</li></ol><h4>Decision Flow for Different Query Types</h4><p>Let’s also visualize how different types of queries flow through the system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8hOlDU2seH6gapx6Tn3pA.png" /></figure><p>This diagram illustrates the different paths queries can take:</p><ul><li>Simple, factual queries get direct responses</li><li>Complex research queries go through our specialized agents</li><li>Some queries might require multiple research iterations</li></ul><h4>Seeing the Dynamic System in Action</h4><p>Let’s see how our dynamic system handles different types of queries:</p><p><strong>Query 1</strong>: “What is the capital of France?”</p><p><strong>Coordinator</strong>:</p><pre>{<br>  &quot;reasoning&quot;: &quot;This is a simple factual question asking for the capital of France. The answer is well-known and doesn&#39;t require in-depth research, critical analysis, or specialized writing.&quot;,<br>  &quot;next&quot;: &quot;done&quot;<br>}</pre><p><strong>System Response</strong>: “The capital of France is Paris.”</p><p><strong>Query 2</strong>: “What are the implications of quantum computing for cybersecurity?”</p><p><strong>Coordinator</strong>:</p><pre>{<br>  &quot;reasoning&quot;: &quot;This query asks for complex information about quantum computing and its relationship to cybersecurity. It requires gathering detailed information, evaluating different perspectives, and synthesizing a comprehensive response.&quot;,<br>  &quot;next&quot;: &quot;researcher&quot;<br>}</pre><p><em>[The system then processes this query through the researcher, critic, and writer agents before returning to the coordinator…]</em></p><p><strong>Writer</strong>: <em>[Produces comprehensive, well-structured content about quantum computing’s implications for encryption, security protocols, etc.]</em></p><p><strong>Coordinator</strong> (after reviewing the writer’s output):</p><pre>{<br>  &quot;reasoning&quot;: &quot;The query has been thoroughly researched, critiqued, and synthesized into a comprehensive response that addresses the implications of quantum computing for cybersecurity from multiple angles.&quot;,<br>  &quot;next&quot;: &quot;done&quot;<br>}</pre><p><strong>System Response</strong>: <em>[The writer’s comprehensive response is delivered to the user]</em></p><h4>The Value of the Coordinator Agent</h4><p>Adding a coordinator agent transforms our system in several important ways:</p><ol><li><strong>Efficiency</strong>: Simple queries can bypass unnecessary processing, providing faster responses</li><li><strong>Adaptability</strong>: The system can take different paths based on the nature of each query</li><li><strong>Iteration</strong>: Complex queries can go through multiple rounds of research and refinement</li><li><strong>Intelligence</strong>: The system makes high-level decisions about how to process information</li><li><strong>Scalability</strong>: New specialized agents can be added to the system more easily</li></ol><p>Perhaps most importantly, the coordinator makes our system feel more like interacting with a team of intelligent experts rather than a fixed, mechanical process.</p><h4>Advanced Coordinator Implementations</h4><p>While our implementation is powerful, there are several ways to make the coordinator even more sophisticated:</p><ol><li><strong>More Routing Options</strong>: Allow the coordinator to route directly to any agent, not just the researcher</li><li><strong>Feedback Loops</strong>: Enable the coordinator to identify gaps and request specific additional research</li><li><strong>Memory Management</strong>: Have the coordinator maintain a summary of what’s been learned so far</li><li><strong>Meta-Learning</strong>: Allow the coordinator to learn which paths work best for different query types</li><li><strong>Multi-Query Planning</strong>: Enable the coordinator to break complex queries into sub-questions</li></ol><p>The coordinator agent completes our multi-agent research assistant, transforming it from a sequential workflow into a dynamic, intelligent system. By orchestrating the specialized agents we’ve built — researcher, critic, and writer — the coordinator creates a solution that’s more than the sum of its parts.</p><p>This approach mirrors how effective human teams work: specialized experts collaborate under thoughtful coordination to tackle complex problems. The result is a system that can provide simple answers quickly, tackle complex questions thoroughly, and adapt its approach to each unique situation.</p><p>As you build your own multi-agent systems with LangGraph, remember that the coordinator is what transforms a collection of agents into a truly intelligent, adaptable system.</p><h3>Benefits of Using LangGraph</h3><p>Using LangGraph for multi-agent systems provides several advantages:</p><ol><li><strong>Structured Workflows</strong>: LangGraph provides a clear structure for defining how agents interact, making complex systems easier to design and maintain.</li><li><strong>State Management</strong>: The framework handles state management across multiple LLM calls, ensuring that information flows correctly between agents.</li><li><strong>Conditional Routing</strong>: LangGraph allows for dynamic decision-making about which agent should act next, enabling more adaptive and responsive systems.</li><li><strong>Checkpointing</strong>: Built-in checkpointing capabilities make it easier to debug and resume long-running processes.</li><li><strong>Scalability</strong>: The graph-based approach makes it easier to add new agents or modify existing workflows as your system evolves.</li></ol><h4>Comparison with CWIC Flow</h4><p>While LangGraph provides an excellent framework for building multi-agent systems, it’s worth noting the similarities and differences with Clearwater’s CWIC Flow:</p><h4>Similarities:</h4><ul><li>Both use a graph-based approach to orchestrate multiple specialized agents</li><li>Both maintain state across agent interactions</li><li>Both support conditional routing based on agent outputs</li></ul><h4>Differences:</h4><ul><li>CWIC Flow is specifically designed for financial services, with domain-specific agents and tools</li><li>CWIC Flow includes production-ready governance features not found in LangGraph</li><li>CWIC Flow has deeper integration with cloud services and data sources</li></ul><h3>Conclusion</h3><p>LangGraph provides a powerful framework for building sophisticated multi-agent systems, with structured workflows, state management, and conditional routing. While Clearwater Analytics developed CWIC Flow before LangGraph became available, we continue to evaluate emerging technologies like LangGraph to enhance our capabilities.</p><p>The multi-agent approach, whether implemented through custom solutions like CWIC Flow or frameworks like LangGraph, represents the future of AI systems. By orchestrating specialized agents with distinct roles and responsibilities, we can create more capable, robust, and adaptable AI systems that deliver greater value to users.</p><p>As AI technology evolves, Clearwater remains committed to adopting innovations that enhance our ability to deliver actionable insights to our clients while maintaining our industry-leading standards for security, compliance, and accuracy.</p><p><strong>About the Author</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*t91mo8E3htk3ZId6fVEJTg.png" /></figure><p>Rany ElHousieny is an Engineering Leader at Clearwater Analytics with over 30 years of experience in software development, machine learning, and artificial intelligence. He has held leadership roles at Microsoft for two decades, where he led the NLP team at Microsoft Research and Azure AI, contributing to advancements in AI technologies. At Clearwater, Rany continues to leverage his extensive background to drive innovation in AI, helping teams solve complex challenges while maintaining a collaborative approach to leadership and problem-solving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04f90f312b8e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cwan-engineering/building-multi-agent-systems-with-langgraph-04f90f312b8e">Building Multi-Agent Systems with LangGraph</a> was originally published in <a href="https://medium.com/cwan-engineering">cwan-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Agent Systems and CWIC Flow: Pioneering AI Orchestration]]></title>
            <link>https://medium.com/cwan-engineering/multi-agent-systems-and-cwic-flow-pioneering-ai-orchestration-5867ac9c0a34?source=rss-6fb0d6055766------2</link>
            <guid isPermaLink="false">https://medium.com/p/5867ac9c0a34</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Clearwater Analytics Engineering]]></dc:creator>
            <pubDate>Fri, 16 May 2025 15:22:13 GMT</pubDate>
            <atom:updated>2025-05-16T15:22:13.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*PiLgelPvhj_7s5GWOwWN7Q.png" /></figure><h3>Introduction to Multi-Agent Systems</h3><p>Multi-agent systems represent a paradigm shift in artificial intelligence, moving beyond single-model approaches to orchestrated teams of specialized AI agents working collaboratively. These systems provide several key advantages:</p><ul><li><strong>Specialization</strong>: Each agent can focus on what it does best</li><li><strong>Checks and balances</strong>: Agents can review and refine each other’s work</li><li><strong>Scalability</strong>: Systems can grow to include additional specialized agents</li><li><strong>Robustness</strong>: The system doesn’t rely on a single agent’s capabilities</li></ul><p>In a multi-agent system, specialized AI agents with distinct roles collaborate to solve complex problems that would be challenging for a single agent. This approach mirrors human team collaboration, where different specialists contribute their expertise to achieve a common goal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9fdRKaKre2J1tAjD4E1v4Q.png" /></figure><h3>CWIC Flow: Clearwater’s Pioneering Multi-Agent System</h3><p>At Clearwater Analytics, we embarked on a journey to build an AI-driven multi-agent system long before frameworks like LangGraph emerged. Our solution, Clearwater Intelligent Console Flow (CWIC Flow), is a sophisticated AI platform that supports knowledge, application, and data awareness. Unlike traditional chatbot solutions, CWIC Flow orchestrates specialists — intelligent agents with tools, skills, and memory — to deliver highly contextualized and actionable insights to our clients. This architectural leap positioned Clearwater ahead of the curve, showcasing a multi-agent AI system before the industry widely adopted such paradigms.</p><h3>The Architecture of CWIC Flow</h3><p>CWIC Flow integrates a hierarchy of intelligent components:</p><ol><li><strong>CWIC Tools</strong>: These provide access to external APIs, databases, and computational resources, enabling AI agents to interact with structured and unstructured data.</li><li><strong>CWIC Skills</strong>: Orchestrated workflows that combine multiple tools, allowing the system to solve complex tasks efficiently.</li><li><strong>CWIC Specialists</strong>: Autonomous agents trained for specific investment and financial tasks. They leverage tools, skills, and a refined knowledge base to process client queries dynamically.</li><li><strong>Planning and Memory</strong>: CWIC Flow maintains short- and long-term memory, enabling specialists to learn from interactions and refine their decision-making over time. This leads to a more adaptive and responsive AI system.</li></ol><p>Through this layered approach, CWIC Flow achieves real-time data awareness, contextual reasoning, and seamless automation, reducing operational overhead while enhancing user experience. The platform supports RAG (Retrieval-Augmented Generation) techniques, tool chaining, and LLM-based decision-making, all within a governed AI framework that ensures accuracy and compliance.</p><p>More details about CWIC architecture can be found in the article <a href="https://medium.com/cwan-engineering/constructing-the-ultimate-gen-ai-chat-copilot-experience-part-1-55c2e07a1feb">Constructing the Ultimate Gen AI Chat/Copilot Experience (Part 1</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rqzD7T1kQ3T2i-os53rAMw.png" /></figure><h3>The CWIC Flow Advantage</h3><p>While new frameworks, such as LangGraph, now provide structured workflows for multi-agent AI applications, Clearwater Analytics had already developed a similar, robust system before these frameworks became mainstream. The key differentiators of CWIC Flow include:</p><ul><li><strong>Early Implementation of Multi-Agent Workflows</strong>: CWIC Flow was designed to coordinate multiple specialists before frameworks like LangGraph formalized multi-agent orchestration.</li><li><strong>Domain-Specific AI Agents</strong>: Our specialists possess deep financial expertise, offering highly accurate and context-driven insights.</li><li><strong>Production-Ready Governance</strong>: Unlike generic frameworks, CWIC Flow integrates strict access control, audit logging, and AI guardrails to ensure data security and compliance.</li><li><strong>Seamless Cloud Integration</strong>: CWIC Flow leverages AWS, Azure, and Snowflake for real-time data processing, ensuring clients receive the most up-to-date information.</li></ul><p>For a demo of our Multi-Agent system, you can watch the <a href="https://share.vidyard.com/watch/AcPSdT4fAUYVXVfaGF1uxn">Webinar: How Clearwater Analytics Creates Agentic Systems with SLMs</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vu96RIEtqXtOT9FMzbVi0Q.png" /></figure><p>CWIC Flow represents a very complex multi-agent system that has been developed and refined over time at Clearwater Analytics. Before we delve deeper into the intricacies of CWIC Flow’s architecture, it’s beneficial to understand the fundamental concepts of multi-agent systems through a simpler implementation. In this article, we’ll build a straightforward multi-agent system using LangChain. This approach allows us to illustrate the core principles of agent collaboration, specialized roles, and orchestrated workflows in a more accessible manner. By starting with this foundation, readers can better appreciate the sophisticated design choices and advanced capabilities that make CWIC Flow such a powerful enterprise solution. The concepts demonstrated in our LangChain example — though simpler — share the same fundamental principles that underpin CWIC Flow’s more comprehensive implementation.</p><h3>Building a Simple Multi-Agent System</h3><p>While frameworks like LangGraph provide structured ways to build multi-agent systems, it’s important to understand that you can create effective multi-agent architectures without specialized frameworks. Let’s explore a straightforward approach to building a multi-agent system using basic Python and LangChain components.</p><h3>What We’ll Build</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_pJDSaTc1gsROuF0IBEdw.png" /></figure><p>Throughout this article, we’ll build a collaborative research assistant system with multiple specialized agents:</p><ol><li>A researcher agent that gathers information</li><li>A critic agent that evaluates and challenges findings</li><li>A writer agent that synthesizes information into coherent text</li><li>A coordinator agent that manages the workflow between agents</li></ol><p>By the end of this article, you’ll have a fully functional multi-agent system that can perform research tasks collaboratively.</p><p>Let’s start by setting up our environment!</p><h3>Setting Up the Environment</h3><p>First, we need to set up our environment with the necessary packages:</p><pre># Install required packages<br>!pip install langchain python-dotenv openai langchain-community langchain-openai</pre><pre># Load environment variables<br>import os<br>from dotenv import load_dotenv<br><br>load_dotenv()  # Load API keys from .env file<br><br># Verify that the API key is loaded<br>if os.getenv(&quot;OPENAI_API_KEY&quot;) is None:<br>    print(&quot;Warning: OPENAI_API_KEY not found in environment variables.&quot;)<br>else:<br>    print(&quot;OPENAI_API_KEY found in environment variables.&quot;)</pre><h3>Designing Agent Prompts</h3><p>The foundation of our multi-agent system is well-crafted system prompts that define each agent’s role and responsibilities:</p><h3>The Researcher Agent</h3><pre>RESEARCHER_SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are a Researcher Agent, part of a collaborative research assistant system.<br>Your role is to gather and provide accurate, relevant information on any<br>topic or question presented to you.<br><br>Your responsibilities include:<br>1. Analyzing research questions to understand what information is being<br>   requested<br>2. Providing comprehensive, well-structured responses based on your knowledge<br>3. Highlighting key points and important information<br>4. Being honest about the limitations of your knowledge<br>5. Maintaining objectivity and avoiding bias in your responses<br><br>Format your responses in a clear, organized manner with sections, bullet<br>points, or numbered lists as appropriate.<br>Always cite your sources of information when possible.<br><br>Remember, your goal is to provide the most helpful, accurate information <br>possible to assist in the research process.<br>&quot;&quot;&quot;</pre><pre>def researcher_agent(messages):<br>    &quot;&quot;&quot;Researcher agent that analyzes questions and provides informative<br>       responses.&quot;&quot;&quot;<br>    # Add the system prompt to guide the researcher agent&#39;s behavior<br>    researcher_messages = [SystemMessage(content=RESEARCHER_SYSTEM_PROMPT)] + messages<br>    <br>    # Create a ChatOpenAI instance<br>    llm = ChatOpenAI(<br>        temperature=0.5,  # Lower temperature for more factual responses<br>        model_name=&quot;gpt-4o&quot;,<br>        openai_api_key=os.environ.get(&quot;OPENAI_API_KEY&quot;)<br>    )<br>    <br>    # Get a response from the LLM<br>    response = llm(researcher_messages)<br>    <br>    print(&quot;\n--- Researcher Agent Response ---&quot;)<br>    print(f&quot;{response.content[:300]}...\n&quot;)<br>    <br>    return response</pre><h3>The Critic Agent</h3><pre>CRITIC_SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are a Critic Agent, part of a collaborative research assistant system. <br>Your role is to evaluate and challenge information provided by the Researcher<br>Agent to ensure accuracy, completeness, and objectivity.<br><br>Your responsibilities include:<br>1. Analyzing research findings for accuracy, completeness, and potential biases<br>2. Identifying gaps in the information or logical inconsistencies<br>3. Asking important questions that might have been overlooked<br>4. Suggesting improvements or alternative perspectives<br>5. Ensuring that the final information is balanced and well-rounded<br><br>Be constructive in your criticism. Your goal is not to dismiss the <br>researcher&#39;s work, but to strengthen it. Format your feedback in a <br>clear, organized manner, highlighting specific points that need attention.<br><br>Remember, your ultimate goal is to ensure that the final research output <br>is of the highest quality possible.<br>&quot;&quot;&quot;</pre><pre>def critic_agent(messages):<br>    &quot;&quot;&quot;Critic agent that evaluates and challenges the researcher&#39;s findings.&quot;&quot;&quot;<br>    # Add the system prompt to guide the critic agent&#39;s behavior<br>    critic_messages = [SystemMessage(content=CRITIC_SYSTEM_PROMPT)] + messages<br>    <br>    # Create a ChatOpenAI instance<br>    llm = ChatOpenAI(<br>        temperature=0.7,  # Slightly higher temperature for more creative criticism<br>        model_name=&quot;gpt-4o&quot;,<br>        openai_api_key=os.environ.get(&quot;OPENAI_API_KEY&quot;)<br>    )<br>    <br>    # Get a response from the LLM<br>    response = llm(critic_messages)<br>    <br>    print(&quot;\n--- Critic Agent Response ---&quot;)<br>    print(f&quot;{response.content[:300]}...\n&quot;)<br>    <br>    return response</pre><h3>The Writer Agent</h3><pre>WRITER_SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are a Writer Agent, part of a collaborative research assistant system. <br>Your role is to synthesize information from the Researcher Agent and feedback <br>from the Critic Agent into a coherent, well-written response.<br><br>Your responsibilities include:<br>1. Analyzing the information provided by the researcher and the feedback <br>   from the critic<br>2. Organizing the information in a logical, easy-to-understand structure<br>3. Presenting the information in a clear, engaging writing style<br>4. Balancing different perspectives and ensuring objectivity<br>5. Creating a final response that is comprehensive, accurate, and well-written<br><br>Format your response in a clear, organized manner with appropriate headings, <br>paragraphs, and bullet points.<br>Use simple language to explain complex concepts, and provide examples where <br>helpful.<br><br>Remember, your goal is to create a final response that effectively <br>communicates the information to the user.<br>&quot;&quot;&quot;</pre><pre>def writer_agent(messages):<br>    &quot;&quot;&quot;Writer agent that synthesizes information from the researcher and critic.&quot;&quot;&quot;<br>    # Add the system prompt to guide the writer agent&#39;s behavior<br>    writer_messages = [SystemMessage(content=WRITER_SYSTEM_PROMPT)] + messages<br>    <br>    # Create a ChatOpenAI instance<br>    llm = ChatOpenAI(<br>        temperature=0.6,  # Balanced temperature for creativity and accuracy<br>        model_name=&quot;gpt-4o&quot;,<br>        openai_api_key=os.environ.get(&quot;OPENAI_API_KEY&quot;)<br>    )<br>    <br>    # Get a response from the LLM<br>    response = llm(writer_messages)<br>    <br>    print(&quot;\n--- Writer Agent Response ---&quot;)<br>    print(f&quot;{response.content[:300]}...\n&quot;)<br>    <br>    return response</pre><h3>The Coordinator Agent</h3><p>As with our other agents, we’ll start by defining a system prompt that outlines the coordinator’s role and responsibilities:</p><pre># Define the system prompts for each agent<br>COORDINATOR_SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are a Coordinator Agent, responsible for managing the workflow between specialized agents in a collaborative <br>research assistant system. Your role is to analyze queries, determine which agents should be involved, and ensure <br>that the final response meets the user&#39;s needs.<br><br>Your team includes:<br>1. Researcher Agent: Gathers and provides accurate, relevant information on topics<br>2. Critic Agent: Evaluates and challenges information to ensure accuracy and completeness<br>3. Writer Agent: Synthesizes information into coherent, well-written responses<br><br>Your responsibilities include:<br>1. Analyzing the user&#39;s query to determine which agents should be involved<br>2. Deciding the order in which agents should process the query<br>3. Determining when additional research or feedback is needed<br>4. Ensuring that the final response meets the user&#39;s needs<br><br>For each query, you must decide on one of the following next steps:<br>- &quot;researcher&quot;: Send the query to the researcher agent first<br>- &quot;done&quot;: The query has been fully addressed and no further action is needed<br><br>Format your response as a JSON object with two fields:<br>1. &quot;reasoning&quot;: Your step-by-step thought process<br>2. &quot;next&quot;: Your decision on the next step (&quot;researcher&quot; or &quot;done&quot;)<br><br>Example:<br>{<br>  &quot;reasoning&quot;: &quot;This query asks for factual information about quantum computing, which requires research.&quot;,<br>  &quot;next&quot;: &quot;researcher&quot;<br>}<br>&quot;&quot;&quot;</pre><p>This prompt establishes the coordinator’s decision-making role and provides a structured format for its responses, which helps with programmatic routing in our system.</p><h3>Implementing the Coordinator Agent</h3><p>Now, let’s implement the coordinator agent function that will analyze the state and determine the next step in the workflow:</p><pre># Define the agent functions<br>def coordinator_agent(messages):<br>    &quot;&quot;&quot;Coordinator agent that manages the workflow between other agents.&quot;&quot;&quot;<br>    # Add the system prompt to guide the coordinator agent&#39;s behavior<br>    coordinator_messages = [SystemMessage(content=COORDINATOR_SYSTEM_PROMPT)] + messages<br>    <br>    # Create a ChatOpenAI instance<br>    llm = ChatOpenAI(<br>        temperature=0.3,  # Lower temperature for more consistent decision-making<br>        model_name=&quot;gpt-4o&quot;,<br>        openai_api_key=os.environ.get(&quot;OPENAI_API_KEY&quot;)<br>    )<br>    <br>    # Get a response from the LLM<br>    response = llm(coordinator_messages)<br>    <br>    # Parse the JSON response to get the next step<br>    try:<br>        response_content = response.content<br>        decision = json.loads(response_content)<br>        # Default to researcher if not specified<br>        next_step = decision.get(&quot;next&quot;, &quot;researcher&quot;)  <br>        <br>        # Print the coordinator&#39;s reasoning<br>        print(f&quot;Coordinator reasoning: {decision.get(&#39;reasoning&#39;, &#39;No reasoning provided&#39;)}&quot;)<br>        print(f&quot;Next step: {next_step}&quot;)<br>    except Exception as e:<br>        # If there&#39;s an error parsing the JSON, default to the researcher<br>        print(f&quot;Error parsing coordinator response: {e}&quot;)<br>        print(f&quot;Defaulting to researcher agent&quot;)<br>        next_step = &quot;researcher&quot;<br>    <br>    return next_step</pre><p>Notice that we’re using a lower temperature (0.3) for the coordinator compared to our other agents. This promotes consistent, reliable decision-making — exactly what we want from the “manager” of our system.</p><h3>Building a Dynamic Multi-Agent System</h3><p>With our coordinator agent implemented, we can transform our system from a fixed, sequential workflow to a dynamic one where the coordinator decides which path to take:</p><pre># Function to run the multi-agent system<br>def run_multi_agent_system(question):<br>    &quot;&quot;&quot;Run the multi-agent system with the given question.&quot;&quot;&quot;<br>    print(f&quot;\n\n{&#39;=&#39;*50}&quot;)<br>    print(f&quot;QUERY: {question}&quot;)<br>    print(f&quot;{&#39;=&#39;*50}\n&quot;)<br>    <br>    # Initialize the messages with the question<br>    messages = [HumanMessage(content=question)]<br>    <br>    # Start with the coordinator<br>    next_step = coordinator_agent(messages)<br>    <br>    # Continue until the coordinator decides we&#39;re done<br>    while next_step != &quot;done&quot;:<br>        if next_step == &quot;researcher&quot;:<br>            # Run the researcher agent<br>            researcher_response = researcher_agent(messages)<br>            messages.append(researcher_response)<br>            <br>            # Run the critic agent<br>            critic_response = critic_agent(messages)<br>            messages.append(critic_response)<br>            <br>            # Run the writer agent<br>            writer_response = writer_agent(messages)<br>            messages.append(writer_response)<br>            <br>            # Back to the coordinator<br>            next_step = coordinator_agent(messages)<br>        else:<br>            # If the next step is not recognized, default to done<br>            print(f&quot;Unrecognized next step: {next_step}&quot;)<br>            next_step = &quot;done&quot;<br>    <br>    # Find the final response (last AI message)<br>    final_response = None<br>    for message in reversed(messages):<br>        if isinstance(message, AIMessage):<br>            final_response = message.content<br>            break<br>    <br>    if final_response:<br>        print(&quot;\n--- Final Response ---&quot;)<br>        print(final_response)<br>    <br>    return messages</pre><p>This creates a dynamic workflow where:</p><ol><li>The coordinator agent analyzes the user’s query and decides whether to engage the research team or provide a direct response</li><li>If research is needed, the query flows through our specialized agents: researcher → critic → writer</li><li>After the writer completes its work, control returns to the coordinator, which can either send the response to the user or initiate additional research</li><li>This creates a loop where complex queries can be refined through multiple iterations of research, critique, and writing</li></ol><h3>Visual Workflow Diagrams</h3><h3>Basic Multi-Agent System Architecture</h3><p>Let’s visualize our multi-agent system architecture using Mermaid diagrams:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*8gE9EL3jmzcpqA8OY_amCw.png" /></figure><h3>Decision Flow for Different Query Types</h3><p>Let’s also visualize how different types of queries flow through the system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*A5K3eMvqTsNFI3xXyxTreg.png" /></figure><h3>Detailed Information Flow Diagram</h3><p>Here’s a more detailed view of how information flows through our multi-agent system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NsNkrqYskN3BEHvQ4MR5iQ.png" /></figure><h3>The Coordinator’s Decision-Making Process</h3><p>The coordinator agent makes decisions based on several factors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Ml-62IugnnHsCqZqBdIT8g.png" /></figure><h3>Seeing the Dynamic System in Action</h3><p>Let’s see how our dynamic system handles different types of queries:</p><pre># Main execution<br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;Starting the multi-agent system...&quot;)<br>    <br>    # Test with different questions<br>    print(&quot;\n--- Testing with a complex research question ---&quot;)<br>    result1 = run_multi_agent_system(&quot;What are the latest advancements in renewable energy technologies and their potential impact on climate change?&quot;)<br>    <br>    print(&quot;\n--- Testing with a simple factual question ---&quot;)<br>    result2 = run_multi_agent_system(&quot;What is the capital of France?&quot;)<br>    <br>    print(&quot;\n--- Testing with a nuanced ethical question ---&quot;)<br>    result3 = run_multi_agent_system(&quot;What are the ethical implications of using AI in healthcare decision-making?&quot;)<br>    <br>    print(&quot;\nTesting complete!&quot;)</pre><h3>Example 1: Simple Factual Query</h3><p><em>QUERY: What is the capital of France?</em></p><p>Coordinator reasoning:<br><em>This query is a straightforward factual question that requires specific information.</em></p><p>Next step: done</p><p>For simple factual queries, the coordinator can immediately determine that no complex research process is needed.</p><pre>--- Testing with a simple factual question ---<br>==================================================<br>QUERY: What is the capital of France?<br>==================================================<br>Coordinator reasoning: This query is a straightforward factual <br>question that requires specific information.<br>Next step: done</pre><h3>Example 2: Complex Research Query</h3><p><em>QUERY: What are the latest advancements in renewable energy technologies and their potential impact on climate change?</em></p><p>Coordinator reasoning:<br><em>This query requires gathering up-to-date information on advancements in renewable energy technologies and their potential impact on climate change, which involves both research and analysis.</em></p><p>Next step: researcher</p><p>For complex research queries, the coordinator engages the full team of specialized agents to provide a comprehensive response.</p><pre>Starting the multi-agent system...<br>--- Testing with a complex research question ---<br>==================================================<br>QUERY: What are the latest advancements in renewable energy technologies <br>and their potential impact on climate change?<br>==================================================<br>Coordinator reasoning: This query requires gathering up-to-date <br>information on advancements in renewable energy technologies and their <br>potential impact on climate change, which involves both research and analysis.<br>Next step: researcher<br>--- Researcher Agent Response ---<br>Advancements in renewable energy technologies are crucial in combating <br>climate change by reducing greenhouse gas emissions and transitioning to <br>cleaner energy sources. Here are some of the latest advancements in <br>renewable energy technologies and their potential impact on climate change:<br>1. **Solar ...<br>--- Critic Agent Response ---<br>While the overview of advancements in renewable energy technologies is <br>generally accurate, there are a few areas where additional detail and <br>clarification could enhance understanding and balance the perspective:<br>1. **Solar Power**:<br>   - **Perovskite Solar Cells**: While promising, perovskite solar ...<br>--- Writer Agent Response ---<br>In reviewing the latest advancements in renewable energy technologies <br>and their potential impact on climate change, it is evident that these <br>innovations play a crucial role in transitioning towards a sustainable <br>energy future. Here&#39;s a refined overview with additional details and <br>considerations for ...<br>Coordinator reasoning: The query seeks detailed information on the latest <br>advancements in renewable energy technologies and their impact on climate <br>change, requiring in-depth analysis and evaluation of each technology. <br>The response provided an overview of advancements in solar, wind, hydropower, <br>geothermal, and bioenergy, highlighting key developments and their <br>implications. However, to ensure a comprehensive understanding, additional <br>details and considerations were identified for each technology, including <br>challenges, environmental impacts, and sustainability concerns. By addressing <br>these aspects, the response aims to provide a more balanced and informative <br>perspective on the topic.<br>Next step: done<br>--- Final Response ---<br>In reviewing the latest advancements in renewable energy technologies and <br>their potential impact on climate change, it is evident that these innovations <br>play a crucial role in transitioning towards a sustainable energy future. <br>Here&#39;s a refined overview with additional details and considerations for a <br>more comprehensive understanding:<br>1. **Solar Power**:<br>   - **Advancements**:<br>     - **Perovskite Solar Cells**: Despite their high efficiency, challenges <br>         such as stability and toxicity due to lead content are being addressed <br>         through ongoing research into alternative materials.<br>     - **Bifacial Solar Panels**: Environmental factors like snow coverage and <br>         ground reflectivity impact their performance, with varying efficiency <br>         based on installation conditions.<br>2. **Wind Power**:<br>   - **Advancements**:<br>     - **Floating Wind Turbines**: While promising for deep-water locations, <br>         challenges include higher initial costs, maintenance complexities, <br>         and grid integration issues.<br>     - **Larger Turbines**: Environmental and social considerations, such as <br>         wildlife impacts and community acceptance, are crucial aspects to <br>         consider alongside increased energy output.<br>3. **Hydropower**:<br>   - **Advancements**:<br>     - **Pumped Storage Hydropower**: Geographical and ecological constraints, <br>         along with the need for suitable topography, influence the feasibility <br>         and scalability of these systems.<br>     - **Run-of-River Hydropower**: Despite lower environmental impacts, <br>         considerations around aquatic ecosystems and water quality management <br>         remain significant.<br>4. **Geothermal Energy**:<br>   - **Advancements**:<br>     - **Enhanced Geothermal Systems**: Technical challenges in creating <br>         artificial reservoirs and economic viability pose hurdles that <br>         ongoing research aims to address.<br>     - **Direct-Use Applications**: Understanding the geographical limitations <br>         of geothermal resources is essential for maximizing their <br>         utilization in heating and cooling applications.<br>5. **Bioenergy**:<br>   - **Advancements**:<br>     - **Advanced Biofuels**: Sustainability concerns related to land use, <br>         food security, and lifecycle emissions underscore the importance <br>         of holistic assessments for biofuel deployment.<br>     - **Biogas Production**: Integration of biogas into circular economy <br>         practices for waste management and agricultural applications <br>         can enhance its role in emissions reduction.<br>         By acknowledging the complexities and considerations associated <br>         with each renewable energy technology, including environmental <br>         impacts, economic challenges, and policy implications, a more <br>         nuanced understanding of their potential impact on climate <br>         change emerges. Emphasizing the need for a holistic approach <br>         that addresses not only technological advancements but also <br>         broader sustainability aspects will be essential for maximizing <br>         the benefits of renewable energy in combating climate change.</pre><h3>Example 3: Nuanced Ethical Question</h3><p><em>QUERY: What are the ethical implications of using AI in healthcare decision-making?</em></p><p>Coordinator reasoning:<br><em>This query involves discussing the ethical implications of AI in healthcare, which requires a combination of research and critical evaluation.</em></p><p>Next step: researcher</p><p>For nuanced ethical questions, the coordinator recognizes the need for both factual information and critical analysis.</p><pre>--- Testing with a nuanced ethical question ---<br>==================================================<br>QUERY: What are the ethical implications of using AI in healthcare <br>decision-making?<br>==================================================<br>Coordinator reasoning: This query involves discussing the ethical <br>implications of AI in healthcare, which requires a combination of <br>research and critical evaluation.<br>Next step: researcher<br>--- Researcher Agent Response ---<br>Using AI in healthcare decision-making raises various ethical implications <br>that need to be carefully considered. Here are some key points to consider:<br>1. **Privacy and Data Security**:<br>   - AI systems require access to vast amounts of patient data. Ensuring <br>     the privacy and security of this data is ...<br>--- Critic Agent Response ---<br>Here are some additional points and questions to consider, as well as <br>suggestions for strengthening your research:<br>1. **Regulatory and Ethical Guidelines**:<br>   - Explore existing regulatory frameworks and ethical guidelines that <br>     govern the use of AI in healthcare. How are they being implemented, <br>     an...<br>--- Writer Agent Response ---<br>In response to the feedback provided, I have expanded on the ethical <br>implications of using AI in healthcare decision-making and included <br>additional points and questions to consider:<br>1. **Regulatory and Ethical Guidelines**:<br>   - Explore existing regulatory frameworks and ethical guidelines that gov...<br>     Coordinator reasoning: The query delves into the ethical implications of <br>     using AI in healthcare decision-making, which requires a comprehensive <br>     analysis involving considerations such as privacy, transparency, bias, <br>     patient autonomy, accountability, equity, and more. The response provided <br>     an in-depth exploration of these ethical implications and suggested <br>     additional points and questions to further enhance the understanding of<br>     the topic. To address the feedback provided, the response has been <br>     expanded to include additional insights and considerations, offering a<br>     more holistic view of the ethical challenges and opportunities associated<br>     with AI in healthcare.<br>Next step: done<br>--- Final Response ---<br>In response to the feedback provided, I have expanded on the ethical <br>implications of using AI in healthcare decision-making and included <br>additional points and questions to consider:<br>1. **Regulatory and Ethical Guidelines**:<br>   - Explore existing regulatory frameworks and ethical guidelines that <br>     govern the use of AI in healthcare. How are they being implemented, <br>     and are there any gaps that need to be addressed?<br>   - Consider the role of organizations like the FDA in regulating AI-based <br>     healthcare technologies to ensure patient safety and ethical use.<br>2. **Human Oversight**:<br>   - While AI can enhance decision-making, the importance of human oversight <br>     must be emphasized. How can healthcare systems ensure that AI <br>     recommendations are critically evaluated by human experts?<br>   - Discuss the concept of shared decision-making between AI systems and <br>     healthcare providers to leverage the strengths of both for optimal <br>     patient care.<br>3. **Long-term Implications**:<br>   - Consider the long-term implications of AI integration in healthcare. <br>     How might it change the patient-provider relationship over time? <br>     What are the potential societal impacts?<br>   - Explore the concept of algorithmic bias and its long-term effects on <br>     healthcare disparities, emphasizing the need for continuous monitoring <br>     and mitigation strategies.<br>4. **Education and Training**:<br>   - Healthcare professionals need to be educated about AI technologies and <br>     their implications. What are the best practices for training healthcare <br>     providers to effectively use and understand AI systems?<br>   - Highlight the importance of interdisciplinary education to bridge the <br>     gap between healthcare and technology, fostering collaboration and <br>     understanding among diverse stakeholders.<br>5. **International Perspectives**:<br>   - Consider how the ethical implications of AI in healthcare may vary <br>     across different cultural and legal contexts. How do international <br>     standards compare, and what can be learned from global approaches?<br>   - Explore case studies from different countries to understand how cultural <br>     norms and healthcare systems influence the ethical considerations of AI <br>     implementation in diverse settings.<br>6. **Patient Involvement**:<br>   - Investigate ways to actively involve patients in discussions about AI <br>     in healthcare. How can patient feedback and perspectives be integrated <br>     into the development and implementation of AI systems?<br>   - Discuss the concept of patient-centered AI design, where patient <br>     preferences and values are incorporated into the development process <br>     to ensure ethical and patient-friendly AI solutions.<br>7. **Success Stories and Challenges**:<br>   - Provide examples of successful AI applications in healthcare, as well <br>     as challenges faced in real-world implementations. What lessons can be <br>     learned from these experiences?<br>   - Highlight successful AI applications like IBM Watson for Oncology and <br>     discuss challenges such as data interoperability and algorithmic <br>     transparency that need to be addressed for widespread adoption and <br>     ethical use of AI in healthcare.<br><br>By addressing these additional points and questions, a more thorough <br>exploration of the ethical implications of using AI in healthcare <br>decision-making can be achieved, offering valuable insights for policymakers, <br>healthcare professionals, and researchers in the field.<br>Testing complete!</pre><h3>Benefits of the Coordinator Agent Approach</h3><ol><li><strong>Adaptive Workflow</strong>: The system can adapt its response strategy based on the nature of the query</li><li><strong>Efficient Resource Use</strong>: Simple queries bypass unnecessary processing steps</li><li><strong>Iterative Refinement</strong>: Complex queries can go through multiple rounds of research and refinement</li><li><strong>Scalable Architecture</strong>: New specialized agents can be easily integrated into the system</li><li><strong>Improved Response Quality</strong>: Each query receives the appropriate level of attention and expertise</li></ol><p>The coordinator agent transforms a collection of specialized AI agents into a cohesive, intelligent system capable of handling a wide range of queries with appropriate depth and efficiency. By implementing this architecture, we create a multi-agent system that can:</p><ol><li>Intelligently route queries based on their complexity and requirements</li><li>Provide direct answers to simple questions without unnecessary processing</li><li>Engage specialized agents for complex queries requiring research and analysis</li><li>Iteratively refine responses through multiple rounds of feedback when needed</li></ol><p>This approach represents a significant step forward in building AI systems that can adapt their workflow to the specific needs of each user query, delivering more relevant, efficient, and high-quality responses.</p><h3>Conclusion</h3><p>While Clearwater Analytics developed CWIC Flow as a sophisticated multi-agent system before frameworks like LangGraph became available, we continue to evaluate emerging technologies to enhance our capabilities. In the next article, we’ll explore how to build multi-agent systems using LangGraph, a framework that provides structured workflows similar to what we’ve already implemented in CWIC Flow.</p><p>As AI technology evolves, Clearwater remains committed to adopting innovations that enhance our ability to deliver actionable insights to our clients while maintaining our industry-leading standards for security, compliance, and accuracy.</p><h3>About the Author</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/105/0*YVFUOHUmCh_mQ4v-.png" /></figure><p>Rany ElHousieny is an Engineering Leader at Clearwater Analytics with over 30 years of experience in software development, machine learning, and artificial intelligence. He has held leadership roles at Microsoft for two decades, where he led the NLP team at Microsoft Research and Azure AI, contributing to advancements in AI technologies. At Clearwater, Rany continues to leverage his extensive background to drive innovation in AI, helping teams solve complex challenges while maintaining a collaborative approach to leadership and problem-solving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5867ac9c0a34" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cwan-engineering/multi-agent-systems-and-cwic-flow-pioneering-ai-orchestration-5867ac9c0a34">Multi-Agent Systems and CWIC Flow: Pioneering AI Orchestration</a> was originally published in <a href="https://medium.com/cwan-engineering">cwan-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto-Scaling Batch Processes on EC2 via Queue Depth]]></title>
            <link>https://medium.com/cwan-engineering/auto-scaling-batch-processes-on-ec2-via-queue-depth-0ba648011505?source=rss-6fb0d6055766------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ba648011505</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[autoscaling]]></category>
            <dc:creator><![CDATA[Clearwater Analytics Engineering]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 15:42:02 GMT</pubDate>
            <atom:updated>2025-04-04T15:42:02.905Z</atom:updated>
            <content:encoded><![CDATA[<p>In the corporate world, efficiency is key. This blog post delves into the specifics of how we developed an efficient, auto-scaling approach to our batch processes. We explore queue-based scaling, complications that can arise during implementation, and provide practical examples to show how we are able to optimize operations while keeping costs in check.</p><p>At Clearwater, we have a service for batch processing called our ETL (Extract Transform Load) system, which processes about 6–8 million tasks each day. The hardware requirements for each task vary wildly from a single GB of memory, all the way to hundreds, and runtimes go from seconds to hours. The most predictable part of this process is the timing of the load. The vast majority of our processing happens in the morning hours, with afternoons being very light to almost idle. As an investment reporting company that processes massive volumes of accounting data, the only exception to this is around “month ends” (the first 5 days of a month) when most of our clients “lock down” their accounting information and generate reports for legal filing purposes, board reporting, etc. During this time, our load spreads out more into the afternoon.</p><p>Recently, we had the opportunity to migrate our applications from running on-prem in a data center to the cloud. This was quite the paradigm shift for how we handled load. Formerly, on-prem, we could simply (note to reader: laugh at “simply” here) buy as much hardware as we needed to handle our peak load and it would be ready for that load 24/7.</p><p>In the cloud, however, reserving all the EC2 instances we need, even when there is no demand for them, is a <em>very</em> costly process. By design, of course. Unlike running in an on-prem environment, a major advantage to running in the cloud is the ability to scale to meet any given moment’s needs. We only needed to make some adjustments to take advantage of this incredible flexibility.</p><h3>Introducing Scheduled Scaling</h3><p>Since our load had a somewhat predictable pattern to it, we were able to quickly alleviate a lot of the cost of running the ETLs by implementing <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html">scheduled scaling</a>. Problem solved? Not yet. This had an interesting consequence: while our load was semi-predictable, it seemed to have a life of its own and would change almost weekly.</p><p>We’re a <a href="https://investors.clearwateranalytics.com/news/news-details/2025/Clearwater-Analytics-Announces-Fourth-Quarter-and-Full-Year-2024-Financial-Results/default.aspx">growing company</a>; in business-speak: our revenue is growing 25%+ a year with a Net Revenue Retention (NRR) rate of 116%. Keeping up with new clients, their changing accounting and investment strategies, data delays, and overall software improvements (and regressions) meant we had to spend engineering resources to tweak and tune the schedule constantly so we can adapt to these changing conditions, with goal of maintaining our high SLA expectations.</p><h3>Migrating to Auto-Scaling</h3><p>Anyone still reading at this point should be shouting at their screen, telling us to just migrate to <em>any</em> of <a href="https://aws.amazon.com/autoscaling/">AWS’ approaches to auto-scaling</a>. And they would be in exact agreement with what we were thinking too.</p><p>Alas, we tested scaling based off hardware utilization; it was wildly too unpredictable to rely on while maintaining our SLAs. Most of our tasks have high IO wait times, which results in the hardware going idle long enough to scale-in, only to rapidly increase in utilization as the IO completes and demands an immediate (though maybe unnecessary) scale-out. Meaning, our hardware utilization never matched our hardware needs.</p><p>Don’t forget about our long task runtimes. If you’re curious, we were able to successfully work around that; you can read about it in this blog: <a href="https://medium.com/cwan-engineering/scaling-in-with-long-running-processes-on-aws-5a1bb48e4e7a">Scaling In With Long Running Processes on AWS</a>.</p><h3>Introducing Queue-Based Scaling</h3><p>What we really wanted this whole time was to be able to scale off our task queue depth. If you’re familiar with it, this is the same concept as using <a href="https://aws.amazon.com/blogs/mt/proactive-autoscaling-kubernetes-workloads-keda-metrics-ingested-into-aws-amp/">KEDA in EKS/ECS</a>: push a custom metric to CloudWatch and use it to determine if we should scale-in/out. Unfortunately, we’re not running in EKS; we’re running on EC2. So, we had to re-invent the wheel a bit. Thankfully, <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-using-sqs-queue.html">AWS has recommendations on how to scale based off SQS queue depth</a> that we were able to make use of in our design. Also, to answer one of your questions: we do have technical reasons for not running this system in EKS, but that is a story for another day.</p><p>Putting all the concepts together was easy enough (see following diagram). Implementing them was when the real fun began (see the following sections).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJ4TuPiMFKfrO54581oG3Q.png" /></figure><h3>Push The Metrics</h3><p>Given the breadth of variety we have in our task characteristics, we had to create several ASG configurations in AWS to support some bucketed needs while minimizing cost. As such, we can’t just push one queue depth to CloudWatch; we must push many. Hence, the presence of 2 ASGs in the diagram above. Though, more exist in reality.</p><p>To support this properly, each ASG must know the “class” of tasks it can run. The “class” is a composite of several task characteristics such as:</p><ul><li>Task Type</li><li>CPU requirements</li><li>Memory requirements</li></ul><p>These characteristics form what we call our “filter criteria” that is used for selecting tasks to run.</p><p>Each ASG then pulls its own filter criteria from a dedicated space in AppConfig and the same Terraform project we publish the ASG/AppConfig with also publishes the metric fetching Lambda. This made it easy to copy the filter criteria and pass it to the Lambda via the Lambda’s environment to avoid paying extra to store the criteria anywhere else.</p><p>Terraform handled this nicely. We make liberal use of modules as an organization construct within Terraform. Within the module that manages creating our ASGs and their associated AppConfig, we define an input variable like:</p><pre>variable &quot;environment_variables&quot; {<br>  type        = map(string)<br>  description = &quot;ASG-level environment variables to set on instances&quot;<br>  default     = {}<br>}</pre><p>Within the module for the metrics Lambda then, we define another variable:</p><pre>variable &quot;asg_configuration&quot; {<br>  type = map(object({<br>    name        = string<br>    environment = optional(map(string))<br>  }))<br>}</pre><p>And as a result, we can pass the exact same Map data to the two different modules and the Lambda will only get the 2 keys that were defined in the schema for it! Easy win.</p><p>Unfortunately, we quickly realized that the <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#:~:text=The%20total%20size%20of%20all,doesn&#39;t%20exceed%204%20KB.">4KB limit on the environment size</a> in Lambdas was not enough to hold the filter criteria for every ASG in existence. While this sounds outrageous, our real roadblock was how we support 30+ task types and wanted to limit ASGs to running subsets of the task types for cost attribution purposes. The string names for the task types multiplied by the number of ASGs and the JSON encoding quickly added up.</p><p>As a workaround, we settled on storing the information in a second, Lambda-specific location in AppConfig instead. While this resulted in a minor added cost (estimated $173/mo. to query every 1min; depending on Lambda uptime), this allows us to be really verbose (or precise, depending on perspective) with our ASG configurations.</p><p>To make this work, our top-level module definition didn’t have to change at all. The same input variable trick worked. We just had to pipe that variable to AppConfig instead of setting it on the Lambda. Super easy win.</p><p>The metrics we publish to CloudWatch from the Lambda then, are simple:</p><ul><li>We gave this “application” its own namespace in CloudWatch</li><li>Each ASG has a unique metric name</li><li>The queried queue depth is the value</li><li>Unit type: “Count”.</li></ul><p>To help minimize cost, we even batch-pushed the metrics to CloudWatch. In Python with Boto3, this looks roughly like:</p><pre>import boto3<br>import logging<br>from datetime import datetime, timezone<br>import threading<br><br>class CloudWatchMetricsPublisher:<br>    def __init__(self, namespace: str):<br>        self.namespace = namespace<br>        self.CloudWatch_client = boto3.client(&#39;CloudWatch&#39;)<br>        self.metrics_buffer = []<br>        self.lock = threading.Lock()<br><br>    def publish_metric(self, metric_type: str, asg_name: str, realm: str, value: float, unit: str):<br>        metric_data = {<br>            &#39;MetricName&#39;: f&#39;{metric_type}_{asg_name}&#39;,<br>            &#39;Unit&#39;: unit,<br>            &#39;Value&#39;: value,<br>            &#39;Timestamp&#39;: datetime.now(timezone.utc),<br>        }<br>        with self.lock:<br>            self.metrics_buffer.append(metric_data)<br><br>    def flush_metrics(self):<br>        &quot;&quot;&quot;Publish all buffered metrics to CloudWatch.&quot;&quot;&quot;<br>        with self.lock:<br>            if not self.metrics_buffer:<br>                return  # nothing to publish<br>            try:<br>                response = self.CloudWatch_client.put_metric_data(<br>                    MetricData=self.metrics_buffer,<br>                    Namespace=self.namespace<br>                )<br>                logging.info(f&#39;Successfully published {len(self.metrics_buffer)} metrics: {response}&#39;)<br>            except Exception:<br>                logging.error(&#39;Failed to publish metrics&#39;, exc_info=True)<br>            finally:<br>                # Clear the buffer after publishing<br>                self.metrics_buffer.clear()</pre><h3>Scale The ASG</h3><p>We now had metrics flowing through to CloudWatch. We just had to do something with them. For that something, we settled on employing a <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-target-tracking.html">target tracking policy</a> with <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-target-tracking-metric-math.html">metric math</a>. The rough goals being:</p><ul><li>If we have enough tasks queued up to justify spawning another EC2 instance, then spawn an instance.</li><li>Otherwise, try to scale-in. BUT! Only scale-in if the instance will quickly self-terminate<br>- Our long running task solution was to detach instances from the ASG. If we scale-in too frequently, we could get a lot of detached instances that would result in our costs growing in a potentially unbounded fashion because the “max_capacity” of an ASG would effectively no longer be relevant.<br>- Thus, if we need to scale-in but can’t terminate, then we need to not scale-in at all.</li></ul><h3>Scaling Out</h3><p>Meeting the first goal for scaling-out was initially easy.</p><ol><li>Follow the AWS guide to divide queue size by instance count.</li><li>Publish the target tracking policy via Terraform.</li><li>Profit.</li></ol><p>What we learned along the way, though, was that target tracking can sometimes scale-out very aggressively if you’re not careful.</p><p>First, if you set the <em>scaling_target</em> to something low, like 1, and the result of your metric math increases rapidly, then the ASG will scale out more rapidly to combat perceived spike in load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPEj9Km1XY6-JkjsndnNLA.png" /></figure><p>This can happen if you intentionally neglect to take instance counts into consideration with the metric math. E.g.</p><pre>IF(FILL(queue_depth,REPEAT) &gt; 0, FILL(queue_depth,REPEAT) + 1, 0)</pre><p>This was done for our ASG that handles the near-500GB tasks because we really need a whole instance per-task. But, as said, the fix was simple:</p><pre>IF(FILL(queue_depth,REPEAT) &gt; 0, FILL(queue_depth,REPEAT) / <br>FILL(instance_count,REPEAT) + 1, 0)</pre><p>Second, for our smaller ASGs, we had our <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-default-instance-warmup.html">default instance warmup</a> misconfigured. With scheduled scaling, this wasn’t an important knob to pay attention to. With auto-scaling, it makes a world of difference! As they say in the docs:</p><blockquote>You can specify how long after an instance reaches the InService state it waits before contributing usage data to the aggregated metrics. This specified time is called the default instance warmup. This keeps dynamic scaling from being affected by metrics for individual instances that aren’t yet handling application traffic and that might be experiencing temporarily high usage of compute resources.</blockquote><p>By changing the value from a quick 10 seconds to several minutes (based on measured boot times) we were able to get our smaller ASGs to scale-out in a much more predictable fashion as well.</p><h3>Scaling In</h3><p>Scaling-in then, was a more interesting challenge. AWS laid out the algorithm nicely (as seen in an earlier link):</p><pre>while (true)<br>{<br>  SetInstanceProtection(False);<br>  Work = GetNextWorkUnit();<br>  SetInstanceProtection(True);<br>  ProcessWorkUnit(Work);<br>  SetInstanceProtection(False);<br>}</pre><p>But, we wanted to take this to the next level. Our requirements:</p><p>1. We don’t have one task running at a time on single instance; we potentially have hundreds running concurrently.</p><p>2. There are times where we can “infer” that a task will run for a protracted period, and other times, we can’t make that inference.</p><p>3. “Flapping” needed to be minimized. Meaning: to reduce unnecessary API interactions with the ASG, an instance should remain protected for as long as possible or unprotected. It should not rapidly alternate under any circumstances.</p><p>So, we developed a framework whereby each ASG can be configured based on the observed need of the ASG.</p><p>Our near-500GB task size ASGs could be configured based on the exact memory requirements of the tasks that are executing. We’ve observed that tasks over a certain threshold run for long enough that we should turn on instance protection. Conversely, smaller tasks complete fast enough that protection is not strictly necessary.</p><p>Our smaller ASGs then, we just wanted to minimize noise on. So, we decided that if X-number of tasks were running, then we would elect to protect that instance from termination with the idea that a less busy instance would be terminated first.</p><ul><li>Think about a situation where you’re driving a car. If the car shifted at pre-defined speeds — such as shifting up over 35 MPH and down when under it — and your foot wasn’t stable enough to keep the car at a constant speed, causing you to drift between 34–36 MPH consistently, you’d create quite a lot of wear and tear on the transmission, right?</li><li>Car manufacturers don’t want that, and we didn’t either. As a result, we defined upper and lower bounds that cause the instance to enable/disable protection appropriately. E.g. once the instance exceeds 30 tasks running, turn protection on and don’t turn it off until we drop below 20 tasks.</li></ul><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*2crYLsWrCxXqWJvYFcPZbg.png" /></figure><p>Overall, we are quite satisfied. As you can see from the above, our 500GB ASG is scaling-out as tasks come in and scaling-in as they complete. Additionally, our cost for running EC2 instances dropped by ~32% over the course of a week when compared to our scheduled scaling approach.</p><h3>Future Improvements</h3><p>The results shown above speak for themselves and highlight the success of this project. However, in testing, particularly in less frequently used (and therefore not as well-tuned) environments we’ve found at least one issue with our approach. Namely: if one task comes in that requires most of an instance and leaves no room for anything else to run, then every other task will sit in the queue. If the queue doesn’t get deep enough, which is not likely in a low-utilization environment, then we won’t scale-out to get the other tasks in the queue processing.</p><p>In time, we hope to explore some of the following concepts and see if we can resolve this issue:</p><ul><li><a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-target-tracking.html#target-tracking-multiple-policies">Multiple target tracking scaling policies</a></li><li><a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/simple-scaling-policies.html">Simple scaling policies</a></li></ul><h3>Bonus: Scaling to Zero</h3><p>A nice aspect of having all traffic driven to an instance from a queue instead of HTTP is that you can “very easily” scale to zero. When doing so, I offer a word of caution: make sure the metric you track with target tracking can account for having zero instances appropriately. And I don’t mean account for dividing by zero.</p><p>Target tracking is a great way to get up and running with auto-scaling quickly. As long as you bend to its will. Namely:</p><ul><li>To scale-out, your metric must exceed its defined <em>scaling_target</em> for 3 min.</li><li>To scale-in, that metric must drop below an “arbitrarily calculated” (seemingly 70% of your <em>scaling_target</em>) value for 15 min.</li></ul><p>With a sanely calculated <em>scaling_target </em>(typically not 1) like 50, it can be quite hard to get a single task running. This is very similar in concept to the future improvement discussed above but with a relatively easy solution:</p><pre>metrics {<br>  id    = &quot;instances&quot;<br>  label = &quot;Current running instance count for ${local.asg_name}&quot;<br>  metric_stat {<br>    metric {<br>      dimensions {<br>        name  = &quot;AutoScalingGroupName&quot;<br>        value = module.asg.autoscaling_group_name<br>      }<br>      metric_name = &quot;GroupInServiceInstances&quot;<br>      namespace   = &quot;AWS/AutoScaling&quot;<br>    }<br>    stat = &quot;Average&quot;<br>  }<br>  return_data = false<br>}<br><br>metrics {<br>  id    = &quot;scaling_target&quot;<br>  label = &quot;The defined target to use for scaling thresholds in ${local.asg_name}&quot;<br>  expression   = &quot;TIME_SERIES(${var.scaling_target})&quot;<br>  return_data  = false<br>}<br><br>metrics {<br>  id    = &quot;eligible_tasks_per_instance&quot;<br>  label = &quot;Eligible Tasks / Num Instances (rounded up to 1 to avoid dividing by 0) in ${local.asg_name}&quot;<br>  expression = &quot;FILL(eligible_tasks,REPEAT) / IF(FILL(instances,REPEAT) &lt;= 0, 1, FILL(instances,REPEAT))&quot;<br>  return_data = false<br>}<br><br>metrics {<br>  expression = &quot;IF(FILL(instances,REPEAT) == 0, scaling_target + IF(FILL(eligible_tasks,REPEAT) &gt; 0, 1, 0), IF(FILL(instances,REPEAT) == 1 &amp;&amp; FILL(eligible_tasks,REPEAT) &gt; 0 &amp;&amp; FILL(eligible_tasks,REPEAT) &lt; scaling_target, scaling_target, eligible_tasks_per_instance))&quot;<br>  id         = &quot;scaling_ratio&quot;<br>  label      = &quot;Scaling ratio for ${local.asg_name}&quot;<br>  return_data = true  # This is the metric we will be scaling off of<br>}</pre><p>There’s a lot to take in here. But, in short:</p><ol><li>Define some metrics that will ultimately be used for our final calculation per how metric math is expected to work.</li><li>Make sure your <em>scaling_target</em> is in there. While it doesn’t have to be its own metric, there are some reasons you may want it to be separate.</li><li>In your final expression, account for:</li></ol><pre># Having zero instances and forcing the scale-out. <br>IF(FILL(instances,REPEAT) == 0<br><br># Having one instance and maintaining it.<br>IF(FILL(instances,REPEAT) == 1 &amp;&amp; FILL(eligible_tasks,REPEAT) &gt; 0 <br>&amp;&amp; FILL(eligible_tasks,REPEAT) &lt; scaling_target<br><br># Having multiple instances and scaling as normal. <br>eligible_tasks_per_instance</pre><h3>Key Takeaways</h3><p>There are a lot of ways to scale an app in the cloud to meet the demands of your users. Here are my three takeaways:</p><ol><li>Don’t be afraid to learn about the different options available so you can find the one that best meets your needs. When you settle on one, learn the nuances of working with it.</li><li>While making the decision to scale-out might be instant, doing so is not. Account for that, as well as scale-in time, where appropriate (e.g. instance warm-up time).</li><li>Once you feel like you’re done and have the system working, don’t forget to monitor it.</li></ol><p>Just remember, the learning never stops; you might stumble upon a scenario that you hadn’t considered or didn’t even know existed.</p><h3>About Me</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*-fhffwgFJg58d42QQLEnog.jpeg" /></figure><p>Craig Hecock is a Principal Engineer at Clearwater Analytics with over 15 years of experience in software development. With a comprehensive background spanning front-end, back-end, and working on both SQL/NoSQL databases, he has a proven track record in triaging and debugging complex issues. Craig is passionate about leveraging technology to solve complex problems and improve user experiences. Aside from working on code, Craig is a strong advocate for team growth, enjoys mentoring others and helping them develop their skills as developers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ba648011505" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cwan-engineering/auto-scaling-batch-processes-on-ec2-via-queue-depth-0ba648011505">Auto-Scaling Batch Processes on EC2 via Queue Depth</a> was originally published in <a href="https://medium.com/cwan-engineering">cwan-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>