Inspiration

In Monterrey, thousands of university students work as delivery couriers in the short time windows available between their classes. However, the gig economy is inherently stacked against them: delivery platforms optimize strictly for platform throughput, treating drivers as interchangeable execution units. When an order pings, couriers have only seconds to accept or skip.

Falling into the "greedy trap"—blindly accepting every offer or chasing immediate high payouts—often leaves couriers stranded across the city in extreme heat, wasting fuel on empty return miles ("deadhead distance") and causing them to miss their next class.

We built CoDriver (powered by our deterministic Navie engine) to level the playing field. Our goal was to create a driver-first financial advocate: an AI copilot that treats delivery routing as an opportunity-cost problem over time, maximizing earnings while guaranteeing that student drivers always make it back to campus on time.


How We Built It

CoDriver combines a microsecond deterministic decision core with an asynchronous strategic AI advisory layer, hands-free voice rationale, and real-time mapping.

System Architecture & Tech Stack

  • Deterministic Decision Core (valor.py / nuez.py / seguridad.py): Built in Python 3.11, the core evaluates real-time opportunity costs over Monterrey's road network using OSMnx street graphs and historical traffic matrices.
  • Backend & API Protocol: High-throughput async FastAPI server running on Uvicorn, implementing the Infosys Courier protocol schema (/zones, /shift/start, /decide) with WebSockets for live event telemetry.
  • Frontend UI: React 19 + TypeScript + Vite 8 + MapLibre GL for real-time visualization of active zones, driver status, and optimal route vectors.
  • Voice AI & Strategy: ElevenLabs API (eleven_flash_v2_5 TTS) for hands-free audio explanations, paired with Google Gemini as an asynchronous strategist that re-evaluates shift context on a fixed cadence (every 5 real minutes, or every 30 simulated minutes in the live demo) — tuning macro economic knobs rather than reacting to individual events.
  • Database & Auditability: PostgreSQL via TigerData / TimescaleDB for time-series logging of every decision and constraint check, backed by a zero-blocking in-memory queue fallback.

The Mathematical Decision Model

For every incoming offer $o$, the engine computes its net payout and compares it against the opportunity cost of the time it would consume:

$$\text{net}(o) = P(o) - d(o) \cdot c_{\text{km}}$$

$$\text{price}(o) = V(t_{\text{restante}}) - V(t_{\text{restante}} - \Delta t(o))$$

Where:

  • $P(o)$ is the order's gross payout in MXN, and $d(o) \cdot c_{\text{km}}$ its direct fuel/distance cost.
  • $V(\cdot)$ is a value table: how much a courier typically earns in the remaining minutes of a shift, built via Monte Carlo evaluation of 300 simulated shifts (Sutton & Barto-style tabular policy evaluation) — not a learned model, and auditable end to end.
  • $\Delta t(o)$ is the marginal time cost of inserting this order into the courier's current route (re-optimized stop order), not the raw trip time — a pass-through pickup can cost 3 minutes, not 25.

The offer is accepted only if:

$$\text{net}(o) \ge \text{price}(o) + \text{margin}$$

where margin is one of the three knobs Gemini tunes asynchronously. During active shocks (a street closure, a surge), a per-zone multiplier makes the destination's time more expensive to accept into — it never forbids a zone outright.

Simultaneously, hard safety and schedule boundaries are evaluated as non-negotiable step functions:

$$S(o) = \begin{cases} 1 & \text{if } T_{\text{current}} + T_{\text{trip}}(o) + T_{\text{return}}(z_{\text{dest}} \to z_{\text{campus}}) + \Delta t_{\text{buffer}} \le T_{\text{class}} \ 0 & \text{otherwise} \end{cases}$$

If $S(o) = 0$, the decision engine forces an immediate SKIP regardless of payout $P(o)$, adhering to our core rule: "Pay math alone says accept, but safety constraints cannot be bought with money."


Challenges We Ran Into

  1. Eliminating Cloud Latency & Financial Hallucinations: Large Language Models are too slow for split-second decision endpoints and risk hallucinating payout calculations. We solved this by strictly decoupling responsibilities: the deterministic Python core handles all numerical calculations and order decisions in-process with no blocking I/O, while Google Gemini operates asynchronously to adjust macro strategy parameters on a fixed schedule.
  2. Zero-Latency Database Operations: High-frequency time-series logging to TigerData can create I/O bottlenecks during live shifts. We implemented an in-memory queue fallback mechanism that handles persistence asynchronously, so /decide never waits on a database write.
  3. Tackling the Deadhead Distance Trap: Naive greedy algorithms frequently send couriers to remote drop-offs that pay well initially but force a 30-minute empty return trip. We spent significant time calibrating return-vector matrices on Monterrey's graph to cut deadhead mileage in half.

