Skip to content

Repository files navigation

🏁 F1 Strategy AI: Machine Learning & Generative AI Race Strategist

Python FastAPI React Tailwind CSS Gemini XGBoost

An advanced, real-time Formula 1 race strategy simulation and decision engine. By combining machine learning (XGBoost trained on 10,000+ historical laps) with generative AI (Google Gemini 2.5 Flash acting as a Chief Race Strategist), this project replicates the decision-making processes of an F1 pit wall.

It handles everything from pre-race strategy planning (1/2/3 stops, tyre compound sequences, and weather risks) to real-time live race monitoring with lap-by-lap telemetry streaming via WebSockets.


📖 The Story

During the Canadian GP, McLaren started Lando Norris on intermediates on a damp track. The track dried up rapidly, forcing them to make a costly pit decision.

F1 strategies aren't just about tyre wear; they're a complex, real-time puzzle of micro-climates, tyre operating windows, gap windows to other cars, safety car probabilities, and strict FIA regulations.

This project was built out of pure curiosity: How do you build a decision system capable of processing real-time telemetry, applying FIA regulations, and explaining its reasoning directly to the driver like an elite Race Engineer?


🛠️ System Architecture

The F1 Strategy AI operates on a dual-engine architecture:

┌─────────────────────────────────────────────────────────────────────────┐
│                           1. Command Center                             │
│       Select Season, Circuit, Driver, Telemetry Source, Replay Speed    │
└────────────────────────────────────┬────────────────────────────────────┘
                                     │
                                     ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                       2. Pre-Race Strategy Planner                      │
│   • Computes 1-Stop, 2-Stop & 3-Stop models (Dry/Wet)                   │
│   • Recommends optimal compound sequences & stint lengths               │
│   • Simulates weather/rain forecasts using Open-Meteo API               │
│   • Generates PDF-printable HTML Strategy Briefing reports              │
└────────────────────────────────────┬────────────────────────────────────┘
                                     │
                                     ▼
┌─────────────────────────────────────────────────────────────────────────┐
│                       3. Live Race Decision Engine                      │
│                                                                         │
│   ┌─────────────────────────┐           ┌──────────────────────────┐    │
│   │  XGBoost Classifier     │           │  F1 Chief Strategist     │    │
│   │  Predicts:              │           │  (Gemini 2.5 Flash API)  │    │
│   │  • Pit Stop Prob.       │           │  Applies Rules:          │    │
│   │  • Next Compound choice │           │  • 2026 Regulations      │    │
│   └────────────┬────────────┘           │  • SC Pit window savings │    │
│                │                        │  • Weather overrides     │    │
│                │                        └────────────┬─────────────┘    │
│                └───────────────┬─────────────────────┘                  │
│                                │ Merge & Validate                       │
│                                ▼                                        │
│                 ┌─────────────────────────────┐                         │
│                 │   Race Engineer Briefing    │                         │
│                 │   "Box, Box, NOR. Mediums." │                         │
│                 └─────────────────────────────┘                         │
└─────────────────────────────────────────────────────────────────────────┘
  1. XGBoost ML Models: Two raw XGBoost models predict (a) pit stop probability (pit_model.json) and (b) next compound recommendation (compound_model.json) based on a normalized 25-feature vector per lap.
  2. Gemini 2.5 Flash Chief Strategist: Intercepts the ML recommendations. If the model suggests a dry slick tyre when heavy rain is forecasted, or forgets a mandatory stint limit under 2026 regulations, Gemini applies a strategic override, corrects the tyre/action choice, and explains why to the driver.

✨ Features

1. Pre-Race Strategy Planner

  • Multi-Strategy Simulator: Automatically calculates and ranks 1-Stop, 2-Stop, and 3-Stop options by estimated total time.
  • Visual Stint Timelines: Custom stint timeline bars showing compound sequences (SOFT, MEDIUM, HARD, INTERMEDIATE, WET) and optimal pit lap markers.
  • Weather Forecast Engine: Resolves timezone-accurate UTC race start times and fetches live hourly precipitation probability from Open-Meteo to assess wet weather risks.
  • Exportable Strategy Reports: Generate and download a beautifully formatted dark-themed HTML report (which prints perfectly to PDF) containing strategy tables, metrics, and the AI briefing.

