<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Om Garkar</title>
    <description>The latest articles on DEV Community by Om Garkar (@om_garkar_b4c757771a07091).</description>
    <link>https://dev.to/om_garkar_b4c757771a07091</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3936246%2Fd0864fdc-50be-4ae8-805d-5d70498ccdf1.jpg</url>
      <title>DEV Community: Om Garkar</title>
      <link>https://dev.to/om_garkar_b4c757771a07091</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/om_garkar_b4c757771a07091"/>
    <language>en</language>
    <item>
      <title>How I Built "Captain Cool": A Multi-Agent AI IPL Strategist for GDG Cloud Pune's Agentic Premier League</title>
      <dc:creator>Om Garkar</dc:creator>
      <pubDate>Sun, 17 May 2026 13:11:34 +0000</pubDate>
      <link>https://dev.to/om_garkar_b4c757771a07091/how-i-built-captain-cool-a-multi-agent-ai-ipl-strategist-for-gdg-cloud-punes-agentic-premier-1ci</link>
      <guid>https://dev.to/om_garkar_b4c757771a07091/how-i-built-captain-cool-a-multi-agent-ai-ipl-strategist-for-gdg-cloud-punes-agentic-premier-1ci</guid>
      <description>&lt;p&gt;published: true&lt;br&gt;
description: A deep-dive into engineering a multi-agent "War Room" utilizing Gemini 2.5 Flash, function calling, custom retry mechanics, and dynamic UI rendering.&lt;br&gt;
tags: &lt;/p&gt;

&lt;p&gt;Have you ever wondered what goes on inside MS Dhoni’s mind during a high-pressure IPL chase? What if we could recreate that legendary tactical brilliance using Artificial Intelligence? &lt;/p&gt;

&lt;p&gt;For the &lt;strong&gt;GDG Cloud Pune Agentic Premier League&lt;/strong&gt;, I decided to tackle this challenge head-on. Meet &lt;strong&gt;Captain Cool&lt;/strong&gt;, a live, multi-agent IPL match strategist powered by Google’s Gemini 2.5 Flash. &lt;/p&gt;

&lt;p&gt;Instead of building a simple chatbot that gives generic cricket advice, I engineered a "War Room" of AI agents that debate, challenge, and synthesize data in real-time to make the ultimate captain’s call. Here is a look under the hood at how I built it from architecture to code.&lt;/p&gt;




&lt;h2&gt;
  
  
  🏗️ System Architecture &amp;amp; The Multi-Agent Pipeline
&lt;/h2&gt;

&lt;p&gt;Single prompts often suffer from hallucination or generic advice when dealing with highly specific sports domains. To solve this, Captain Cool uses &lt;strong&gt;Agentic Orchestration&lt;/strong&gt;. The application spins up four distinct Gemini instances, each initialized with strict system instructions, distinct responsibilities, and specific constraints. &lt;/p&gt;