Accomplishments That We're Proud Of & What We Learned

Empirical Benchmark Results

We evaluated CoDriver across 50 unseen holdout shift simulations (seeds 2000–2049, Motorcycle, 14:00 Start, Tec Campus Anchor with a 10-minute return margin):

Benchmark Policy Mean Earnings (MXN) Hourly Yield (MXN/hr) Orders Completed Deadhead % (Empty KM) Safety Violations Deadline Misses
NearestFirst $401.55 $50.19 8.26 43.62% 0 0
AcceptAll $660.33 $82.54 14.18 52.90% 0 1
HighestPay $756.08 $94.51 7.44 50.19% 0 0
GreedyRate (Baseline) $805.40 $100.68 11.14 46.94% 0 0
Our Agent (CoDriver) $1,106.56 $138.32 20.30 26.69% 0 0
Oracle (Offline Optimal) $1,122.28 $140.29 20.08 28.71% 0 0
  • +37.4% Revenue Growth: CoDriver increased mean shift earnings from $805.40 MXN to $1,106.56 MXN (+ $301.16 MXN per 8-hour shift).
  • 98.6% Oracle Efficiency: Achieved 98.6% of the theoretical offline Oracle planner, which possesses complete advance knowledge of all future orders.
  • 43% Reduction in Deadhead Distance: Reduced empty return travel from 46.94% down to 26.69%.
  • 100% Safety & Schedule Compliance: Zero safety violations and zero campus return deadline misses across all test runs.

Key Takeaways

Building CoDriver taught us that effective AI engineering isn't about applying LLMs everywhere—it's about knowing where NOT to use them. Combining deterministic mathematics for microsecond-scale, non-blocking decision logic with generative AI for strategic advisory created a system that is fast, resilient, financially optimal, and fundamentally driver-first.

What We Learned

  • Architectural Separation is Crucial for Real-Time AI: We learned that forcing Large Language Models into split-second execution paths leads to high latency and unacceptable risk of financial hallucinations. Decoupling our deterministic Python core for instant decision-making from an asynchronous LLM strategic advisory layer created a fast, resilient, and reliable system.
  • The Hidden Cost of the Deadhead Trap: Drivers lose a massive percentage of their shift revenue not because they lack diligence, but because platform dispatchers push them into remote areas without factoring in the unpaid return trip. Modeling opportunity cost against Monterrey's street graph proved that cutting empty return miles is the single most effective way to increase driver yield.
  • Zero-Blocking System Resilience: Implementing an in-memory queue fallback for time-series logging taught us how to maintain auditability in PostgreSQL/TimescaleDB without ever letting persistence latency touch the decision endpoint.

What's Next for CoDriver

  • Multi-Platform Order Aggregation: Expanding the decision core to parse incoming orders across multiple gig platforms simultaneously (e.g., Rappi, UberEats, DoorDash), allowing couriers to cross-optimize payloads and eliminate downtime between platforms.
  • On-Device Predictive Demand Heatmaps: Training lightweight edge ML models to predict localized order surges and heat shifts minutes before platforms broadcast them, helping couriers position themselves in high-yield zones before pings arrive.
  • Smart Helmet & Bluetooth HUD Integration: Extending the ElevenLabs hands-free audio interface into smart helmet audio hardware, providing HUD overlay cues and full voice interaction for zero-distraction driving.
  • Peer-to-Peer Road Incident Network: Enabling a driver community feedback loop where couriers report hyper-local road closures, active police checkpoints, or university gate access shifts to automatically update routing matrices for all active CoDriver users.

Challenge Tracks We Integrated

Best Use of Gemini API — The "Slow Brain" Architecture

Nuez's decision engine responds without any blocking calls; placing an LLM call inside the /decide loop would violate the Courier protocol's strict latency limits. To solve this, we decoupled the architecture into a dual-speed agent (backendruta/strategy.py):

  • Fast Path (/decide): A deterministic engine reads three memory-resident strategy parameters (margen_mxn, descuento_parado, multiplicador_zona) and returns decisions instantly without ever hitting an external LLM endpoint.
  • Slow Path (Strategic Advisory): A background thread queries Gemini 3.5 Flash Lite on a fixed 5-minute cadence (30 simulated minutes during demos), feeding it the latest shift context — including any active shocks. Gemini evaluates that context and dynamically tunes macro economic knobs — it never decides individual order accept/skip calls, and it never runs on a shock-triggered or otherwise event-driven basis.

Production-Grade Defensibility

  • Graceful Degradation: If Gemini experiences latency, network drops, or API key exhaustion, the core engine continues running uninterrupted using the last valid strategy parameters, setting a degraded state flag, and attempting automatic recovery on the next polling cycle.
  • Accurate Token Accounting: Tracks exact promptTokenCount and candidatesTokenCount returned by the API response rather than relying on character approximations.
  • Honest UI State (frontend/src/lib/gemini-status.ts): The frontend badge displays Gemini: Active strictly when active strategy parameters originated from Gemini (strategy_source === 'gemini'), preventing false status reporting.
  • Safety Isolation: Hard constraints (nighttime restrictions, mandatory driver breaks, heat thresholds, vehicle capacity) are hardcoded into deterministic validation rules (seguridad.py) and are never delegated to the LLM.

Best Use of ElevenLabs — Hands-Free Voice Interface

Operating a motorcycle between delivery points makes screen-based interaction unsafe. We integrated ElevenLabs as a bi-directional voice interface (voz/tts.py, voz/stt.py) to keep driver eyes on the road.

  • Text-to-Speech (TTS): Narrates every decision rationale in real time using the eleven_flash_v2_5 low-latency model, streamed as audio chunks generate.

Resilience Engineering

  • Content-Addressed Disk Caching (cache/voz/): All generated phrases are cached locally to handle tier limits and mitigate unreliable event Wi-Fi. Re-encountered phrases incur zero API character cost and zero network overhead.
  • Atomic Cache Writes: Audio files write to temporary .part buffers and execute an atomic rename upon completion, preventing cache corruption from dropped streams.
  • Precache Tooling: Includes a pre-generation script (python -m voz precache) to bake static demo audio to disk prior to live presentations.
  • Classified Error Handling: System distinguishes fatal API key errors (pausar=True) from transient rate limits, pausing voice synthesis gracefully without crashing the shift workflow.

Best Use of TigerData (TimescaleDB) — Time-Series Decision Audit

Courier delivery operations generate time-indexed data streams: minute-by-minute street traffic, temporary road incidents, and continuous accept/skip decisions. The database schema is engineered specifically for time-series persistence (backendruta/database.py).

  • Hypertables Schema: Converts trafico_calles and decisiones_courier into Timescale hypertables via create_hypertable(...), optimizing point-in-time range queries (WHERE time >= X).
  • Unmodified Event Storage: Stores full official decision payloads as JSONB blobs, providing an un-manipulated audit log aligned with the official protocol specification.
  • Fault-Tolerant Bootstrapping: If CREATE EXTENSION timescaledb fails (e.g., executing on standard Postgres instances), the application falls back safely inside a SQL SAVEPOINT to generate standard relational tables without failing application boot.
  • Non-Blocking Writer Queue: To protect the /decide execution path from any I/O stall, decisions are written to an in-memory queue. A background worker thread drains this queue asynchronously into TigerData.
  • Designed for continuous aggregates: the schema's time+zone shape (decisiones_courier) maps directly onto a time_bucket('15 minutes', ...) materialized view for expected-value-per-zone — the natural next step once the demo needs live analytics instead of the current on-request Python aggregation.

Best Use of Vultr — High-Availability Cloud Infrastructure (codrivernavie.tech)

To deliver sub-millisecond /decide responses and maintain seamless WebSocket streaming for judging panels, our entire production stack is deployed on Vultr Cloud Compute under our custom domain codrivernavie.tech.

  • Low-Latency Production Endpoint: Hosts the FastAPI asynchronous engine, high-throughput WebSocket event pipeline, and TigerData database instance on dedicated cloud compute, eliminating local networking bottlenecks and cold starts.
  • Containerized Deployment: Fully dockerized production setup isolating the Python backend runtime, static React/Vite assets, and background worker threads for automated health checks and instant restarts.
  • Production-Grade SSL & WebSockets: Configured with NGINX reverse-proxying, SSL/TLS certificates, and secure WebSockets (wss://codrivernavie.tech), providing judges with a live, accessible production endpoint for real-time protocol testing.

Built With

Share this project:

Updates