2. Live Race Monitor

  • WebSocket Telemetry Stream: Streams lap-by-lap telemetry data asynchronously.
  • OpenF1 Live Connection: Connects to the real-time OpenF1 API feed for live track status, position data, and lap times.
  • Live Strategy Overrides: Real-time evaluation of tyre degradation, safety car gap window savings (saving 10-15s), and rain risk.
  • Predictive Leaderboard: Predicts final finishing positions using real-time tyre wear degradation curves and remaining pit requirements.

3. F1 Broadcast Dashboard UI

  • Fully responsive dark-mode dashboard themed on official Formula 1 broadcast telemetry.
  • Timing Tower displaying driver positions, compound choices, tyre ages, and gap-to-leader values.
  • Recharts-powered graphs tracking live Rain Risk, Safety Car Probability, and Lap Time trends.

🗂️ Tech Stack

Component Technology Description
Frontend React 19, TypeScript, Vite, Tailwind CSS v4, Lucide React, Recharts Fast, modern SPA with custom CSS variables and F1 theme
Backend FastAPI, Uvicorn, WebSockets, Python 3.10+ Relays REST requests and handles streaming connections
Data Sources FastF1 API, OpenF1 API, Open-Meteo Weather API Retrieves telemetry history, live data, and weather
ML Engine XGBoost, pandas, numpy, scikit-learn Fast inference of classification models on 25-feature vectors
GenAI Layer Google GenAI SDK (gemini-2.5-flash) Implements strategic rules, validation, and briefings

🚀 Setup & Installation

Prerequisites

  • Python 3.10 or higher
  • Node.js 18 or higher (with npm)
  • A Gemini API Key (optional, template mode will be used if not provided). Obtain one for free on Google AI Studio.

1. Clone the Repository

git clone https://github.com/yourusername/f1-strategy-ai.git
cd f1-strategy-ai

2. Backend Setup

  1. Create a virtual environment and activate it:
    python -m venv .venv
    # On Windows:
    .venv\Scripts\activate
    # On macOS/Linux:
    source .venv/bin/activate
  2. Install Python dependencies:
    pip install -r requirements.txt
  3. Set your Gemini API key environment variable (optional):
    # On Windows (CMD):
    set GEMINI_API_KEY=your_api_key_here
    # On Windows (PowerShell):
    $env:GEMINI_API_KEY="your_api_key_here"
    # On macOS/Linux:
    export GEMINI_API_KEY="your_api_key_here"
  4. Start the FastAPI backend server:
    python main.py
    The backend will start on http://localhost:8000.

3. Frontend Setup

  1. Open a new terminal window and navigate to the frontend directory:
    cd frontend
  2. Install Node packages:
    npm install
  3. Start the Vite development server:
    npm run dev
    The frontend dashboard will be available at http://localhost:5173.

📈 Machine Learning Details

The strategy models are trained on historical F1 lap telemetry data. For each lap, a 25-dimension feature vector is engineered, containing:

  • Tire Performance: tyre_age_normalised, tyre_life, tyre_life_squared, compound_encoded, compound_x_tyrelife
  • Race Situation: lap_number, stint_number, relative_position, laps_remaining, pct_race_complete, gap_to_leader_lap
  • Degradation & Trends: lap_time_delta, deg_trend_3, deg_trend_5, deg_acceleration, fuel_corrected_delta
  • Race Controls: is_sc_vsc, field_pit_fraction, is_wet_condition

Core Strategy Rules (Gemini Override Layer)

  1. Weather: Wet tyres (WET) are selected for rain risk > 60%. Intermediates (INTERMEDIATE) are chosen for rain risk between 30% and 60%.
  2. 2026 Regulations: strict tyre stint limits are enforced: SOFT max 15 laps, MEDIUM max 25 laps, HARD max 35 laps. Pitting is mandated when exceeded.
  3. Safety Car Advantage: Pitting under VSC/SC saves ~10-15 seconds of pit lane loss time compared to green flag conditions. Gemini triggers early pit calls if the tyre age is within 5-6 laps of the typical window.

🤝 Acknowledgements

  • FastF1: The incredible Python library that makes historical F1 telemetry accessible.
  • OpenF1: For providing real-time live telemetry endpoints.
  • Open-Meteo: For the free weather forecast coordinate lookup.
  • Formula 1: For the design inspiration behind the broadcast timing screens.

Disclaimer: This project is an independent developer educational tool and is not affiliated, endorsed, or associated with Formula 1, the FIA, or any F1 team.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages