DEV Community

Soham Barkase
Soham Barkase

Posted on

Building "Captain Cool": A Multi-Agent Cricket Strategist Using Google ADK & Gemini

Building "Captain Cool": A Multi-Agent IPL Cricket Strategist with FastAPI and Google's ADK

In sports, as in software engineering, some of the best decisions don't come from a single voice. They come from intense, high-stakes debate.

Think about an Indian Premier League (IPL) cricket match. With 3 overs left, 35 runs to defend, a heavy dew falling, and a world-class batsman like Suryakumar Yadav on strike, what does the captain do?

  • Does he go with the textbook option?
  • Does he trust a spinner despite the wet ball?
  • Does he gamble on a high-risk contrarian boundary field?

To explore this, we built Captain Cool—a collaborative multi-agent AI cricket strategist that acts as a real-time tactical board. Powered by Google's new Agent Development Kit (ADK), Gemini 2.5 Flash, FastAPI, and React, it simulates a complete coaching staff debate to deliver definitive, elite tactical decisions.

In this post, we'll walk through the architectural design, show you how to orchestrate multi-agent pipelines with Google's ADK, and share the full implementation code so you can build your own cooperative AI agents.


The Multi-Agent Architecture

Rather than asking a single LLM prompt to "act like a cricket captain," we designed a collaborative pipeline with three distinct AI roles, each with its own specialized prompts, behaviors, and tools:

[Stats Analyst Agent]
Grounded, data-centric. Its job is to retrieve current ground metadata (dimensions, pitch soil behavior, dew probability, historical trends) using a custom API tool and build a structured tactical briefing.

