DEV Community

Prantik Chandra
Prantik Chandra

Posted on

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

What if you could bottle the tactical mastermind of MS Dhoni—his legendary calm, his sudden bowling shifts, his field-placing wizardry—and put it into a live-updating artificial intelligence?

That is exactly the challenge I set out to tackle for the Agentic Premier League (APL) 2026, a phenomenal vibe-coding hackathon hosted by the incredible team at GDG Cloud Pune and powered by Google Gemini.

In this blog, I’ll walk you through how I built "Captain Cool"—a fully functional, live-scraping, multi-agent IPL match strategist built entirely using the official google-genai Python SDK, Streamlit, and Google Antigravity.

🏗️ Architectural Blueprint
To solve the complex, dynamic decision-making flow of an IPL match, "Captain Cool" splits the workload among four distinct, collaborative Gemini-powered agents that engage in a structured debate loop before arriving at a final tactical proposal.

mermaid
graph TD
A[Cricbuzz Match URL] -->|Dual-Page Scraper| B[MatchState Dataclass]
B -->|Active Fields / Squads| C[Streamlit UI Form]
C -->|🧠 Make Captain's Call| D[Orchestrator Debate Loop]

subgraph Orchestrator [CaptainCoolOrchestrator]
    D -->|Step 1| E[Stats Analyst Agent]
    E -->|Stats Intelligence| F[Strategist Agent]
    F -->|Tactical Proposal| G[Devil's Advocate Agent]
    G -->|Critical Challenge| H[Strategist Defense]
    H -->|Final Tactical Call| I[Commentator Agent]
end
I -->|TV Broadcast Narrator| J[Harsha Bhogle Commentary Output]
H -->|Calculate Similarities| K[Confidence Index %]
Enter fullscreen mode Exit fullscreen mode

👥 Meet the Multi-Agent Roster
Instead of a single LLM trying to wear multiple hats, "Captain Cool" runs four independent agents, each equipped with its own specialized system prompt:

📊 The Stats Analyst Agent: The "numbers geek." It analyzes pitch conditions, calculates dynamic win probabilities, runs bowler resource audits, and evaluates player matchups.
🧠 The Strategist Agent (MS Dhoni Persona): The master strategist. Inspired by "Thala's" bold tactical mindset, it proposes the primary "Captain's Call" (e.g. which bowler to bring on, field placement, timeout triggers, or Impact Player usage).
👹 The Devil's Advocate Agent: The challenger. It actively seeks blind spots in the Strategist's proposal, stress-tests the decision against variables like dew, and suggests statistically safer alternatives.
🎙️ The Match Commentator Agent: The voice of the match. It takes the finalized, defended tactical decision and explains it to the fans in a high-tempo, TV-style broadcast voice resembling Harsha Bhogle.
🛠️ Gemini Tech Stack & Live Tool Integration
APL is Google's house, and "Captain Cool" takes full advantage of the official google-genai SDK capabilities:

  1. Function Calling & Tool Use The Stats Analyst doesn't hallucinate stats. It implements real Gemini Function Calling to query custom Python tools:

calculate_win_probability(): Computes real-time win probability dynamically based on wickets, runs needed, and overs.
get_player_stats(): Queries detailed player profiles, economy rates, and boundary percentages.
get_head_to_head(): Composes live batter-vs-bowler matchups (e.g., runs scored, balls faced, and dismissals).

  1. State-of-the-Art Quota-Exhaustion Resiliency A major highlight of the build is the Multi-Model Hot-Fallback handler built into our orchestrator.py:

The orchestrator targets gemini-2.5-flash by default.
If it detects a 429 RESOURCE_EXHAUSTED error due to free-tier daily or per-minute quotas, it instantly switches all agents to gemini-flash-latest (Gemini 1.5 Flash) on the fly.
It throws a sleek UI toast (st.toast("🔄 Quota exhausted on 2.5-flash. Switched to 1.5-flash fallback!")) and immediately retries the request, giving you 24/7 seamless execution without crashing!
🚀 Advanced Stretch Goals (Our Secret Weapons!)
To push the project to the absolute top of the leaderboard, we went far beyond a basic chatbot and implemented four game-changing, premium stretch features:

🎙️ 1. Voice Commands (Web Speech Recognition)
Don't want to type? You can now speak directly to Captain Dhoni! By clicking Dictate Command, the browser listens to your micro-strategy, transcribes it in real time using Chrome's native Speech-to-Text engine, and passes it directly to Dhoni's core logic!

🔊 2. Audio Commentary (Web Speech Text-to-Speech)
Once Captain Cool makes his final call, a premium Play Voice Commentary button lets you listen to the Harsha Bhogle-styled commentary out loud. It filters hashtags and formats the narrative into a high-energy broadcast spoken voice!

🖼️ 3. Multimodal Analysis (Pitch & Scorecard Uploads)
Gemini's multimodal vision is fully utilized. You can upload a photo of the pitch (to capture cracks or grass density) or a screenshot of the scorecard. The Stats Analyst agent automatically parses the uploaded image and integrates visual cues directly into the debate!

📐 4. Simulated Counterfactual Scenarios
Rather than just a static confidence metric, we built a mathematically-backed scenario simulator. If Dhoni proposes bowling Rasikh Salam Dar, the app runs a counterfactual comparison against other active bowlers (e.g., Lockie Ferguson or Starc) and displays an explicit callout:

📉 If you had bowled Mitchell Starc instead of Rasikh Salam Dar, the expected run rate would rise, dropping the team's win probability by 6.8%!

📐 Live Scraper & Bowler Resource Math
Paste a live Cricbuzz URL, and the app automatically triggers a dual-page crawler:

Commentary Page: Extracts real-time score, overs, wickets, and on-strike batters.
Scorecard Page: Parses playing XI lists, venue information, and 1st Innings total scores (automatically computing Target = 1st_innings_score + 1).
📐 Squad Segregation & Bowler Workload Resource Model
To advise the strategist on who to bowl next, we built a mathematical model to trace bowler workloads as ball values: $$\text{Balls Bowled} = (\text{Overs} \times 6) + \text{Remaining Balls}$$ $$\text{Overs Remaining} = \text{Overs_To_Balls}(24 - \text{Balls Bowled})$$

To prevent mixed-team rosters, the scraper maps the active bowling team (team_bowling) to its parsed roster and strictly filters bowlers_used to only include players in their playing XI and bench. Opponent players are completely isolated and ignored!

🏆 Thank You GDG Cloud Pune!
Building this system has been an absolute blast. Vibe-coding with Google Antigravity allowed me to iterate, fix rate limits on the fly, and build a highly resilient multi-agent orchestration loop in record time.

Huge shoutout to the organizers at GDG Cloud Pune for hosting the Agentic Premier League and giving us the perfect sandbox to push the boundaries of Google Gemini! We are currently sitting comfortably at 2nd place with 960 points and gunning straight for the championship! 🥇🏆

GitHub Repository: https://github.com/Prantik-1811/Agentic-Premier-League
Try it locally: Follow the installation guide in the README!

Top comments (0)