&lt;p&gt;The match telemetry flows linearly through a pipeline where the output of one agent becomes the foundational context for the next:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;          ┌──────────────────────┐
          │  Live Match Context  │
          └──────────┬───────────┘
                     │
                     ▼
       ┌────────────────────────────┐
       │ 1. Stats Analyst (Tool)   │
       └─────────────┬──────────────┘
                     │  [Telemetry &amp;amp; Match-ups]
                     ▼
       ┌────────────────────────────┐
       │ 2. The Strategist          │
       └─────────────┬──────────────┘
                     │  [Proposed Plan]
                     ▼
       ┌────────────────────────────┐
       │ 3. The Devil's Advocate    │
       └─────────────┬──────────────┘
                     │  [Critique &amp;amp; Pushback]
                     ▼
       ┌────────────────────────────┐
       │ 4. "Captain Cool" (Final)  │
       └────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  The War Room Personnel Breakdown
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;📊 The Stats Analyst (Tool-Augmented):&lt;/strong&gt; This agent is equipped with client-side function declarations. It acts as the ground-truth data layer, executing mathematical evaluations, analyzing pitch metrics (such as the dew factor and soil composition), and pulling historical head-to-head records. It is strictly constrained to avoid speculation.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;🧠 The Strategist:&lt;/strong&gt; Consuming the structured output of the Stats Analyst, this agent simulates a seasoned head coach. It builds a proactive plan: calculating exact over-by-over bowling match-ups, analyzing boundary dimensions, and deciding when to deploy the Impact Player.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;😈 The Devil's Advocate:&lt;/strong&gt; This agent’s sole instruction is to poke holes in the Strategist’s plan. It deliberately introduces edge-case vulnerabilities—such as historical batting weaknesses against specific variations, sudden field placement openings, or fatigue metrics—forcing the system to re-evaluate risk.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;🏏 Captain Cool:&lt;/strong&gt; Acting as the final arbiter, this agent ingests the entire conversational transcript of the previous three models. It filters the noise, accepts or rejects the critique, and outputs the definitive tactical action plan delivered in the calm, collected persona of MS Dhoni.&lt;/li&gt;
&lt;/ol&gt;


&lt;h2&gt;
  
  
  🛠️ Deep Dive: The Multi-Agent Conversation Loop
&lt;/h2&gt;

&lt;p&gt;To establish this structured debate, the application uses a state machine to pass context down the line. Below is a simplified representation of how the Next.js API route chains these agents together sequentially, appending the thoughts of previous agents to the system state:&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
typescript
// /app/api/analyze-match/route.ts
import { GoogleGenAI } from '@google/genai';

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

export async function POST(req: Request) {
  const { matchData } = await req.json();

  // Step 1: Gather raw, verified analytics from the Stats Analyst
  const statsResponse = await ai.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: `Analyze the following match situation: ${JSON.stringify(matchData)}`,
    config: {
      systemInstruction: "You are an elite Cricket Data Scientist. Extract win probabilities, dew impact, and player-to-player match-up stats. Provide facts only.",
      // Tools/Functions would be mapped here
    }
  });
  const statsOutput = statsResponse.text;

  // Step 2: Pass analytics to the Coach/Strategist
  const strategistResponse = await ai.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: `Based on this statistical report:\n${statsOutput}\nFormulate the primary tactical strategy.`,
    config: {
      systemInstruction: "You are an aggressive IPL Head Coach. Design a clear, actionable bowling and fielding strategy."
    }
  });
  const strategyOutput = strategistResponse.text;

  // Step 3: Run the strategy through the Devil's Advocate
  const critiqueResponse = await ai.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: `Review this strategy:\n${strategyOutput}\nIdentify all hidden risks, match-up flaws, or potential tactical errors.`,
    config: {
      systemInstruction: "You are a critical, contrarian Cricket Analyst. Ruthlessly dismantle the proposed strategy and expose its weaknesses."
    }
  });
  const critiqueOutput = critiqueResponse.text;

  // Step 4: Final synthesis by Captain Cool
  const finalCall = await ai.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: `Review the full war-room briefing:\n- Stats: ${statsOutput}\n- Strategy: ${strategyOutput}\n- Pushback: ${critiqueOutput}\nMake the absolute final tactical decision.`,
    config: {
      systemInstruction: "You are 'Captain Cool' MS Dhoni. Deliver the ultimate, definitive strategic decision in your signature calm, tactical, and brief tone."
    }
  });

  return Response.json({
    stats: statsOutput,
    strategy: strategyOutput,
    critique: critiqueOutput,
    decision: finalCall.text
  });
}
🎙️ UX Innovations: Companion Modes &amp;amp; Multimodal Extensions
To make the application more than just text logs, I engineered two high-fidelity companion modules designed to run asynchronously alongside the main engine:

🌟 The Sachin Tendulkar Live Dashboard
This component provides real-time nostalgic and modern sentiment analysis. Using Gemini's function calling capabilities, the model evaluates live event streaming data and triggers two unique workflows:

