<?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 Swwapnil Kambley on Medium]]></title>
        <description><![CDATA[Stories by Swwapnil Kambley on Medium]]></description>
        <link>https://medium.com/@swwapnil303?source=rss-283f16443bcd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*H9iZ4Phy15gRHOyz</url>
            <title>Stories by Swwapnil Kambley on Medium</title>
            <link>https://medium.com/@swwapnil303?source=rss-283f16443bcd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:38:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swwapnil303/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[From Chatbot to Microservice: Engineering Cost-Aware AI Agents for SRE]]></title>
            <link>https://medium.com/@swwapnil303/from-chatbot-to-microservice-engineering-cost-aware-ai-agents-for-sre-90b58f0af258?source=rss-283f16443bcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/90b58f0af258</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Swwapnil Kambley]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 10:39:01 GMT</pubDate>
            <atom:updated>2026-04-27T10:39:01.939Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop talking to AI; start designing predictable, reliable infrastructure tools.</h3><p>By Swwapnil Kambley</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHi57t4wSS742epW8Ymr5A.png" /></figure><p>As I pivot from traditional Kubernetes DevOps to AI-Native Platform Engineering, the biggest mental shift hasn’t been learning new languages. It’s been unlearning how to treat AI like a chatbot.</p><p>When you are building tools for Platform Engineering, you don’t want “conversations.” You need reliability, deterministic behavior, machine-readable outputs, and strict cost controls.</p><p>Today, I’m sharing how to build a Level 1 SRE Log Analyzer using the google-genai SDK and Gemini 2.5 Flash. To make this work at an enterprise level, we have to stop thinking about AI as a chat window and start treating it like a microservice.</p><p>Here are the three core architectural pillars to make that happen: <strong>Immutable Personas,JSON Forcing,</strong> and <strong>FinOps Token Management</strong>.</p><h3>1. The Immutable Config (System Instructions)</h3><p>If you deploy a Docker container, you use an ENTRYPOINT to define its core executable behavior. In the world of Large Language Models (LLMs), we use <strong>System Instructions</strong>.</p><p>Instead of passing a weak prompt like <em>“Can you please help me fix this log?”</em>, we configure the client at the API level with a strict identity.</p><p>Think of it as the AI’s immutable job description:</p><blockquote>“You are a strict GKE Site Reliability Engineer. Analyze the provided error log. You must respond in strict JSON format with exactly three keys: root_cause, severity, and recommended_fix.”</blockquote><p>This creates a hard boundary. It forces the model out of “chat mode” and ensures that whatever raw server log you feed it cannot override the tool’s core directive.</p><h3>2. The API Contract (JSON Forcing)</h3><p>An SRE tool is completely useless if its output can’t be easily piped into a Slack webhook, a Jira API, or a PagerDuty alert.</p><p>By adjusting the API parameters specifically setting our response type to application/json and dropping the temperature (our &quot;creativity slider&quot;) down to 0.1 we force the backend to reject any output that isn&#39;t perfectly formatted JSON.</p><p>We effectively strip away the “chatty” nature of a probabilistic AI and turn it into a predictable, deterministic API endpoint. Computers talking to computers, exactly how it should be.</p><h3>3. LLM FinOps: Pre-flight vs. Post-flight Billing</h3><p>You wouldn’t deploy a Kubernetes Pod without setting CPU and Memory limits. Similarly, you shouldn’t deploy an AI agent without Token counting.</p><p>In the AI world, compute isn’t measured in vCPU seconds; it’s measured in <strong>Tokens</strong> (roughly 4 characters of text).</p><ul><li><strong>Input Tokens (Ingress):</strong> The text the AI reads (your System Instruction + the Log file). This is computationally cheap.</li><li><strong>Output Tokens (Egress):</strong> The text the AI generates (the JSON response). Because text generation requires heavy, iterative math, this is usually 3x to 4x more expensive than reading.</li></ul><h4>The Math at Scale:</h4><p>Let’s say Gemini 2.5 Flash costs $0.075 per 1 Million Input tokens, and $0.30 per 1 Million Output tokens. If your new agent processes 10,000 logs a day, the math looks like this:</p><ul><li><strong>Input:</strong> 10,000 logs * 1,000 tokens/log = 10 Million Tokens <em>(~$0.75/day)</em></li><li><strong>Output:</strong> 10,000 responses * 200 tokens/JSON = 2 Million Tokens <em>(~$0.60/day)</em></li><li><strong>Total Cost:</strong> <strong>$1.35 a day</strong> to automate 10,000 Level 1 SRE tickets.</li></ul><p>To protect our FinOps budget from massive, unexpected log dumps, we implement a <strong>Pre-flight Check</strong> (counting the tokens <em>before</em> we run the prompt) and extract a <strong>Post-flight Receipt</strong> (logging the actual usage metadata <em>after</em> execution) to push billing metrics straight to Prometheus.</p><h3>See it in Action</h3><p>By applying standard DevOps principles ,immutable configs, strict API contracts, and capacity planning , we can safely integrate generative AI into mission-critical infrastructure pipelines without breaking the bank or dealing with unpredictable outputs.</p><p>If you want to see exactly how these three pillars look in Python, I’ve open-sourced the code for this Level 1 SRE Log Analyzer.</p><p>👉 <strong>[Check out the full repository and code examples on my GitHub here]</strong> <em>(</em><a href="https://github.com/SwwapnilKambley/AI-Platform-Engineer/blob/master/phase1/02_sre_analyzer.py">https://github.com/SwwapnilKambley/AI-Platform-Engineer/</a><em>)</em></p><p><strong>Next up:</strong> <em>Building multi-turn memory and tool-calling orchestration. Make sure to follow so you don’t miss it!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90b58f0af258" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Debugging K8s at 2 AM: I Built a Gemini-Powered Agent to Fix My Cluster]]></title>
            <link>https://medium.com/@swwapnil303/stop-debugging-k8s-at-2-am-i-built-a-gemini-powered-agent-to-fix-my-cluster-a019e886f1ad?source=rss-283f16443bcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a019e886f1ad</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Swwapnil Kambley]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 14:21:53 GMT</pubDate>
            <atom:updated>2026-04-23T14:24:04.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uOO36NzdS3fNxnZdWTtqA.png" /></figure><h3>The 2am Problem</h3><p>If you’ve been in DevOps long enough, you know the feeling. It’s late. Your phone buzzes. A pod is down. You kubectl get pods, see ImagePullBackOff or CrashLoopBackOff, and your brain starts the familiar loop like check logs, check events, check the deployment, Google the error, fix it, go back to sleep.</p><p>I’ve done this hundreds of times. And recently I thought “<em>what if an AI could do this investigation for me?”</em></p><p>That question led me to build the <strong>K8s Troubleshooting Agent </strong>an AI-powered agent that reads your Kubernetes cluster, investigates broken pods, and tells you exactly what’s wrong and how to fix it.</p><h3>What Is an AI Agent? (Quick Concept)</h3><p>Before the code, let’s clear this up fast.</p><p>An AI agent is just this loop:</p><pre>LLM thinks → decides to call a tool → gets result → thinks again <br>→ repeat → final answer</pre><p>The “magic” is an LLM (like Gemini) that has access to functions it can call <strong>tools</strong>. It decides <em>when</em> to call them, <em>what</em> to pass in, and <em>how</em> to reason over the results.</p><p>In our case:</p><ul><li><strong>Tools</strong> = Kubernetes API calls (pod status, logs, events)</li><li><strong>LLM</strong> = Google Gemini 2.5 Flash</li><li><strong>Loop</strong> = Agent keeps investigating until it has enough info to diagnose</li></ul><h3>Prerequisites</h3><p>Before you start, make sure you have the following:</p><p><strong>Local setup:</strong></p><ul><li>Python 3.9+</li><li>kubectl installed and configured</li><li>A running Kubernetes cluster — any of these works:</li><li><strong>Minikube</strong> (local, free, recommended for beginners)</li><li><strong>GKE</strong> (Google Kubernetes Engine)</li><li><strong>EKS / AKS</strong> (AWS or Azure)</li></ul><p><strong>API:</strong></p><ul><li>A free Gemini API key from <a href="https://aistudio.google.com/">aistudio.google.com</a></li><li>Sign in with your Google account → Get API Key → Create → Done</li></ul><p><strong>Install Minikube (if starting local):</strong></p><p>bash</p><pre>brew install minikube<br>minikube start<br>kubectl get nodes   # should show control-plane as Ready</pre><h3>Project Structure</h3><pre>k8s-troubleshooting-agent/<br>├── agent/<br>│   ├── main.py          # Entry point<br>│   ├── k8s_tools.py     # K8s API tools (pods, logs, events)<br>│   └── llm_agent.py     # Gemini-powered reasoning loop<br>├── k8s/<br>│   └── test-app/<br>│       └── broken-deployment.yaml   # Sample broken app<br>├── requirements.txt<br>└── README.md</pre><h3>Step 1 — Setup</h3><p>bash</p><pre>git clone https://github.com/SwwapnilKambley/k8s-troubleshooting-agent.git<br>cd k8s-troubleshooting-agent</pre><pre>python3 -m venv venv<br>source venv/bin/activate</pre><pre>pip install -r requirements.txt</pre><pre>export GEMINI_API_KEY=&quot;your-key-here&quot;</pre><h3>Step 2 — The Eyes: k8s_tools.py</h3><p>This file gives the agent the ability to <em>see</em> your cluster. Three tools:</p><p>python</p><pre>from kubernetes import client, config</pre><pre>def load_k8s_config():<br>    config.load_kube_config()<br>def get_pod_status(namespace: str) -&gt; list[dict]:<br>    load_k8s_config()<br>    v1 = client.CoreV1Api()<br>    pods = v1.list_namespaced_pod(namespace)<br>    result = []<br>    for pod in pods.items:<br>        result.append({<br>            &quot;name&quot;: pod.metadata.name,<br>            &quot;status&quot;: pod.status.phase,<br>            &quot;conditions&quot;: [<br>                {&quot;type&quot;: c.type, &quot;status&quot;: c.status, &quot;reason&quot;: c.reason}<br>                for c in (pod.status.conditions or [])<br>            ],<br>            &quot;containers&quot;: [<br>                {<br>                    &quot;name&quot;: cs.name,<br>                    &quot;ready&quot;: cs.ready,<br>                    &quot;restart_count&quot;: cs.restart_count,<br>                    &quot;state&quot;: str(cs.state)<br>                }<br>                for cs in (pod.status.container_statuses or [])<br>            ]<br>        })<br>    return result<br>def get_pod_logs(namespace: str, pod_name: str, tail: int = 50) -&gt; str:<br>    load_k8s_config()<br>    v1 = client.CoreV1Api()<br>    try:<br>        logs = v1.read_namespaced_pod_log(<br>            name=pod_name, namespace=namespace, tail_lines=tail<br>        )<br>        return logs if logs else &quot;No logs available&quot;<br>    except Exception as e:<br>        return f&quot;Could not fetch logs: {str(e)}&quot;<br>def get_pod_events(namespace: str) -&gt; list[dict]:<br>    load_k8s_config()<br>    v1 = client.CoreV1Api()<br>    events = v1.list_namespaced_event(namespace)<br>    result = []<br>    for event in events.items:<br>        if event.type == &quot;Warning&quot;:<br>            result.append({<br>                &quot;reason&quot;: event.reason,<br>                &quot;message&quot;: event.message,<br>                &quot;object&quot;: event.involved_object.name,<br>                &quot;count&quot;: event.count<br>            })<br>    return result</pre><p>Each function does one thing fetch pod status, fetch logs, fetch warning events. Clean and readable.</p><h3>Step 3 — The Brain: llm_agent.py</h3><p>This is where Gemini takes over. We use <strong>automatic function calling</strong> — Gemini decides which tools to call and when, all on its own.</p><p>python</p><pre>from google import genai<br>from google.genai import types<br>import json, os<br>from k8s_tools import get_pod_status, get_pod_logs, get_pod_events</pre><pre>client = genai.Client(api_key=os.environ[&quot;GEMINI_API_KEY&quot;])<br>def get_pod_status_tool(namespace: str) -&gt; str:<br>    &quot;&quot;&quot;Get all pods in a namespace with their status, conditions and container states&quot;&quot;&quot;<br>    return json.dumps(get_pod_status(namespace), indent=2)<br>def get_pod_logs_tool(namespace: str, pod_name: str, tail: int = 50) -&gt; str:<br>    &quot;&quot;&quot;Get the last N lines of logs from a specific pod&quot;&quot;&quot;<br>    return get_pod_logs(namespace, pod_name, tail)<br>def get_pod_events_tool(namespace: str) -&gt; str:<br>    &quot;&quot;&quot;Get warning events in a namespace to understand what is going wrong&quot;&quot;&quot;<br>    return json.dumps(get_pod_events(namespace), indent=2)<br>available_tools = {<br>    &quot;get_pod_status_tool&quot;: get_pod_status_tool,<br>    &quot;get_pod_logs_tool&quot;: get_pod_logs_tool,<br>    &quot;get_pod_events_tool&quot;: get_pod_events_tool,<br>}<br>def run_agent(namespace: str, user_query: str):<br>    system_prompt = &quot;&quot;&quot;You are a Kubernetes troubleshooting expert agent.<br>Your job is to investigate issues in a Kubernetes cluster and provide clear diagnosis and fixes.<br>When given a namespace or problem:<br>1. First check pod status<br>2. Get events to understand warnings<br>3. Fetch logs if needed<br>4. Provide a clear diagnosis and exact fix commands<br>Always end with:<br>- 🔍 Root Cause<br>- 🛠️ Fix (with exact kubectl commands)<br>- 🛡️ Prevention tip&quot;&quot;&quot;<br>    print(f&quot;\n🤖 Agent starting investigation on namespace: {namespace}\n&quot;)<br>    print(&quot;-&quot; * 50)<br>    messages = [f&quot;{user_query}\nNamespace: {namespace}&quot;]<br>    while True:<br>        response = client.models.generate_content(<br>            model=&quot;gemini-2.5-flash&quot;,<br>            config=types.GenerateContentConfig(<br>                system_instruction=system_prompt,<br>                tools=[get_pod_status_tool, get_pod_logs_tool, get_pod_events_tool],<br>                automatic_function_calling=types.AutomaticFunctionCallingConfig(<br>                    disable=False<br>                )<br>            ),<br>            contents=messages<br>        )<br>        has_tool_call = False<br>        for part in response.candidates[0].content.parts:<br>            if part.function_call:<br>                has_tool_call = True<br>                tool_name = part.function_call.name<br>                tool_args = dict(part.function_call.args)<br>                print(f&quot;🔧 Calling tool: {tool_name}({tool_args})&quot;)<br>                result = available_tools[tool_name](**tool_args)<br>                print(f&quot;📊 Result preview: {result[:200]}...\n&quot;)<br>        if not has_tool_call:<br>            print(&quot;-&quot; * 50)<br>            print(&quot;\n📋 AGENT DIAGNOSIS:\n&quot;)<br>            print(response.text)<br>            break<br>        messages.append(response.candidates[0].content)</pre><p>Key insight: <strong>we don’t write the investigation logic</strong>. We give Gemini the tools and let it reason. That’s what makes this an <em>agent</em> rather than a script.</p><h3>Step 4 — Deploy a Broken App to Test</h3><p>bash</p><pre>kubectl create namespace demo<br>kubectl apply -f k8s/test-app/broken-deployment.yaml<br>kubectl get pods -n demo</pre><p>Output:</p><pre>NAME                         READY   STATUS             RESTARTS   AGE<br>broken-app-dfcb74dd5-vhhkt   0/1     ImagePullBackOff   0          17s</pre><p>The deployment uses nginx:this-tag-does-not-exist — a classic ImagePullBackOff. Our agent&#39;s first patient. 🏥</p><h3>Step 5 — Run the Agent</h3><p>bash</p><pre>cd agent<br>python main.py demo</pre><h3>The Output</h3><pre>🤖 Agent starting investigation on namespace: demo</pre><pre>🔧 Calling tool: get_pod_status_tool({&#39;namespace&#39;: &#39;demo&#39;})<br>🔧 Calling tool: get_pod_events_tool({&#39;namespace&#39;: &#39;demo&#39;})</pre><pre>📋 AGENT DIAGNOSIS:</pre><pre>🔍 Root Cause<br>The pod broken-app-dfcb74dd5-vhhkt is stuck in ImagePullBackOff<br>because the image nginx:this-tag-does-not-exist does not exist on Docker Hub.</pre><pre>🛠️ Fix<br>kubectl edit deployment broken-app -n demo<br># Change image to: nginx:latest</pre><pre>🛡️ Prevention tip<br>Always verify image tags before deploying. Pin exact versions<br>(e.g. nginx:1.21.0) in production and add image scanning to your CI/CD pipeline.</pre><p>The agent investigated the cluster, identified the root cause, and gave exact fix commands — autonomously.</p><h3>Roadmap</h3><p>This is version 1. More scenarios coming:</p><ul><li>ImagePullBackOff detection</li><li>CrashLoopBackOff diagnosis</li><li>OOMKilled detection</li><li>Pending pod (resource limits) diagnosis</li><li>Slack/webhook alerting</li><li>Deploy on GKE + Vertex AI</li></ul><h3>Try It Yourself</h3><p>👉 <strong>GitHub:</strong> <a href="https://github.com/SwwapnilKambley/k8s-troubleshooting-agent">github.com/SwwapnilKambley/k8s-troubleshooting-agent</a></p><p>Get your free Gemini API key at <a href="https://aistudio.google.com/">aistudio.google.com</a>, clone the repo, and run it against your own cluster.</p><p><em>Follow me for more DevOps + AI content. I’m documenting my entire AI learning journey publicly, one project at a time.</em></p><p><strong>Tags:</strong> Kubernetes DevOps AI Agents Gemini Python GCP SRE</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a019e886f1ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>