Behind the Scenes: Building “Captain Cool” — The Agentic Multi-Agent IPL Strategist Powered by Gemini

In the Indian Premier League (IPL), a split-second decision can define the fate of a multi-million dollar franchise. Should a leg-spinner bowl the 18th over against a left-handed pinch-hitter when the dew is setting in? Should the captain invoke the “Impact Player” rule right now, or hold it back?

Traditionally, captains rely on gut instinct, and analysts rely on static historical databases. But what if you could combine Dhoni’s calm strategic foresight, Ricky Ponting’s aggressive counter-analyses, real-time live match state integration, and advanced generative AI to create the ultimate virtual captain?

Welcome to Captain Cool — a state-of-the-art, multi-agent AI cricket strategist built using the Google Gemini stack and Next.js.

🌟 The Vision: Why “Captain Cool” Stands Out

Most hackathon entries build either simple wrappers around LLMs or basic static data dashboards. Captain Cool breaks this mold by introducing Collaborative Agentic Reasoning directly into live sports analytics.

Instead of asking a single AI to spit out a recommendation, Captain Cool simulates a high-stakes virtual dugout debate between specialized AI agents before presenting a unified, bulletproof tactic:

  1. The Stats Analyst (Data & Environment): Feeds live match API data and dynamically queries real-time weather and stadium dew conditions.
  2. The Strategist (Dhoni Style): Formulates the calm, optimal tactical decision, prioritizing matchups and situational math.
  3. The Devil’s Advocate (Ricky Ponting Style): Forcefully challenges the plan, highlighting critical flaws, matchup anomalies, and overlooked risks.
  4. Captain Cool (Consensus Synthesizer): The final decision-maker. It digests the debate, resolves the conflicts, and delivers a structured, authoritative captain’s call.

🏗️ Technical Architecture: Under the Hood

The application is built on a highly performant, responsive stack designed to deliver instantaneous, real-time streamed responses.

graph TD
    A[User / CricAPI Live Data] -->|Match Context| B[Next.js API Route]
    B -->|Fetch Weather| C[Open-Meteo API]
    C -->|Dew & Wind Data| D[Agent 1: Stats Analyst]
    D -->|Situation Brief| E[Agent 2: Strategist]
    E -->|DHONI-style Tactic| F[Agent 3: Devil's Advocate]
    F -->|PONTING-style Critique| G[Agent 4: Captain Cool]
    G -->|Consensus Synthesis| H[SSE Streaming Stream]
    H -->|Premium Glassmorphic UI| I[Client Dashboard]

1. The Collaborative Multi-Agent Loop

The core intelligence runs inside a Next.js API route (src/app/api/captain/route.js). It leverages the new @google/genai SDK and utilizes gemini-2.5-flash for lighting-fast generation speeds.

Here is how the sequential context handoff works:

// Agent 1: Stats Analyst queries stadium conditions
const analystResponse = await chat.sendMessage({ 
  message: `Analyze this match state and check the weather for Chennai...` 
});

// Agent 2: Strategist proposes the initial Dhoni-style plan
const strategistPlan = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  config: { systemInstruction: "You are MS Dhoni, the master tactician..." },
  contents: `Stats: ${analystResponse}. Match Context: ${matchContext}`
});

// Agent 3: Devil's Advocate aggressively critiques
const devilCritique = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  config: { systemInstruction: "You are the Devil's Advocate (Ricky Ponting style)..." },
  contents: `Strategist proposed: ${strategistPlan}`
});

// Agent 4: Captain Cool synthesizes into a 3-part consensus
const finalDecision = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  config: { systemInstruction: "Synthesize this debate into the final captain's call..." },
  contents: `Strategist: ${strategistPlan}. Devil's Advocate: ${devilCritique}`
});

2. Solving the “Live Data” Challenge

Unlike static simulators, Captain Cool connects to CricAPI to fetch actual live match data.
Because live matches aren’t always active during development hours, we engineered a brilliant three-step lookup pipeline in src/app/api/live-match/route.js:

  1. Search specifically for the active IPL Series (/v1/series?search=IPL).
  2. Resolve the latest match from the tournament schedule (/v1/series_info).
  3. Fetch detailed innings-by-innings scorelines (/v1/match_info) to build a perfect, up-to-the-minute tactical dataset for our agent debate loop.

3. Server-Sent Events (SSE) Streaming

To make the dashboard feel alive, we didn’t want the user waiting 15 seconds for all four agents to finish talking. We built a custom ReadableStream returning text/event-stream. As each agent finishes their thought, it is streamed immediately to the user’s dashboard, visualizing the internal dugout debate in real-time.

🎨 Premium Sports-Themed Glassmorphism UI

A great algorithm deserves an equally stunning interface. We rejected boring default templates in favor of a custom, highly premium design:

  • Atmospheric Stadium Lights: A dynamic background featuring slowly pulsing radial gradients simulating Chennai/Wankhede floodlights under the night sky.
  • Premium Glassmorphic Panels: High-blur backdrops (backdrop-filter: blur(16px)), bright top-left borders for 3D depth, and clean micro-animations.
  • Color-Coded Agent Identities:

    • 🔵 Stats Analyst: Cool Data Blue
    • 🟢 Strategist: Calm Matchup Green
    • 🔴 Devil’s Advocate: Aggressive Dissenting Red
    • 🟡 Captain Cool: Golden Masterpiece Glow

📊 The Ultimate Output: What the Submission Replies With

When you hit the “Generate Captain’s Strategy” button, the debate wraps up, and Captain Cool delivers a distinct, beautifully structured three-part response:

1. The Next Decision

Tactic: Bring in the Left-Arm orthodox spinner from the Pavilion End. Immediately transition to a defensive 6-3 field setup on the leg side (deep mid-wicket, deep square leg, long-on back). Keep the Impact Player (pinch-hitting opener) padded up in the dugout.

2. The Reasoning

“Look, the data shows the dew is settling in fast, making the ball like a cake of soap. However, we’ve got a fresh right-handed batter who struggles immensely when forced to hit against the spin on a gripping pitch. Bringing the spinner now forces him to hit into the wind toward the longer boundary. It’s about squeezing the run rate, not just chasing wickets.”

3. What the Dissenting Agent Said

“The Devil’s Advocate strongly argued that exposing a spinner during heavy dew is suicide, as wet balls lead to full tosses and easy boundary balls. They suggested sticking to hard-length pace bowling. However, we have overridden this warning because the batter’s negative matchup index against left-arm spin (-35%) outweighs the wet ball risk if we instruct the bowler to bowl slightly flatter through the air.”

🚀 Impact & Future Scope

Captain Cool is more than a hackathon proof-of-concept. It represents the future of real-time sports broadcasting and tactical coaching:

  • Interactive Live Broadcasts: Imagine streaming platforms (like JioCinema or Hotstar) letting viewers click a button to see what “Captain Cool” would do right now during a live match.
  • Smart Coaching Systems: Local clubs and academy teams can input their current scorecard to receive elite, professional-level tactical debates on how to turn the game around.
  • Voice-Activated Strategy: Integrating speech-to-text to let a physical captain discuss scenarios with the dugout assistant on the field.

🛠️ How to Run Locally

Get the dugout running on your machine in under 3 minutes:

# 1. Clone the repository
git clone https://github.com/your-username/captain-cool.git
cd captain-cool

# 2. Install dependencies
npm install

# 3. Create your .env.local file
CRIC_API_KEY=your_cricapi_key
GEMINI_API_KEY=your_gemini_api_key

# 4. Spin up the development server
npm run dev

Open http://localhost:3000 and start captaining your team!

Developed with ❤️ for the Google Gemini Developer Hackathon. Elevate your sports strategy today with Captain Cool!

@gdgcmu #gdgcloudpune #

Captain Cool: Building an Enterprise Multi-Agent IPL Match Strategist with Google Gemini 🏏🏆

🌟 Introduction: The High-Stakes World of T20 Cricket
In the ultra-competitive arena of the Indian Premier League (IPL), matches are won and lost in the margins. A single tactical miscalculation—bowling a spinner in the death overs against a power-hitter, misplacing a fielder at cow corner, or misjudging the heavy dew factor—can alter the fate of a championship.

While modern IPL franchises employ armies of data analysts, real-time tactical decision-making in the dugout remains incredibly stressful. Captains must synthesize vast amounts of historical data, pitch conditions, and gut instinct in seconds.

To solve this, we built Captain Cool—an enterprise-grade, virtual IPL captain powered by a multi-agent Google Gemini AI think-tank. Designed for the Google Build with AI Hackathon (#gdgcloudpune), Captain Cool simulates an elite dugout debate in real-time to deliver the ultimate tactical call.

🧠 The Core Innovation: Multi-Agent Debate Loop
Single-prompt LLMs often suffer from “sycophancy”—they agree with whatever parameters the user inputs without challenging underlying assumptions. In cricket strategy, blind agreement is a recipe for disaster.

To build a robust tactical engine, Captain Cool implements an advanced Multi-Agent Debate Architecture using four autonomous Gemini 3.1 Flash Lite agents orchestrated via a sequential LangChain-style debate loop:

[ Live Cricbuzz Scraper / Form Input ]
│
▼
📊 Agent 1: Stats Analyst (Tool Calling)
│
▼
🎯 Agent 2: Strategist (Initial Call)
│
▼
⚔️ Agent 3: Devil’s Advocate (Dissent & Challenge)
│
▼
💪 Agent 2: Strategist (Revised Defense)
│
▼
🎙️ Agent 4: Match Commentator (Final Verdict & Confidence %)

  1. 📊 The Stats Analyst (Tool-Calling Head)
    Acting as the head of data intelligence, this agent is equipped with custom JavaScript tools to fetch real-time match context:

getWinProbability(): Calculates dynamic win percentages based on target, balls remaining, and wickets.
getPlayerProfile(): Pulls elite batting/bowling stats (strike rates, death over economy, weakness against spin/pace).
getPitchAssessment(): Evaluates venue history (Wankhede dew, Chepauk turn) and current phase dynamics.

  1. 🎯 The Strategist (Tactical Captain)
    Taking the data report from the Stats Analyst, the Strategist formulates the initial over-by-over plan, selecting the ideal bowler, field placements, and bowling lines.

  2. ⚔️ The Devil’s Advocate (Opposition Analyst)
    This is where the magic happens. The Devil’s Advocate is strictly instructed to act as the opposition head coach. It inspects the Strategist’s plan, identifies glaring tactical blind spots (e.g., “You’re bowling Bumrah now, but who bowls the 20th over?” or “Kohli loves stepping out to spin, your mid-off is too deep”), and aggressively challenges the captain.

  3. 🎙️ The Match Commentator (Broadcast Verdict)
    Finally, the Commentator observes the debate, synthesizes the opposing viewpoints, and delivers an official broadcast-quality verdict complete with a calculated Tactical Confidence Percentage.

🚀 Key Technical Features
🔴 1. Automated Live Cricbuzz Web Scraper
To ensure the AI operates on absolute real-time data, we built a native Node.js web scraper directly into the Stats Analyst agent.

How it works: When a user pastes a live Cricbuzz match URL, the backend instantly fetches the live HTML, strips out all DOM overhead, extracts the pure live scorecard and commentary text (up to 15KB), and injects it into Gemini’s context window.
Absolute Truth: The AI is instructed to treat this scraped live Cricbuzz data as the primary source of truth, overriding any conflicting manual form inputs.
📍 2. Interactive 2D/3D Fielding Oval
Field placements are critical to T20 bowling plans. We implemented a custom, interactive top-down cricket ground UI directly in the command console.

Users can click anywhere on the grass to place up to 9 fielders.
Using advanced polar coordinate math, the frontend instantly calculates the exact cricket position clicked (e.g., Deep Point, Slips / Gully, Cow Corner, Short Fine Leg).
This exact fielding list is fed into the AI prompts, allowing the agents to analyze physical field gaps and suggest bowling lines to match!
🌌 3. Cinematic 3D Enterprise UI (Vercel/Apple Inspired)
We elevated the application from a standard dashboard into an immersive, executive-grade sports broadcast platform:

Photorealistic Championship Trophy: Replaced cartoon emojis with a hyper-realistic 3D golden championship trophy cup rendered with professional studio lighting.
3D Mouse Parallax: As users move their cursor across the screen, background glassmorphism stat cards (⚡ REQ RATE: 12.5 RPO, 🎯 MATCHUP INTEL) and geometric rings shift at varying speeds, creating a stunning illusion of multi-layered depth.
Auto-Scroll Choreography: Clicking Analyze & Decide ignites a glowing neon progress bar and smoothly auto-scrolls down into the Live Debate Arena, spotlighting each agent card as it slides up with 3D tilt effects.
🛠️ Tech Stack & Architecture
AI Engine: Google Gemini 3.1 Flash Lite (via @google/genai SDK)
Backend: Node.js, Express.js, native fetch HTML scraping
Frontend: HTML5, Vanilla JavaScript, CSS3 (Glassmorphism, 3D Perspective Transforms, CSS Grid/Flexbox)
Version Control: Git & GitHub
🏆 Conclusion & Hackathon Journey
Building Captain Cool for the Google Build with AI Hackathon (#gdgcloudpune) was an incredible journey in exploring the power of agentic workflows. By combining tool-calling, multi-agent debate, live web scraping, and premium 3D UI design, we demonstrated how Gemini can transform complex sports analytics into an engaging, real-time decision-making platform.

🔗 Check out the Project:
GitHub Repository: https://github.com/gauravshinde2162006-hash/Captain-cool
We would love to hear your thoughts, feedback, and tactical ideas in the comments below! 👇

Built with ❤️ for #gdgcloudpune

🏏 Building “Captain Cool” — A Multi-Agent IPL Strategist Powered by Google Gemini

What if an AI system could think like a cricket captain during a live IPL match?

Not just predict outcomes — but actually debate tactics, analyze player matchups, calculate bowling resources, and make pressure decisions the way elite captains do.

That was the idea behind “Captain Cool”, a multi-agent AI system I built for the Agentic Premier League 2026 using the official Gemini SDK, Streamlit, and real-time cricket data.

The project was inspired by the tactical calm and decision-making style of MS Dhoni.

🚀 The Idea

Modern LLM applications often rely on a single AI model handling everything.

But cricket strategy is not a one-dimensional problem.

During a match, multiple perspectives matter simultaneously:

Statistical analysis
Match conditions
Risk management
Psychological pressure
Tactical adaptability

So instead of one AI agent, I designed a multi-agent orchestration system where different AI agents specialize in different responsibilities and debate decisions before arriving at a final tactical recommendation.

🧠 Multi-Agent Architecture

The system consists of four independent Gemini-powered agents:

📊 Stats Analyst Agent

Responsible for:

Match state analysis
Win probability estimation
Batter vs bowler matchups
Resource optimization
Economy rate analysis
🧠 Strategist Agent

The “captain brain” of the system.

This agent proposes tactical decisions such as:

Bowling changes
Field placement ideas
Match-up exploitation
Death-over planning
Impact Player usage
👹 Devil’s Advocate Agent

This was one of the most fun parts to build.

Instead of blindly accepting the strategist’s decision, this agent actively:

Challenges assumptions
Detects tactical risks
Suggests safer alternatives
Simulates counter scenarios

This significantly improved output quality.

🎙️ Match Commentator Agent

Transforms the final tactical decision into a broadcast-style explanation inspired by professional cricket commentary.

⚙️ Tech Stack

Built using:

Python
Streamlit
Official Gemini SDK (google-genai)
Google Antigravity
BeautifulSoup
Cricbuzz live scraping
Multi-agent orchestration logic
📡 Live Match Intelligence

The app accepts a live Cricbuzz URL and extracts:

Score
Overs
Wickets
Batters
Bowlers
Playing XI
First innings score
Venue details

This data becomes the shared “world state” for all agents.

📐 Bowling Resource Engine

One challenge in cricket strategy is managing bowling resources properly.

I implemented a workload model using ball-level calculations:

text{Balls Bowled} = (text{Overs} times 6) + text{Balls}

and:

text{Overs Remaining} = 24 – text{Balls Bowled}

This allowed the strategist to intelligently preserve death-over specialists instead of exhausting them too early.

🔥 Gemini Fallback System

One major engineering challenge during development was API quota exhaustion.

To solve this, I built a hot-fallback mechanism:

Primary model → gemini-2.5-flash
Automatic fallback → gemini-flash-latest

If the orchestrator detects:
429 RESOURCE_EXHAUSTED

the system instantly switches models and retries automatically without crashing the application.

This made the system far more resilient during rapid testing.

🏏 Example Tactical Debate
Match Situation

RCB: 222/4
PBKS: 10/1 chasing 223

Strategist Agent

Bowl Chahal in the 18th over. Use spin against the new batter and force the aerial shot.

Devil’s Advocate Agent

Risky call. Chahal’s death-over economy is vulnerable on shorter boundaries. Starc provides safer seam angles.

Final Decision

Hold Starc for the 19th. Attack immediately with spin while the batter is unsettled.

This debate-driven workflow produced noticeably more nuanced decisions than direct prompting.

🧩 Key Learnings

Building this project taught me a lot about:

Multi-agent orchestration
Tool calling with Gemini
Structured prompting
Context passing between agents
Real-time data systems
Reliability engineering for LLM apps
Designing AI systems around disagreement instead of consensus

One of the biggest insights:
AI systems become significantly more reliable when agents are allowed to critique each other.

🏆 Final Thoughts

This project was an incredibly fun exploration into combining:

Sports analytics
Multi-agent systems
Real-time AI orchestration
Tactical simulation

Huge thanks to GDG Cloud Pune for organizing the Agentic Premier League and creating a space to experiment with agentic AI systems.

🔗 GitHub Repository: https://github.com/Prantik-1811/Agentic-Premier-League

Agentic Premier League Repository

Would love feedback from:

AI engineers
Cricket nerds
Multi-agent system builders
Anyone experimenting with Gemini workflows

If you were the captain in the 18th over — spin or pace? 👀🏏

I built a multi-agent IPL captain cool AI on Gemini

Cricket is a captain’s game. And for 3 hours at a Google AI hackathon, I became one — by building Captain Cool, a multi-agent IPL strategist powered entirely by Google Gemini. Not a chatbot. Not a form with a Gemini call. A real debate between AI agents — the way a captain’s brain actually works.

The problem

Every IPL captain faces split-second decisions — who bowls the death over, when to bring in the Impact Player, how to set the field against a left-hander in dew. These calls win or lose matches.

I wanted to build an AI that doesn’t just answer “who should bowl?” but actually debates it, shows its reasoning, and tells you what happens if you make the wrong call.

Architecture

Instead of one Gemini call wearing 4 hats, I built 4 named agents with distinct roles that talk to each other:

User Input (Cricbuzz URL or manual match state)
                ↓
         Orchestrator
┌─────────────────────────────────────┐
│ Agent 1: Stats Analyst              │ ← Google Search tool call
│ Agent 2: Strategist (persona-based) │ ← Proposes the call
│ Agent 3: Devil's Advocate           │ ← Challenges it hard
│ Agent 4: Commentator                │ ← Final output + counterfactual
└─────────────────────────────────────┘
                ↓
    Decision + Debate UI + Voice Output

The 4 agents

Agent 1 — Stats Analyst

Uses Gemini’s built-in Google Search tool to fetch live player form and head-to-head stats. Not hardcoded JSON — real tool use.

System prompt:

You are an IPL stats analyst. Analyze pitch conditions, dew factor,
bowler economy rates, and batter weaknesses. Use Google Search to
fetch current player form. Output structured JSON with: key_stats,
batter_weakness, bowler_recommendation, win_probability (%).

Agent 2 — Strategist (Persona-driven)

The user picks a captain persona — and the entire system prompt personality changes:

🧊 Dhoni mode:

You are MS Dhoni. Ice in your veins. You back your bowlers,
never panic, always think 2 overs ahead. Make ONE decisive call. No hedging.

💥 Rohit mode:

You are Rohit Sharma. Bold and aggressive. Back your instincts
and your big hitters. Make the attacking call others won't.

🔥 Hardik mode:

You are Hardik Pandya. Unconventional and fearless.
Make the call that surprises everyone but works.

Agent 3 — Devil’s Advocate

You are a sharp rival captain. Challenge the Strategist's decision hard.
Find the flaw. Propose a specific alternative.
Format: CHALLENGE: [what's wrong] | ALTERNATIVE: [what you'd do instead]

Agent 4 — Commentator

You are Harsha Bhogle. Explain the final call in vivid cricket language
a passionate fan would love. Include: why this decision, why NOT the
alternative, a counterfactual ("if they'd bowled X, win prob drops ~Y%"),
and a confidence score out of 10.

Orchestrator flow

  1. Extract match state from Cricbuzz URL using Gemini’s URL context tool
  2. Stats Analyst runs Google Search → structured JSON with win probability
  3. Strategist (selected persona) proposes tactical decision
  4. Devil’s Advocate challenges with a specific alternative
  5. Strategist defends or revises → final call
  6. Commentator delivers cricket-language output + counterfactual + confidence score + voice via Web Speech API

One full match scenario

Match state:

  • MI vs CSK · 2nd innings · Over 16 · CSK need 34 off 24 · 4 wickets down
  • Rohit Sharma on strike (67*) · Jadeja non-striker (12*)
  • Bumrah has 2 overs left · Chahal has 1 · Flat pitch · Heavy dew · Wankhede

Stats Analyst: Win prob MI 58% / CSK 42%. Dew negating seam movement. Jadeja vulnerable to pace outside off.

Strategist (Dhoni mode): Bowl Bumrah now — back him to nail yorkers despite the dew.

Devil’s Advocate: Dew renders Bumrah’s seam movement useless tonight. Save him for over 19. Bowl Chahal now while Jadeja is on strike — he’s the weak link against leg spin.

Strategist (final call): Point conceded. Chahal to bowl over 17. Bumrah held for over 19.

Commentator: “In dew-heavy Wankhede, Bumrah’s famous seam is rendered ineffective. Rohit holds him back for the 19th — calm, calculated captaincy. If they’d bowled Bumrah here, win probability drops to 51%. Confidence: 8/10.” 🎙️

What made us stand out

At the hackathon, 100+ developers were building the same thing — a form that calls Gemini and returns formatted text. Here’s what we did differently:

  • Real agent debate visible in the UI — shown as chat bubbles, not hidden or summarized
  • Captain persona selector — same agents, completely different personality per captain
  • Live Cricbuzz scraping — paste a URL, Gemini extracts the match state automatically
  • Counterfactual — we don’t just tell you what to do, we tell you what happens if you don’t
  • Voice output — the commentator speaks the final call aloud via Web Speech API

Tech stack

Layer Technology
Frontend TypeScript + Vite + CSS
AI model Google Gemini 2.5 Flash
SDK @google/genai
Tool use Gemini built-in Google Search
Voice output Web Speech API
Build environment Google AI Studio

Links

Built by Uddhav Bhople — Associate Microsoft Learn Student Ambassador · Google Student Ambassador · B.Tech Computer Engineering Student @ D.Y. Patil University Pune

googleai #gemini #cricket #apl #hackathon #multiagent #typescript #gdgcloudpune #gdgcloudpune2026

Captain Cool: A Gemini Multi-Agent IPL Match Strategist

Cricket captaincy is not just “pick the best bowler.” It is matchups, dew, field dimensions, batter psychology, bowler workload, Impact Player timing, and the courage to make a call before the obvious moment arrives.

Captain Cool is my attempt to turn that into an agentic AI system: a virtual IPL captain that reads the match state, runs an internal dugout debate, and returns the next tactical decision in cricket language.

The stack is intentionally Google-first:

  • Next.js frontend and API routes
  • Gemini via @google/genai
  • Model: gemini-2.5-flash
  • Gemini function calling for tools
  • CricAPI / CricketData live score integration
  • Free no-key Cricbuzz-backed fallback endpoint
  • Custom multi-agent orchestration

The multi-agent loop is custom TypeScript orchestration, but the tool use is real Gemini function calling.

What Captain Cool Does

The user enters or fetches the current match state:

  • innings, over, ball
  • score and wickets
  • striker and non-striker
  • bowling resources
  • pitch condition
  • dew factor
  • venue
  • target / required rate
  • Impact Player availability
  • optional live match ID or URL

Captain Cool replies with:

  • the next captaincy decision
  • cricket-language reasoning
  • visible dissent from the Devil’s Advocate agent
  • confidence score
  • counterfactual
  • full debate transcript

Example output:

Captain's Call:
BOWL PATHIRANA - OVER 16

Why:
The wet ball has taken Jadeja's grip away. Pathirana's skiddy angle
is harder for Tilak to get underneath, and the field protects the
midwicket release shot.

Dissent:
The risk is burning Pathirana before the 18th. If this over leaks 14,
the death plan gets thin.

Architecture

┌─────────────────────────────────────────────────────────────┐
│                         Next.js UI                           │
│  Premium cricket broadcast dashboard                         │
│  Manual match state + live match fetch + agent debate view    │
└──────────────────────────────┬──────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────────┐
│                    Next.js API Routes                        │
│                                                             │
│  /api/strategy                                               │
│  /api/cricket/current                                        │
│  /api/cricket/match?id=...                                   │
│  /api/cricket/free-score?match=...                           │
│  /api/live-matches                                           │
│  /api/live-strategy                                          │
└──────────────────────────────┬──────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────────┐
│                 Gemini Agent Orchestrator                    │
│                                                             │
│  1. Stats Analyst                                            │
│     ├─ fetchLiveMatchData tool, when match ID is present      │
│     └─ calculateMatchPressure tool                           │
│                                                             │
│  2. Tactical Strategist                                      │
│     └─ proposes first captaincy call                         │
│                                                             │
│  3. Devil's Advocate                                         │
│     └─ challenges the plan                                   │
│                                                             │
│  4. Tactical Strategist                                      │
│     └─ defends or revises                                    │
│                                                             │
│  5. Match Commentator                                        │
│     └─ formats fan-friendly final answer                     │
└──────────────────────────────┬──────────────────────────────┘
                               │
                               ▼
┌─────────────────────────────────────────────────────────────┐
│                         UI Result                            │
│  Captain's Call + Why + Dissent + Confidence + Debate         │
└─────────────────────────────────────────────────────────────┘

Agent Design

The system uses four named Gemini-powered agents. Each agent is a separate Gemini call with its own system prompt and role.

1. Stats Analyst

The Stats Analyst does not make tactical decisions. It reads numbers, phase, pressure, match conditions, and live data.

Prompt excerpt:

You are a world-class cricket statistician — think of ESPNcricinfo's
StatsGuru merged with a baseball sabermetrician.

YOUR IDENTITY:
- You speak in numbers, trends, and matchups ONLY
- You NEVER suggest a decision or give an opinion
- You respond to queries with structured statistical evidence
- Every claim must include a number: average, strike rate, economy,
  sample size, historical trend
- If a CricAPI live match ID is present in the match state, your FIRST
  action must be calling fetchLiveMatchData before any analysis.

Output shape:

STATISTICAL BRIEF:
• Matchup
• Venue Trend
• Phase Analysis
• Condition Factor
• Historical Parallel

2. Tactical Strategist

The Strategist is the captaincy brain. It makes the first call: who bowls, how the field is set, whether to use the Impact Player, when to take the timeout, and what the contingency is.

Prompt excerpt:

You are the tactical brain of an IPL captaincy team. Think MS Dhoni's
instinct + Rohit Sharma's bowling changes + Hardik Pandya's aggression.

YOUR IDENTITY:
- You make BOLD, specific tactical decisions
- You think 2-3 overs ahead, not just the next ball
- You understand cricket psychology, momentum, and pressure
- You're not afraid to use unorthodox options

Output shape:

TACTICAL DECISION:
• Next Bowler
• Field Setup
• Batting Move
• Impact Player
• Strategic Timeout
• Contingency

TACTICAL LOGIC:
...

3. Devil’s Advocate

This agent exists to disagree. It challenges the Strategist’s first plan with the kind of objection an assistant coach would raise in a real dugout.

Prompt excerpt:

You are the cautious inner voice of a cricket captain — the part
that asks "what if this goes horribly wrong?" before every decision.

YOUR IDENTITY:
- Your job is to FIND FLAWS in every tactical proposal
- You think about WORST-CASE SCENARIOS
- You remember cricket history where similar decisions backfired
- You are NOT negative — you are rigorous.

Critique framework:

1. Matchup counter
2. Resource mismanagement
3. Condition misread
4. Psychological backfire
5. Historical precedent
6. Opportunity cost

4. Match Commentator

The Commentator turns the internal debate into something a non-technical fan can enjoy.

Prompt excerpt:

You are the voice of cricket — imagine Harsha Bhogle's storytelling
meets Ravi Shastri's energy meets Ian Bishop's gravitas.

YOUR IDENTITY:
- You translate complex tactical decisions into ELECTRIC commentary
- You make cricket strategy accessible to a 12-year-old fan
- You capture the DRAMA, the tension, the "what if"
- You speak like you're on live television

Final output:

CAPTAIN COOL'S CALL
THE COMMENTARY
THE DUGOUT DEBATE
CONFIDENCE METER

Gemini Function Calling

Captain Cool uses Gemini function calling for real tool use. The two important tools are:

Tool 1: fetchLiveMatchData

This tool fetches live match information before analysis when a live match ID or URL is available.

Schema:

export const fetchLiveMatchDataTool: FunctionDeclaration = {
  name: "fetchLiveMatchData",
  description:
    "Fetch live match score, status, teams, venue, scorecard, and innings details. Prefer CricAPI match IDs; also accepts a Cricbuzz URL or numeric match ID through a free no-key fallback.",
  parameters: {
    type: Type.OBJECT,
    properties: {
      matchId: {
        type: Type.STRING,
        description: "A CricAPI match ID, Cricbuzz match ID, or Cricbuzz live match URL.",
      },
    },
    required: ["matchId"],
  },
};

Handler:

export async function handleFetchLiveMatchData(args: {
  matchId?: string;
}) {
  if (!args.matchId) {
    return { error: "Missing live match ID or URL." };
  }

  try {
    if (!/^https?:///i.test(args.matchId) && process.env.CRICAPI_KEY) {
      return await getLiveCricketMatchDetails(args.matchId);
    }
  } catch {
    // Fall through to the free no-key provider.
  }

  return await getFreeLiveCricketScore(args.matchId);
}

Tool 2: calculateMatchPressure

This local tool converts match state into tactical context.

It calculates:

  • current over
  • balls remaining
  • innings phase
  • current run rate
  • required run rate
  • runs needed
  • pressure score
  • pressure label
  • bowler overs remaining
  • tactical flags

Example output:

{
  "phase": "death",
  "currentRunRate": 9.16,
  "requiredRunRate": 9.78,
  "pressureScore": 72,
  "pressureLabel": "high",
  "tacticalFlags": [
    "Death-over specialists and boundary protection take priority.",
    "Dew reduces grip, so yorkers, hard lengths, and pace-off cutters become safer than big spin."
  ]
}

Orchestration Flow

The orchestration is intentionally multi-turn:

Step 1:
Stats Analyst checks if liveMatchId exists.
If yes, Gemini calls fetchLiveMatchData.

Step 2:
Stats Analyst calls calculateMatchPressure.

Step 3:
Stats Analyst summarizes tactical context.

Step 4:
Tactical Strategist proposes the first plan.

Step 5:
Devil's Advocate challenges the plan.

Step 6:
Tactical Strategist defends or revises.

Step 7:
Match Commentator converts the whole debate into final fan-facing JSON.

The important bit: this is not one Gemini call pretending to be multiple agents. Each role is a separate Gemini request with its own prompt and context.

Real-Time Data

Captain Cool supports three live-data paths:

1. CricAPI / CricketData

Used for current match lists and detailed scorecards.

Routes:

GET /api/cricket/current
GET /api/cricket/match?id=<match-id>

Environment variable:

CRICAPI_KEY=...

2. Free No-Key Fallback

For quick demos without a key, the app can fetch from a Cricbuzz-backed JSON endpoint.

Route:

GET /api/cricket/free-score?match=<id-or-url>

This accepts:

  • Cricbuzz numeric match ID
  • Cricbuzz live match URL

3. SportMonks

SportMonks is available as a richer live source when a token is present.

Routes:

GET /api/live-matches
POST /api/live-strategy

Environment variable:

SPORTMONKS_API_TOKEN=...

UI Design

I wanted the interface to feel like a premium cricket broadcast truck, not a generic chatbot.

The dashboard includes:

  • dark navy broadcast-studio theme
  • pitch green and gold accents
  • scoreboard-style match state
  • live match ticker
  • pitch visualization
  • field placement diagram
  • agent debate bubbles
  • confidence gauge
  • live metrics sparklines
  • “Ask Captain” action button
  • “Free Fetch” live-score fallback

The UI sections are:

Top Bar:
THE DUGOUT, AI status, match clock, ticker

Left Panel:
Match state, scoreboard, pitch, batters, bowlers

Center Panel:
Live score fetcher, Captain's Call, controls

Right Panel:
Agent debate and confidence meter

Bottom:
Live metrics

End-to-End Walkthrough

Scenario:

Match: CSK vs MI at Chepauk
Innings: 2
Score: 142/4
Overs: 15.3
Target: 186
Striker: Tilak Varma, 47* off 31
Non-striker: Hardik Pandya, 12* off 8
Pitch: turning
Dew: setting in
Impact Player: available
Strategic Timeout: available

Step 1: Fetch Live Data

The user can either:

  • click “Fetch Current” with a CricAPI key
  • paste a Cricbuzz match ID or URL and click “Free Fetch”

The dashboard renders:

MI 142/4
15.3 overs
Target 186
Required rate around 9.8
Status: Live

Step 2: Ask Captain

The user clicks:

ASK CAPTAIN

The four-agent spinner starts:

Stats Analyst
Strategist
Devil's Advocate
Commentator

Step 3: Stats Analyst Tool Calls

If a live match ID is present:

fetchLiveMatchData(matchId)

Then:

calculateMatchPressure(matchState)

The Stats Analyst returns something like:

• Phase Analysis: Over 15.3 means the match is entering the death phase.
• Required Rate: MI need 44 from 27 balls, about 9.78 RPO.
• Condition Factor: Dew reduces grip, so spin is less reliable.
• Resource View: Pathirana has one high-leverage over available.

Step 4: Strategist Makes the First Call

The Strategist proposes:

Bowl Pathirana for over 16.
Set deep midwicket, long-on, long-off, deep square.
Keep fine leg up and protect the hard-length release shot.
Hold the Impact Player unless a wicket falls.

Step 5: Devil’s Advocate Pushes Back

The Devil’s Advocate challenges:

If Pathirana leaks 12-14 now, CSK lose their death-over cushion.
Jadeja has completed his quota, so the fallback death plan becomes thin.
The wet ball could turn yorkers into low full tosses.

Step 6: Strategist Revises or Defends

The Strategist responds:

Proceed with Pathirana, but bowl over the wicket to Tilak.
If the first two balls go for boundaries, switch the plan next over:
hard-length pace-off into the pitch, not spin.

Step 7: Commentator Finalizes

The final answer becomes:

CAPTAIN'S CALL:
BOWL PATHIRANA - OVER 16

WHY:
The dew has made spin risky. Pathirana's skiddy angle is the better
weapon against a set left-hander. The field protects Tilak's strongest
release shot and asks him to hit to the bigger, weaker zone.

DISSENT:
The dugout worry is resource burn. If this over goes badly, the 18th
and 20th over plan gets uncomfortable.

CONFIDENCE:
78%

AI Studio Prompt Link

I prototyped prompts locally in code during the build. I have not published a Google AI Studio prompt link yet.

Before publishing the final dev.to post, add it here:

Final Thought

A massive shoutout to ** @gdgcloudpune , especially *@antrixsh_gupta *, *@pratik_kale *, and the entire organizing team. The problem statement was brilliant, the vibe was electric, and events like this push the developer community to level up in incredible ways.

👇 Check out the code and try it yourself:

GitHub Repository: https://github.com/swamiabhishek45/captain-cool
Live Link : https://captain-cool-dusl.vercel.app/

Captain Cool

Building “Captain Cool”: An AI-Powered IPL Match Strategist

Cricket, particularly the high-octane IPL T20 format, is a game of fine margins. A single tactical decision—who bowls the 19th over, when to deploy the Impact Player, or how to counter a left-handed power hitter on a turning track—can change the course of a match. Behind these decisions is a captain who thinks two overs ahead, absorbing data and intuition in real-time.

But what if we could replicate this decision-making process using Generative AI?

Enter Captain Cool, a multi-agent orchestration pipeline built with the Google Gemini model and the official Google GenAI SDK.

In this post, we’ll dive into how we built an AI system that acts as an elite IPL strategist, debating tactical moves in a simulated “coaching staff” environment before making the final call.

The Architecture: A Three-Agent Coaching Staff

To mimic the intense debate in a cricket dugout, we designed a three-agent architecture where AI agents communicate sequentially to form a final strategy.

1. The Stats Analyst 📊

Data is the backbone of modern T20 cricket. The Stats Analyst agent is responsible for consuming the real-time match state (e.g., “16th over, 145/3, heavy dew”) and utilizing Tool Calling.

We equipped the Analyst with Python functions (fetch_historical_stats and fetch_live_match_data). When prompted, the Gemini model automatically knows when to invoke these tools, fetching mock data like MS Dhoni’s strike rate or the current win probability. It then synthesizes a purely data-driven report without making any actual strategic calls.

2. The Strategist (Captain Cool) 🧠

Armed with the Analyst’s data, the Strategist takes the stage. Prompted to embody the calm, calculated persona of legendary IPL captains like MS Dhoni or Rohit Sharma, this agent proposes a single tactical move.

Crucially, we employed strict prompt engineering here: the agent is instructed to use authentic cricket terminology (“bowling into the pitch”, “matchups”, “taking the game deep”) and explicitly forbidden from using generic AI jargon.

3. The Devil’s Advocate 👿

No strategy is foolproof. To ensure robustness, we introduced the Devil’s Advocate. This agent acts as a highly critical assistant coach whose sole job is to aggressively challenge the Strategist’s proposal. It looks for counter-matchups, momentum risks, and potential pitfalls in the plan.

The Final Call 🏆

Finally, the loop returns to the Strategist, who evaluates the Devil’s Advocate’s critique. Like a true captain, it decides whether to stick to its guns or pivot, providing the final cricket logic behind the move.

Handling the Chaos: Resiliency and UX

Building AI pipelines comes with challenges, notably API rate limits and network instability. To counter this, we integrated the tenacity library, wrapping our API calls in robust exponential backoff retries. If the Gemini API hits a rate limit, the system gracefully pauses and retries, ensuring the pipeline doesn’t crash mid-debate.

On the user experience front, we utilized the rich Python library. Instead of a boring wall of text, users interact with a beautifully formatted CLI. Colored panels represent each agent’s turn, and spinner animations keep the user engaged while the AI “crunches the numbers.”

Why Gemini 2.5 Pro / Flash?

For an interactive application like this, speed is just as important as intelligence. We chose Gemini because it offers the perfect balance: it’s fast enough to keep the CLI feeling responsive in real-time while possessing the deep reasoning capabilities required for complex tool calling and contextual multi-agent debate.

The Result

The end result is an incredibly fun, dynamic tool that genuinely feels like you are sitting in an IPL dugout in 2026. You feed it a stressful match scenario, and it gives you a data-backed, heavily debated, and authentically phrased tactical masterplan.

Developed for GDG APL Pune 🚀

This project was built and showcased as part of the GDG APL Pune event. A huge shoutout to the @gdgcloudpune community for organizing such an incredible platform for developers to push the boundaries of Generative AI and share real-world implementations.

If you were at the event, let’s connect in the comments and discuss how you’re leveraging multi-agent systems!

Building a Virtual IPL Captain with 5 Gemini Agents arguing Strategy (Google ADK Hackathon)

Have you ever yelled at your TV during an IPL match, wondering why the captain gave the ball to a part-timer in the 18th over?

For the Google Gemini Hackathon, I decided to build a system that answers that exact question. I built IPL Captain AI — an agentic AI think-tank that ingests live match states and makes data-driven tactical decisions the way MS Dhoni, Rohit Sharma, or Pat Cummins would.

But I didn’t want just a simple LLM wrapper. I wanted to see the reasoning behind the call. To do this, I built a system where 5 distinct Gemini agents actively debate with each other before making a final decision.

Here’s how I built it using the newly released Google Agent Development Kit (ADK) and Gemini 2.5 Flash.

🎯 The Problem Statement
Goal: Build an agentic AI system that acts as a virtual IPL captain — making the next tactical decision in a live match.

A user inputs the current match state (or pastes a live Cricbuzz URL). The system must reply with:

The next decision — who bowls, who comes in to bat, field setup, or when to deploy the Impact Player.
The reasoning — explained in cricket-language a real commentator would use.
The dissenting view — an internal debate where a “Devil’s Advocate” agent challenges the strategy before committing to the call.
🏗️ The Architecture: A 5-Agent Think Tank
Using Google ADK, I orchestrated 5 distinct agents. I split the pipeline into two phases using ADK’s ParallelAgent and SequentialAgent constructs.

Phase 1: Intelligence Gathering (Parallel)
Before making a decision, a captain looks at the numbers and the pitch. These run simultaneously:

📊 Stats Analyst: Has access to a custom database tool to pull head-to-head records, strike rates, and venue history.
🌤️ Pitch & Conditions Analyst: Uses an OpenWeatherMap API tool to check humidity and dew factors, assessing how the pitch will behave in the second innings.
🔍 Live Scout: Uses Google Search grounding to pull live news and current match conditions from the web.
Phase 2: The Debate Loop (Sequential)
This is where the magic happens.

🎯 Strategist (The Captain): Looks at the intelligence from Phase 1 and proposes a tactical plan, backed by a mathematical Win Probability Calculator tool.
😈 Devil’s Advocate: Its only job is to find flaws in the Strategist’s plan. It forces the system to consider counterfactuals (“What if we save Bumrah for the 20th over?”).
🔄 Strategist Revision: The Strategist reviews the dissent and either defends the original call with data or revises the plan.
Phase 3: Output
🎙️ Match Commentator: Takes the entire raw agent trace and synthesizes it into engaging, jargon-free cricket commentary (think Harsha Bhogle meets Ravi Shastri).
🛠️ The Tech Stack & Tools
Google ADK (Agent Development Kit): The backbone of the orchestration.
Gemini 2.5 Flash: Used for all agent nodes due to its incredible speed, low latency, and massive context window.
Function Calling: Built 4 custom Python tools for the agents to invoke:
get_weather_conditions (API integration)
calculate_win_probability (Math model)
get_cricket_stats (Data lookup)
live_scraper (URL parsing)
Google Search Grounding: Built-in ADK tool for live, hallucination-free web data.
Streamlit: For a premium, dark-themed UI that visualizes the agent pipeline and the debate trace.
💡 Key Learnings & Challenges

  1. Tool Conflicts
    I learned the hard way that the Gemini API currently doesn’t allow mixing built-in tools (like google_search) and custom function calling in the exact same request. To solve this, I separated the Live Scout (Google Search only) from the Stats Analyst (custom functions only) and ran them in parallel using ADK’s ParallelAgent.

  2. Multi-Agent Debate produces better LLM results
    By forcing the LLM to act as a Devil’s Advocate and critique its own prior output, the final tactical decisions became infinitely more robust. Instead of generic advice (“bowl your best bowler”), the system started producing hyper-specific tactical nuances (“bowl the off-spinner now because the left-hander is on strike, despite the short boundary”).

🚀 The Result
When you input a scenario — say, CSK defending 18 runs in the final over — you don’t just get an answer. You watch a live debate where one agent suggests bowling a spinner, the Devil’s Advocate screams about the heavy dew factor fetched via the API, and the Captain ultimately makes the right call.

You can check out the full open-source code and run it yourself here: 👉 GitHub: [https://github.com/pranav2983/google-agentic-premiere-league]

If you are building multi-agent systems, I highly recommend checking out Google ADK. It makes complex sequential/parallel orchestration a breeze!

Have you built anything with the new Gemini 2.5 tools? Let me know in the comments!

gdgcloudpune

How We Built “Captain Cool OS” : A Multi-Agent AI Tactical Intelligence System for Cricket Captains Using Gemini

🏏 Captain Cool OS

Captain Cool OS is an AI-powered tactical decision engine for cricket captains, built using Google Gemini and a multi-agent orchestration system.

The idea was simple:
What if an AI could think through high-pressure IPL moments like a real captain?

Not just predict outcomes.
Actually debate tactics.

The Idea

Cricket is one of the few sports where a captain can completely change the game with a single decision.

Who bowls the next over?
Do you trust pace in heavy dew?
Do you go defensive or attack for wickets?
Do you protect square boundaries or long-off?
Do you stick with the matchup or adapt to pressure?

In real matches, these decisions happen ball-by-ball under insane pressure.

We wanted to build a system that could simulate that kind of tactical thinking.

What We Built

Captain Cool OS is a multi-agent AI system that behaves like a cricket team’s tactical war room.

A user provides the current match situation:

  • score
  • wickets
  • venue
  • dew conditions
  • batter matchups
  • bowlers remaining
  • death-over pressure

The system then runs an internal debate between specialized AI agents before locking in a tactical decision.

Instead of generating one generic response, the agents challenge each other, identify weaknesses, revise plans, and finally arrive at a tactical consensus.

The Multi-Agent System

We built multiple Gemini-powered agents, each with a clear responsibility.

📊 Stats Analyst

Looks at:

  • venue trends
  • bowler vs batter matchups
  • recent form
  • pressure metrics
  • death-over effectiveness

This agent acts like the analytics department.

🧠 Strategist

Creates the initial tactical plan.

This includes:

  • who bowls next
  • line and length
  • field setup
  • contingency plans
  • execution strategy

⚠️ Devil’s Advocate

This is where things get interesting.

Instead of agreeing blindly, this agent actively attacks the proposed plan:

  • identifies tactical risks
  • exposes weak execution points
  • challenges matchup assumptions
  • questions field placements

This creates a real reasoning loop instead of a single-pass AI answer.

🧩 Reflection Evaluator

Acts like a head coach reviewing the plan.

It checks:

  • contradictions
  • execution feasibility
  • tactical instability
  • risk exposure

If the strategy looks flawed, the system forces a revision loop.

🎙 Narrative Translator

Converts structured tactical reasoning into natural cricket language.

The final output feels closer to commentary or dugout strategy discussion rather than raw AI output.

Tactical Orchestration Flow

The orchestration pipeline works like this:

  1. Stats Analyst gathers evidence
  2. Strategist proposes a tactical plan
  3. Devil’s Advocate stress-tests it
  4. Reflection Evaluator checks for contradictions
  5. Strategist revises the plan if needed
  6. Final tactical consensus is generated

The system doesn’t just answer.

It debates before deciding.

Tactical Visualization Layer

One of the most fun parts of the project was building the cinematic tactical interface.

We added:

  • confidence evolution tracking
  • tactical instability alerts
  • live orchestration timelines
  • bowling trajectory targeting
  • field placement radar visualizations

The goal was to make the reasoning process feel visible and understandable instead of hidden behind a chatbot response.

Why We Think This Is Interesting

Most sports AI tools focus only on predictions.

Captain Cool OS focuses on decision-making under pressure.

We wanted the system to:

  • explain itself
  • challenge itself
  • adapt its reasoning
  • communicate like a cricket strategist

The debate between agents became the most interesting part of the project.

Tech Stack

  • Google Gemini 2.5 Flash
  • Google Antigravity
  • FastAPI
  • Next.js
  • TypeScript
  • TailwindCSS
  • WebSockets
  • Custom SVG tactical visualizations

Future Scope

There’s a lot we’d love to explore further:

  • live Cricbuzz/ESPN integration
  • ball-by-ball adaptive tactics
  • live win probability shifts
  • voice-enabled captain interaction
  • reinforcement learning memory
  • multimodal pitch analysis


Captain Cool AI — Building a Multi-Agent IPL Tactical Engine with FastAPI, Next.js & Gemini AI 🚀🏏

Introduction

What if an AI could think like an IPL captain during a high-pressure chase?

That idea led me to build Captain Cool AI — a multi-agent cricket strategy engine inspired by the calm tactical mindset of legendary IPL captains.

The system analyzes match situations, debates strategies internally using multiple AI agents, and finally generates tactical recommendations in real-time.

This project combines:

FastAPI backend
Next.js frontend
Gemini AI
Multi-agent architecture
Cricket analytics
Tactical reasoning
The Idea 💡

During a T20 chase, captains constantly make decisions like:

Should we attack or rotate strike?
Which bowler should be targeted?
How does dew affect spin?
Should we preserve wickets?

Instead of using a single AI response, I designed a multi-agent workflow where different agents think independently before making a final decision.

Multi-Agent Architecture 🧠

The system contains 5 specialized AI agents:

  1. Stats Analyst

Analyzes:

Required run rate
Batter matchups
Pitch behavior
Historical trends
Dew factor

  1. Strategist

Creates the tactical plan:

Batting intent
Over-by-over approach
Bowler targeting strategy

  1. Devil’s Advocate

Challenges the proposed strategy:

Risks
Weaknesses
Failure possibilities
Alternate viewpoints

  1. Decision Maker (Captain Cool)

Acts like the final captain:

Evaluates all viewpoints
Makes final tactical call
Assigns confidence score
Suggests backup plan

  1. Match Commentator

Explains the decision in a commentator-style narrative.

Tech Stack ⚙️
Frontend
Next.js
React
Tailwind CSS
Axios
Backend
FastAPI
Python
Pydantic
AI
Gemini AI API
Backend Architecture 🔥

The FastAPI backend exposes 3 main routes:

POST /analyze
POST /debate
POST /decision
/analyze
Generates statistical analysis
Produces strategic proposal
/debate
Devil’s Advocate critiques strategy
/decision
Final tactical decision
Confidence score
Backup strategy
Commentary generation
Cricket Intelligence Layer 🏏

I created custom cricket insight tools such as:

lookup_venue_average_score()
get_batter_vs_bowler_matchup()
analyze_phase_economy()

These simulate:

Venue behavior
Batter matchups
Dew impact
Pitch conditions
Frontend UI 🎨

The UI was designed to feel like:

An IPL tactical dashboard
A captain’s strategy room
Real-time match intelligence panel

Features include:

Match context input
Tactical strategy generation
Multi-agent output display
Confidence indicators
Commentary section
Biggest Challenges 😅

  1. Python Import Errors

Initially faced:

ModuleNotFoundError

Solved using:

Proper project structure
init.py
Correct uvicorn execution path

  1. API Connection Issues

Frontend was unable to connect to backend because of:

Wrong API URLs
CORS configuration
Incorrect localhost routing

Solved by:

CORSMiddleware

and proper API base configuration.

  1. Gemini API Quota Limits

The Gemini free tier rate limits caused:

429 RESOURCE_EXHAUSTED

To handle this:

Added fallback strategies
Optimized prompts
Used lighter models for faster responses
What Makes This Project Unique? 🚀

Unlike basic AI chat apps, this system:

Simulates collaborative AI reasoning
Uses debate-driven decision making
Mimics real IPL tactical analysis
Produces explainable strategies

It’s closer to a real AI coaching engine than a chatbot.

Future Improvements 🔮

Planned upgrades:

Real-time IPL API integration
Ball-by-ball live prediction
Win probability engine
Voice commentary
Captain personality modes
Agent memory system
Final Thoughts ❤️

Building this project taught me:

Multi-agent system design
Backend/frontend integration
AI orchestration
Prompt engineering
FastAPI architecture
Real-world debugging under pressure 😄

This was one of the most exciting AI projects I’ve built so far.

GitHub Repository
https://github.com/HemantXCode/captain-cool-ai
Conclusion

AI is no longer just about generating text.

The future is collaborative AI systems where multiple agents reason together to solve complex problems.

And cricket strategy turned out to be a perfect playground for experimenting with that idea.

🏏🔥 @gdgcloudpune , @antrixsh_gupta , @pratik_kale

🏏 Captain Cool — Building a Multi-Agent IPL Strategy Engine with Google Gemini, Antigravity & AI Debate

🏏 Captain Cool — AI That Thinks Like an IPL Captain

What happens when you combine cricket strategy, multi-agent reasoning, and the Google Gemini ecosystem in a 3-hour hackathon sprint?

You get Captain Cool — an AI-powered IPL match strategist where multiple Gemini agents debate tactical cricket decisions like a real dressing room before making the final captain’s call.

Instead of building a generic chatbot with cricket terminology sprinkled on top, we wanted to simulate something much closer to a real IPL strategy room:

  • analysts studying matchups,
  • captains balancing risk,
  • assistant coaches challenging decisions,
  • and commentators explaining the logic to fans.

Built entirely on the Google AI ecosystem, Captain Cool became our attempt at turning agentic AI into a tactical cricket brain.

⚡ The Core Idea

During an IPL match, captains constantly make micro-decisions:

  • Who bowls the next over?
  • Should the spinner continue despite dew?
  • Is it the right moment for the Impact Player?
  • Do we attack or delay Bumrah’s final over?
  • Which field setup reduces boundary probability?

Captain Cool processes the live match state and lets multiple AI agents argue over the best tactical decision before producing a final recommendation.

The result feels surprisingly close to a real cricket strategy meeting.

🧠 Multi-Agent Architecture

Instead of relying on a single prompt, we decomposed the system into specialized Gemini-powered agents.

🕵️ Match Analyst Agent

Responsible for:

  • venue conditions
  • batter vs bowler matchups
  • dew impact
  • phase analysis
  • tactical statistics

This agent also performs tool execution to fetch structured cricket insights.

💡 Strategist Agent

The “captain brain” of the system.

Inspired by tactical IPL leadership styles, this agent:

  • proposes bowling changes,
  • plans death overs,
  • controls field aggression,
  • and balances risk vs reward.

🔥 Devil’s Advocate Agent

This became the most interesting part of the project.

Its sole responsibility:
challenge the strategist.

Example:

“If we use Bumrah now, who controls the 19th over against Tim David?”

This created genuine multi-agent reasoning instead of fake roleplay.

🎙️ Commentator Agent

The final layer converts raw AI logic into human cricket language.

Instead of:

“Probability optimization suggests pace utilization.”

The system explains:

“The pitch is gripping slightly, so bowling pace-off cutters into the surface makes more tactical sense than feeding spin into the arc.”

This dramatically improved explainability.

🔄 The Agentic Debate Loop

Our orchestration flow:

Match State
    ↓
Analyst Agent
    ↓
Strategist Proposal
    ↓
Devil’s Advocate Critique
    ↓
Strategist Revision
    ↓
Commentator Explanation
    ↓
Final Captain's Call

The important part:
the disagreement is visible.

We intentionally expose the internal tactical debate instead of hiding the reasoning.

🛠️ Tech Stack

AI & Agent Layer

  • Google Gemini API
  • google-genai SDK
  • Multi-agent orchestration inspired by Google ADK
  • Gemini function/tool calling

Backend

  • Python
  • FastAPI
  • Pydantic

Frontend

  • Streamlit dashboard
  • Custom dark-mode tactical UI

Development Workflow

  • Built using Google Antigravity
  • AI-assisted vibe coding
  • Autonomous file scaffolding and iteration

🏏 Example Match Scenario

We tested Captain Cool using a pressure scenario:

Match Situation

  • RCB vs PBKS
  • 150/2 after 14.2 overs
  • Virat Kohli on strike
  • Chahal bowling
  • Heavy dew expected later

📊 Analyst Insight

The Match Analyst agent triggered tool execution and identified:

  • Kohli performs strongly against traditional spin,
  • but his scoring rate drops against googly-heavy leg-spin variations on slower surfaces.

🧠 Internal Debate

Strategist

“Attack with leg-spin now before the dew settles in.”

Devil’s Advocate

“Risky. If Kohli survives the first six balls, the short boundary becomes a major issue.”

Strategist Revision

“Fair. We hold the spinner back for one over and use hard-length pace into the surface first.”

🏆 Final Captain’s Call

“Bring back the pace bowler from the Pavilion End. Use cross-seam hard lengths into the pitch and protect square boundaries. Delay spin until the new batter arrives.”

⚡ Biggest Learnings

The most interesting realization from this build:

Multi-agent systems feel dramatically more intelligent when disagreement is visible.

The Devil’s Advocate agent consistently improved decisions by forcing counterfactual thinking.

Instead of:
“one smart AI”

the project started feeling like:
“a real strategy room.”

🚀 Future Improvements

If we continue developing Captain Cool, the next additions would be:

  • Live Cricbuzz/ESPN integration
  • Real-time win probability engine
  • Voice commentary using Gemini Live API
  • Memory across overs
  • Multimodal pitch image analysis
  • Full Google ADK orchestration

📂 GitHub Repository

👉 https://github.com/So-rush/captain-cool[](url)

🏏 Final Thoughts

Cricket is ultimately a captain’s game.

Captain Cool was our attempt to explore what happens when tactical sports intelligence meets agentic AI reasoning inside the Google Gemini ecosystem.

And honestly…

watching AI agents argue about death-over bowling plans was way more fun than expected. 🏆