Skip to main content
← Monday's Prompts

Automate Route Optimization 🚀

Turn Monday's 3 prompts into production-ready code

November 25, 2025
28 min read
🚚 Logistics🐍 Python + TypeScript⚡ 0 → 5000 deliveries/day

The Problem

On Monday you tested the 3 prompts in ChatGPT. You saw how extraction → validation → optimization works. But here's the reality: you can't ask dispatchers to copy-paste 200 times per day. One dispatcher spending 3 hours manually planning routes? That's $90/day in labor costs. Multiply that across a fleet operation and you're looking at $27,000/year just on route planning admin. Plus the human errors that lead to missed deliveries, wasted fuel, and unhappy customers.

3+ hours
Per day planning routes manually
35% error
From manual route mistakes
Can't scale
Beyond 20-30 deliveries/day

See It Work

Watch the 3 prompts chain together automatically. This is what you'll build.

Watch It Work

See the AI automation in action

Live Demo • No Setup Required

The Code

Three levels: start simple, add reliability, then scale to production. Pick where you are.

Basic = Quick startProduction = Full featuresAdvanced = Custom + Scale

Simple API Calls

Good for: 0-100 deliveries/day | Setup time: 30 minutes

Simple API Calls
Good for: 0-100 deliveries/day | Setup time: 30 minutes
# Simple Route Optimization (0-100 deliveries/day)
import openai
import json
import os
from typing import Dict, List, Optional
from datetime import datetime

# Set your API key
openai.api_key = os.getenv('OPENAI_API_KEY')

def optimize_routes(delivery_text: str) -> Dict:
    """Chain the 3 prompts: extract → validate → optimize"""
    
    # Step 1: Extract delivery data
    extraction_prompt = f"""Extract delivery information from this text and format as JSON.
Showing 15 of 116 lines

When to Level Up

1

Simple API Calls

  • Direct OpenAI/Claude API calls
  • Sequential processing (one route at a time)
  • No caching or retries
  • Manual error handling
  • Results in memory (no database)
Level Up
2

With Error Handling & Caching

  • Retry logic with exponential backoff
  • Redis caching (avoid re-processing same routes)
  • Structured logging (Winston/Python logging)
  • Request timeouts
  • Basic monitoring
Level Up
3

Production Pattern with Queue System

  • RabbitMQ/SQS for job queuing
  • PostgreSQL for job persistence
  • Multiple workers (horizontal scaling)
  • Dead letter queues for failed jobs
  • Health checks and auto-recovery
  • Prometheus metrics
Level Up
4

Multi-Agent System

  • LangGraph orchestration
  • Specialized agents (extraction, validation, optimization, traffic)
  • Real-time traffic data integration (Google Maps API)
  • Dynamic re-routing based on delays
  • Load balancing across multiple LLM providers
  • Advanced monitoring (Datadog/New Relic)
  • Cost optimization (model selection per task)

Logistics-Specific Gotchas

Things that will bite you if you don't handle them upfront.

Real-Time Traffic Integration

Integrate Google Maps Distance Matrix API with traffic data. Recalculate ETAs every 30 minutes during active deliveries.

Solution
# Integrate real-time traffic data
import googlemaps
from datetime import datetime, timedelta

gmaps = googlemaps.Client(key=os.getenv('GOOGLE_MAPS_API_KEY'))

def get_realistic_travel_time(origin: str, destination: str, departure_time: datetime) -> int:
    """Get travel time accounting for traffic"""
Showing 8 of 47 lines

Vehicle Capacity Constraints

Validate constraints BEFORE optimization. Use hard limits in prompts and double-check outputs programmatically.

Solution
# Enforce hard capacity constraints
from typing import List, Dict

def validate_route_capacity(route: Dict, max_weight: int, max_hours: int) -> Dict:
    """Validate route doesn't exceed vehicle capacity"""
    total_weight = sum(stop['weight_lbs'] for stop in route['sequence'])
    total_time = route['estimated_time_hours']
    
Showing 8 of 59 lines

Time Window Conflicts

Pre-validate time windows. Flag conflicts. Ask LLM to prioritize or suggest alternatives.

Solution
# Detect and resolve time window conflicts
from datetime import datetime, timedelta
from typing import List, Dict, Tuple

def detect_time_conflicts(deliveries: List[Dict]) -> List[Dict]:
    """Find deliveries with overlapping time windows that can't both be met"""
    conflicts = []
    
Showing 8 of 69 lines

Address Geocoding Errors

Always geocode addresses. Validate coordinates. Flag ambiguous addresses for manual review.

Solution
# Robust address geocoding with validation
import googlemaps
from typing import Dict, Optional, List
import logging

logger = logging.getLogger(__name__)
gmaps = googlemaps.Client(key=os.getenv('GOOGLE_MAPS_API_KEY'))
Showing 8 of 85 lines

Dynamic Re-Routing for Delays

Pre-compute backup routes. Use fast heuristics for minor adjustments. Only call LLM for major re-routes.

Solution
# Dynamic re-routing with fast heuristics
from datetime import datetime, timedelta
from typing import List, Dict, Optional
import logging

logger = logging.getLogger(__name__)

class DynamicRouter:
Showing 8 of 107 lines

Adjust Your Numbers

500
105,000
5 min
1 min60 min
$50/hr
$15/hr$200/hr

❌ Manual Process

Time per item:5 min
Cost per item:$4.17
Daily volume:500 items
Daily:$2,083
Monthly:$45,833
Yearly:$550,000

✅ AI-Automated

Time per item:~2 sec
API cost:$0.02
Review (10%):$0.42
Daily:$218
Monthly:$4,803
Yearly:$57,640

You Save

0/day
90% cost reduction
Monthly Savings
$41,030
Yearly Savings
$492,360
💡 ROI payback: Typically 1-2 months for basic implementation
🚚

Want This Running in Your Fleet?

We build custom logistics AI systems that integrate with your existing dispatch software, ERP, and telematics. From proof-of-concept to production in 2-4 weeks.

©

2026 Randeep Bhatia. All Rights Reserved.

No part of this content may be reproduced, distributed, or transmitted in any form without prior written permission.