[Devil's Advocate Agent]
Contrarian and aggressive. It despises conventional plays. It analyzes the stats briefing and match state to propose a high-risk/high-reward, unexpected strategy (e.g., bowling a part-timer or setting a hyper-aggressive close field).

[Captain Cool Strategist Agent]
The decision-maker. Inspired by legendary captains, he is calm and highly analytical. He debates the Devil's Advocate's contrarian proposal point-by-point, weighs it against the Stats Analyst's findings, and delivers the definitive tactical game plan (bowling changes, specific ball-by-ball variations, and exact field placements).


Step 1: Defining Custom Agent Tools

Google's ADK allows us to easily register Python functions as tools. For our Stats Analyst, we created a comprehensive venue-lookup tool get_pitch_and_weather_conditions that maps IPL grounds (like Wankhede, Chinnaswamy, Chepauk) to realistic pitch types, boundary dimensions, dew factors, and humidity statistics.

def get_pitch_and_weather_conditions(venue: str) -> dict:
    """
    Returns realistic pitch and weather conditions for the given IPL venue.
    Use this tool to get current ground conditions before forming any strategy.
    """
    venue_data = {
        "Wankhede Stadium": {
            "venue": "Wankhede Stadium, Mumbai",
            "pitch_type": "Flat batting track with slight cracks on Day 3+",
            "pace_bounce": "Medium-High",
            "spin_turn": "Low in first innings, increases under lights",
            "dew_factor": "Heavy dew after 8 PM, very significant in second innings",
            "average_first_innings_score": 175,
            "boundary_dimensions": {"straight": "75m", "square": "70m"},
            "historical_trend": "Chasing sides win 58% of matches here under lights"
        },
        # ... additional venues mapped here
    }

    # Matching logic...
    return venue_data.get(venue, default_data)
Enter fullscreen mode Exit fullscreen mode

Step 2: Defining ADK Agents

Using Google ADK, we configure each agent's system instructions, specify the Gemini model to use (gemini-2.5-flash for blazing-fast speed and reasoning), and attach the required tools.

from google.adk.agents import Agent

# 1. Stats Analyst with Custom Venue Tool
stats_analyst = Agent(
    name="stats_analyst",
    model="gemini-2.5-flash",
    description="IPL Stats Analyst that gathers pitch, weather, and venue condition data",
    instruction="""You are an elite IPL cricket stats analyst. Your job is to:
1. Use the `get_pitch_and_weather_conditions` tool to fetch data for the given venue.
2. Analyze the venue conditions and present a structured tactical briefing.
3. Highlight factors influencing bowling and fielding: pitch behavior, dew, boundaries, and trends.
Format your analysis as a clear, structured briefing. Use cricket terminology.""",
    tools=[get_pitch_and_weather_conditions],
)

# 2. Devil's Advocate for Contrarian Play
devils_advocate = Agent(
    name="devils_advocate",
    model="gemini-2.5-flash",
    description="Contrarian cricket strategist who challenges conventional wisdom",
    instruction="""You are the Devil's Advocate — a fearless, aggressive cricket tactician who HATES conventional thinking.
Propose a CONTRARIAN, high-risk/high-reward strategy.
- If textbook says spin, argue for pace.
- Challenge batting weaknesses and suggest one bold 'wildcard' move.
Tone: Provocative, confident, and sharp.""",
)

# 3. Captain Cool (The Decision Maker)
captain_cool = Agent(
    name="captain_cool",
    model="gemini-2.5-flash",
    description="The final strategist who debates and decides the optimal IPL game plan",
    instruction="""You are Captain Cool — the ultimate IPL strategist. Calm, analytical, and decisive.
1. Debate the Devil's Advocate's proposal point-by-point, showing where you agree/disagree.
2. Reference specific match conditions, venue data, and cricket fundamentals.
3. Deliver your FINAL TACTICAL DECISION (Bowling Plan, Field Placements, and Captain's Note).
Use authentic cricket terminology (e.g., 'back-of-a-length cutters', 'slip cordon', 'blockhole').""",
)
Enter fullscreen mode Exit fullscreen mode

Step 3: Orchestrating the Sequential Pipeline in FastAPI

To execute the debate, we set up a sequential pipeline. The output of the Stats Analyst is fed into the Devil's Advocate, and then both outputs are handed over to Captain Cool for the final judgment.

We use ADK's InMemorySessionService and Runner to handle execution states:

import json
from fastapi import FastAPI
from pydantic import BaseModel
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai.types import Content, Part

app = FastAPI(title="Captain Cool — IPL Multi-Agent Strategist")
APP_NAME = "captain_cool_ipl"

class MatchState(BaseModel):
    venue: str
    overs: float
    wickets: int
    runs: int
    target: int
    batsman_on_strike: str
    bowler: str
    run_rate: float
    batting_team: str
    bowling_team: str

async def run_agent(agent: Agent, prompt: str) -> str:
    session_service = InMemorySessionService()
    session = await session_service.create_session(app_name=APP_NAME, user_id="ipl_user")
    runner = Runner(agent=agent, app_name=APP_NAME, session_service=session_service)

    content = Content(role="user", parts=[Part(text=prompt)])
    final_response = ""

    async for event in runner.run_async(session_id=session.id, user_id="ipl_user", new_message=content):
        if event.is_final_response() and event.content and event.content.parts:
            for part in event.content.parts:
                if part.text:
                    final_response += part.text
    return final_response

@app.post("/strategize")
async def strategize(match_state: MatchState):
    match_json = json.dumps(match_state.model_dump(), indent=2)

    # Step 1: Get Stats Analyst Venue Briefing
    analyst_prompt = f"Analyze the conditions for this match:\n{match_json}"
    analyst_res = await run_agent(stats_analyst, analyst_prompt)

    # Step 2: Pitch to Devil's Advocate
    advocate_prompt = f"Situation:\n{match_json}\n\nAnalyst Briefing:\n{analyst_res}"
    advocate_res = await run_agent(devils_advocate, advocate_prompt)

    # Step 3: Captain Cool's Debate & Decision
    captain_prompt = f"Situation:\n{match_json}\n\nAnalyst:\n{analyst_res}\n\nDevil's Advocate:\n{advocate_res}"
    captain_res = await run_agent(captain_cool, captain_prompt)

    return {
        "match_state": match_state.model_dump(),
        "analyst_data": analyst_res,
        "advocate_strategy": advocate_res,
        "strategist_decision": captain_res
    }
Enter fullscreen mode Exit fullscreen mode

The Dashboard: Bringing the Debate to Life

A multi-agent debate is only as good as its visualization. If developers or users can't see the "thinking process" of each agent, they miss the magic of collaborative AI.

Using React and custom CSS, we built a dynamic dashboard where users input the live match state and watch the agents build the strategy in real-time.

  • Vibrant, modern dark mode featuring neon green accents and smooth glassmorphism.
  • Interactive agent debate timeline: Users can expand or collapse cards representing the Stats Analyst's briefing, the Devil's Advocate's contrarian push, and Captain Cool's ultimate verdict.
  • Seamless loading micro-animations: A spinning cricket ball indicator that updates users as each agent takes the turn to analyze.

What We Learned Building with Google ADK

  1. Role Separation Enhances Reasoning: Instead of asking an LLM to balance statistics and high-risk strategies simultaneously, delegating these tasks to separate agents yields far more detailed and focused responses.
  2. Structured Workflows Avoid Collisions: For deterministic pipelines (like sports coaching, software code review, or financial audits), sequential agent routing is highly reliable and ensures each agent builds directly on verified facts.
  3. Google ADK is Clean and Lightweight: Orchestrating sessions and registering python functions as tools feels incredibly pythonic compared to heavier, more rigid agent frameworks.

Get the Code & Build Your Own

Want to deploy Captain Cool or build your own multi-agent sports strategist? The entire repository—including the full FastAPI backend, Google ADK definitions, and React dashboard—is available on GitHub!

Check out the Captain Cool Repository on GitHub:
https://github.com/sohambarkase04/captain-cool-ipl

Let us know: How would you use multi-agent AI to change sports analytics?

Top comments (0)