Contextual Meme Mapping: Maps high-tension moments to popular cultural sentiments (e.g., Moye Moye, Absolute Cinema).

Text-to-Speech Integration: Feeds the structured text response into the Web Speech API (window.speechSynthesis) on the frontend, giving "Sachin" an audible voice to guide users through the match state.

🔥 Live Hype-Man Mode (Structured Prompt Engineering)
The Hype-Man mode acts as an on-the-fly content generation engine. When a boundary or wicket occurs, it produces rapid-fire commentary in vivid "Spicy Hinglish." Concurrently, it outputs a highly specific structured image prompt optimized for Google Imagen 3.

For example, when a critical wicket falls, it outputs:

"A highly detailed cinematic neon graphic of a cricket bipedal robot shattering glowing stumps, cosmic sparks flying across a dark stadium, hyper-realistic, volumetric lighting, T20 banner aesthetic."

This prompt is instantly piped into the Imagen API to update the UI background dynamically.

🚧 Hardening the Application Against API Rate Limits
Running recursive multi-agent loops on the free tier means confronting a brutal constraint: Rate Limits (429 RESOURCE_EXHAUSTED).

Because a single dashboard interaction triggers multiple nested loops across independent models, it was easy to exhaust the allowable Requests Per Minute (RPM) threshold.

The Engineering Solution: Resilient Mid-tier Handshaking
To handle this elegantly, I engineered a highly resilient fetching utility featuring an exponential backoff algorithm with jitter. Instead of letting errors bubble up and break the user experience, the system parses the Google API's error payload to locate backoff instructions:

TypeScript
// utils/geminiRetry.ts
export async function geminiWithRetry(fn: () =&amp;gt; Promise&amp;lt;any&amp;gt;, retries = 3, delay = 2000): Promise&amp;lt;any&amp;gt; {
  try {
    return await fn();
  } catch (error: any) {
    // Detect standard 429 Resource Exhausted status codes
    if ((error.status === 429 || error.message?.includes('429')) &amp;amp;&amp;amp; retries &amp;gt; 0) {
      console.warn(`[Rate Limit Hit]: Retrying in ${delay}ms... (${retries} attempts remaining)`);

      // Look for a custom cool-down hint from the API metadata if available, or use exponential backoff
      const dynamicDelay = error.statusText?.retryAfter 
        ? parseInt(error.statusText.retryAfter) * 1000 
        : delay;

      await new Promise((resolve) =&amp;gt; setTimeout(resolve, dynamicDelay));

      // Recursive call with increased delay (exponential backoff factor of 2)
      return geminiWithRetry(fn, retries - 1, delay * 2);
    }
    throw error;
  }
}
By encapsulating our model initializations inside this geminiWithRetry utility, the system safely buffers incoming execution peaks, drops maximum agent iteration loops by 50% without dropping data quality, and ensures 100% processing reliability.

🚀 Key Takeaways &amp;amp; Lessons Learned
Developing Captain Cool for the GDG Cloud Pune Agentic Premier League reshaped my understanding of LLM application design. The core lesson is clear: The true potential of Large Language Models is unlocked when we move away from monolithic single prompts and step into Agentic Orchestration.

By giving specialized AI models isolated objectives, discrete personalities, and structured collaboration pathways, we can build highly stable, domain-expert workflows capable of parsing complex real-world logic.

🛠️ Technical Stack Checklist
Framework: Next.js 15 (App Router), TypeScript, Tailwind CSS

Orchestration &amp;amp; Intelligence: Google Gen AI SDK (Gemini 2.5 Flash, Imagen 3)

Hosting Platform: Vercel

What tactical match scenario or classic historic collapse would you want to put through the Captain Cool War Room? Let's discuss in the comments below! 🏏
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>gdgcloudpune</category>
      <category>googlecloud</category>
      <category>ai</category>
      <category>apl</category>
    </item>
  </channel>
</rss>
