Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- .gitignoreAdded+75
- README.md+630-15
- brain/.env.exampleAdded+26
- brain/.github/workflows/test.ymlAdded+42
- brain/.gitignoreAdded+95
- brain/DockerfileAdded+23
- brain/MakefileAdded+34
- brain/README.mdAdded+484
- brain/alembic.iniAdded+114
- brain/alembic/env.pyAdded+92
- brain/alembic/script.py.makoAdded+26
- brain/alembic/versions/001_initial_schema.pyAdded+145
- brain/alembic/versions/002_phase2_phase3_models.pyAdded+179
- brain/alembic/versions/003_add_pending_status.pyAdded+36
- brain/alembic/versions/004_add_explanation_fields.pyAdded+42
- brain/alembic/versions/005_phase7_ev_recovery.pyAdded+59
- brain/alembic/versions/006_phase8_learning_agent.pyAdded+119
- brain/app/__init__.pyAdded+1
- brain/app/api/__init__.pyAdded+24
- brain/app/api/admin.pyAdded+298
- brain/app/api/admin_learning.pyAdded+368
- brain/app/api/agent_events.pyAdded+93
- brain/app/api/allocation.pyAdded+808
- brain/app/api/allocation_langgraph.pyAdded+513
- brain/app/api/consolidation.pyAdded+109
- brain/app/api/driver_api.pyAdded+175
- brain/app/api/drivers.pyAdded+136
- brain/app/api/feedback.pyAdded+108
- brain/app/api/routes.pyAdded+93
- brain/app/api/runs.pyAdded+251
- brain/app/config.pyAdded+77
- brain/app/core/__init__.pyAdded+1
- brain/app/core/events.pyAdded+154
- brain/app/database.pyAdded+108
- brain/app/main.pyAdded+187
- brain/app/models/__init__.pyAdded+49
- brain/app/models/allocation_run.pyAdded+64
- brain/app/models/appeal.pyAdded+77
- brain/app/models/assignment.pyAdded+71
- brain/app/models/decision_log.pyAdded+55
- brain/app/models/delivery_log.pyAdded+102
- brain/app/models/driver.pyAdded+226
- brain/app/models/driver_effort_model.pyAdded+90
- brain/app/models/fairness_config.pyAdded+69
- brain/app/models/learning_episode.pyAdded+92
- brain/app/models/manual_override.pyAdded+73
- brain/app/models/package.pyAdded+68
- brain/app/models/route.pyAdded+97
- brain/app/models/route_swap.pyAdded+89
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textops/logistic_flutter/orchastra_ps4/ecology/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475# ========================# FairRelay Monorepo# ========================
# Environment & Secrets.env.env.local.env.*.local*.pem*.key
# Python__pycache__/*.py[cod]*$py.class*.so.Pythonvenv/.venv/ENV/*.egg-info/*.egg
# Node.jsnode_modules/npm-debug.log*yarn-error.log*
# Flutter / Android**/android/local.properties**/android/.gradle/**/android/app/build/**/android/build/**/.dart_tool/**/.flutter-plugins**/.flutter-plugins-dependencies**/.packages*.apk*.aab
# iOS**/ios/Pods/**/ios/.symlinks/
# Build artifactsdist/build/
# IDE.idea/.vscode/*.swp*.swo*~
# OS.DS_StoreThumbs.dbDesktop.ini
# Logs*.log
# Database*.sqlite*.sqlite3*.db
# RL Experience (regenerated at runtime)brain/data/rl_experience.json
# Coverage / Testing.coveragehtmlcov/.pytest_cache/1234567891011121314151617181920212223242526---tags:- ml-intern---# MouleeswaranM/FairRelay<!-- ml-intern-provenance -->## Generated by ML InternThis model repository was generated by [ML Intern](https://github.com/huggingface/ml-intern), an agent for machine learning research and development on the Hugging Face Hub.- Try ML Intern: https://smolagents-ml-intern.hf.space- Source code: https://github.com/huggingface/ml-intern## Usage```pythonfrom transformers import AutoModelForCausalLM, AutoTokenizermodel_id = "MouleeswaranM/FairRelay"tokenizer = AutoTokenizer.from_pretrained(model_id)model = AutoModelForCausalLM.from_pretrained(model_id)```For non-causal architectures, replace `AutoModelForCausalLM` with the appropriate `AutoModel` class.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641<p align="center"><img src="https://img.shields.io/badge/Challenge-%235_AI_Load_Consolidation-f97316?style=for-the-badge" alt="Challenge #5" /><img src="https://img.shields.io/badge/LogisticsNow-Hackathon_2026-3b82f6?style=for-the-badge" alt="LogisticsNow" /><img src="https://img.shields.io/badge/Team-FairRelay-10b981?style=for-the-badge" alt="Team FairRelay" /></p><h1 align="center">FairRelay</h1><p align="center"><strong>AI-Powered Load Consolidation Engine · Fairness-Aware Route Allocation · Multi-Agent Intelligence</strong></p><p align="center"><a href="#-the-problem">Problem</a> •<a href="#-our-solution">Solution</a> •<a href="#-5-agent-consolidation-pipeline">Consolidation Pipeline</a> •<a href="#-fair-dispatch-pipeline">Fair Dispatch</a> •<a href="#-architecture">Architecture</a> •<a href="#-dashboards--visualization">Dashboards</a> •<a href="#-quick-start">Quick Start</a> •<a href="#-api-reference">API Reference</a></p>---## The Problem> Logistics networks transport shipments with **partially filled vehicles** due to poor load planning. There is **no AI-driven system** for automatic load consolidation that intelligently groups shipments, maximizes vehicle capacity, simulates strategies, and learns continuously.>> At the same time, **15M+ gig delivery workers** in India face systemic dispatch bias — traditional systems assign **3x more deliveries** to some drivers (Gini = 0.85) while others earn near nothing.**FairRelay solves both.**---## Our SolutionFairRelay is a **full-stack AI logistics platform** with two core engines:| Engine | What It Does | Agents ||--------|-------------|--------|| **Load Consolidation Engine** | Groups shipments by geography + time windows, bin-packs into trucks using OR-Tools CP-SAT solver, scores confidence, and learns via Q-Learning | 5 agents || **Fair Dispatch Engine** | Allocates routes to drivers using fairness-aware AI with Gini coefficient optimization, wellness tracking, EV-aware routing, and LLM explanations | 8+ agents |Both engines are orchestrated via **LangGraph** multi-agent workflows, exposed as single API endpoints, and come with live visualization dashboards.### Hackathon Deliverables Mapping| Expected Deliverable | Our Implementation ||---------------------|-------------------|| **Consolidation Engine Prototype** | 5-agent LangGraph pipeline — KMeans geo-clustering + OR-Tools CP-SAT bin-packing || **Visualization Dashboard** | Interactive dark-themed dashboard with Leaflet maps, Chart.js analytics, agent pipeline viz, heatmaps || **Performance Simulation** | Multi-scenario simulator comparing Tight/Balanced/Aggressive strategies with full KPI comparison || **Continuous Optimization** | Tabular Q-Learning agent with file-based experience store, reward function, and policy recommendation |---## 5-Agent Consolidation Pipeline```POST /api/v1/consolidate → One API call. Five agents. Optimized loads.``````┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐│ AGENT 1 │ │ AGENT 2 │ │ AGENT 3 ││ Geo-Clustering │───>│ Time-Window │───>│ Capacity ││ (KMeans + │ │ Filtering │ │ Optimization ││ Silhouette) │ │ (Overlap check) │ │ (OR-Tools SAT) │└──────────────────┘ └──────────────────┘ └──────────────────┘│▼┌──────────────────┐ ┌──────────────────┐│ AGENT 5 │ │ AGENT 4 ││ Continuous │<───│ Scoring & ││ Learning │ │ Confidence ││ (Q-Learning) │ │ (Composite AI) │└──────────────────┘ └──────────────────┘```### Agent Breakdown| # | Agent | Algorithm | What It Does ||---|-------|-----------|-------------|| 1 | **Geo-Clustering** | scikit-learn KMeans + Silhouette scoring | Groups shipments by pickup/drop proximity. Auto-selects optimal K (2–10). Splits oversized clusters via greedy radius fallback. || 2 | **Time-Window** | Interval overlap analysis | Filters clusters by delivery time compatibility. Configurable tolerance (default 120 min). Splits time-incompatible shipments into separate groups. || 3 | **Capacity Optimization** | Google OR-Tools CP-SAT Integer Programming | Bin-packs shipments into trucks respecting weight + volume. Minimizes trucks used. Falls back to First-Fit-Decreasing heuristic if solver unavailable. 3-second solver timeout. || 4 | **Scoring & Confidence** | Weighted composite scoring | Per-group confidence = `capFit×0.4 + geoScore×0.35 + timeScore×0.25`. Global optimization score factors in utilization, trip reduction, and improvement gain. Computes all KPIs vs naive baseline. || 5 | **Continuous Learning** | Tabular Q-Learning (RL) | Stores experience in `data/rl_experience.json` (max 500 episodes). Reward = f(utilization, trips, carbon, score). Updates Q-table to recommend optimal (radius, tolerance) parameters. Detects policy convergence/degradation trends. |### Consolidation KPIs Produced| KPI | Description ||-----|-------------|| Vehicle Utilization (Before/After) | Percentage improvement from naive to consolidated || Trips Reduced | Absolute count + percentage of eliminated trips || Distance Saved (km) | Haversine-calculated route distance reduction || CO2 Saved (kg) | `distanceSaved × 0.21 kg/km` || Carbon Credit Value (USD) | `carbonSaved / 1000 × $25/ton` || Fuel Saved (INR) | `distanceSaved × Rs.22.5/km` || Cost Reduction (%) | Direct cost savings from trip elimination || Optimization Score (0–100) | Weighted composite with letter grade (A+/A/B/C/D) || Avg AI Confidence (0–100) | Mean per-group confidence across all bins |### Scenario Simulation```POST /api/v1/consolidate/simulate```Run multiple consolidation strategies in parallel and get the best recommendation:| Scenario | Radius | Time Tolerance | Use Case ||----------|--------|---------------|----------|| **Tight Clustering** | 15 km | 60 min | Dense urban, strict deadlines || **Balanced** | 30 km | 120 min | General purpose || **Aggressive Merge** | 60 km | 240 min | Inter-city, flexible windows |The system runs all scenarios, compares optimization scores, and recommends the best strategy.---## Fair Dispatch Pipeline```POST /api/v1/allocate/langgraph → Fairness-aware route allocation``````┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐│ Initialize │ → │ Clustering │ → │ ML Effort ││ Node │ │ Agent (KMeans) │ │ Agent (XGBoost)│└─────────────────┘ └─────────────────┘ └─────────────────┘│▼┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐│ EV Recovery │ ← │ Fairness │ ← │ Route Planner ││ Node │ │ Manager │ │ (Hungarian) │└─────────────────┘ └─────────────────┘ └─────────────────┘│ │▼ ▼ (if Gini > 0.25)┌─────────────────┐ ┌─────────────────┐│ Driver Liaison │ │ Reoptimize ││ Agent │ │ Loop │└─────────────────┘ └─────────────────┘│▼┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐│ Learning │ → │ LLM Explain │ → │ Finalize ││ Agent │ │ (Gemini) │ │ Node │└─────────────────┘ └─────────────────┘ └─────────────────┘```| Agent | Purpose | Key Algorithm ||-------|---------|---------------|| **Initialize Node** | Validates inputs, sets up allocation state | Schema validation || **Clustering Agent** | Groups packages by geography | K-Means || **ML Effort Agent** | Scores driver-route effort pairs | XGBoost || **Route Planner** | Solves optimal driver-route assignment | Hungarian Algorithm || **Fairness Manager** | Evaluates workload inequality | Gini Index (threshold: 0.25) || **EV Recovery Node** | Handles electric vehicle battery constraints | Charging station insertion || **Driver Liaison** | Processes driver negotiations/appeals | Rule-based + AI || **Learning Agent** | Improves future allocations from feedback | Feedback loop || **LLM Explain Node** | Generates natural language explanations | Google Gemini |### Fairness Algorithms**Workload Score:**```workload = a × num_packages + b × total_weight_kg + c × route_difficulty + d × estimated_time```**Gini Index** (0 = perfect equality, 1 = maximum inequality):```G = (2 × Σ(i × x_i)) / (n × Σx_i) − (n + 1) / n```**Individual Fairness Score:**```fairness_score = 1 − |workload − avg_workload| / max(avg_workload, 1)```Key Result: **Gini reduced from 0.85 → 0.12** (Grade A fairness)---## Architecture```┌──────────────────────────────────────────────────────────────────────┐│ FAIRRELAY PLATFORM │├──────────────┬──────────────┬──────────────┬────────────────────────┤│ Landing │ AI Supply │ Flutter │ Streamlit ││ Page │ Chain │ Mobile │ Women ││ (React) │ Dashboard │ App │ Empowerment Hub ││ Vercel │ (React) │ (Android) │ (Python) ││ │ Vercel │ │ │├──────────────┴──────┬───────┴──────────────┴────────────────────────┤│ │ ││ Backend-DM (Node.js/Express) ││ JWT Auth · Prisma ORM · Socket.IO ││ Driver Relay · Absorption Handshake · e-Way Bills ││ Render ││ │ ││ │ BRAIN_URL proxy ││ ▼ ││ Brain (Python/FastAPI) ││ LangGraph Multi-Agent Orchestration ││ 5-Agent Consolidation + 8-Agent Fair Dispatch ││ OR-Tools · XGBoost · KMeans · Q-Learning · Gemini ││ Render ││ │ ││ PostgreSQL (Neon) │└─────────────────────────────────────────────────────────────────────┘```### Tech Stack| Layer | Technology ||-------|-----------|| **AI Engine (Brain)** | Python 3.11, FastAPI, LangGraph, scikit-learn, XGBoost, Google OR-Tools CP-SAT, Gemini API || **Operations Backend** | Node.js, Express 5, Prisma ORM, PostgreSQL, Socket.IO, Puppeteer, JWT/RBAC || **Dashboard** | React 19, TypeScript, Vite, Redux Toolkit, TailwindCSS, Leaflet, Recharts || **Mobile** | Flutter, Dart, Google Maps, Provider, Dio || **Landing Page** | React, TypeScript, Vite || **Visualization** | Leaflet maps, Chart.js, custom agent pipeline UI, heatmaps || **Database** | PostgreSQL 14+ (Neon serverless), SQLAlchemy async || **Deployment** | Render (backends), Vercel (frontends), Gunicorn |---## Dashboards & Visualization### Load Consolidation Dashboard (`/demo/consolidation`)- **5-Agent Pipeline Visualization** — Each agent lights up in sequence with execution time and output metrics- **AI Optimization Score Ring** — Doughnut chart with letter grade (A+/A/B/C/D)- **8 KPI Cards** — Utilization, trips reduced, distance saved, CO2, fuel savings, confidence, groups, cost reduction- **Interactive Route Map** — Three views: Optimized (color-coded), Before (naive gray), Compare (overlay)- **Consolidated Groups Table** — Truck assignment, weight/volume utilization bars, AI confidence badges- **Analytics Charts** — Utilization before vs after, Group confidence radar, Weight distribution doughnut- **Shipment Compatibility Heatmap** — N x N pairwise compatibility matrix (geo + time)- **Scenario Comparison Panel** — Side-by-side results for Tight/Balanced/Aggressive with recommendation badge- **AI Learning Insights** — Pattern detection, corridor identification, Q-Learning convergence status- **Agent Decision Logs** — Terminal-style log viewer for full pipeline transparency### Fair Dispatch Visualization (`/demo/visualization`)- **8-Agent Pipeline Visualization** — Real-time agent status with animated transitions- **Live Map** — Route visualization on Leaflet with driver assignments- **Fairness Metrics** — Gini index, individual scores, equity analysis- **Agent Activity Feed** — Decision logs from every agent in the pipeline### Operations Dashboard (React)- **Real-time Driver Tracking** — Live map with Socket.IO updates- **Dispatch Management** — Assign missions, view driver profiles, experience-based routing- **Absorption Handshake** — Peer-to-peer goods exchange with QR codes- **e-Way Bill Generation** — Professional government-format PDFs via Puppeteer- **Analytics** — Fleet KPIs, delivery stats, driver performance---## Key Features### AI Load Consolidation- **Intelligent Shipment Grouping** — KMeans geo-clustering with silhouette optimization + time window filtering- **Capacity Optimization** — OR-Tools CP-SAT integer programming to minimize trucks, maximize utilization- **Scenario Simulation** — Multi-strategy comparison with automated recommendation- **Continuous Optimization** — Q-Learning RL agent that improves radius/tolerance parameters over time- **Shipment Compatibility Analysis** — Pairwise heatmap scoring (60% geo + 40% time)### Fairness-Aware Dispatch- **Gini Coefficient Optimization** — Measurably fair workload distribution (Gini <= 0.15 guaranteed)- **Driver Wellness Engine** — Hours worked, rest tracking, illness flags, burnout prevention- **Night Safety Routing** — Automatic safety filtering for women drivers on night routes- **EV-Aware Routing** — Battery constraints and charging station integration- **Explainable Decisions** — 100% of allocations come with Gemini-generated natural language explanations### Operations Platform- **Driver Relay System** — Multi-zone handoffs at virtual hubs for long-haul optimization- **Absorption Handshake** — Offline-capable cryptographic QR verification for goods exchange- **Dynamic e-Way Bills** — Government-format PDF generation via Puppeteer, no external APIs- **Real-time Tracking** — Socket.IO powered live driver and delivery status updates---## SDG Impact| SDG | Target | Our Contribution ||-----|--------|-----------------|| **SDG 8** — Decent Work | Fair income distribution | Gini 0.85 → 0.12 across all drivers || **SDG 10** — Reduced Inequalities | Equal opportunity | Wellness-aware, gender-safe dispatch || **SDG 13** — Climate Action | Reduce emissions | 14.2 kg CO2 saved per allocation run, EV-first routing |---## Quick Start### Prerequisites- Python 3.11+- Node.js 18+- PostgreSQL 14+ (or SQLite for development)- Git### 1. Brain (AI Engine)```bashcd brain# Create virtual environmentpython -m venv venvvenv\Scripts\activate # Windows# source venv/bin/activate # Linux/macOS# Install dependenciespip install -r requirements.txt# Configure environmentcp .env.example .env# Edit .env with your DATABASE_URL, GOOGLE_API_KEY etc.# Run database migrationsalembic upgrade head# Start the serveruvicorn app.main:app --reload --host 0.0.0.0 --port 8000```**Access Points:**| Page | URL ||------|-----|| API Docs (Swagger) | http://localhost:8000/docs || ReDoc | http://localhost:8000/redoc || Consolidation Dashboard | http://localhost:8000/demo/consolidation || Fair Dispatch Demo | http://localhost:8000/demo/allocate || Agent Visualization | http://localhost:8000/demo/visualization |### 2. Backend-DM (Operations Server)```bashcd ops/backend-dmnpm installcp .env.example .env# Edit .env: DATABASE_URL, JWT_SECRET, BRAIN_URL=http://localhost:8000npx prisma generatenpx prisma db pushnode index.js# Runs on http://localhost:3000```### 3. AI Supply Chain Dashboard```bashcd ops/AIsupplychain/aisupplynpm install# Create .envecho "VITE_API_URL=http://localhost:3000" > .envnpm run dev# Runs on http://localhost:5173```### 4. Landing Page```bashcd landingnpm installnpm run dev# Runs on http://localhost:5174```---## API Reference### Load Consolidation| Method | Endpoint | Description ||--------|----------|-------------|| `POST` | `/api/v1/consolidate` | Run 5-agent consolidation pipeline (LangGraph) || `POST` | `/api/v1/consolidate/sync` | Run consolidation (sync fallback, no LangGraph) || `POST` | `/api/v1/consolidate/simulate` | Multi-scenario simulation with recommendation |#### Consolidation Request```json{"shipments": [{"id": "SH-001","pickupLat": 19.076, "pickupLng": 72.877,"dropLat": 18.520, "dropLng": 73.856,"pickupLocation": "Mumbai", "dropLocation": "Pune","weight": 450, "volume": 2.1,"timeWindowStart": "2026-03-10T08:00:00","timeWindowEnd": "2026-03-10T18:00:00","priority": "HIGH"}],"trucks": [{"id": "TRK-001","name": "Tata Ace Gold","maxWeight": 2000, "maxVolume": 8.0,"co2PerKm": 0.21}],"options": {"maxGroupRadiusKm": 30,"timeWindowToleranceMinutes": 120}}```#### Consolidation Response```json{"groups": [{"groupId": 0,"truckId": "TRK-001","truckName": "Tata Ace Gold","shipmentCount": 4,"shipments": [{ "id": "SH-001", "pickupLocation": "Mumbai", "dropLocation": "Pune", "weight": 450, "volume": 2.1 }],"totalWeight": 1680, "totalVolume": 6.8,"utilizationWeight": 84.0, "utilizationVolume": 85.0,"confidence": 87}],"metrics": {"utilizationBefore": 38.2,"utilizationAfter": 78.5,"utilizationImprovement": 40.3,"tripsReduced": 6,"tripReductionPercent": 60.0,"distanceSavedKm": 487.3,"carbonSavedKg": 102.3,"carbonCreditUSD": 2.56,"fuelSavedINR": 10964.25,"optimizationScore": 82,"avgConfidence": 85},"insights": [{ "type": "pattern", "text": "High-density corridor: Mumbai-Pune (4 shipments)", "impact": "high" },{ "type": "learning", "text": "Q-table updated. Reward: 76.4. Best action: radius=30km, tolerance=120min", "impact": "medium" }],"agentSteps": [{ "agent": "GeoClusteringAgent", "action": "completed", "method": "kmeans", "clusters": 3, "duration_ms": 45 }]}```### Fair Dispatch| Method | Endpoint | Description ||--------|----------|-------------|| `POST` | `/api/v1/allocate/langgraph` | Run 8-agent fair dispatch pipeline || `GET` | `/api/v1/drivers/{id}` | Get driver details and stats || `GET` | `/api/v1/routes/{id}` | Get route details and packages || `POST` | `/api/v1/feedback` | Submit driver feedback for learning |#### Fair Dispatch Request```json{"date": "2026-03-10","warehouse": { "lat": 12.9716, "lng": 77.5946 },"packages": [{"id": "pkg_001","weight_kg": 2.5,"address": "123 Main St, Bangalore","latitude": 12.97, "longitude": 77.60,"priority": "NORMAL"}],"drivers": [{"id": "driver_001","name": "Raju","vehicle_capacity_kg": 150,"vehicle_type": "PETROL"}]}```#### Fair Dispatch Response```json{"status": "SUCCESS","global_fairness": {"gini_index": 0.12,"avg_workload": 63.2,"std_dev": 5.4},"assignments": [{"driver_id": "driver_001","fairness_score": 0.92,"route_summary": { "num_packages": 22, "total_weight_kg": 48.5, "estimated_time_minutes": 145 },"explanation": "Your route covers the Koramangala area with 22 packages. Expected completion: 2.5 hours."}]}```### Operations (Backend-DM)| Method | Endpoint | Description ||--------|----------|-------------|| `GET` | `/api/dashboard/stats` | Dashboard KPIs || `GET` | `/api/drivers` | List all drivers || `POST` | `/api/dispatch/assign` | Assign mission to driver || `POST` | `/api/absorption/initiate` | Initiate goods handover || `POST` | `/api/absorption/verify` | Verify QR handshake || `GET` | `/api/ewaybill/generate/:id` | Generate e-Way Bill PDF || `GET` | `/api/hubs` | List virtual relay hubs |---## Project Structure```fairrelay/├── brain/ # AI Engine (Python/FastAPI)│ ├── app/│ │ ├── api/│ │ │ ├── consolidation.py # Load consolidation endpoints│ │ │ ├── allocation_langgraph.py # Fair dispatch endpoints│ │ │ ├── admin.py│ │ │ ├── drivers.py│ │ │ └── feedback.py│ │ ├── services/│ │ │ ├── consolidation_engine.py # 5 consolidation agents│ │ │ ├── consolidation_workflow.py # LangGraph consolidation flow│ │ │ ├── langgraph_workflow.py # LangGraph dispatch flow│ │ │ ├── langgraph_nodes.py # Dispatch agent implementations│ │ │ ├── ml_effort_agent.py # XGBoost scoring│ │ │ ├── fairness_manager_agent.py # Gini evaluation│ │ │ ├── route_planner_agent.py # Hungarian algorithm│ │ │ └── gemini_explain_node.py # LLM explanations│ │ ├── schemas/│ │ │ ├── consolidation.py # Consolidation Pydantic models│ │ │ └── allocation.py # Dispatch Pydantic models│ │ ├── models/ # SQLAlchemy ORM models│ │ ├── config.py│ │ ├── database.py│ │ └── main.py│ ├── frontend/│ │ ├── consolidation.html # Consolidation dashboard│ │ ├── visualization.html # Agent visualization│ │ └── demo.html # API demo page│ ├── data/│ │ └── rl_experience.json # Q-Learning experience store│ ├── alembic/ # Database migrations│ ├── requirements.txt│ ├── Dockerfile│ ├── gunicorn.conf.py│ └── render.yaml│├── ops/ # Operations Platform│ ├── backend-dm/ # Node.js backend│ │ ├── controllers/│ │ │ ├── routeController.js # Relay logic & assignment│ │ │ ├── ewayBillController.js # PDF generation│ │ │ └── dispatchController.js # Brain proxy│ │ ├── services/│ │ │ ├── dispatch.js # Brain API integration│ │ │ ├── puppeteer.service.js # PDF rendering│ │ │ └── qr.service.js # QR code generation│ │ ├── prisma/schema.prisma│ │ ├── render.yaml│ │ └── index.js│ ││ ├── AIsupplychain/aisupply/ # React Dashboard (Vite)│ │ ├── src/│ │ │ ├── pages/ # Dashboard, Drivers, Routes, Bills, Tracking│ │ │ ├── store/ # Redux slices│ │ │ └── components/│ │ └── vercel.json│ ││ └── logistic_flutter/│ ├── orchastra_ps4/ecology/ # Flutter Mobile App│ └── streamlit/ # Women Empowerment Hub│└── landing/ # Marketing Website (React/Vite)├── src/components/│ ├── Hero.tsx # Problem statement + stats│ ├── Features.tsx # 6 feature cards│ ├── LiveDemo.tsx # Interactive allocation demo│ └── HowItWorks.tsx # 3-step integration guide└── vercel.json```---## Deployment| Component | Platform | URL Pattern ||-----------|----------|-------------|| Brain (AI Engine) | Render | `brain-api.onrender.com` || Backend-DM | Render | `backend-dm.onrender.com` || Dashboard | Vercel | `dashboard.fairrelay.io` || Landing Page | Vercel | `fairrelay.io` |Both backend services include `render.yaml` for one-click Render deployment. Frontend apps include `vercel.json` with API rewrites configured.---## Performance Results| Metric | Before | After | Improvement ||--------|--------|-------|-------------|| Vehicle Utilization | ~38% | ~78% | **+40 percentage points** || Trips Required | 10 | 4 | **60% reduction** || Distance Traveled | 2,847 km | 1,523 km | **46% less** || CO2 Emissions | — | -102 kg saved | **Carbon negative** || Fuel Cost | — | -Rs. 10,964 saved | **Per consolidation run** || Workload Gini Index | 0.85 | 0.12 | **Grade A fairness** || Decision Explainability | 0% | 100% | **Full transparency** |---<p align="center"><strong>Fair routes. Optimized loads. Explainable by default.</strong><br/>Built for <a href="#">LogisticsNow Hackathon 2026</a> · Challenge #5: AI Load Consolidation</p>
1234567891011121314151617181920212223242526# Database ConfigurationDATABASE_URL=postgresql+asyncpg://postgres:password@localhost:5432/fairrelay
# Application SettingsAPP_ENV=developmentDEBUG=true
# CORS origins (comma-separated, used in production)CORS_ORIGINS=https://fairrelay.vercel.app,https://fairrelay-dashboard.vercel.app
# Workload Score WeightsWORKLOAD_WEIGHT_A=1.0WORKLOAD_WEIGHT_B=0.5WORKLOAD_WEIGHT_C=10.0WORKLOAD_WEIGHT_D=0.2
# Clustering SettingsTARGET_PACKAGES_PER_ROUTE=20
# LangGraph / LangSmith (optional - for tracing)LANGCHAIN_TRACING_V2=falseLANGCHAIN_API_KEY=LANGCHAIN_PROJECT=fair-dispatch-dev
# Gemini API (optional - for LLM explanations)GOOGLE_API_KEY=123456789101112131415161718192021222324252627282930313233343536373839404142name: Testson: [push, pull_request]
jobs: test: runs-on: ubuntu-latest services: postgres: image: postgres:15 env: POSTGRES_DB: fair_dispatch_test POSTGRES_USER: test POSTGRES_PASSWORD: test options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432 steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: '3.11' - name: Install dependencies run: | pip install -r requirements.txt pip install pytest pytest-asyncio pytest-xdist pytest-cov httpx faker factory-boy - name: Run tests env: TEST_DATABASE_URL: postgresql+asyncpg://test:test@localhost:5432/fair_dispatch_test run: | pytest tests/ -n auto --cov=app --cov-report=xml --cov-fail-under=90 - name: Upload coverage uses: codecov/codecov-action@v3 with: file: coverage.xml1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495# Environment files.env.env.local.env.*.local
# Python__pycache__/*.py[cod]*$py.class*.so.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/*.egg-info/.installed.cfg*.egg
# Virtual environmentsvenv/ENV/env/.venv/
# IDE.idea/.vscode/*.swp*.swo*~
# Testing.pytest_cache/.coveragehtmlcov/.tox/.nox/
# Database*.db*.sqlite3
# Logs*.log
# OS.DS_StoreThumbs.db
# Debug and test filesdebug_*.pytest_*_output.txterror*.txt*_error.txt
# Cache directoriescache/**/cache/*.json.cache.mypy_cache/
# Node.js (if applicable)node_modules/npm-debug.log*yarn-debug.log*yarn-error.log*package-lock.jsonyarn.lock
# Jupyter Notebooks.ipynb_checkpoints/
# Local test datatest_*.json
# Alembic versions (keep tracked but ignore temp files)alembic/versions/__pycache__/
# Streamlit.streamlit/
# Local development files*.local*.bak*.tmp*.temp1234567891011121314151617181920212223FROM python:3.11-slim
WORKDIR /app
# Install system dependenciesRUN apt-get update && apt-get install -y --no-install-recommends \ gcc \ && rm -rf /var/lib/apt/lists/*
# Copy requirements first for layer cachingCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Copy application codeCOPY . .
# Create non-root userRUN useradd --create-home appuserUSER appuser
EXPOSE 8000
CMD ["gunicorn", "app.main:app", "-c", "gunicorn.conf.py"]12345678910111213141516171819202122232425262728293031323334.PHONY: test test-e2e test-parallel test-cov lint
# Run all teststest: pytest tests/ -v --tb=short
# Run E2E tests onlytest-e2e: pytest tests/test_full_workflow.py tests/test_ev_recovery_e2e.py tests/test_admin_api.py -v
# Run tests in parallel (requires pytest-xdist)test-parallel: pytest tests/ -n auto -v
# Run with coveragetest-cov: pytest tests/ --cov=app --cov-report=html --cov-report=term --cov-fail-under=90
# Lintlint: # ruff check app/ tests/ # ruff might not be installed # mypy app/ echo "Linting skipped (install ruff/mypy to enable)"
# Start test databasetest-db-up: docker-compose -f tests/docker-compose.test.yml up -d
# Stop test databasetest-db-down: docker-compose -f tests/docker-compose.test.yml down -v
# Full CI pipelineci: test-cov123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484<p align="center"> <h1 align="center">🚚 Fair Dispatch System</h1> <p align="center"> <strong>Single‑API Fair Routing · Angelic Fairness Engine · Live Agent Visualization</strong> </p> <p align="center"> <a href="#-quick-start">Quick Start</a> • <a href="#-features">Features</a> • <a href="#-architecture">Architecture</a> • <a href="#-api-reference">API Reference</a> • <a href="#-visualization-dashboard">Dashboard</a> </p></p>
---
Fair Dispatch is an AI‑assisted, **fairness‑aware route allocation engine** designed as a single seamless API that any logistics stack can plug into.
**You send today's drivers and packages as JSON. The system does everything else:**- 📦 Clustering packages into optimal routes- ⚖️ Calculating effort scores and fairness metrics- 🛣️ Planning routes with EV-aware optimization- 🤝 Balancing workload across drivers- 🤖 AI-powered driver negotiation and explanation- 📊 Learning from feedback to improve over time
...and streams the whole multi‑agent process into a **live visualization**.
## ✨ Features
| Feature | Description ||---------|-------------|| **🎯 Single API Endpoint** | One POST to `/api/v1/langgraph/allocate` handles everything || **🤖 5+ Specialized AI Agents** | LangGraph-orchestrated multi-agent workflow || **⚖️ Fairness-First Design** | Gini index, individual fairness scores, and equity metrics || **🗣️ Natural Language Explanations** | Gemini-powered driver-friendly route explanations || **📊 Live Agent Visualization** | Real-time Streamlit dashboard showing agent workflow || **🔄 Continuous Learning** | Feedback loop improves allocations over time || **⚡ EV-Aware Routing** | Battery constraints and charging station integration || **🔐 Full Audit Trail** | Complete decision logging for transparency |
## 🏗️ Architecture
### Multi-Agent Workflow (LangGraph)
```┌────────────────────────────────────────────────────────────────────────────────┐│ FAIR DISPATCH WORKFLOW │└────────────────────────────────────────────────────────────────────────────────┘ │ ▼┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐│ 🔧 Initialize │ → │ 📦 Clustering │ → │ 💪 ML Effort ││ Node │ │ Agent │ │ Agent │└─────────────────┘ └─────────────────┘ └─────────────────┘ │ ▼┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐│ ⚡ EV Recovery │ ← │ ⚖️ Fairness │ ← │ 🛣️ Route ││ Node │ │ Manager │ │ Planner │└─────────────────┘ └─────────────────┘ └─────────────────┘ │ │ ▼ ▼ (if unfair)┌─────────────────┐ ┌─────────────────┐│ 🤝 Driver │ │ 🔄 Reoptimize ││ Liaison │ │ Loop │└─────────────────┘ └─────────────────┘ │ ▼┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐│ 🎓 Learning │ → │ 🗣️ LLM │ → │ ✅ Finalize ││ Agent │ │ Explain │ │ Node │└─────────────────┘ └─────────────────┘ └─────────────────┘```
### Agent Descriptions
| Agent | Purpose | Key Outputs ||-------|---------|-------------|| **Initialize Node** | Sets up allocation state, validates inputs | Validated driver/package data || **Clustering Agent** | Groups packages using K-Means by geography | Route clusters with centroids || **ML Effort Agent** | Builds effort matrix for all driver-route pairs | Effort scores, XGBoost predictions || **Route Planner Agent** | Solves optimal assignment (Hungarian algorithm) | Driver-route assignments || **Fairness Manager** | Evaluates Gini index, std dev, thresholds | ACCEPT or REOPTIMIZE decision || **EV Recovery Node** | Handles EV battery constraints | Charging station insertions || **Driver Liaison Agent** | Handles driver negotiations/appeals | Appeal resolutions || **Learning Agent** | Updates models from feedback | Improved future allocations || **LLM Explain Node** | Generates natural language explanations | Human-readable route descriptions |
## 🚀 Quick Start
### Prerequisites
- **Python 3.11+**- **PostgreSQL 14+** (or SQLite for development)- **Git**
### 1. Clone & Setup
```bash# Clone the repositorygit clone https://github.com/your-org/fair-dispatch-system.gitcd fair-dispatch-system
# Create virtual environmentpython -m venv venv
# Activate virtual environment# Windows:venv\Scripts\activate# Linux/macOS:source venv/bin/activate
# Install dependenciespip install -r requirements.txt```
### 2. Configure Environment
```bash# Copy example environment filecp .env.example .env
# Edit .env with your configuration```
**Essential environment variables:**
```env# Database (PostgreSQL recommended for production)DATABASE_URL=postgresql+asyncpg://postgres:password@localhost:5432/fair_dispatch
# ApplicationAPP_ENV=developmentDEBUG=true
# Optional: Gemini API for AI explanationsGOOGLE_API_KEY=your-gemini-api-key
# Optional: LangSmith tracingLANGCHAIN_TRACING_V2=trueLANGCHAIN_API_KEY=your-langsmith-key```
### 3. Setup Database
```bash# Create PostgreSQL databasecreatedb fair_dispatch
# Run migrationsalembic upgrade head```
### 4. Start the Server
```bash# Development server with hot reloaduvicorn app.main:app --reload --host 0.0.0.0 --port 8000```
### 5. Access the System
| Endpoint | URL ||----------|-----|| **API Documentation** | http://localhost:8000/docs || **ReDoc** | http://localhost:8000/redoc || **Demo Page** | http://localhost:8000/demo/allocate || **Admin Dashboard** | http://localhost:8000/admin |
## 📊 Visualization Dashboard
The system includes a **real-time Streamlit dashboard** for monitoring allocations:
```bash# Navigate to dashboard directorycd supply_chain_dashboard
# Install dashboard dependenciespip install -r requirements.txt
# Run the dashboardstreamlit run dashboard.py```
**Dashboard Features:**- 🗺️ **Live Map Visualization** - See routes on an interactive map- 📈 **Fairness Metrics** - Real-time Gini index and equity scores- 🤖 **Agent Activity Feed** - Watch agents work in real-time- 📊 **Analytics Charts** - Workload distribution and trends
## 📡 API Reference
### Primary Endpoint: Allocate Routes
**`POST /api/v1/langgraph/allocate`**
This single endpoint handles the complete allocation workflow.
#### Request
```json{ "date": "2026-02-10", "warehouse": { "lat": 12.9716, "lng": 77.5946 }, "packages": [ { "id": "pkg_001", "weight_kg": 2.5, "fragility_level": 3, "address": "123 Main St, Bangalore", "latitude": 12.97, "longitude": 77.60, "priority": "NORMAL" }, { "id": "pkg_002", "weight_kg": 1.0, "fragility_level": 1, "address": "456 Oak Ave, Bangalore", "latitude": 12.98, "longitude": 77.61, "priority": "HIGH" } ], "drivers": [ { "id": "driver_001", "name": "Raju", "vehicle_capacity_kg": 150, "preferred_language": "en", "vehicle_type": "PETROL" }, { "id": "driver_002", "name": "Kumar", "vehicle_capacity_kg": 200, "preferred_language": "ta", "vehicle_type": "EV", "ev_range_km": 120 } ]}```
#### Response
```json{ "allocation_run_id": "550e8400-e29b-41d4-a716-446655440000", "date": "2026-02-10", "status": "SUCCESS", "global_fairness": { "avg_workload": 63.2, "std_dev": 5.4, "gini_index": 0.12, "max_gap": 8.3 }, "assignments": [ { "driver_id": "driver_001", "driver_name": "Raju", "route_id": "route_uuid", "workload_score": 65.3, "fairness_score": 0.92, "route_summary": { "num_packages": 22, "total_weight_kg": 48.5, "num_stops": 14, "estimated_time_minutes": 145 }, "explanation": "Your route covers the Koramangala area with 22 packages, mostly residential. Expected completion time is around 2.5 hours with moderate traffic." } ], "agent_events": [ { "agent": "clustering_agent", "status": "completed", "message": "Created 5 route clusters" }, { "agent": "fairness_manager", "status": "completed", "message": "Allocation ACCEPTED (Gini: 0.12)" } ]}```
### Additional Endpoints
| Method | Endpoint | Description ||--------|----------|-------------|| `GET` | `/api/v1/drivers/{id}` | Get driver details and stats || `GET` | `/api/v1/routes/{id}` | Get route details and packages || `POST` | `/api/v1/feedback` | Submit driver feedback || `GET` | `/api/v1/admin/dashboard` | Admin dashboard data || `GET` | `/api/v1/runs` | List allocation runs || `GET` | `/api/v1/runs/{id}/events` | Get agent events for a run |
## 🧪 Testing
```bash# Run all testsmake test
# Run with coveragemake test-cov
# Run specific test filepytest tests/test_allocation.py -v
# Run E2E tests onlymake test-e2e
# Run tests in parallel (faster)pytest tests/ -n auto```
## ⚙️ Configuration
### Environment Variables
| Variable | Default | Description ||----------|---------|-------------|| `DATABASE_URL` | - | PostgreSQL connection string || `DEBUG` | `true` | Enable debug mode || `GOOGLE_API_KEY` | - | Gemini API key for explanations || `LANGCHAIN_TRACING_V2` | `false` | Enable LangSmith tracing || `LANGCHAIN_API_KEY` | - | LangSmith API key |
### Workload Score Weights
| Variable | Default | Description ||----------|---------|-------------|| `WORKLOAD_WEIGHT_A` | `1.0` | Weight for num_packages || `WORKLOAD_WEIGHT_B` | `0.5` | Weight for total_weight_kg || `WORKLOAD_WEIGHT_C` | `10.0` | Weight for route_difficulty_score || `WORKLOAD_WEIGHT_D` | `0.2` | Weight for estimated_time_minutes |
### Fairness Thresholds
| Variable | Default | Description ||----------|---------|-------------|| `TARGET_PACKAGES_PER_ROUTE` | `20` | Target packages per cluster || `GINI_THRESHOLD` | `0.25` | Max acceptable Gini index || `STD_DEV_THRESHOLD` | `15.0` | Max acceptable standard deviation |
## 📐 Algorithms
### Workload Score Formula
```workload_score = a × num_packages + b × total_weight_kg + c × route_difficulty_score + d × estimated_time_minutes```
### Gini Index
Measures inequality in workload distribution (0 = perfect equality, 1 = maximum inequality):
```G = (2 × Σ(i × x_i)) / (n × Σx_i) - (n + 1) / n```
### Individual Fairness Score
Per-driver fairness relative to average:
```fairness_score = 1 - |workload - avg_workload| / max(avg_workload, 1)```
## 📁 Project Structure
```fair-dispatch-system/├── 📂 alembic/ # Database migrations│ └── versions/ # Migration files├── 📂 app/│ ├── 📂 api/ # FastAPI routers│ │ ├── allocation.py # POST /allocate (basic)│ │ ├── allocation_langgraph.py # POST /langgraph/allocate│ │ ├── admin.py # Admin endpoints│ │ ├── drivers.py # Driver endpoints│ │ ├── feedback.py # Feedback endpoints│ │ └── routes.py # Route endpoints│ ├── 📂 models/ # SQLAlchemy models│ │ ├── driver.py│ │ ├── package.py│ │ ├── route.py│ │ └── assignment.py│ ├── 📂 schemas/ # Pydantic DTOs│ ├── 📂 services/ # Business logic│ │ ├── langgraph_workflow.py # Agent orchestration│ │ ├── langgraph_nodes.py # Individual agents│ │ ├── ml_effort_agent.py # ML scoring│ │ ├── fairness_manager_agent.py│ │ ├── route_planner_agent.py│ │ ├── driver_liaison_agent.py│ │ ├── learning_agent.py│ │ ├── gemini_explain_node.py│ │ └── ...│ ├── config.py # Settings│ ├── database.py # DB connection│ └── main.py # FastAPI app├── 📂 frontend/ # Static frontend files│ ├── index.html # Demo UI│ └── visualization.html # Live visualization├── 📂 supply_chain_dashboard/ # Streamlit dashboard│ ├── dashboard.py│ └── api_client.py├── 📂 tests/ # Test suite├── .env.example├── requirements.txt├── Makefile└── README.md```
## 🔧 Development
### Running in Development Mode
```bash# Start with auto-reloaduvicorn app.main:app --reload
# Start with custom portuvicorn app.main:app --reload --port 3000
# Start with debug loggingDEBUG=true uvicorn app.main:app --reload```
### Database Migrations
```bash# Create new migrationalembic revision --autogenerate -m "Add new table"
# Apply migrationsalembic upgrade head
# Rollback one versionalembic downgrade -1
# View migration historyalembic history```
### Makefile Commands
```bashmake test # Run all testsmake test-cov # Run with coveragemake test-e2e # Run E2E testsmake test-parallel # Run tests in parallelmake lint # Run lintingmake format # Format codemake ci # Full CI pipeline```
## 🤝 Contributing
1. Fork the repository2. Create your feature branch (`git checkout -b feature/amazing-feature`)3. Commit your changes (`git commit -m 'Add amazing feature'`)4. Push to the branch (`git push origin feature/amazing-feature`)5. Open a Pull Request
## 📄 License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
---
<p align="center"> Built with ❤️ for fairer logistics</p>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114# A generic, single database configuration.
[alembic]# path to migration scriptsscript_location = alembic
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s# Uncomment the line below if you want the files to be named in numerical order# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.# defaults to the current working directory.prepend_sys_path = .
# timezone to use when rendering the date within the migration file# as well as the filename.# If specified, requires the python-dateutil library that can be# installed by adding `alembic[tz]` to the pip requirements# string value is passed to dateutil.tz.gettz()# leave blank for localtime# timezone =
# max length of characters to apply to the# "slug" field# truncate_slug_length = 40
# set to 'true' to run the environment during# the 'revision' command, regardless of autogenerate# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without# a source .py file to be detected as revisions in the# versions/ directory# sourceless = false
# version location specification; This defaults# to alembic/versions. When using multiple version# directories, initial revisions must be specified with --version-path.# The path separator used here should be the separator specified by "version_path_separator" below.# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
# version path separator; As mentioned above, this is the character used to split# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.# Valid values for version_path_separator are:## version_path_separator = :# version_path_separator = ;# version_path_separator = spaceversion_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# set to 'true' to search source files recursively# in each "version_locations" directory# new in Alembic version 1.10# recursive_version_locations = false
# the output encoding used when revision files# are written from script.py.mako# output_encoding = utf-8
sqlalchemy.url = driver://user:pass@localhost/dbname
[post_write_hooks]# post_write_hooks defines scripts or Python functions that are run# on newly generated revision scripts. See the documentation for further# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint# hooks = black# black.type = console_scripts# black.entrypoint = black# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary# hooks = ruff# ruff.type = exec# ruff.executable = %(here)s/.venv/bin/ruff# ruff.options = --fix REVISION_SCRIPT_FILENAME
# Logging configuration[loggers]keys = root,sqlalchemy,alembic
[handlers]keys = console
[formatters]keys = generic
[logger_root]level = WARNhandlers = consolequalname =
[logger_sqlalchemy]level = WARNhandlers =qualname = sqlalchemy.engine
[logger_alembic]level = INFOhandlers =qualname = alembic
[handler_console]class = StreamHandlerargs = (sys.stderr,)level = NOTSETformatter = generic
[formatter_generic]format = %(levelname)-5.5s [%(name)s] %(message)sdatefmt = %H:%M:%S1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""Alembic environment configuration.Handles database connection and migration context."""
import asynciofrom logging.config import fileConfig
from sqlalchemy import poolfrom sqlalchemy.engine import Connectionfrom sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# Import models to ensure they're registered with Base.metadatafrom app.database import Basefrom app.models import * # noqa: F401, F403from app.config import get_settings
# this is the Alembic Config objectconfig = context.config
# Get database URL from settingssettings = get_settings()config.set_main_option("sqlalchemy.url", settings.database_url)
# Interpret the config file for Python logging.if config.config_file_name is not None: fileConfig(config.config_file_name)
# add your model's MetaData object here for 'autogenerate' supporttarget_metadata = Base.metadata
def run_migrations_offline() -> None: """Run migrations in 'offline' mode.
This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the script output. """ url = config.get_main_option("sqlalchemy.url") context.configure( url=url, target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, )
with context.begin_transaction(): context.run_migrations()
def do_run_migrations(connection: Connection) -> None: """Run migrations with the provided connection.""" context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction(): context.run_migrations()
async def run_async_migrations() -> None: """Run migrations in async mode.""" connectable = async_engine_from_config( config.get_section(config.config_ini_section, {}), prefix="sqlalchemy.", poolclass=pool.NullPool, )
async with connectable.connect() as connection: await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None: """Run migrations in 'online' mode.
In this scenario we need to create an Engine and associate a connection with the context. """ asyncio.run(run_async_migrations())
if context.is_offline_mode(): run_migrations_offline()else: run_migrations_online()1234567891011121314151617181920212223242526"""${message}
Revision ID: ${up_revision}Revises: ${down_revision | comma,n}Create Date: ${create_date}
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as sa${imports if imports else ""}
# revision identifiers, used by Alembic.revision: str = ${repr(up_revision)}down_revision: Union[str, None] = ${repr(down_revision)}branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None: ${upgrades if upgrades else "pass"}
def downgrade() -> None: ${downgrades if downgrades else "pass"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145"""Initial schema - Create all tables
Revision ID: 001_initial_schemaRevises: Create Date: 2026-02-03
"""from typing import Sequence, Union
from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.revision: str = '001_initial_schema'down_revision: Union[str, None] = Nonebranch_labels: Union[str, Sequence[str], None] = Nonedepends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None: # Create enum types op.execute("CREATE TYPE preferredlanguage AS ENUM ('en', 'ta', 'hi', 'te', 'kn')") op.execute("CREATE TYPE vehicletype AS ENUM ('ICE', 'EV', 'BICYCLE')") op.execute("CREATE TYPE packagepriority AS ENUM ('NORMAL', 'HIGH', 'EXPRESS')") op.execute("CREATE TYPE hardestaspect AS ENUM ('traffic', 'parking', 'stairs', 'weather', 'heavy_load', 'customer', 'navigation', 'other')") # Create drivers table op.create_table( 'drivers', sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True), sa.Column('external_id', sa.String(100), unique=True, nullable=True, index=True), sa.Column('name', sa.String(255), nullable=False), sa.Column('phone', sa.String(20), nullable=True), sa.Column('whatsapp_number', sa.String(20), nullable=True), sa.Column('preferred_language', postgresql.ENUM('en', 'ta', 'hi', 'te', 'kn', name='preferredlanguage', create_type=False), nullable=False, server_default='en'), sa.Column('vehicle_type', postgresql.ENUM('ICE', 'EV', 'BICYCLE', name='vehicletype', create_type=False), nullable=False, server_default='ICE'), sa.Column('vehicle_capacity_kg', sa.Float(), nullable=False, server_default='100.0'), sa.Column('license_number', sa.String(50), nullable=True), sa.Column('ev_charging_pref', postgresql.JSON(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), ) # Create packages table op.create_table( 'packages', sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True), sa.Column('external_id', sa.String(100), unique=True, nullable=False, index=True), sa.Column('weight_kg', sa.Float(), nullable=False, server_default='1.0'), sa.Column('fragility_level', sa.Integer(), nullable=False, server_default='1'), sa.Column('address', sa.Text(), nullable=False), sa.Column('latitude', sa.Float(), nullable=False), sa.Column('longitude', sa.Float(), nullable=False), sa.Column('priority', postgresql.ENUM('NORMAL', 'HIGH', 'EXPRESS', name='packagepriority', create_type=False), nullable=False, server_default='NORMAL'), sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), ) # Create routes table op.create_table( 'routes', sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True), sa.Column('date', sa.Date(), nullable=False, index=True), sa.Column('cluster_id', sa.Integer(), nullable=False), sa.Column('total_weight_kg', sa.Float(), nullable=False, server_default='0.0'), sa.Column('num_packages', sa.Integer(), nullable=False, server_default='0'), sa.Column('num_stops', sa.Integer(), nullable=False, server_default='0'), sa.Column('route_difficulty_score', sa.Float(), nullable=False, server_default='1.0'), sa.Column('estimated_time_minutes', sa.Integer(), nullable=False, server_default='60'), sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), ) # Create route_packages association table op.create_table( 'route_packages', sa.Column('route_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('routes.id', ondelete='CASCADE'), primary_key=True), sa.Column('package_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('packages.id', ondelete='CASCADE'), primary_key=True), sa.Column('stop_order', sa.Integer(), nullable=False, server_default='0'), ) # Create assignments table op.create_table( 'assignments', sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True), sa.Column('date', sa.Date(), nullable=False, index=True), sa.Column('driver_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('drivers.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('route_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('routes.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('workload_score', sa.Float(), nullable=False, server_default='0.0'), sa.Column('fairness_score', sa.Float(), nullable=False, server_default='1.0'), sa.Column('explanation', sa.Text(), nullable=True), sa.Column('allocation_run_id', postgresql.UUID(as_uuid=True), nullable=False, index=True), sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), ) # Create driver_stats_daily table op.create_table( 'driver_stats_daily', sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True), sa.Column('driver_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('drivers.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('date', sa.Date(), nullable=False, index=True), sa.Column('avg_workload_score', sa.Float(), nullable=False, server_default='0.0'), sa.Column('total_routes', sa.Integer(), nullable=False, server_default='0'), sa.Column('gini_contribution', sa.Float(), nullable=True), sa.Column('reported_stress_level', sa.Float(), nullable=True), sa.Column('reported_fairness_score', sa.Float(), nullable=True), ) # Create driver_feedback table op.create_table( 'driver_feedback', sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True), sa.Column('driver_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('drivers.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('assignment_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('assignments.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('fairness_rating', sa.Integer(), nullable=False), sa.Column('stress_level', sa.Integer(), nullable=False), sa.Column('tiredness_level', sa.Integer(), nullable=False), sa.Column('hardest_aspect', postgresql.ENUM('traffic', 'parking', 'stairs', 'weather', 'heavy_load', 'customer', 'navigation', 'other', name='hardestaspect', create_type=False), nullable=True), sa.Column('comments', sa.Text(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), ) # Create indexes for common queries op.create_index('ix_assignments_allocation_run', 'assignments', ['allocation_run_id']) op.create_index('ix_driver_stats_driver_date', 'driver_stats_daily', ['driver_id', 'date'])
def downgrade() -> None: # Drop indexes op.drop_index('ix_driver_stats_driver_date', table_name='driver_stats_daily') op.drop_index('ix_assignments_allocation_run', table_name='assignments') # Drop tables in reverse order (respecting foreign keys) op.drop_table('driver_feedback') op.drop_table('driver_stats_daily') op.drop_table('assignments') op.drop_table('route_packages') op.drop_table('routes') op.drop_table('packages') op.drop_table('drivers') # Drop enum types op.execute("DROP TYPE IF EXISTS hardestaspect") op.execute("DROP TYPE IF EXISTS packagepriority") op.execute("DROP TYPE IF EXISTS vehicletype") op.execute("DROP TYPE IF EXISTS preferredlanguage")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179"""Add Phase 2 and Phase 3 models
Revision ID: 002_phase2_phase3_modelsRevises: 001_initial_schemaCreate Date: 2026-02-04
Creates tables:- delivery_logs- route_swap_requests- stop_issues- appeals- manual_overrides- fairness_configs- allocation_runs- decision_logs
Modifies tables:- driver_feedback (adds new columns)"""
from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects.postgresql import UUID
# revision identifiers, used by Alembic.revision = '002_phase2_phase3_models'down_revision = '001_initial_schema'branch_labels = Nonedepends_on = None
def upgrade() -> None: # Create allocation_runs table first (referenced by decision_logs) op.create_table( 'allocation_runs', sa.Column('id', UUID(as_uuid=True), primary_key=True), sa.Column('date', sa.Date(), nullable=False, index=True), sa.Column('num_drivers', sa.Integer(), nullable=False, default=0), sa.Column('num_routes', sa.Integer(), nullable=False, default=0), sa.Column('num_packages', sa.Integer(), nullable=False, default=0), sa.Column('global_gini_index', sa.Float(), default=0.0), sa.Column('global_std_dev', sa.Float(), default=0.0), sa.Column('global_max_gap', sa.Float(), default=0.0), sa.Column('status', sa.Enum('SUCCESS', 'FAILED', name='allocationrunstatus'), nullable=False), sa.Column('error_message', sa.Text(), nullable=True), sa.Column('started_at', sa.DateTime(), nullable=False), sa.Column('finished_at', sa.DateTime(), nullable=True), )
# Create delivery_logs table op.create_table( 'delivery_logs', sa.Column('id', UUID(as_uuid=True), primary_key=True), sa.Column('assignment_id', UUID(as_uuid=True), sa.ForeignKey('assignments.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('route_id', UUID(as_uuid=True), sa.ForeignKey('routes.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('driver_id', UUID(as_uuid=True), sa.ForeignKey('drivers.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('stop_order', sa.Integer(), nullable=False), sa.Column('package_id', UUID(as_uuid=True), sa.ForeignKey('packages.id', ondelete='SET NULL'), nullable=True), sa.Column('status', sa.Enum('DELIVERED', 'FAILED', 'PARTIAL', name='deliverystatus'), nullable=False), sa.Column('issue_type', sa.Enum('NONE', 'NOT_AT_HOME', 'WRONG_ADDRESS', 'SAFETY', 'ACCESS_DENIED', 'OTHER', name='deliveryissuetype'), nullable=False), sa.Column('photo_url', sa.String(500), nullable=True), sa.Column('signature_data', sa.Text(), nullable=True), sa.Column('notes', sa.Text(), nullable=True), sa.Column('timestamp', sa.DateTime(), nullable=False), )
# Create route_swap_requests table op.create_table( 'route_swap_requests', sa.Column('id', UUID(as_uuid=True), primary_key=True), sa.Column('from_driver_id', UUID(as_uuid=True), sa.ForeignKey('drivers.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('to_driver_id', UUID(as_uuid=True), sa.ForeignKey('drivers.id', ondelete='SET NULL'), nullable=True), sa.Column('assignment_id', UUID(as_uuid=True), sa.ForeignKey('assignments.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('reason', sa.Text(), nullable=False), sa.Column('preferred_date', sa.Date(), nullable=True), sa.Column('status', sa.Enum('PENDING', 'APPROVED', 'REJECTED', 'CANCELLED', name='swaprequeststatus'), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), )
# Create stop_issues table op.create_table( 'stop_issues', sa.Column('id', UUID(as_uuid=True), primary_key=True), sa.Column('assignment_id', UUID(as_uuid=True), sa.ForeignKey('assignments.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('route_id', UUID(as_uuid=True), sa.ForeignKey('routes.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('driver_id', UUID(as_uuid=True), sa.ForeignKey('drivers.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('stop_order', sa.Integer(), nullable=False), sa.Column('issue_type', sa.Enum('NAVIGATION', 'SAFETY', 'TIME_WINDOW', 'CUSTOMER_UNAVAILABLE', 'OTHER', name='stopissuetype'), nullable=False), sa.Column('notes', sa.Text(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False), )
# Create appeals table op.create_table( 'appeals', sa.Column('id', UUID(as_uuid=True), primary_key=True), sa.Column('driver_id', UUID(as_uuid=True), sa.ForeignKey('drivers.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('assignment_id', UUID(as_uuid=True), sa.ForeignKey('assignments.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('reason', sa.Text(), nullable=False), sa.Column('status', sa.Enum('PENDING', 'APPROVED', 'REJECTED', 'RESOLVED', name='appealstatus'), nullable=False), sa.Column('admin_note', sa.Text(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), )
# Create manual_overrides table op.create_table( 'manual_overrides', sa.Column('id', UUID(as_uuid=True), primary_key=True), sa.Column('allocation_run_id', UUID(as_uuid=True), nullable=False, index=True), sa.Column('old_driver_id', UUID(as_uuid=True), sa.ForeignKey('drivers.id', ondelete='SET NULL'), nullable=True), sa.Column('new_driver_id', UUID(as_uuid=True), sa.ForeignKey('drivers.id', ondelete='SET NULL'), nullable=True), sa.Column('route_id', UUID(as_uuid=True), sa.ForeignKey('routes.id', ondelete='SET NULL'), nullable=True), sa.Column('reason', sa.Text(), nullable=True), sa.Column('before_metrics', sa.JSON(), nullable=True), sa.Column('after_metrics', sa.JSON(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), )
# Create fairness_configs table op.create_table( 'fairness_configs', sa.Column('id', UUID(as_uuid=True), primary_key=True), sa.Column('is_active', sa.Boolean(), nullable=False, index=True), sa.Column('workload_weight_packages', sa.Float(), default=1.0), sa.Column('workload_weight_weight_kg', sa.Float(), default=0.5), sa.Column('workload_weight_difficulty', sa.Float(), default=10.0), sa.Column('workload_weight_time', sa.Float(), default=0.2), sa.Column('gini_threshold', sa.Float(), default=0.33), sa.Column('stddev_threshold', sa.Float(), default=25.0), sa.Column('max_gap_threshold', sa.Float(), default=25.0), sa.Column('recovery_mode_enabled', sa.Boolean(), default=False), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), )
# Create decision_logs table op.create_table( 'decision_logs', sa.Column('id', UUID(as_uuid=True), primary_key=True), sa.Column('allocation_run_id', UUID(as_uuid=True), sa.ForeignKey('allocation_runs.id', ondelete='CASCADE'), nullable=False, index=True), sa.Column('agent_name', sa.String(100), nullable=False, index=True), sa.Column('step_type', sa.String(100), nullable=False), sa.Column('input_snapshot', sa.JSON(), nullable=True), sa.Column('output_snapshot', sa.JSON(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), )
# Add new columns to driver_feedback table for Phase 2 extended feedback op.add_column('driver_feedback', sa.Column('route_difficulty_self_report', sa.Integer(), nullable=True)) op.add_column('driver_feedback', sa.Column('would_take_similar_route_again', sa.Boolean(), nullable=True)) op.add_column('driver_feedback', sa.Column('most_unfair_aspect', sa.String(100), nullable=True))
def downgrade() -> None: # Remove new columns from driver_feedback op.drop_column('driver_feedback', 'most_unfair_aspect') op.drop_column('driver_feedback', 'would_take_similar_route_again') op.drop_column('driver_feedback', 'route_difficulty_self_report')
# Drop tables in reverse order op.drop_table('decision_logs') op.drop_table('fairness_configs') op.drop_table('manual_overrides') op.drop_table('appeals') op.drop_table('stop_issues') op.drop_table('route_swap_requests') op.drop_table('delivery_logs') op.drop_table('allocation_runs')
# Drop enums op.execute("DROP TYPE IF EXISTS allocationrunstatus") op.execute("DROP TYPE IF EXISTS deliverystatus") op.execute("DROP TYPE IF EXISTS deliveryissuetype") op.execute("DROP TYPE IF EXISTS swaprequeststatus") op.execute("DROP TYPE IF EXISTS stopissuetype") op.execute("DROP TYPE IF EXISTS appealstatus")123456789101112131415161718192021222324252627282930313233343536"""Add PENDING status to allocation_run_status enum.
Revision ID: 003_add_pending_statusRevises: 002_phase2_phase3_modelsCreate Date: 2026-02-04"""
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision = '003_add_pending_status'down_revision = '002_phase2_phase3_models'branch_labels = Nonedepends_on = None
def upgrade() -> None: """Add PENDING to allocationrunstatus enum.""" # For PostgreSQL, we need to add the new value to the enum type op.execute("ALTER TYPE allocationrunstatus ADD VALUE IF NOT EXISTS 'PENDING' BEFORE 'SUCCESS'")
def downgrade() -> None: """Note: PostgreSQL does not support removing enum values directly. To fully downgrade, you would need to: 1. Create a new enum without PENDING 2. Update all PENDING rows to another status 3. Alter the column to use the new enum 4. Drop the old enum For simplicity, this downgrade is a no-op. """ pass123456789101112131415161718192021222324252627282930313233343536373839404142"""Add driver_explanation and admin_explanation columns to assignments.
Revision ID: 004Revises: 003_add_pending_statusCreate Date: 2026-02-04"""
from alembic import opimport sqlalchemy as sa
# revision identifiers, used by Alembic.revision = '004'down_revision = '003_add_pending_status'branch_labels = Nonedepends_on = None
def upgrade(): # Add driver_explanation column op.add_column( 'assignments', sa.Column('driver_explanation', sa.Text(), nullable=True) ) # Add admin_explanation column op.add_column( 'assignments', sa.Column('admin_explanation', sa.Text(), nullable=True) ) # Backfill: copy existing explanation to driver_explanation op.execute(""" UPDATE assignments SET driver_explanation = explanation WHERE explanation IS NOT NULL """)
def downgrade(): op.drop_column('assignments', 'admin_explanation') op.drop_column('assignments', 'driver_explanation')1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""Phase 7: EV-aware routing and Recovery Mode
Revision ID: 005_phase7_ev_recoveryRevises: 004_add_explanation_fieldsCreate Date: 2026-02-04"""
from alembic import opimport sqlalchemy as sa
# revision identifiersrevision = '005_phase7_ev_recovery'down_revision = '004_add_explanation_fields'branch_labels = Nonedepends_on = None
def upgrade(): # Driver EV fields op.add_column('drivers', sa.Column('battery_range_km', sa.Float(), nullable=True)) op.add_column('drivers', sa.Column('charging_time_minutes', sa.Integer(), nullable=True)) # Route distance field op.add_column('routes', sa.Column('total_distance_km', sa.Float(), nullable=True)) # DriverStatsDaily recovery fields op.add_column('driver_stats_daily', sa.Column('is_hard_day', sa.Boolean(), nullable=False, server_default='false')) op.add_column('driver_stats_daily', sa.Column('complexity_debt', sa.Float(), nullable=False, server_default='0.0')) op.add_column('driver_stats_daily', sa.Column('is_recovery_day', sa.Boolean(), nullable=False, server_default='false')) # FairnessConfig recovery/EV fields op.add_column('fairness_configs', sa.Column('complexity_debt_hard_threshold', sa.Float(), nullable=False, server_default='2.0')) op.add_column('fairness_configs', sa.Column('recovery_lightening_factor', sa.Float(), nullable=False, server_default='0.7')) op.add_column('fairness_configs', sa.Column('recovery_penalty_weight', sa.Float(), nullable=False, server_default='3.0')) op.add_column('fairness_configs', sa.Column('ev_charging_penalty_weight', sa.Float(), nullable=False, server_default='0.3')) op.add_column('fairness_configs', sa.Column('ev_safety_margin_pct', sa.Float(), nullable=False, server_default='10.0'))
def downgrade(): # FairnessConfig op.drop_column('fairness_configs', 'ev_safety_margin_pct') op.drop_column('fairness_configs', 'ev_charging_penalty_weight') op.drop_column('fairness_configs', 'recovery_penalty_weight') op.drop_column('fairness_configs', 'recovery_lightening_factor') op.drop_column('fairness_configs', 'complexity_debt_hard_threshold') # DriverStatsDaily op.drop_column('driver_stats_daily', 'is_recovery_day') op.drop_column('driver_stats_daily', 'complexity_debt') op.drop_column('driver_stats_daily', 'is_hard_day') # Route op.drop_column('routes', 'total_distance_km') # Driver op.drop_column('drivers', 'charging_time_minutes') op.drop_column('drivers', 'battery_range_km')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Phase 8: Learning Agent tables and DriverStatsDaily extensions.
Revision ID: 006_phase8_learningRevises: 005_phase7_ev_recoveryCreate Date: 2026-02-04
Creates:- learning_episodes table for bandit learning- driver_effort_models table for per-driver XGBoost models- Extends driver_stats_daily with learning fields"""
from alembic import opimport sqlalchemy as safrom sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.revision = '006_phase8_learning'down_revision = '005_phase7_ev_recovery'branch_labels = Nonedepends_on = None
def upgrade() -> None: # Create learning_episodes table op.create_table( 'learning_episodes', sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True), sa.Column('allocation_run_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('allocation_runs.id', ondelete='CASCADE'), nullable=False, unique=True), sa.Column('config_hash', sa.String(64), nullable=False), sa.Column('fairness_config', postgresql.JSONB, nullable=False), sa.Column('arm_idx', sa.Integer, nullable=False, default=0), sa.Column('num_drivers', sa.Integer, nullable=False, default=0), sa.Column('num_routes', sa.Integer, nullable=False, default=0), sa.Column('episode_reward', sa.Float, nullable=True), sa.Column('reward_computed_at', sa.DateTime, nullable=True), sa.Column('alpha_prior', sa.Float, default=1.0), sa.Column('beta_prior', sa.Float, default=1.0), sa.Column('samples_count', sa.Integer, default=0), sa.Column('is_experimental', sa.Boolean, default=False), sa.Column('avg_fairness_rating', sa.Float, nullable=True), sa.Column('avg_stress_level', sa.Float, nullable=True), sa.Column('completion_rate', sa.Float, nullable=True), sa.Column('feedback_count', sa.Integer, default=0), sa.Column('created_at', sa.DateTime, nullable=False, server_default=sa.func.now()), ) # Create indexes for learning_episodes op.create_index('ix_learning_episodes_config_hash', 'learning_episodes', ['config_hash']) op.create_index('ix_learning_episodes_created_at', 'learning_episodes', ['created_at']) op.create_index('ix_learning_episodes_is_experimental', 'learning_episodes', ['is_experimental']) op.create_index('ix_learning_episodes_allocation_run_id', 'learning_episodes', ['allocation_run_id']) # Create driver_effort_models table op.create_table( 'driver_effort_models', sa.Column('driver_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('drivers.id', ondelete='CASCADE'), primary_key=True), sa.Column('model_version', sa.Integer, nullable=False, default=1), sa.Column('model_pickle', sa.LargeBinary, nullable=True), sa.Column('training_samples', sa.Integer, default=0), sa.Column('feature_names', postgresql.JSONB, nullable=True), sa.Column('mse_history', postgresql.JSONB, nullable=True), sa.Column('current_mse', sa.Float, nullable=True), sa.Column('r2_score', sa.Float, nullable=True), sa.Column('active', sa.Boolean, default=True), sa.Column('last_trained_at', sa.DateTime, nullable=True), sa.Column('created_at', sa.DateTime, nullable=False, server_default=sa.func.now()), sa.Column('updated_at', sa.DateTime, nullable=False, server_default=sa.func.now(), onupdate=sa.func.now()), ) # Create index for driver_effort_models op.create_index('ix_driver_effort_models_active', 'driver_effort_models', ['active']) # Extend driver_stats_daily with learning fields op.add_column('driver_stats_daily', sa.Column('predicted_effort', sa.Float, nullable=True)) op.add_column('driver_stats_daily', sa.Column('actual_effort', sa.Float, nullable=True)) op.add_column('driver_stats_daily', sa.Column('prediction_error', sa.Float, nullable=True)) op.add_column('driver_stats_daily', sa.Column('model_version_used', sa.Integer, nullable=True)) op.add_column('driver_stats_daily', sa.Column('allocation_run_id', postgresql.UUID(as_uuid=True), sa.ForeignKey('allocation_runs.id', ondelete='SET NULL'), nullable=True)) # Create index for allocation_run_id op.create_index('ix_driver_stats_daily_allocation_run_id', 'driver_stats_daily', ['allocation_run_id'])
def downgrade() -> None: # Remove indexes op.drop_index('ix_driver_stats_daily_allocation_run_id', 'driver_stats_daily') op.drop_index('ix_driver_effort_models_active', 'driver_effort_models') op.drop_index('ix_learning_episodes_allocation_run_id', 'learning_episodes') op.drop_index('ix_learning_episodes_is_experimental', 'learning_episodes') op.drop_index('ix_learning_episodes_created_at', 'learning_episodes') op.drop_index('ix_learning_episodes_config_hash', 'learning_episodes') # Remove columns from driver_stats_daily op.drop_column('driver_stats_daily', 'allocation_run_id') op.drop_column('driver_stats_daily', 'model_version_used') op.drop_column('driver_stats_daily', 'prediction_error') op.drop_column('driver_stats_daily', 'actual_effort') op.drop_column('driver_stats_daily', 'predicted_effort') # Drop tables op.drop_table('driver_effort_models') op.drop_table('learning_episodes')1"""App package initialization."""123456789101112131415161718192021222324"""API routers package initialization."""
from app.api.allocation import router as allocation_routerfrom app.api.drivers import router as drivers_routerfrom app.api.routes import router as routes_routerfrom app.api.feedback import router as feedback_routerfrom app.api.driver_api import router as driver_api_routerfrom app.api.admin import router as admin_routerfrom app.api.admin_learning import router as admin_learning_routerfrom app.api.allocation_langgraph import router as allocation_langgraph_routerfrom app.api.consolidation import router as consolidation_router
__all__ = [ "allocation_router", "drivers_router", "routes_router", "feedback_router", "driver_api_router", "admin_router", "admin_learning_router", "allocation_langgraph_router", "consolidation_router",]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298"""Phase 3 Admin-facing API endpoints.Handles admin operations: health, allocation runs, assignments, metrics, appeals, overrides, config."""
from datetime import date
from fastapi import APIRouter, Depends, HTTPException, Query, statusfrom sqlalchemy.ext.asyncio import AsyncSessionfrom uuid import UUID
from app.database import get_dbfrom app.schemas.admin import ( HealthResponse, AllocationRunsListResponse, AdminAssignmentsListResponse, FairnessMetricsResponse, WorkloadHeatmapResponse, DriverHistoryResponse, AppealsListResponse, AppealDecisionRequest, AppealDecisionResponse, ManualOverrideRequest, ManualOverrideResponse, FairnessConfigRequest, FairnessConfigResponse, AgentTimelineResponse, DriverAllocationStoryResponse,)from app.services.admin_service import ( get_system_health, get_allocation_runs, get_assignments_paginated, get_fairness_metrics_series, get_workload_heatmap, get_driver_history, list_appeals, decide_appeal, perform_manual_override, get_active_fairness_config, create_fairness_config, get_agent_timeline, get_driver_allocation_story,)
router = APIRouter(prefix="/admin", tags=["Admin"])
@router.get( "/health", response_model=HealthResponse, summary="System health check", description="Get system health status including database and latest allocation run.",)async def health_check( db: AsyncSession = Depends(get_db),) -> HealthResponse: """Check system health.""" return await get_system_health(db)
@router.get( "/allocation_runs", response_model=AllocationRunsListResponse, summary="List allocation runs", description="Get allocation runs for a specific date.",)async def get_allocation_runs_endpoint( date: date = Query(..., description="Date to query"), db: AsyncSession = Depends(get_db),) -> AllocationRunsListResponse: """List allocation runs for date.""" return await get_allocation_runs(db, date)
@router.get( "/assignments", response_model=AdminAssignmentsListResponse, summary="List assignments", description="Get paginated list of assignments with filters.",)async def get_assignments_endpoint( date: date = Query(..., description="Date to query"), driver_id: UUID = Query(default=None, description="Filter by driver"), min_fairness: float = Query(default=None, ge=0, le=1, description="Minimum fairness score"), max_fairness: float = Query(default=None, ge=0, le=1, description="Maximum fairness score"), page: int = Query(default=1, ge=1, description="Page number"), page_size: int = Query(default=50, ge=1, le=100, description="Items per page"), db: AsyncSession = Depends(get_db),) -> AdminAssignmentsListResponse: """Get paginated assignments.""" return await get_assignments_paginated( db, date, driver_id, min_fairness, max_fairness, page, page_size )
@router.get( "/metrics/fairness", response_model=FairnessMetricsResponse, summary="Fairness metrics time series", description="Get fairness metrics over a date range.",)async def get_fairness_metrics_endpoint( start_date: date = Query(..., description="Start date"), end_date: date = Query(..., description="End date"), db: AsyncSession = Depends(get_db),) -> FairnessMetricsResponse: """Get fairness metrics time series.""" return await get_fairness_metrics_series(db, start_date, end_date)
@router.get( "/workload_heatmap", response_model=WorkloadHeatmapResponse, summary="Workload heatmap", description="Get workload heatmap data for visualization.",)async def get_heatmap_endpoint( start_date: date = Query(..., description="Start date"), end_date: date = Query(..., description="End date"), db: AsyncSession = Depends(get_db),) -> WorkloadHeatmapResponse: """Get workload heatmap data.""" return await get_workload_heatmap(db, start_date, end_date)
@router.get( "/driver/{driver_id}/history", response_model=DriverHistoryResponse, summary="Driver history", description="Get detailed driver history including appeals and overrides.",)async def get_driver_history_endpoint( driver_id: UUID, window_days: int = Query(default=30, ge=1, le=365, description="Days to look back"), db: AsyncSession = Depends(get_db),) -> DriverHistoryResponse: """Get driver history.""" result = await get_driver_history(db, driver_id, window_days) if not result: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Driver not found", ) return result
@router.get( "/appeals", response_model=AppealsListResponse, summary="List appeals", description="Get list of appeals with optional status filter.",)async def get_appeals_endpoint( status: str = Query(default=None, description="Filter by status (PENDING, APPROVED, REJECTED, RESOLVED)"), db: AsyncSession = Depends(get_db),) -> AppealsListResponse: """List appeals.""" return await list_appeals(db, status)
@router.post( "/appeals/{appeal_id}/decision", response_model=AppealDecisionResponse, summary="Decide appeal", description="Update appeal status with admin decision.",)async def decide_appeal_endpoint( appeal_id: UUID, request: AppealDecisionRequest, db: AsyncSession = Depends(get_db),) -> AppealDecisionResponse: """Make decision on an appeal.""" try: result = await decide_appeal(db, appeal_id, request.status, request.admin_note) if not result: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Appeal not found", ) await db.commit() return result except ValueError as e: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(e), )
@router.post( "/manual_override", response_model=ManualOverrideResponse, summary="Manual override", description="Manually reassign a route from one driver to another.",)async def manual_override_endpoint( request: ManualOverrideRequest, db: AsyncSession = Depends(get_db),) -> ManualOverrideResponse: """Perform manual route override.""" try: result = await perform_manual_override( db=db, allocation_run_id=request.allocation_run_id, old_driver_id=request.old_driver_id, new_driver_id=request.new_driver_id, route_id=request.route_id, reason=request.reason, ) await db.commit() return result except ValueError as e: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(e), )
@router.get( "/fairness_config", response_model=FairnessConfigResponse, summary="Get fairness config", description="Get the currently active fairness configuration.",)async def get_fairness_config_endpoint( db: AsyncSession = Depends(get_db),) -> FairnessConfigResponse: """Get active fairness config.""" result = await get_active_fairness_config(db) if not result: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="No active fairness config found", ) return result
@router.post( "/fairness_config", response_model=FairnessConfigResponse, status_code=status.HTTP_201_CREATED, summary="Create fairness config", description="Create new fairness config and deactivate existing ones.",)async def create_fairness_config_endpoint( request: FairnessConfigRequest, db: AsyncSession = Depends(get_db),) -> FairnessConfigResponse: """Create new fairness config.""" result = await create_fairness_config( db=db, workload_weight_packages=request.workload_weight_packages, workload_weight_weight_kg=request.workload_weight_weight_kg, workload_weight_difficulty=request.workload_weight_difficulty, workload_weight_time=request.workload_weight_time, gini_threshold=request.gini_threshold, stddev_threshold=request.stddev_threshold, max_gap_threshold=request.max_gap_threshold, recovery_mode_enabled=request.recovery_mode_enabled, ) await db.commit() return result
@router.get( "/agent_timeline", response_model=AgentTimelineResponse, summary="Agent timeline", description="Get agent decision logs for an allocation run.",)async def get_agent_timeline_endpoint( allocation_run_id: UUID = Query(..., description="Allocation run ID"), db: AsyncSession = Depends(get_db),) -> AgentTimelineResponse: """Get agent timeline for allocation run.""" return await get_agent_timeline(db, allocation_run_id)
@router.get( "/driver_allocation_story", response_model=DriverAllocationStoryResponse, summary="Driver allocation story", description="Get complete allocation story for a driver on a specific date.",)async def get_driver_allocation_story_endpoint( driver_id: UUID = Query(..., description="Driver ID"), date: date = Query(..., description="Date to query (ISO format)"), db: AsyncSession = Depends(get_db),) -> DriverAllocationStoryResponse: """Get driver allocation story for a specific date.""" result = await get_driver_allocation_story(db, driver_id, date) if not result: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="No assignment found for driver on given date", ) return result
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368"""Admin Learning API endpoints for Phase 8.Provides monitoring, control, and debugging for the Learning Agent."""
from datetime import datetime, timedeltafrom typing import Optionalfrom uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query, statusfrom sqlalchemy import select, funcfrom sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_dbfrom app.models import ( LearningEpisode, DriverEffortModel, FairnessConfig, Driver,)from app.services.learning_agent import LearningAgent, hash_configfrom app.schemas.learning_schemas import ( LearningStatusResponse, LearningEpisodeResponse, LearningEpisodesListResponse, DriverModelStatusResponse, ForceConfigRequest, ForceConfigResponse, TriggerLearningRequest, TriggerLearningResponse, DriverModelUpdateRequest, DriverModelUpdateResponse, AllDriverModelsListResponse, BanditStatistics,)
router = APIRouter(prefix="/admin/learning", tags=["Admin - Learning Agent"])
@router.get( "/status", response_model=LearningStatusResponse, summary="Get learning agent status", description="Returns overall learning status including bandit statistics, " "active driver models, and top performing configurations.",)async def get_learning_status( db: AsyncSession = Depends(get_db),) -> LearningStatusResponse: """Get current learning agent status.""" agent = LearningAgent(db) status_dict = await agent.get_learning_status() return LearningStatusResponse( current_config=status_dict.get("current_config"), top_performing_configs=status_dict.get("top_performing_configs", []), driver_models_active=status_dict.get("driver_models_active", 0), avg_prediction_mse=status_dict.get("avg_prediction_mse", 0.0), recent_episodes_7d=status_dict.get("recent_episodes_7d", 0), total_arms=status_dict.get("total_arms", 81), bandit_statistics=BanditStatistics( total_samples=status_dict.get("bandit_statistics", {}).get("total_samples", 0), explored_arms=status_dict.get("bandit_statistics", {}).get("explored_arms", 0), total_arms=status_dict.get("total_arms", 81), ), )
@router.get( "/episodes", response_model=LearningEpisodesListResponse, summary="List learning episodes", description="Returns paginated list of learning episodes with rewards.",)async def list_episodes( page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100), has_reward: Optional[bool] = Query(None), is_experimental: Optional[bool] = Query(None), db: AsyncSession = Depends(get_db),) -> LearningEpisodesListResponse: """List learning episodes with optional filters.""" # Build query query = select(LearningEpisode).order_by(LearningEpisode.created_at.desc()) count_query = select(func.count(LearningEpisode.id)) # Apply filters if has_reward is True: query = query.where(LearningEpisode.episode_reward.isnot(None)) count_query = count_query.where(LearningEpisode.episode_reward.isnot(None)) elif has_reward is False: query = query.where(LearningEpisode.episode_reward.is_(None)) count_query = count_query.where(LearningEpisode.episode_reward.is_(None)) if is_experimental is not None: query = query.where(LearningEpisode.is_experimental == is_experimental) count_query = count_query.where(LearningEpisode.is_experimental == is_experimental) # Get total count total_result = await db.execute(count_query) total = total_result.scalar() or 0 # Apply pagination offset = (page - 1) * page_size query = query.offset(offset).limit(page_size) result = await db.execute(query) episodes = result.scalars().all() return LearningEpisodesListResponse( episodes=[LearningEpisodeResponse.model_validate(ep) for ep in episodes], total=total, page=page, page_size=page_size, has_next=(offset + len(episodes)) < total, )
@router.get( "/episodes/{episode_id}", response_model=LearningEpisodeResponse, summary="Get learning episode details",)async def get_episode( episode_id: UUID, db: AsyncSession = Depends(get_db),) -> LearningEpisodeResponse: """Get details of a specific learning episode.""" result = await db.execute( select(LearningEpisode).where(LearningEpisode.id == episode_id) ) episode = result.scalar_one_or_none() if not episode: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Episode {episode_id} not found", ) return LearningEpisodeResponse.model_validate(episode)
@router.post( "/force_config", response_model=ForceConfigResponse, summary="Force a specific fairness config", description="Override bandit selection with a specific config. " "Use for emergency rollbacks or testing.",)async def force_config( request: ForceConfigRequest, db: AsyncSession = Depends(get_db),) -> ForceConfigResponse: """Force a specific fairness configuration.""" # Get current active config result = await db.execute( select(FairnessConfig).where(FairnessConfig.is_active == True).limit(1) ) current = result.scalar_one_or_none() previous_config = None if current: previous_config = { "gini_threshold": current.gini_threshold, "stddev_threshold": current.stddev_threshold, "recovery_lightening_factor": current.recovery_lightening_factor, "ev_charging_penalty_weight": current.ev_charging_penalty_weight, } current.is_active = False # Create new config new_config = FairnessConfig( is_active=True, gini_threshold=request.gini_threshold, stddev_threshold=request.stddev_threshold, recovery_lightening_factor=request.recovery_lightening_factor, ev_charging_penalty_weight=request.ev_charging_penalty_weight, max_gap_threshold=request.max_gap_threshold, ) db.add(new_config) await db.commit() return ForceConfigResponse( status="success", message=f"Config forced. Reason: {request.reason}", config_applied={ "gini_threshold": request.gini_threshold, "stddev_threshold": request.stddev_threshold, "recovery_lightening_factor": request.recovery_lightening_factor, "ev_charging_penalty_weight": request.ev_charging_penalty_weight, "max_gap_threshold": request.max_gap_threshold, }, previous_config=previous_config, )
@router.post( "/trigger", response_model=TriggerLearningResponse, summary="Manually trigger learning pipeline", description="Trigger the daily learning pipeline manually. " "Useful for testing or forcing immediate updates.",)async def trigger_learning( request: TriggerLearningRequest, db: AsyncSession = Depends(get_db),) -> TriggerLearningResponse: """Manually trigger learning pipeline.""" from cron.daily_learning import DailyLearningPipeline start_time = datetime.utcnow() metrics = { "episodes_processed": 0, "rewards_computed": 0, "models_updated": 0, "config_selection": None, "errors": [], } try: pipeline = DailyLearningPipeline(db) if request.process_episodes: await pipeline._process_pending_episodes() metrics["episodes_processed"] = pipeline.metrics.get("episodes_processed", 0) metrics["rewards_computed"] = pipeline.metrics.get("rewards_computed", 0) if request.select_config: await pipeline._select_todays_config() metrics["config_selection"] = pipeline.metrics.get("config_selection") if request.update_models: await pipeline._update_driver_models() metrics["models_updated"] = pipeline.metrics.get("models_updated", 0) await db.commit() return TriggerLearningResponse( status="success", episodes_processed=metrics["episodes_processed"], rewards_computed=metrics["rewards_computed"], models_updated=metrics["models_updated"], config_selection=metrics["config_selection"], duration_seconds=(datetime.utcnow() - start_time).total_seconds(), errors=metrics.get("errors", []), ) except Exception as e: return TriggerLearningResponse( status="error", duration_seconds=(datetime.utcnow() - start_time).total_seconds(), errors=[str(e)], )
@router.get( "/models", response_model=AllDriverModelsListResponse, summary="List all driver effort models",)async def list_driver_models( active_only: bool = Query(True), db: AsyncSession = Depends(get_db),) -> AllDriverModelsListResponse: """List all driver effort models.""" query = select(DriverEffortModel) if active_only: query = query.where(DriverEffortModel.active == True) query = query.order_by(DriverEffortModel.last_trained_at.desc().nullsfirst()) result = await db.execute(query) models = result.scalars().all() # Calculate stats active_count = sum(1 for m in models if m.active) mse_values = [m.current_mse for m in models if m.current_mse is not None] avg_mse = sum(mse_values) / len(mse_values) if mse_values else None return AllDriverModelsListResponse( models=[ DriverModelStatusResponse( driver_id=m.driver_id, model_version=m.model_version, training_samples=m.training_samples, current_mse=m.current_mse, r2_score=m.r2_score, mse_history=m.mse_history, active=m.active, last_trained_at=m.last_trained_at, ) for m in models ], total=len(models), active_count=active_count, avg_mse=avg_mse, )
@router.get( "/models/{driver_id}", response_model=DriverModelStatusResponse, summary="Get driver model status",)async def get_driver_model( driver_id: UUID, db: AsyncSession = Depends(get_db),) -> DriverModelStatusResponse: """Get status of a specific driver's effort model.""" result = await db.execute( select(DriverEffortModel).where(DriverEffortModel.driver_id == driver_id) ) model = result.scalar_one_or_none() if not model: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"No model found for driver {driver_id}", ) return DriverModelStatusResponse( driver_id=model.driver_id, model_version=model.model_version, training_samples=model.training_samples, current_mse=model.current_mse, r2_score=model.r2_score, mse_history=model.mse_history, active=model.active, last_trained_at=model.last_trained_at, )
@router.post( "/models/{driver_id}/retrain", response_model=DriverModelUpdateResponse, summary="Retrain a driver's model",)async def retrain_driver_model( driver_id: UUID, db: AsyncSession = Depends(get_db),) -> DriverModelUpdateResponse: """Manually trigger retraining of a driver's effort model.""" # Check driver exists result = await db.execute( select(Driver).where(Driver.id == driver_id) ) driver = result.scalar_one_or_none() if not driver: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Driver {driver_id} not found", ) agent = LearningAgent(db) result = await agent.effort_learner.update_model(driver_id) await db.commit() return DriverModelUpdateResponse( status=result.get("status", "unknown"), driver_id=driver_id, model_version=result.get("model_version"), training_samples=result.get("training_samples"), mse=result.get("mse"), r2_score=result.get("r2_score"), reason=result.get("reason"), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""Agent Events SSE Endpoint.
Provides Server-Sent Events stream for real-time agent status updatesto visualization frontends."""
from fastapi import APIRouter, Queryfrom fastapi.responses import StreamingResponsefrom typing import Optionalimport jsonimport asyncio
from app.core.events import agent_event_bus
router = APIRouter(prefix="/api/v1", tags=["agent-events"])
@router.get("/agent-events/stream")async def agent_events_stream( run_id: Optional[str] = Query(None, description="Filter by allocation run ID")): """ Server-Sent Events endpoint for agent events. Returns a continuous stream of agent events for real-time visualization. Optionally filter by allocation_run_id via query parameter. Args: run_id: Optional allocation run ID to filter events Returns: SSE stream of agent events """
async def event_generator(): # Send initial connection event init_event = { "type": "connected", "message": "SSE connection established", "filter_run_id": run_id, } yield f"data: {json.dumps(init_event)}\n\n" # Send any recent events for this run if run_id: recent = agent_event_bus.get_recent_events(allocation_run_id=run_id) for event in recent: yield f"data: {json.dumps(event)}\n\n" # Stream live events async for event in agent_event_bus.subscribe(): # Filter by run_id if specified if run_id and event.get("allocation_run_id") != run_id: continue # SSE format: "data: {...}\n\n" yield f"data: {json.dumps(event)}\n\n"
return StreamingResponse( event_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no", # Disable nginx buffering }, )
@router.get("/agent-events/recent")async def get_recent_events( run_id: Optional[str] = Query(None, description="Filter by allocation run ID"), limit: int = Query(50, ge=1, le=200, description="Maximum events to return"),): """ Get recent agent events (non-streaming). Useful for initial page load or debugging. Args: run_id: Optional allocation run ID to filter events limit: Maximum number of events to return Returns: List of recent agent events """ events = agent_event_bus.get_recent_events( allocation_run_id=run_id, limit=limit, ) return {"events": events, "count": len(events)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808"""Allocation API endpoint.Handles POST /api/v1/allocate for fair route allocation using multi-agent pipeline.
Phase 4.1: Multi-agent architecture with MLEffortAgent, RoutePlannerAgent, FairnessManagerAgent.Phase 4.2: Added Driver Liaison Agents and Final Resolution for negotiation.Phase 4.3: Added ExplainabilityAgent v2 for template-based explanations.Phase 8: Learning Agent integration for bandit-based config tuning."""
import statisticsimport uuidfrom datetime import datetime, timedeltafrom typing import Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_dbfrom app.models import Driver, Package, Route, RoutePackage, Assignmentfrom app.models.driver import PreferredLanguage, VehicleTypefrom app.models.package import PackagePriorityfrom app.models.allocation_run import AllocationRun, AllocationRunStatusfrom app.models.decision_log import DecisionLogfrom app.schemas.allocation import ( AllocationRequest, AllocationResponse, AssignmentResponse, GlobalFairness, RouteSummary,)from app.schemas.agent_schemas import ( FairnessThresholds, DriverAssignmentProposal, DriverContext, DriverLiaisonDecision,)from app.services.clustering import cluster_packages, order_stops_by_nearest_neighborfrom app.services.workload import calculate_workload, calculate_route_difficulty, estimate_route_timefrom app.services.fairness import calculate_fairness_scorefrom app.services.explainability import ExplainabilityAgent, generate_explanationfrom app.services.ml_effort_agent import MLEffortAgentfrom app.services.route_planner_agent import RoutePlannerAgentfrom app.services.fairness_manager_agent import FairnessManagerAgentfrom app.services.driver_liaison_agent import DriverLiaisonAgentfrom app.services.final_resolution import FinalResolutionAgentfrom app.models.driver import DriverStatsDaily, DriverFeedbackfrom app.models.manual_override import ManualOverridefrom app.models.fairness_config import FairnessConfigfrom app.schemas.explainability import DriverExplanationInputfrom app.services.learning_agent import LearningAgent, hash_config
router = APIRouter(prefix="/allocate", tags=["Allocation"])
@router.post( "", response_model=AllocationResponse, status_code=status.HTTP_200_OK, summary="Allocate packages to drivers", description=""" Main allocation endpoint using multi-agent pipeline: 1. Phase 0: Cluster packages into routes 2. Phase 1: ML Effort Agent builds effort matrix 3. Phase 2: Route Planner Agent generates optimal assignment (Proposal 1) 4. Phase 3: Fairness Manager evaluates; may request re-optimization (Proposal 2) 5. Persist AllocationRun, Assignments, and DecisionLog entries """,)async def allocate( request: AllocationRequest, db: AsyncSession = Depends(get_db),) -> AllocationResponse: """Perform fair route allocation using multi-agent pipeline.""" # Validate input if not request.packages: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="At least 1 package is required", ) if not request.drivers: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="At least 1 driver is required", ) # ========== START ALLOCATION RUN ========== allocation_run = AllocationRun( date=request.allocation_date, num_drivers=len(request.drivers), num_packages=len(request.packages), num_routes=0, # Updated after clustering status=AllocationRunStatus.PENDING, started_at=datetime.utcnow(), ) db.add(allocation_run) await db.flush() # Get allocation_run.id try: # ========== PHASE 0: UPSERT DATA & CLUSTERING ========== # Step 1: Upsert drivers driver_map = {} # external_id -> Driver model driver_models: List[Driver] = [] for driver_input in request.drivers: result = await db.execute( select(Driver).where(Driver.external_id == driver_input.id) ) driver = result.scalar_one_or_none() if driver: driver.name = driver_input.name driver.vehicle_capacity_kg = driver_input.vehicle_capacity_kg driver.preferred_language = PreferredLanguage(driver_input.preferred_language) else: driver = Driver( external_id=driver_input.id, name=driver_input.name, vehicle_capacity_kg=driver_input.vehicle_capacity_kg, preferred_language=PreferredLanguage(driver_input.preferred_language), vehicle_type=VehicleType.ICE, ) db.add(driver) driver_map[driver_input.id] = driver await db.flush() driver_models = list(driver_map.values()) # Step 2: Upsert packages package_map = {} package_dicts = [] for pkg_input in request.packages: result = await db.execute( select(Package).where(Package.external_id == pkg_input.id) ) package = result.scalar_one_or_none() if package: package.weight_kg = pkg_input.weight_kg package.fragility_level = pkg_input.fragility_level package.address = pkg_input.address package.latitude = pkg_input.latitude package.longitude = pkg_input.longitude package.priority = PackagePriority(pkg_input.priority) else: package = Package( external_id=pkg_input.id, weight_kg=pkg_input.weight_kg, fragility_level=pkg_input.fragility_level, address=pkg_input.address, latitude=pkg_input.latitude, longitude=pkg_input.longitude, priority=PackagePriority(pkg_input.priority), ) db.add(package) package_map[pkg_input.id] = package package_dicts.append({ "external_id": pkg_input.id, "weight_kg": pkg_input.weight_kg, "fragility_level": pkg_input.fragility_level, "address": pkg_input.address, "latitude": pkg_input.latitude, "longitude": pkg_input.longitude, "priority": pkg_input.priority, }) await db.flush() # Step 3: Cluster packages into routes clusters = cluster_packages( packages=package_dicts, num_drivers=len(request.drivers), ) # Step 4: Create routes route_models: List[Route] = [] route_dicts = [] for cluster in clusters: ordered_packages = order_stops_by_nearest_neighbor( cluster.packages, request.warehouse.lat, request.warehouse.lng, ) # Calculate total distance (Warehouse -> Stop 1 -> ... -> Stop N -> Warehouse) from app.services.clustering import haversine_distance total_dist = 0.0 curr_lat, curr_lng = request.warehouse.lat, request.warehouse.lng for p in ordered_packages: dist = haversine_distance(curr_lat, curr_lng, p["latitude"], p["longitude"]) total_dist += dist curr_lat, curr_lng = p["latitude"], p["longitude"] # Add return trip to warehouse total_dist += haversine_distance(curr_lat, curr_lng, request.warehouse.lat, request.warehouse.lng) avg_fragility = sum(p["fragility_level"] for p in cluster.packages) / max(len(cluster.packages), 1) difficulty = calculate_route_difficulty( total_weight_kg=cluster.total_weight_kg, num_stops=cluster.num_stops, avg_fragility=avg_fragility, ) est_time = estimate_route_time( num_packages=cluster.num_packages, num_stops=cluster.num_stops, ) route = Route( date=request.allocation_date, cluster_id=cluster.cluster_id, total_weight_kg=cluster.total_weight_kg, num_packages=cluster.num_packages, num_stops=cluster.num_stops, route_difficulty_score=difficulty, estimated_time_minutes=est_time, total_distance_km=total_dist, ) db.add(route) route_models.append(route) workload = calculate_workload({ "num_packages": cluster.num_packages, "total_weight_kg": cluster.total_weight_kg, "route_difficulty_score": difficulty, "estimated_time_minutes": est_time, }) route_dicts.append({ "cluster_id": cluster.cluster_id, "num_packages": cluster.num_packages, "total_weight_kg": cluster.total_weight_kg, "num_stops": cluster.num_stops, "route_difficulty_score": difficulty, "estimated_time_minutes": est_time, "workload_score": workload, "packages": ordered_packages, }) await db.flush() # Update allocation run with route count allocation_run.num_routes = len(route_models) # Create RoutePackage associations for i, route in enumerate(route_models): for stop_order, pkg_data in enumerate(route_dicts[i]["packages"]): package = package_map[pkg_data["external_id"]] route_package = RoutePackage( route_id=route.id, package_id=package.id, stop_order=stop_order + 1, ) db.add(route_package) # ========== PHASE 1: ML EFFORT AGENT ========== ml_agent = MLEffortAgent() # Get active fairness config for EV settings config_result = await db.execute( select(FairnessConfig).where(FairnessConfig.is_active == True).limit(1) ) active_config = config_result.scalar_one_or_none() ev_config = { "safety_margin_pct": active_config.ev_safety_margin_pct if active_config else 10.0, "charging_penalty_weight": active_config.ev_charging_penalty_weight if active_config else 0.3, } effort_result = ml_agent.compute_effort_matrix( drivers=driver_models, routes=route_models, ev_config=ev_config, ) # Log decision ml_log = DecisionLog( allocation_run_id=allocation_run.id, agent_name="ML_EFFORT", step_type="MATRIX_GENERATION", input_snapshot=ml_agent.get_input_snapshot(driver_models, route_models), output_snapshot={ **ml_agent.get_output_snapshot(effort_result), "num_infeasible_ev_pairs": len(effort_result.infeasible_pairs), }, ) db.add(ml_log) # ========== PHASE 1.5: RECOVERY TARGETS (Phase 7) ========== from app.services.recovery_service import get_driver_recovery_targets driver_ids = [d.id for d in driver_models] recovery_targets = await get_driver_recovery_targets( db, driver_ids, request.allocation_date, active_config ) recovery_penalty_weight = active_config.recovery_penalty_weight if active_config else 3.0 # ========== PHASE 2: ROUTE PLANNER AGENT - PROPOSAL 1 ========== planner_agent = RoutePlannerAgent() proposal1 = planner_agent.plan( effort_result=effort_result, drivers=driver_models, routes=route_models, recovery_targets=recovery_targets, recovery_penalty_weight=recovery_penalty_weight, proposal_number=1, ) # Log proposal 1 proposal1_log = DecisionLog( allocation_run_id=allocation_run.id, agent_name="ROUTE_PLANNER", step_type="PROPOSAL_1", input_snapshot=planner_agent.get_input_snapshot(effort_result), output_snapshot=planner_agent.get_output_snapshot(proposal1), ) db.add(proposal1_log) # ========== PHASE 3: FAIRNESS MANAGER AGENT ========== fairness_agent = FairnessManagerAgent( thresholds=FairnessThresholds( gini_threshold=0.33, stddev_threshold=25.0, max_gap_threshold=25.0, ) ) fairness_check1 = fairness_agent.check(proposal1, proposal_number=1) # Log fairness check 1 fairness1_log = DecisionLog( allocation_run_id=allocation_run.id, agent_name="FAIRNESS_MANAGER", step_type="FAIRNESS_CHECK_PROPOSAL_1", input_snapshot=fairness_agent.get_input_snapshot(proposal1), output_snapshot=fairness_agent.get_output_snapshot(fairness_check1), ) db.add(fairness1_log) # Determine final allocation final_plan = proposal1 final_fairness = fairness_check1 if fairness_check1.status == "REOPTIMIZE" and fairness_check1.recommendations: # Build penalties and run Proposal 2 penalties = planner_agent.build_penalties_from_recommendations( fairness_check1.recommendations, proposal1.per_driver_effort, ) proposal2 = planner_agent.plan( effort_result=effort_result, drivers=driver_models, routes=route_models, fairness_penalties=penalties, recovery_targets=recovery_targets, recovery_penalty_weight=recovery_penalty_weight, proposal_number=2, ) # Log proposal 2 proposal2_log = DecisionLog( allocation_run_id=allocation_run.id, agent_name="ROUTE_PLANNER", step_type="PROPOSAL_2", input_snapshot=planner_agent.get_input_snapshot(effort_result, penalties), output_snapshot=planner_agent.get_output_snapshot(proposal2), ) db.add(proposal2_log) # Check fairness of proposal 2 fairness_check2 = fairness_agent.check(proposal2, proposal_number=2) # Log fairness check 2 fairness2_log = DecisionLog( allocation_run_id=allocation_run.id, agent_name="FAIRNESS_MANAGER", step_type="FAIRNESS_CHECK_PROPOSAL_2", input_snapshot=fairness_agent.get_input_snapshot(proposal2), output_snapshot=fairness_agent.get_output_snapshot(fairness_check2), ) db.add(fairness2_log) # Use proposal 2 if it improves fairness if (fairness_check2.metrics.gini_index <= fairness_check1.metrics.gini_index or fairness_check2.metrics.max_gap < fairness_check1.metrics.max_gap): final_plan = proposal2 final_fairness = fairness_check2 # ========== PHASE 4: DRIVER LIAISON AGENTS (Phase 4.2) ========== # Build DriverAssignmentProposals with ranking sorted_allocations = sorted( final_plan.allocation, key=lambda x: x.effort, reverse=True # Highest effort = rank 1 ) driver_proposals: List[DriverAssignmentProposal] = [] for rank, alloc_item in enumerate(sorted_allocations, start=1): driver_proposals.append(DriverAssignmentProposal( driver_id=str(alloc_item.driver_id), route_id=str(alloc_item.route_id), effort=alloc_item.effort, rank_in_team=rank, )) # Build DriverContexts from recent stats (last 7 days) driver_contexts: Dict[str, DriverContext] = {} cutoff_date = request.allocation_date - timedelta(days=7) for driver in driver_models: driver_id_str = str(driver.id) # Query recent daily stats stats_result = await db.execute( select(DriverStatsDaily) .where(DriverStatsDaily.driver_id == driver.id) .where(DriverStatsDaily.date >= cutoff_date) .order_by(DriverStatsDaily.date.desc()) ) recent_stats = stats_result.scalars().all() if recent_stats: recent_efforts = [s.avg_workload_score for s in recent_stats if s.avg_workload_score] if recent_efforts: recent_avg = statistics.mean(recent_efforts) recent_std = statistics.stdev(recent_efforts) if len(recent_efforts) > 1 else 0.0 else: recent_avg = final_fairness.metrics.avg_effort recent_std = final_fairness.metrics.std_dev # Count hard days (above avg + std) hard_threshold = recent_avg + recent_std hard_days = sum(1 for e in recent_efforts if e > hard_threshold) else: recent_avg = final_fairness.metrics.avg_effort recent_std = final_fairness.metrics.std_dev hard_days = 0 # Get recent fatigue score from feedback feedback_result = await db.execute( select(DriverFeedback) .where(DriverFeedback.driver_id == driver.id) .order_by(DriverFeedback.created_at.desc()) .limit(1) ) recent_feedback = feedback_result.scalar_one_or_none() fatigue_score = float(recent_feedback.tiredness_level) if recent_feedback else 3.0 fatigue_score = max(1.0, min(5.0, fatigue_score)) # Clamp to 1-5 driver_contexts[driver_id_str] = DriverContext( driver_id=driver_id_str, recent_avg_effort=recent_avg, recent_std_effort=recent_std, recent_hard_days=hard_days, fatigue_score=fatigue_score, preferences={}, # TODO: Pull from driver preferences if available ) # Run Driver Liaison Agent liaison_agent = DriverLiaisonAgent() negotiation_result = liaison_agent.run_for_all_drivers( proposals=driver_proposals, driver_contexts=driver_contexts, effort_matrix=effort_result.matrix, driver_ids=effort_result.driver_ids, route_ids=effort_result.route_ids, global_avg_effort=final_fairness.metrics.avg_effort, global_std_effort=final_fairness.metrics.std_dev, ) # Log Driver Liaison decisions liaison_log = DecisionLog( allocation_run_id=allocation_run.id, agent_name="DRIVER_LIAISON", step_type="NEGOTIATION_DECISIONS", input_snapshot=liaison_agent.get_input_snapshot( driver_proposals, final_fairness.metrics.avg_effort, final_fairness.metrics.std_dev, ), output_snapshot=liaison_agent.get_output_snapshot(negotiation_result), ) db.add(liaison_log) # ========== PHASE 5: FINAL RESOLUTION (Phase 4.2) ========== # Check if any COUNTER decisions need resolution counter_decisions = [ d for d in negotiation_result.decisions if d.decision == "COUNTER" ] # Variables for final allocation final_allocation = final_plan.allocation final_per_driver_effort = final_plan.per_driver_effort if counter_decisions: # Run Final Resolution resolution_agent = FinalResolutionAgent() resolution_result = resolution_agent.resolve_counters( approved_proposal=final_plan, decisions=negotiation_result.decisions, effort_matrix=effort_result.matrix, driver_ids=effort_result.driver_ids, route_ids=effort_result.route_ids, current_metrics=final_fairness.metrics, ) # Log Final Resolution resolution_log = DecisionLog( allocation_run_id=allocation_run.id, agent_name="ROUTE_PLANNER", step_type="FINAL_RESOLUTION", input_snapshot=resolution_agent.get_input_snapshot( len(counter_decisions), final_fairness.metrics, final_fairness.metrics.avg_effort, ), output_snapshot=resolution_agent.get_output_snapshot(resolution_result), ) db.add(resolution_log) # Update final metrics with resolution result if resolution_result.swaps_applied: # Use resolved allocation final_per_driver_effort = resolution_result.per_driver_effort # Update allocation_run metrics allocation_run.global_gini_index = resolution_result.metrics.get("gini_index", final_fairness.metrics.gini_index) allocation_run.global_std_dev = resolution_result.metrics.get("std_dev", final_fairness.metrics.std_dev) allocation_run.global_max_gap = resolution_result.metrics.get("max_gap", final_fairness.metrics.max_gap) # ========== PHASE 6: EXPLAINABILITY AGENT (Phase 4.3) ========== # Build lookup for route by ID route_by_id = {str(r.id): r for r in route_models} route_dict_by_id = {} for i, r in enumerate(route_models): route_dict_by_id[str(r.id)] = route_dicts[i] driver_by_id = {str(d.id): d for d in driver_models} # Compute per-driver ranks (1=hardest) sorted_efforts = sorted( final_per_driver_effort.items(), key=lambda x: x[1], reverse=True ) rank_by_driver = {did: idx + 1 for idx, (did, _) in enumerate(sorted_efforts)} num_drivers = len(final_per_driver_effort) # Build liaison decisions lookup liaison_by_driver = {} if 'negotiation_result' in dir(): for decision in negotiation_result.decisions: liaison_by_driver[decision.driver_id] = decision # Build swaps lookup swapped_drivers = set() if 'resolution_result' in dir() and resolution_result.swaps_applied: for swap in resolution_result.swaps_applied: swapped_drivers.add(swap.driver_a) swapped_drivers.add(swap.driver_b) # Initialize ExplainabilityAgent explain_agent = ExplainabilityAgent() category_counts: Dict[str, int] = {} avg_effort = final_fairness.metrics.avg_effort assignments_response = [] for alloc_item in final_plan.allocation: driver_id_str = str(alloc_item.driver_id) driver = driver_by_id[driver_id_str] route = route_by_id[str(alloc_item.route_id)] route_dict = route_dict_by_id[str(alloc_item.route_id)] # Use resolved effort if available (after swaps), else original effort = final_per_driver_effort.get(driver_id_str, alloc_item.effort) fairness_score = calculate_fairness_score(effort, avg_effort) # Get driver context for explanation driver_context = driver_contexts.get(driver_id_str) history_efforts = [] history_hard_days = 0 if driver_context: history_efforts = [driver_context.recent_avg_effort] if driver_context.recent_avg_effort else [] history_hard_days = driver_context.recent_hard_days # Get effort breakdown from ML agent breakdown_key = f"{driver_id_str}:{alloc_item.route_id}" effort_breakdown_obj = effort_result.breakdown.get(breakdown_key) effort_breakdown = {} if effort_breakdown_obj: effort_breakdown = { "physical_effort": effort_breakdown_obj.physical_effort, "route_complexity": effort_breakdown_obj.route_complexity, "time_pressure": effort_breakdown_obj.time_pressure, } # Get liaison decision liaison_decision = liaison_by_driver.get(driver_id_str) # Check for manual override had_override = False try: override_result = await db.execute( select(ManualOverride) .where(ManualOverride.allocation_run_id == allocation_run.id) .where(ManualOverride.new_driver_id == driver.id) .limit(1) ) had_override = override_result.scalar_one_or_none() is not None except Exception: pass # ManualOverride may not exist yet # Determine if recovery day is_recovery = ( history_hard_days >= 3 and effort < avg_effort * 0.85 ) # Build explanation input explain_input = DriverExplanationInput( driver_id=driver_id_str, driver_name=driver.name, num_drivers=num_drivers, today_effort=effort, today_rank=rank_by_driver.get(driver_id_str, num_drivers), route_id=str(alloc_item.route_id), route_summary={ "num_packages": route.num_packages, "total_weight_kg": route.total_weight_kg, "num_stops": route.num_stops, "difficulty_score": route.route_difficulty_score, "estimated_time_minutes": route.estimated_time_minutes, }, effort_breakdown=effort_breakdown, global_avg_effort=avg_effort, global_std_effort=final_fairness.metrics.std_dev, global_gini_index=final_fairness.metrics.gini_index, global_max_gap=final_fairness.metrics.max_gap, history_efforts_last_7_days=history_efforts, history_hard_days_last_7=history_hard_days, is_recovery_day=is_recovery, had_manual_override=had_override, liaison_decision=liaison_decision.decision if liaison_decision else None, swap_applied=driver_id_str in swapped_drivers, ) # Generate explanations explain_output = explain_agent.build_explanation_for_driver(explain_input) # Track category counts category_counts[explain_output.category] = category_counts.get(explain_output.category, 0) + 1 # Create assignment with both explanations assignment = Assignment( date=request.allocation_date, driver_id=driver.id, route_id=route.id, workload_score=effort, fairness_score=fairness_score, explanation=explain_output.driver_explanation, # Legacy field driver_explanation=explain_output.driver_explanation, admin_explanation=explain_output.admin_explanation, allocation_run_id=allocation_run.id, ) db.add(assignment) # Build response assignments_response.append(AssignmentResponse( driver_id=driver.id, driver_external_id=driver.external_id, driver_name=driver.name, route_id=route.id, workload_score=effort, fairness_score=fairness_score, route_summary=RouteSummary( num_packages=route.num_packages, total_weight_kg=route.total_weight_kg, num_stops=route.num_stops, route_difficulty_score=route.route_difficulty_score, estimated_time_minutes=route.estimated_time_minutes, ), explanation=explain_output.driver_explanation, )) # Log ExplainabilityAgent step explain_log = DecisionLog( allocation_run_id=allocation_run.id, agent_name="EXPLAINABILITY", step_type="EXPLANATIONS_GENERATED", input_snapshot=explain_agent.get_input_snapshot( num_drivers=num_drivers, avg_effort=avg_effort, std_effort=final_fairness.metrics.std_dev, gini_index=final_fairness.metrics.gini_index, category_counts=category_counts, ), output_snapshot=explain_agent.get_output_snapshot( total_explanations=len(assignments_response), category_counts=category_counts, ), ) db.add(explain_log) # ========== PHASE 7: UPDATE DAILY STATS (Phase 7) ========== from app.services.recovery_service import update_daily_stats_for_run await update_daily_stats_for_run( db=db, allocation_run_id=allocation_run.id, target_date=request.allocation_date, config=active_config, ) # ========== PHASE 8: CREATE LEARNING EPISODE ========== # Create a learning episode for bandit feedback (reward computed later by cron) try: learning_agent = LearningAgent(db) # Build config snapshot for the episode config_snapshot = {} if active_config: config_snapshot = { "gini_threshold": active_config.gini_threshold, "stddev_threshold": active_config.stddev_threshold, "recovery_lightening_factor": active_config.recovery_lightening_factor, "ev_charging_penalty_weight": active_config.ev_charging_penalty_weight, "max_gap_threshold": active_config.max_gap_threshold, } # Determine if this is experimental (10% of runs) import random is_experimental = random.random() < 0.10 await learning_agent.create_episode( allocation_run_id=allocation_run.id, fairness_config=config_snapshot, num_drivers=len(driver_models), num_routes=len(route_models), is_experimental=is_experimental, ) # Log learning episode creation learning_log = DecisionLog( allocation_run_id=allocation_run.id, agent_name="LEARNING", step_type="EPISODE_CREATED", input_snapshot={ "config_hash": hash_config(config_snapshot), "is_experimental": is_experimental, }, output_snapshot={ "status": "pending_reward", }, ) db.add(learning_log) except Exception as learning_error: # Learning is non-critical, log but don't fail allocation import logging logging.warning(f"Failed to create learning episode: {learning_error}") # ========== FINALIZE ALLOCATION RUN ========== allocation_run.global_gini_index = final_fairness.metrics.gini_index allocation_run.global_std_dev = final_fairness.metrics.std_dev allocation_run.global_max_gap = final_fairness.metrics.max_gap allocation_run.status = AllocationRunStatus.SUCCESS allocation_run.finished_at = datetime.utcnow() await db.commit() return AllocationResponse( allocation_run_id=allocation_run.id, allocation_date=request.allocation_date, global_fairness=GlobalFairness( avg_workload=final_fairness.metrics.avg_effort, std_dev=final_fairness.metrics.std_dev, gini_index=final_fairness.metrics.gini_index, ), assignments=assignments_response, ) except Exception as e: # Mark allocation run as failed allocation_run.status = AllocationRunStatus.FAILED allocation_run.error_message = str(e)[:500] allocation_run.finished_at = datetime.utcnow() await db.commit() raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail={ "message": "Allocation failed", "run_id": str(allocation_run.id), "error": str(e)[:200], }, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513"""LangGraph-enabled Allocation API endpoint.Wraps the existing allocation logic with LangGraph orchestration."""
import osimport statisticsimport uuidfrom datetime import datetime, timedeltafrom typing import Dict, List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Queryfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_dbfrom app.models import Driver, Package, Route, RoutePackage, Assignmentfrom app.models.driver import PreferredLanguage, VehicleTypefrom app.models.package import PackagePriorityfrom app.models.allocation_run import AllocationRun, AllocationRunStatusfrom app.models.decision_log import DecisionLogfrom app.models.driver import DriverStatsDaily, DriverFeedbackfrom app.models.fairness_config import FairnessConfigfrom app.schemas.allocation import ( AllocationRequest, AllocationResponse, AssignmentResponse, GlobalFairness, RouteSummary,)from app.services.clustering import cluster_packages, order_stops_by_nearest_neighbor, haversine_distancefrom app.services.workload import calculate_workload, calculate_route_difficulty, estimate_route_timefrom app.services.fairness import calculate_fairness_scorefrom app.services.learning_agent import LearningAgent, hash_configfrom app.schemas.allocation_state import AllocationStatefrom app.services.langgraph_workflow import invoke_allocation_workflow
router = APIRouter(prefix="/allocate", tags=["Allocation"])
@router.post( "/langgraph", response_model=AllocationResponse, status_code=status.HTTP_200_OK, summary="Allocate packages to drivers (LangGraph)", description=""" LangGraph-enabled allocation endpoint using multi-agent workflow: 1. ML Effort Agent builds effort matrix 2. Route Planner Agent generates optimal assignment 3. Fairness Manager evaluates; may trigger re-optimization 4. Driver Liaison Agent negotiates per-driver 5. Final Resolution resolves counter-proposals 6. Explainability Agent generates explanations 7. (Optional) Gemini 1.5 Flash for personalized explanations Uses LangGraph StateGraph for orchestration with LangSmith tracing. """,)async def allocate_langgraph( request: AllocationRequest, db: AsyncSession = Depends(get_db), enable_gemini: bool = Query(False, description="Enable Gemini 1.5 Flash explanations"),) -> AllocationResponse: """Perform fair route allocation using LangGraph workflow.""" # Validate input if not request.packages: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="At least 1 package is required", ) if not request.drivers: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="At least 1 driver is required", ) allocation_date = request.allocation_date # ========== START ALLOCATION RUN ========== allocation_run = AllocationRun( date=allocation_date, num_drivers=len(request.drivers), num_packages=len(request.packages), num_routes=0, status=AllocationRunStatus.PENDING, started_at=datetime.utcnow(), ) db.add(allocation_run) await db.flush() try: # ========== PHASE 0: UPSERT DATA & CLUSTERING ========== # (Same as original - this is DB-dependent and must stay in endpoint) # Step 1: Upsert drivers driver_map = {} driver_models: List[Driver] = [] for driver_input in request.drivers: result = await db.execute( select(Driver).where(Driver.external_id == driver_input.id) ) driver = result.scalar_one_or_none() if driver: driver.name = driver_input.name driver.vehicle_capacity_kg = driver_input.vehicle_capacity_kg driver.preferred_language = PreferredLanguage(driver_input.preferred_language) else: driver = Driver( external_id=driver_input.id, name=driver_input.name, vehicle_capacity_kg=driver_input.vehicle_capacity_kg, preferred_language=PreferredLanguage(driver_input.preferred_language), vehicle_type=VehicleType.ICE, ) db.add(driver) driver_map[driver_input.id] = driver await db.flush() driver_models = list(driver_map.values()) # Step 2: Upsert packages package_map = {} package_dicts = [] for pkg_input in request.packages: result = await db.execute( select(Package).where(Package.external_id == pkg_input.id) ) package = result.scalar_one_or_none() if package: package.weight_kg = pkg_input.weight_kg package.fragility_level = pkg_input.fragility_level package.address = pkg_input.address package.latitude = pkg_input.latitude package.longitude = pkg_input.longitude package.priority = PackagePriority(pkg_input.priority) else: package = Package( external_id=pkg_input.id, weight_kg=pkg_input.weight_kg, fragility_level=pkg_input.fragility_level, address=pkg_input.address, latitude=pkg_input.latitude, longitude=pkg_input.longitude, priority=PackagePriority(pkg_input.priority), ) db.add(package) package_map[pkg_input.id] = package package_dicts.append({ "external_id": pkg_input.id, "weight_kg": pkg_input.weight_kg, "fragility_level": pkg_input.fragility_level, "address": pkg_input.address, "latitude": pkg_input.latitude, "longitude": pkg_input.longitude, "priority": pkg_input.priority, }) await db.flush() # Step 3: Cluster packages into routes clusters = cluster_packages( packages=package_dicts, num_drivers=len(request.drivers), ) # Step 4: Create routes route_models: List[Route] = [] route_dicts = [] for cluster in clusters: ordered_packages = order_stops_by_nearest_neighbor( cluster.packages, request.warehouse.lat, request.warehouse.lng, ) # Calculate total distance total_dist = 0.0 curr_lat, curr_lng = request.warehouse.lat, request.warehouse.lng for p in ordered_packages: dist = haversine_distance(curr_lat, curr_lng, p["latitude"], p["longitude"]) total_dist += dist curr_lat, curr_lng = p["latitude"], p["longitude"] total_dist += haversine_distance(curr_lat, curr_lng, request.warehouse.lat, request.warehouse.lng) avg_fragility = sum(p["fragility_level"] for p in cluster.packages) / max(len(cluster.packages), 1) difficulty = calculate_route_difficulty( total_weight_kg=cluster.total_weight_kg, num_stops=cluster.num_stops, avg_fragility=avg_fragility, ) est_time = estimate_route_time( num_packages=cluster.num_packages, num_stops=cluster.num_stops, ) route = Route( date=allocation_date, cluster_id=cluster.cluster_id, total_weight_kg=cluster.total_weight_kg, num_packages=cluster.num_packages, num_stops=cluster.num_stops, route_difficulty_score=difficulty, estimated_time_minutes=est_time, total_distance_km=total_dist, allocation_run_id=allocation_run.id, ) db.add(route) route_models.append(route) workload = calculate_workload({ "num_packages": cluster.num_packages, "total_weight_kg": cluster.total_weight_kg, "route_difficulty_score": difficulty, "estimated_time_minutes": est_time, }) route_dicts.append({ "cluster_id": cluster.cluster_id, "num_packages": cluster.num_packages, "total_weight_kg": cluster.total_weight_kg, "num_stops": cluster.num_stops, "route_difficulty_score": difficulty, "estimated_time_minutes": est_time, "workload_score": workload, "packages": ordered_packages, }) await db.flush() allocation_run.num_routes = len(route_models) # Create RoutePackage associations for i, route in enumerate(route_models): for stop_order, pkg_data in enumerate(route_dicts[i]["packages"]): package = package_map[pkg_data["external_id"]] route_package = RoutePackage( route_id=route.id, package_id=package.id, stop_order=stop_order + 1, ) db.add(route_package) # ========== GET CONFIG ========== config_result = await db.execute( select(FairnessConfig).where(FairnessConfig.is_active == True).limit(1) ) active_config = config_result.scalar_one_or_none() config_used = {} if active_config: config_used = { "gini_threshold": active_config.gini_threshold, "stddev_threshold": active_config.stddev_threshold, "max_gap_threshold": active_config.max_gap_threshold, "ev_safety_margin_pct": active_config.ev_safety_margin_pct, "ev_charging_penalty_weight": active_config.ev_charging_penalty_weight, "recovery_penalty_weight": active_config.recovery_penalty_weight, "recovery_lightening_factor": active_config.recovery_lightening_factor, } # ========== GET RECOVERY TARGETS ========== from app.services.recovery_service import get_driver_recovery_targets driver_ids = [d.id for d in driver_models] recovery_targets = await get_driver_recovery_targets( db, driver_ids, allocation_date, active_config ) recovery_targets_str = {str(k): v for k, v in recovery_targets.items()} # ========== BUILD DRIVER CONTEXTS ========== driver_contexts: Dict[str, dict] = {} cutoff_date = allocation_date - timedelta(days=7) for driver in driver_models: driver_id_str = str(driver.id) stats_result = await db.execute( select(DriverStatsDaily) .where(DriverStatsDaily.driver_id == driver.id) .where(DriverStatsDaily.date >= cutoff_date) .order_by(DriverStatsDaily.date.desc()) ) recent_stats = stats_result.scalars().all() if recent_stats: recent_efforts = [s.avg_workload_score for s in recent_stats if s.avg_workload_score] if recent_efforts: recent_avg = statistics.mean(recent_efforts) recent_std = statistics.stdev(recent_efforts) if len(recent_efforts) > 1 else 0.0 else: recent_avg = 60.0 recent_std = 15.0 hard_threshold = recent_avg + recent_std hard_days = sum(1 for e in recent_efforts if e > hard_threshold) else: recent_avg = 60.0 recent_std = 15.0 hard_days = 0 feedback_result = await db.execute( select(DriverFeedback) .where(DriverFeedback.driver_id == driver.id) .order_by(DriverFeedback.created_at.desc()) .limit(1) ) recent_feedback = feedback_result.scalar_one_or_none() fatigue_score = float(recent_feedback.tiredness_level) if recent_feedback else 3.0 fatigue_score = max(1.0, min(5.0, fatigue_score)) driver_contexts[driver_id_str] = { "driver_id": driver_id_str, "recent_avg_effort": recent_avg, "recent_std_effort": recent_std, "recent_hard_days": hard_days, "fatigue_score": fatigue_score, "preferences": {}, } # ========== SERIALIZE MODELS FOR LANGGRAPH ========== driver_model_dicts = [] for d in driver_models: driver_model_dicts.append({ "id": str(d.id), "external_id": d.external_id, "name": d.name, "vehicle_capacity_kg": d.vehicle_capacity_kg, "preferred_language": d.preferred_language.value if hasattr(d.preferred_language, 'value') else d.preferred_language, "vehicle_type": d.vehicle_type.value if hasattr(d.vehicle_type, 'value') else str(d.vehicle_type), "battery_range_km": getattr(d, 'battery_range_km', None), "charging_time_minutes": getattr(d, 'charging_time_minutes', None), "is_ev": d.vehicle_type.value == "EV" if hasattr(d.vehicle_type, 'value') else str(d.vehicle_type) == "EV", "experience_years": getattr(d, 'experience_years', 2), }) route_model_dicts = [] for r in route_models: route_model_dicts.append({ "id": str(r.id), "date": str(r.date), "cluster_id": r.cluster_id, "total_weight_kg": r.total_weight_kg, "num_packages": r.num_packages, "num_stops": r.num_stops, "route_difficulty_score": r.route_difficulty_score, "estimated_time_minutes": r.estimated_time_minutes, "total_distance_km": r.total_distance_km, }) # Add route IDs to route_dicts for i, rd in enumerate(route_dicts): rd["id"] = str(route_models[i].id) # ========== INVOKE LANGGRAPH WORKFLOW ========== if enable_gemini: os.environ["ENABLE_GEMINI_EXPLAIN"] = "true" workflow_result = await invoke_allocation_workflow( request_dict=request.model_dump(mode="json"), config_used=config_used, driver_models=driver_model_dicts, route_models=route_model_dicts, route_dicts=route_dicts, driver_contexts=driver_contexts, recovery_targets=recovery_targets_str, allocation_run_id=str(allocation_run.id), thread_id=str(allocation_run.id), ) # ========== PERSIST DECISION LOGS ========== for log_entry in workflow_result.decision_logs: decision_log = DecisionLog( allocation_run_id=allocation_run.id, agent_name=log_entry["agent_name"], step_type=log_entry["step_type"], input_snapshot=log_entry.get("input_snapshot", {}), output_snapshot=log_entry.get("output_snapshot", {}), ) db.add(decision_log) # ========== CREATE ASSIGNMENTS ========== final_proposal = workflow_result.final_proposal or workflow_result.route_proposal_1 final_fairness = workflow_result.final_fairness or workflow_result.fairness_check_1 final_per_driver_effort = workflow_result.final_per_driver_effort or final_proposal["per_driver_effort"] driver_by_id = {str(d.id): d for d in driver_models} route_by_id = {str(r.id): r for r in route_models} assignments_response = [] for alloc_item in final_proposal["allocation"]: driver_id_str = str(alloc_item["driver_id"]) route_id_str = str(alloc_item["route_id"]) driver = driver_by_id.get(driver_id_str) route = route_by_id.get(route_id_str) if not driver or not route: continue effort = final_per_driver_effort.get(driver_id_str, alloc_item["effort"]) avg_effort = final_fairness["metrics"]["avg_effort"] fairness_score = calculate_fairness_score(effort, avg_effort) explanation_data = workflow_result.explanations.get(driver_id_str, {}) driver_explanation = explanation_data.get("driver_explanation", "Route assigned.") admin_explanation = explanation_data.get("admin_explanation", "") assignment = Assignment( date=allocation_date, driver_id=driver.id, route_id=route.id, workload_score=effort, fairness_score=fairness_score, explanation=driver_explanation, driver_explanation=driver_explanation, admin_explanation=admin_explanation, allocation_run_id=allocation_run.id, ) db.add(assignment) assignments_response.append(AssignmentResponse( driver_id=driver.id, driver_external_id=driver.external_id, driver_name=driver.name, route_id=route.id, workload_score=effort, fairness_score=fairness_score, route_summary=RouteSummary( num_packages=route.num_packages, total_weight_kg=route.total_weight_kg, num_stops=route.num_stops, route_difficulty_score=route.route_difficulty_score, estimated_time_minutes=route.estimated_time_minutes, ), explanation=driver_explanation, )) # ========== UPDATE DAILY STATS ========== from app.services.recovery_service import update_daily_stats_for_run await update_daily_stats_for_run( db=db, allocation_run_id=allocation_run.id, target_date=allocation_date, config=active_config, ) # ========== CREATE LEARNING EPISODE ========== try: learning_agent = LearningAgent(db) import random is_experimental = random.random() < 0.10 await learning_agent.create_episode( allocation_run_id=allocation_run.id, fairness_config=config_used, num_drivers=len(driver_models), num_routes=len(route_models), is_experimental=is_experimental, ) except Exception as learning_error: import logging logging.warning(f"Failed to create learning episode: {learning_error}") # ========== FINALIZE ========== metrics = final_fairness["metrics"] allocation_run.global_gini_index = metrics["gini_index"] allocation_run.global_std_dev = metrics["std_dev"] allocation_run.global_max_gap = metrics["max_gap"] allocation_run.status = AllocationRunStatus.SUCCESS allocation_run.finished_at = datetime.utcnow() await db.commit() return AllocationResponse( allocation_run_id=allocation_run.id, allocation_date=allocation_date, global_fairness=GlobalFairness( avg_workload=metrics["avg_effort"], std_dev=metrics["std_dev"], gini_index=metrics["gini_index"], ), assignments=assignments_response, ) except Exception as e: allocation_run.status = AllocationRunStatus.FAILED allocation_run.error_message = str(e)[:500] allocation_run.finished_at = datetime.utcnow() await db.commit() raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail={ "message": "LangGraph allocation failed", "run_id": str(allocation_run.id), "error": str(e)[:200], }, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""API endpoints for AI Load Consolidation.
POST /consolidate — Run consolidation (LangGraph multi-agent pipeline)POST /consolidate/sync — Run consolidation (synchronous fallback)POST /consolidate/simulate — Compare multiple scenarios"""
from typing import Listfrom uuid import uuid4
from fastapi import APIRouter, HTTPException
from app.schemas.consolidation import ( ConsolidationRequest, SimulationRequest, ConsolidationResult,)from app.services.consolidation_engine import run_consolidation_pipeline
router = APIRouter(prefix="/consolidate", tags=["Consolidation"])
@router.post("", response_model=ConsolidationResult)async def consolidate(req: ConsolidationRequest): """ Run AI Load Consolidation through the 5-agent LangGraph pipeline.
Agents executed in order: 1. GeoClusteringAgent — geographic proximity clustering 2. TimeWindowAgent — time-window compatibility filtering 3. CapacityOptimizationAgent — FFD bin-packing 4. ScoringConfidenceAgent — AI confidence + optimization score 5. ContinuousLearningAgent — actionable insights """ if not req.shipments: raise HTTPException(400, "shipments array must not be empty") if not req.trucks: raise HTTPException(400, "trucks array must not be empty")
shipments = [s.model_dump() for s in req.shipments] trucks = [t.model_dump() for t in req.trucks] options = req.options.model_dump()
try: from app.services.consolidation_workflow import invoke_consolidation_workflow result = await invoke_consolidation_workflow( shipments=shipments, trucks=trucks, options=options, thread_id=str(uuid4()), ) except Exception as e: # Fallback to synchronous pipeline if LangGraph fails print(f"LangGraph consolidation failed ({e}), using sync pipeline") result = run_consolidation_pipeline(shipments, trucks, options)
return ConsolidationResult(**result)
@router.post("/sync", response_model=ConsolidationResult)async def consolidate_sync(req: ConsolidationRequest): """ Run consolidation using the synchronous multi-agent pipeline (no LangGraph). Useful for environments without LangGraph installed. """ if not req.shipments: raise HTTPException(400, "shipments array must not be empty") if not req.trucks: raise HTTPException(400, "trucks array must not be empty")
shipments = [s.model_dump() for s in req.shipments] trucks = [t.model_dump() for t in req.trucks] options = req.options.model_dump()
result = run_consolidation_pipeline(shipments, trucks, options) return ConsolidationResult(**result)
@router.post("/simulate")async def simulate_scenarios(req: SimulationRequest): """ Compare multiple consolidation strategies side-by-side. Returns results for each scenario and a recommendation. """ if not req.shipments or not req.trucks: raise HTTPException(400, "shipments and trucks arrays required") if not req.scenarios: raise HTTPException(400, "at least one scenario required")
shipments = [s.model_dump() for s in req.shipments] trucks = [t.model_dump() for t in req.trucks]
results = [] for sc in req.scenarios: opts = { "maxGroupRadiusKm": sc.maxGroupRadiusKm, "timeWindowToleranceMinutes": sc.timeWindowToleranceMinutes, "scenarioName": sc.name, } r = run_consolidation_pipeline(shipments, trucks, opts) results.append({"name": sc.name, **r})
best = max(results, key=lambda r: r["metrics"]["optimizationScore"])
return { "scenarios": results, "recommendation": best["name"], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175"""Phase 2 Driver-facing API endpoints.Handles driver operations: assignments, stats, deliveries, feedback, swaps, issues."""
from datetime import date as date_type
from fastapi import APIRouter, Depends, HTTPException, Query, statusfrom sqlalchemy.ext.asyncio import AsyncSessionfrom uuid import UUID
from app.database import get_dbfrom app.schemas.driver_api import ( TodayAssignmentResponse, DriverStatsWindowResponse, DeliveryLogRequest, DeliveryLogResponse, RouteSwapRequestCreate, RouteSwapRequestResponse, StopIssueRequest, StopIssueResponse,)from app.services.driver_service import ( get_today_assignment, get_driver_stats, log_delivery, create_route_swap_request, create_stop_issue,)
router = APIRouter(tags=["Driver"])
@router.get( "/assignments/today", response_model=TodayAssignmentResponse, summary="Get today's assignment", description="Fetch the driver's assignment for the given date with full stop details.",)async def get_assignment_today( driver_id: UUID = Query(..., description="Driver UUID"), target_date: date_type = Query(default=None, description="Date (defaults to today)"), db: AsyncSession = Depends(get_db),) -> TodayAssignmentResponse: """Get driver's assignment for today or specified date.""" actual_date = target_date or date_type.today() result = await get_today_assignment(db, driver_id, actual_date) if not result: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="No assignment found for driver on given date", ) return result
@router.get( "/drivers/{driver_id}/stats", response_model=DriverStatsWindowResponse, summary="Get driver stats", description="Get driver statistics over a time window.",)async def get_driver_stats_endpoint( driver_id: UUID, window_days: int = Query(default=7, ge=1, le=90, description="Days to look back"), db: AsyncSession = Depends(get_db),) -> DriverStatsWindowResponse: """Get driver stats over time window.""" result = await get_driver_stats(db, driver_id, window_days) if not result: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Driver not found", ) return result
@router.post( "/deliveries/log", response_model=DeliveryLogResponse, status_code=status.HTTP_201_CREATED, summary="Log delivery", description="Log a delivery attempt at a stop.",)async def log_delivery_endpoint( request: DeliveryLogRequest, db: AsyncSession = Depends(get_db),) -> DeliveryLogResponse: """Log a delivery at a stop.""" try: result = await log_delivery( db=db, assignment_id=request.assignment_id, route_id=request.route_id, driver_id=request.driver_id, stop_order=request.stop_order, status=request.status, issue_type=request.issue_type, package_id=request.package_id, photo_url=request.photo_url, signature_data=request.signature_data, notes=request.notes, ) await db.commit() return result except ValueError as e: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(e), )
@router.post( "/route_swap_requests", response_model=RouteSwapRequestResponse, status_code=status.HTTP_201_CREATED, summary="Request route swap", description="Submit a route swap request.",)async def create_route_swap_endpoint( request: RouteSwapRequestCreate, db: AsyncSession = Depends(get_db),) -> RouteSwapRequestResponse: """Create a route swap request.""" try: result = await create_route_swap_request( db=db, from_driver_id=request.from_driver_id, assignment_id=request.assignment_id, reason=request.reason, to_driver_id=request.to_driver_id, preferred_date=request.preferred_date, ) await db.commit() return result except ValueError as e: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(e), )
@router.post( "/stop_issues", response_model=StopIssueResponse, status_code=status.HTTP_201_CREATED, summary="Report stop issue", description="Report an issue at a specific stop.",)async def create_stop_issue_endpoint( request: StopIssueRequest, db: AsyncSession = Depends(get_db),) -> StopIssueResponse: """Create a stop issue report.""" try: result = await create_stop_issue( db=db, assignment_id=request.assignment_id, route_id=request.route_id, driver_id=request.driver_id, stop_order=request.stop_order, issue_type=request.issue_type, notes=request.notes, ) await db.commit() return result except ValueError as e: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=str(e), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""Drivers API endpoint.Handles GET /api/v1/drivers/{id} for driver details."""
from datetime import date, timedeltafrom uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import selectinload
from app.database import get_dbfrom app.models import Driver, DriverStatsDailyfrom app.schemas.driver import DriverResponse, DriverStatsResponse
router = APIRouter(prefix="/drivers", tags=["Drivers"])
@router.get( "/{driver_id}", response_model=DriverResponse, summary="Get driver details", description="Returns driver details including recent fairness statistics (last 7 days).",)async def get_driver( driver_id: UUID, db: AsyncSession = Depends(get_db),) -> DriverResponse: """Get driver details by ID.""" # Fetch driver with recent stats result = await db.execute( select(Driver) .where(Driver.id == driver_id) .options(selectinload(Driver.daily_stats)) ) driver = result.scalar_one_or_none() if not driver: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Driver with ID {driver_id} not found", ) # Get stats for last 7 days seven_days_ago = date.today() - timedelta(days=7) recent_stats = [ DriverStatsResponse( date=stat.date, avg_workload_score=stat.avg_workload_score, total_routes=stat.total_routes, gini_contribution=stat.gini_contribution, reported_stress_level=stat.reported_stress_level, reported_fairness_score=stat.reported_fairness_score, ) for stat in driver.daily_stats if stat.date >= seven_days_ago ] # Sort by date descending recent_stats.sort(key=lambda x: x.date, reverse=True) return DriverResponse( id=driver.id, external_id=driver.external_id, name=driver.name, phone=driver.phone, whatsapp_number=driver.whatsapp_number, preferred_language=driver.preferred_language.value, vehicle_type=driver.vehicle_type.value, vehicle_capacity_kg=driver.vehicle_capacity_kg, license_number=driver.license_number, created_at=driver.created_at, updated_at=driver.updated_at, recent_stats=recent_stats, )
@router.get( "/external/{external_id}", response_model=DriverResponse, summary="Get driver by external ID", description="Returns driver details by external ID (from integration system).",)async def get_driver_by_external_id( external_id: str, db: AsyncSession = Depends(get_db),) -> DriverResponse: """Get driver details by external ID.""" result = await db.execute( select(Driver) .where(Driver.external_id == external_id) .options(selectinload(Driver.daily_stats)) ) driver = result.scalar_one_or_none() if not driver: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Driver with external ID {external_id} not found", ) # Get stats for last 7 days seven_days_ago = date.today() - timedelta(days=7) recent_stats = [ DriverStatsResponse( date=stat.date, avg_workload_score=stat.avg_workload_score, total_routes=stat.total_routes, gini_contribution=stat.gini_contribution, reported_stress_level=stat.reported_stress_level, reported_fairness_score=stat.reported_fairness_score, ) for stat in driver.daily_stats if stat.date >= seven_days_ago ] recent_stats.sort(key=lambda x: x.date, reverse=True) return DriverResponse( id=driver.id, external_id=driver.external_id, name=driver.name, phone=driver.phone, whatsapp_number=driver.whatsapp_number, preferred_language=driver.preferred_language.value, vehicle_type=driver.vehicle_type.value, vehicle_capacity_kg=driver.vehicle_capacity_kg, license_number=driver.license_number, created_at=driver.created_at, updated_at=driver.updated_at, recent_stats=recent_stats, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Feedback API endpoint.Handles POST /api/v1/feedback for driver feedback submission."""
from fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_dbfrom app.models import Driver, Assignment, DriverFeedbackfrom app.models.driver import HardestAspectfrom app.schemas.feedback import FeedbackRequest, FeedbackResponse
router = APIRouter(prefix="/feedback", tags=["Feedback"])
@router.post( "", response_model=FeedbackResponse, status_code=status.HTTP_201_CREATED, summary="Submit driver feedback", description="Allows drivers to submit feedback about their assignment.",)async def submit_feedback( request: FeedbackRequest, db: AsyncSession = Depends(get_db),) -> FeedbackResponse: """Submit driver feedback for an assignment.""" # Verify driver exists result = await db.execute( select(Driver).where(Driver.id == request.driver_id) ) driver = result.scalar_one_or_none() if not driver: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Driver with ID {request.driver_id} not found", ) # Verify assignment exists and belongs to driver result = await db.execute( select(Assignment).where(Assignment.id == request.assignment_id) ) assignment = result.scalar_one_or_none() if not assignment: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Assignment with ID {request.assignment_id} not found", ) if assignment.driver_id != request.driver_id: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Assignment does not belong to the specified driver", ) # Check for duplicate feedback result = await db.execute( select(DriverFeedback) .where(DriverFeedback.driver_id == request.driver_id) .where(DriverFeedback.assignment_id == request.assignment_id) ) existing_feedback = result.scalar_one_or_none() if existing_feedback: raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail="Feedback already submitted for this assignment", ) # Create feedback hardest_aspect = None if request.hardest_aspect: try: hardest_aspect = HardestAspect(request.hardest_aspect) except ValueError: hardest_aspect = HardestAspect.OTHER feedback = DriverFeedback( driver_id=request.driver_id, assignment_id=request.assignment_id, fairness_rating=request.fairness_rating, stress_level=request.stress_level, tiredness_level=request.tiredness_level, hardest_aspect=hardest_aspect, comments=request.comments, ) db.add(feedback) await db.commit() await db.refresh(feedback) return FeedbackResponse( id=feedback.id, driver_id=feedback.driver_id, assignment_id=feedback.assignment_id, fairness_rating=feedback.fairness_rating, stress_level=feedback.stress_level, tiredness_level=feedback.tiredness_level, hardest_aspect=feedback.hardest_aspect.value if feedback.hardest_aspect else None, comments=feedback.comments, created_at=feedback.created_at, message="Feedback submitted successfully", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""Routes API endpoint.Handles GET /api/v1/routes/{id} for route details."""
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import selectinload
from app.database import get_dbfrom app.models import Route, Assignment, Driver, RoutePackagefrom app.schemas.route import RouteResponse, RouteAssignmentInfo, RouteStopInfo
router = APIRouter(prefix="/routes", tags=["Routes"])
@router.get( "/{route_id}", response_model=RouteResponse, summary="Get route details", description="Returns route details including assignment information and stops.",)async def get_route( route_id: UUID, db: AsyncSession = Depends(get_db),) -> RouteResponse: """Get route details by ID.""" # Fetch route with assignments and packages result = await db.execute( select(Route) .where(Route.id == route_id) .options( selectinload(Route.assignments).selectinload(Assignment.driver), selectinload(Route.route_packages).selectinload(RoutePackage.package) ) ) route = result.scalar_one_or_none() if not route: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Route with ID {route_id} not found", ) # Get assignment info if exists assignment_info = None if route.assignments: # Get the most recent assignment assignment = max(route.assignments, key=lambda a: a.created_at) assignment_info = RouteAssignmentInfo( assignment_id=assignment.id, driver_id=assignment.driver_id, driver_name=assignment.driver.name if assignment.driver else "Unknown", workload_score=assignment.workload_score, fairness_score=assignment.fairness_score, explanation=assignment.explanation, ) # Get stops info stops = [] if route.route_packages: # Sort by stop order sorted_packages = sorted(route.route_packages, key=lambda rp: rp.stop_order) for rp in sorted_packages: if rp.package: stops.append(RouteStopInfo( package_id=rp.package.id, stop_order=rp.stop_order, address=rp.package.address, latitude=rp.package.latitude, longitude=rp.package.longitude, weight_kg=rp.package.weight_kg, priority=rp.package.priority.value if hasattr(rp.package.priority, 'value') else str(rp.package.priority), fragility_level=rp.package.fragility_level )) return RouteResponse( id=route.id, date=route.date, cluster_id=route.cluster_id, total_weight_kg=route.total_weight_kg, num_packages=route.num_packages, num_stops=route.num_stops, route_difficulty_score=route.route_difficulty_score, estimated_time_minutes=route.estimated_time_minutes, created_at=route.created_at, assignment=assignment_info, stops=stops, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251"""Run-scoped API endpoints.Provides endpoints for fetching data specific to an allocation run."""
import jsonimport uuidfrom datetime import datetimefrom typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, statusfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModelfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_dbfrom app.models import Route, RoutePackage, Package, Assignment, Driverfrom app.models.allocation_run import AllocationRun, AllocationRunStatusfrom app.core.events import agent_event_bus
router = APIRouter(prefix="/runs", tags=["Runs"])
# =============================================================================# Pydantic Schemas# =============================================================================
class StopInfo(BaseModel): """Stop information for map display.""" lat: float lng: float package_id: str stop_order: int address: Optional[str] = None
class RouteOnMap(BaseModel): """Route information for map display.""" route_id: str driver_id: Optional[str] = None driver_name: Optional[str] = None stops: List[StopInfo] total_weight_kg: float num_packages: int estimated_time_minutes: int
class RoutesOnMapResponse(BaseModel): """Response for routes-on-map endpoint.""" allocation_run_id: str routes: List[RouteOnMap]
class RunSummaryResponse(BaseModel): """Summary information for an allocation run.""" allocation_run_id: str date: str status: str num_drivers: int num_routes: int num_packages: int global_gini_index: float global_std_dev: float global_max_gap: float started_at: Optional[str] = None finished_at: Optional[str] = None
# =============================================================================# Endpoints# =============================================================================
@router.get( "/{run_id}/routes-on-map", response_model=RoutesOnMapResponse, summary="Get routes for map visualization", description=""" Returns all routes and their stop coordinates for a given allocation run. Used exclusively by the 8090 visualization map. Each route includes driver info and ordered stops with coordinates. """,)async def get_routes_for_map( run_id: uuid.UUID, db: AsyncSession = Depends(get_db),) -> RoutesOnMapResponse: """Return routes and stops for map visualization, scoped to run_id.""" # Verify run exists run_result = await db.execute( select(AllocationRun).where(AllocationRun.id == run_id) ) allocation_run = run_result.scalar_one_or_none() if not allocation_run: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Allocation run {run_id} not found", ) # Get all routes for this run routes_result = await db.execute( select(Route).where(Route.allocation_run_id == run_id) ) routes = routes_result.scalars().all() # Get assignments to map routes to drivers assignments_result = await db.execute( select(Assignment, Driver) .join(Driver, Assignment.driver_id == Driver.id) .where(Assignment.allocation_run_id == run_id) ) assignments = assignments_result.all() # Build driver lookup by route_id driver_by_route: dict[uuid.UUID, tuple] = {} for assignment, driver in assignments: driver_by_route[assignment.route_id] = (str(driver.id), driver.name) route_objs: List[RouteOnMap] = [] for route in routes: # Get stops for this route ordered by stop_order stops_result = await db.execute( select(RoutePackage, Package) .join(Package, RoutePackage.package_id == Package.id) .where(RoutePackage.route_id == route.id) .order_by(RoutePackage.stop_order) ) stops_data = stops_result.all() stops = [ StopInfo( lat=pkg.latitude, lng=pkg.longitude, package_id=str(pkg.id), stop_order=rp.stop_order, address=pkg.address, ) for rp, pkg in stops_data ] driver_info = driver_by_route.get(route.id) route_objs.append(RouteOnMap( route_id=str(route.id), driver_id=driver_info[0] if driver_info else None, driver_name=driver_info[1] if driver_info else None, stops=stops, total_weight_kg=route.total_weight_kg, num_packages=route.num_packages, estimated_time_minutes=route.estimated_time_minutes, )) return RoutesOnMapResponse( allocation_run_id=str(run_id), routes=route_objs, )
@router.get( "/{run_id}/summary", response_model=RunSummaryResponse, summary="Get allocation run summary", description="Returns metadata and metrics for a specific allocation run.",)async def get_run_summary( run_id: uuid.UUID, db: AsyncSession = Depends(get_db),) -> RunSummaryResponse: """Return summary information for an allocation run.""" result = await db.execute( select(AllocationRun).where(AllocationRun.id == run_id) ) allocation_run = result.scalar_one_or_none() if not allocation_run: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Allocation run {run_id} not found", ) return RunSummaryResponse( allocation_run_id=str(allocation_run.id), date=str(allocation_run.date), status=allocation_run.status.value, num_drivers=allocation_run.num_drivers, num_routes=allocation_run.num_routes, num_packages=allocation_run.num_packages, global_gini_index=allocation_run.global_gini_index, global_std_dev=allocation_run.global_std_dev, global_max_gap=allocation_run.global_max_gap, started_at=allocation_run.started_at.isoformat() if allocation_run.started_at else None, finished_at=allocation_run.finished_at.isoformat() if allocation_run.finished_at else None, )
@router.get( "/{run_id}/recent-events", summary="Get recent agent events for a run", description="Returns recent agent events from the in-memory event bus for a specific run.",)async def get_recent_events_for_run(run_id: uuid.UUID): """Return cached recent events for a run (for late joiners).""" run_id_str = str(run_id) events = agent_event_bus.get_recent_events(allocation_run_id=run_id_str, limit=50) return {"allocation_run_id": run_id_str, "events": events}
@router.get( "/{run_id}/agent-events", summary="SSE stream for agent events (run-scoped)", description=""" Server-Sent Events stream of agent events filtered by allocation_run_id. Only events matching the specified run_id will be streamed. Connect using EventSource in browser. """,)async def agent_events_for_run(run_id: uuid.UUID): """SSE endpoint filtered by allocation_run_id.""" run_id_str = str(run_id) async def event_generator(): # Send initial connection event connected_event = { "type": "connected", "allocation_run_id": run_id_str, "message": f"Subscribed to events for run {run_id_str[:8]}...", "timestamp": datetime.utcnow().isoformat(), } yield f"data: {json.dumps(connected_event)}\n\n" # Subscribe to event bus and filter by run_id async for event in agent_event_bus.subscribe(): # Only emit events for this specific run if event.get("allocation_run_id") == run_id_str: yield f"data: {json.dumps(event)}\n\n" return StreamingResponse( event_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no", }, )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Application configuration using Pydantic Settings.Loads from environment variables and .env file."""
from functools import lru_cachefrom typing import Optional
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings): """Application settings loaded from environment variables."""
model_config = SettingsConfigDict( env_file=".env", env_file_encoding="utf-8", case_sensitive=False, )
# Database (must be set via DATABASE_URL env var in production) database_url: str = ""
# Application app_env: str = "production" debug: bool = False app_title: str = "Fair Dispatch System" app_version: str = "1.0.0" api_prefix: str = "/api/v1"
# CORS - comma-separated allowed origins cors_origins: str = "https://fairrelay.vercel.app,https://fairrelay-dashboard.vercel.app"
# Workload Score Weights workload_weight_a: float = 1.0 # num_packages weight workload_weight_b: float = 0.5 # total_weight_kg weight workload_weight_c: float = 10.0 # route_difficulty_score weight workload_weight_d: float = 0.2 # estimated_time_minutes weight
# Clustering Settings target_packages_per_route: int = 20
# Route Difficulty Weights difficulty_weight_per_kg: float = 0.01 difficulty_weight_per_stop: float = 0.1 difficulty_base: float = 1.0
# Time Estimation (minutes) time_per_package: float = 5.0 time_per_stop: float = 3.0 base_route_time: float = 30.0
# LangGraph / LangSmith (optional) langchain_tracing_v2: bool = False langchain_api_key: Optional[str] = None langchain_project: str = "fair-dispatch-dev"
# Gemini API (optional) google_api_key: Optional[str] = None enable_gemini_explain: bool = False
@property def is_production(self) -> bool: return self.app_env == "production"
@property def cors_origin_list(self) -> list[str]: origins = [o.strip() for o in self.cors_origins.split(",") if o.strip()] if not self.is_production: origins.extend(["http://localhost:5173", "http://localhost:3000", "http://localhost:8000"]) return origins
@lru_cache()def get_settings() -> Settings: """Get cached settings instance.""" return Settings()1# Core module for Fair Dispatch System123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Agent Event Bus for real-time SSE synchronization.
Provides pub/sub mechanism for agent events that can be consumedby multiple SSE clients (visualization UI, demo page, etc.)."""
from typing import AsyncIterator, Dict, Any, List, Optionalfrom uuid import UUIDimport asyncioimport time
class AgentEventBus: """ Simple in-process pub/sub for agent events. Multiple listeners (SSE connections) can subscribe and receive events published by LangGraph nodes during allocation runs. """
def __init__(self) -> None: self._subscribers: List[asyncio.Queue] = [] self._lock = asyncio.Lock() self._recent_events: List[Dict[str, Any]] = [] self._max_recent = 100 # Keep last 100 events for late joiners
async def subscribe(self) -> AsyncIterator[Dict[str, Any]]: """ Async generator yielding events. Callers iterate and send as SSE. Yields: Agent event dictionaries """ queue: asyncio.Queue = asyncio.Queue() async with self._lock: self._subscribers.append(queue) # Send recent events to catch up for event in self._recent_events[-20:]: await queue.put(event)
try: while True: event = await queue.get() yield event finally: async with self._lock: if queue in self._subscribers: self._subscribers.remove(queue)
async def publish(self, event: Dict[str, Any]) -> None: """ Publish an event to all subscribers. Args: event: Agent event dictionary """ async with self._lock: # Store in recent events self._recent_events.append(event) if len(self._recent_events) > self._max_recent: self._recent_events = self._recent_events[-self._max_recent:] # Broadcast to all subscribers for queue in self._subscribers: try: await queue.put(event) except Exception: pass # Ignore failed subscribers
def get_recent_events( self, allocation_run_id: Optional[str] = None, limit: int = 50 ) -> List[Dict[str, Any]]: """ Get recent events, optionally filtered by allocation run. Args: allocation_run_id: Filter by specific run (optional) limit: Maximum events to return Returns: List of recent events """ events = self._recent_events if allocation_run_id: events = [ e for e in events if e.get("allocation_run_id") == allocation_run_id ] return events[-limit:]
# Global singletonagent_event_bus = AgentEventBus()
def make_agent_event( allocation_run_id: str, agent_name: str, step_type: str, state: str, payload: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]: """ Create a standardized agent event dictionary. Args: allocation_run_id: UUID string of the allocation run agent_name: Agent identifier (e.g., "ML_EFFORT", "ROUTE_PLANNER") step_type: Step identifier (e.g., "MATRIX_GENERATION", "PROPOSAL_1") state: Event state - "STARTED", "COMPLETED", or "ERROR" payload: Optional additional data for the event Returns: Formatted event dictionary """ return { "allocation_run_id": str(allocation_run_id), "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "agent_name": agent_name, "step_type": step_type, "state": state, "payload": payload or {}, }
async def publish_agent_event( allocation_run_id: str, agent_name: str, step_type: str, state: str, payload: Optional[Dict[str, Any]] = None,) -> None: """ Convenience function to publish an agent event. Args: allocation_run_id: UUID string of the allocation run agent_name: Agent identifier step_type: Step identifier state: Event state payload: Optional additional data """ event = make_agent_event( allocation_run_id=allocation_run_id, agent_name=agent_name, step_type=step_type, state=state, payload=payload, ) await agent_event_bus.publish(event)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Database connection and session management.Uses async SQLAlchemy with asyncpg driver."""
import uuid
from sqlalchemy import CHAR, textfrom sqlalchemy.dialects.postgresql import UUID as PG_UUIDfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmakerfrom sqlalchemy.orm import DeclarativeBasefrom sqlalchemy.types import TypeDecorator
from app.config import get_settings
class GUID(TypeDecorator): """ Platform-independent GUID type. Uses PostgreSQL's UUID type when available, otherwise uses CHAR(32) for SQLite. Stores as stringified hex values in SQLite. """ impl = CHAR cache_ok = True
def load_dialect_impl(self, dialect): if dialect.name == 'postgresql': return dialect.type_descriptor(PG_UUID(as_uuid=True)) else: return dialect.type_descriptor(CHAR(32))
def process_bind_param(self, value, dialect): if value is None: return value elif dialect.name == 'postgresql': return value else: if isinstance(value, uuid.UUID): return value.hex else: return uuid.UUID(value).hex
def process_result_value(self, value, dialect): if value is None: return value elif dialect.name == 'postgresql': return value else: if isinstance(value, uuid.UUID): return value return uuid.UUID(value)
settings = get_settings()
# Create async engine with production-ready pool settingsengine = create_async_engine( settings.database_url, echo=settings.debug, future=True, pool_size=20, max_overflow=10, pool_recycle=3600, pool_pre_ping=True,)
# Session factoryasync_session_maker = async_sessionmaker( engine, class_=AsyncSession, expire_on_commit=False,)
class Base(DeclarativeBase): """Base class for all SQLAlchemy models.""" pass
async def get_db() -> AsyncSession: """ Dependency that provides a database session. Yields a session and ensures it's closed after use. """ async with async_session_maker() as session: try: yield session await session.commit() except Exception: await session.rollback() raise finally: await session.close()
async def check_db_health() -> bool: """Check database connectivity by running a simple query.""" try: async with engine.connect() as conn: await conn.execute(text("SELECT 1")) return True except Exception: return False
async def init_db() -> None: """Initialize database tables (for development only).""" async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187"""Fair Dispatch System - FastAPI ApplicationMain entry point for the API server."""
import loggingfrom contextlib import asynccontextmanagerfrom pathlib import Path
from fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, JSONResponsefrom starlette.responses import Responsefrom fastapi.staticfiles import StaticFiles
from app.config import get_settingsfrom app.api import ( allocation_router, drivers_router, routes_router, feedback_router, driver_api_router, admin_router, admin_learning_router, allocation_langgraph_router, consolidation_router,)from app.api.agent_events import router as agent_events_routerfrom app.api.runs import router as runs_router
# Configure structured logginglogging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",)logger = logging.getLogger("fairrelay.brain")
settings = get_settings()
# Path to frontend directoryFRONTEND_DIR = Path(__file__).parent.parent / "frontend"
@asynccontextmanagerasync def lifespan(app: FastAPI): """Application lifespan handler for startup and shutdown events.""" # Startup logger.info(f"Starting {settings.app_title} v{settings.app_version} (env={settings.app_env})")
if not settings.is_production: try: from app.database import init_db await init_db() logger.info("Database tables initialized (dev mode)") except Exception as e: logger.warning(f"Database unavailable - running without persistence: {e}") else: # In production, just verify connectivity try: from app.database import check_db_health healthy = await check_db_health() if healthy: logger.info("Database connected successfully") else: logger.warning("Database health check failed - some endpoints may not work") except Exception as e: logger.warning(f"Database check failed: {e}")
yield # Shutdown logger.info("Shutting down...")
# Create FastAPI applicationapp = FastAPI( title=settings.app_title, version=settings.app_version, description=""" ## Fair Dispatch System API
A fairness-focused route allocation system for delivery operations.
### Features - **Route Clustering**: Groups packages using K-Means for efficient routes - **Workload Scoring**: Calculates balanced workload metrics - **Fairness Metrics**: Computes Gini index and fairness scores - **Explainability**: Provides human-readable explanations for allocations - **LangGraph Workflow**: Multi-agent orchestration with LangSmith tracing
### Main Endpoints - `POST /api/v1/allocate` - Allocate packages to drivers (original) - `POST /api/v1/allocate/langgraph` - Allocate with LangGraph workflow - `POST /api/v1/consolidate` - AI Load Consolidation (5-agent LangGraph pipeline) - `POST /api/v1/consolidate/simulate` - Compare consolidation scenarios - `GET /api/v1/drivers/{id}` - Get driver details and stats - `GET /api/v1/routes/{id}` - Get route details - `POST /api/v1/feedback` - Submit driver feedback - `GET /api/v1/agent-events/stream` - SSE stream for agent events """, lifespan=lifespan, docs_url="/docs" if not settings.is_production else None, redoc_url="/redoc" if not settings.is_production else None,)
# Global exception handler - prevent stack trace leaks in production@app.exception_handler(Exception)async def global_exception_handler(request: Request, exc: Exception): logger.error(f"Unhandled error on {request.method} {request.url.path}: {exc}", exc_info=True) return JSONResponse( status_code=500, content={"detail": "Internal server error"}, )
# Add CORS middleware with configurable originsapp.add_middleware( CORSMiddleware, allow_origins=settings.cors_origin_list, allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# Include API routersapp.include_router(allocation_router, prefix=settings.api_prefix)app.include_router(allocation_langgraph_router, prefix=settings.api_prefix)app.include_router(drivers_router, prefix=settings.api_prefix)app.include_router(routes_router, prefix=settings.api_prefix)app.include_router(feedback_router, prefix=settings.api_prefix)app.include_router(driver_api_router, prefix=settings.api_prefix)app.include_router(admin_router, prefix=settings.api_prefix)app.include_router(admin_learning_router, prefix=settings.api_prefix)app.include_router(consolidation_router, prefix=settings.api_prefix)
# Include SSE agent events router (no prefix - it defines its own)app.include_router(agent_events_router)
# Include run-scoped endpointsapp.include_router(runs_router, prefix=settings.api_prefix)
@app.get("/", tags=["Health"])async def root(): """Root endpoint - health check.""" return { "status": "healthy", "service": settings.app_title, "version": settings.app_version, }
@app.get("/health", tags=["Health"])async def health_check(): """Health check endpoint with actual DB verification.""" from app.database import check_db_health db_ok = await check_db_health() status = "healthy" if db_ok else "degraded" return { "status": status, "database": "connected" if db_ok else "disconnected", }
# Mount static files and demo endpointsif FRONTEND_DIR.exists(): app.mount("/static", StaticFiles(directory=str(FRONTEND_DIR)), name="static")
NO_CACHE = {"Cache-Control": "no-cache, no-store, must-revalidate", "Pragma": "no-cache", "Expires": "0"}
@app.get("/demo/allocate", tags=["Demo"]) async def demo_allocate(): """Serve the API demo page for testing allocation endpoint.""" demo_path = FRONTEND_DIR / "demo.html" return FileResponse(demo_path, media_type="text/html", headers=NO_CACHE)
@app.get("/demo/visualization", tags=["Demo"]) async def demo_visualization(): """Serve the agent visualization page.""" viz_path = FRONTEND_DIR / "visualization.html" return FileResponse(viz_path, media_type="text/html", headers=NO_CACHE)
@app.get("/demo/consolidation", tags=["Demo"]) async def demo_consolidation(): """Serve the 5-agent load consolidation pipeline visualization.""" path = FRONTEND_DIR / "consolidation.html" return FileResponse(path, media_type="text/html", headers=NO_CACHE)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""Models package initialization - imports all models for easy access."""
from app.models.driver import Driver, DriverStatsDaily, DriverFeedback, VehicleType, PreferredLanguagefrom app.models.package import Packagefrom app.models.route import Route, RoutePackagefrom app.models.assignment import Assignmentfrom app.models.delivery_log import DeliveryLog, DeliveryStatus, DeliveryIssueTypefrom app.models.route_swap import RouteSwapRequest, SwapRequestStatusfrom app.models.stop_issue import StopIssue, StopIssueTypefrom app.models.appeal import Appeal, AppealStatusfrom app.models.manual_override import ManualOverridefrom app.models.fairness_config import FairnessConfigfrom app.models.allocation_run import AllocationRun, AllocationRunStatusfrom app.models.decision_log import DecisionLogfrom app.models.learning_episode import LearningEpisodefrom app.models.driver_effort_model import DriverEffortModel
__all__ = [ # Phase 1 models "Driver", "DriverStatsDaily", "DriverFeedback", "VehicleType", "PreferredLanguage", "Package", "Route", "RoutePackage", "Assignment", # Phase 2 models "DeliveryLog", "DeliveryStatus", "DeliveryIssueType", "RouteSwapRequest", "SwapRequestStatus", "StopIssue", "StopIssueType", # Phase 3 models "Appeal", "AppealStatus", "ManualOverride", "FairnessConfig", "AllocationRun", "AllocationRunStatus", "DecisionLog", # Phase 8 models "LearningEpisode", "DriverEffortModel",]
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""AllocationRun database model.High-level metadata per /allocate execution."""
import enumimport uuidfrom datetime import datetime, datefrom typing import Optional
from sqlalchemy import Integer, Float, Text, Date, DateTime, Enumfrom sqlalchemy.orm import Mapped, mapped_column
from app.database import Base, GUID
class AllocationRunStatus(str, enum.Enum): """Status of an allocation run.""" PENDING = "PENDING" SUCCESS = "SUCCESS" FAILED = "FAILED"
class AllocationRun(Base): """ AllocationRun model for high-level allocation metadata. Tracks each allocation execution with global metrics. """ __tablename__ = "allocation_runs"
id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) date: Mapped[date] = mapped_column(Date, nullable=False, index=True) num_drivers: Mapped[int] = mapped_column(Integer, nullable=False, default=0) num_routes: Mapped[int] = mapped_column(Integer, nullable=False, default=0) num_packages: Mapped[int] = mapped_column(Integer, nullable=False, default=0) # Global fairness metrics global_gini_index: Mapped[float] = mapped_column(Float, default=0.0) global_std_dev: Mapped[float] = mapped_column(Float, default=0.0) global_max_gap: Mapped[float] = mapped_column(Float, default=0.0) status: Mapped[AllocationRunStatus] = mapped_column( Enum(AllocationRunStatus), nullable=False, default=AllocationRunStatus.SUCCESS, ) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) started_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, nullable=False, ) finished_at: Mapped[Optional[datetime]] = mapped_column( DateTime, nullable=True, )
def __repr__(self) -> str: return f"<AllocationRun(id={self.id}, date={self.date}, status={self.status})>"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Appeal database model.Represents a driver raising an appeal about a route's fairness."""
import enumimport uuidfrom datetime import datetimefrom typing import Optional, TYPE_CHECKING
from sqlalchemy import Text, DateTime, ForeignKey, Enumfrom sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database import Base, GUID
if TYPE_CHECKING: from app.models.driver import Driver from app.models.assignment import Assignment
class AppealStatus(str, enum.Enum): """Status of an appeal.""" PENDING = "PENDING" APPROVED = "APPROVED" REJECTED = "REJECTED" RESOLVED = "RESOLVED"
class Appeal(Base): """ Appeal model for driver fairness appeals. Allows drivers to contest route assignments they feel are unfair. """ __tablename__ = "appeals"
id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) driver_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("drivers.id", ondelete="CASCADE"), nullable=False, index=True, ) assignment_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("assignments.id", ondelete="CASCADE"), nullable=False, index=True, ) reason: Mapped[str] = mapped_column(Text, nullable=False) status: Mapped[AppealStatus] = mapped_column( Enum(AppealStatus), nullable=False, default=AppealStatus.PENDING, ) admin_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True) created_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, nullable=False, ) updated_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, )
# Relationships driver: Mapped["Driver"] = relationship("Driver") assignment: Mapped["Assignment"] = relationship("Assignment")
def __repr__(self) -> str: return f"<Appeal(id={self.id}, driver_id={self.driver_id}, status={self.status})>"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Assignment database model.Represents the allocation of a route to a driver."""
import uuidfrom datetime import datetime, datefrom typing import Optional, List, TYPE_CHECKING
from sqlalchemy import Float, Text, Date, DateTime, ForeignKeyfrom sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database import Base, GUID
if TYPE_CHECKING: from app.models.driver import Driver, DriverFeedback from app.models.route import Route
class Assignment(Base): """ Assignment model representing the allocation of a route to a driver. Contains workload and fairness scores plus explanation. """ __tablename__ = "assignments" id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) date: Mapped[date] = mapped_column(Date, nullable=False, index=True) driver_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("drivers.id", ondelete="CASCADE"), nullable=False, index=True, ) route_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("routes.id", ondelete="CASCADE"), nullable=False, index=True, ) workload_score: Mapped[float] = mapped_column(Float, default=0.0) fairness_score: Mapped[float] = mapped_column(Float, default=1.0) explanation: Mapped[Optional[str]] = mapped_column(Text, nullable=True) driver_explanation: Mapped[Optional[str]] = mapped_column(Text, nullable=True) admin_explanation: Mapped[Optional[str]] = mapped_column(Text, nullable=True) allocation_run_id: Mapped[uuid.UUID] = mapped_column( GUID(), nullable=False, index=True, ) created_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, ) # Relationships driver: Mapped["Driver"] = relationship("Driver", back_populates="assignments") route: Mapped["Route"] = relationship("Route", back_populates="assignments") feedback: Mapped[List["DriverFeedback"]] = relationship( "DriverFeedback", back_populates="assignment", cascade="all, delete-orphan", ) def __repr__(self) -> str: return f"<Assignment(id={self.id}, driver_id={self.driver_id}, route_id={self.route_id})>"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"""DecisionLog database model.Stores per-agent step logs for workflow visualization."""
import uuidfrom datetime import datetimefrom typing import Optional
from sqlalchemy import String, DateTime, ForeignKey, JSONfrom sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database import Base, GUID
class DecisionLog(Base): """ DecisionLog model for agent workflow visualization. Records per-agent step logs during allocation with input/output snapshots. """ __tablename__ = "decision_logs"
id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) allocation_run_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("allocation_runs.id", ondelete="CASCADE"), nullable=False, index=True, ) agent_name: Mapped[str] = mapped_column( String(100), nullable=False, index=True, ) step_type: Mapped[str] = mapped_column( String(100), nullable=False, ) input_snapshot: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) output_snapshot: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) created_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, nullable=False, )
# Relationships allocation_run = relationship("AllocationRun")
def __repr__(self) -> str: return f"<DecisionLog(id={self.id}, agent={self.agent_name}, step={self.step_type})>"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""DeliveryLog database model.Represents a delivery attempt at a given stop."""
import enumimport uuidfrom datetime import datetimefrom typing import Optional, TYPE_CHECKING
from sqlalchemy import String, Integer, Text, DateTime, ForeignKey, Enumfrom sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database import Base, GUID
if TYPE_CHECKING: from app.models.assignment import Assignment from app.models.route import Route from app.models.driver import Driver from app.models.package import Package
class DeliveryStatus(str, enum.Enum): """Status of a delivery attempt.""" DELIVERED = "DELIVERED" FAILED = "FAILED" PARTIAL = "PARTIAL"
class DeliveryIssueType(str, enum.Enum): """Type of issue encountered during delivery.""" NONE = "NONE" NOT_AT_HOME = "NOT_AT_HOME" WRONG_ADDRESS = "WRONG_ADDRESS" SAFETY = "SAFETY" ACCESS_DENIED = "ACCESS_DENIED" OTHER = "OTHER"
class DeliveryLog(Base): """ DeliveryLog model representing a delivery attempt at a given stop. Tracks delivery status, issues, and proof of delivery. """ __tablename__ = "delivery_logs"
id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) assignment_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("assignments.id", ondelete="CASCADE"), nullable=False, index=True, ) route_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("routes.id", ondelete="CASCADE"), nullable=False, index=True, ) driver_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("drivers.id", ondelete="CASCADE"), nullable=False, index=True, ) stop_order: Mapped[int] = mapped_column(Integer, nullable=False) package_id: Mapped[Optional[uuid.UUID]] = mapped_column( GUID(), ForeignKey("packages.id", ondelete="SET NULL"), nullable=True, ) status: Mapped[DeliveryStatus] = mapped_column( Enum(DeliveryStatus), nullable=False, default=DeliveryStatus.DELIVERED, ) issue_type: Mapped[DeliveryIssueType] = mapped_column( Enum(DeliveryIssueType), nullable=False, default=DeliveryIssueType.NONE, ) photo_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True) signature_data: Mapped[Optional[str]] = mapped_column(Text, nullable=True) notes: Mapped[Optional[str]] = mapped_column(Text, nullable=True) timestamp: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, nullable=False, )
# Relationships assignment: Mapped["Assignment"] = relationship("Assignment") route: Mapped["Route"] = relationship("Route") driver: Mapped["Driver"] = relationship("Driver") package: Mapped[Optional["Package"]] = relationship("Package")
def __repr__(self) -> str: return f"<DeliveryLog(id={self.id}, stop_order={self.stop_order}, status={self.status})>"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226"""Driver-related database models.Includes Driver, DriverStatsDaily, and DriverFeedback models."""
import enumimport uuidfrom datetime import datetime, datefrom typing import Optional, List, TYPE_CHECKING
from sqlalchemy import String, Float, Integer, Text, Date, DateTime, ForeignKey, Enum, JSON, Booleanfrom sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database import Base, GUID
if TYPE_CHECKING: from app.models.assignment import Assignment
class PreferredLanguage(str, enum.Enum): """Supported languages for driver communication.""" EN = "en" TA = "ta" HI = "hi" TE = "te" KN = "kn"
class VehicleType(str, enum.Enum): """Types of vehicles used for delivery.""" ICE = "ICE" EV = "EV" BICYCLE = "BICYCLE"
class Driver(Base): """ Driver model representing delivery personnel. Stores personal info, vehicle details, and preferences. """ __tablename__ = "drivers" id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) external_id: Mapped[Optional[str]] = mapped_column( String(100), unique=True, nullable=True, index=True, ) name: Mapped[str] = mapped_column(String(255), nullable=False) phone: Mapped[Optional[str]] = mapped_column(String(20), nullable=True) whatsapp_number: Mapped[Optional[str]] = mapped_column(String(20), nullable=True) preferred_language: Mapped[PreferredLanguage] = mapped_column( Enum(PreferredLanguage), default=PreferredLanguage.EN, ) vehicle_type: Mapped[VehicleType] = mapped_column( Enum(VehicleType), default=VehicleType.ICE, ) vehicle_capacity_kg: Mapped[float] = mapped_column(Float, default=100.0) license_number: Mapped[Optional[str]] = mapped_column(String(50), nullable=True) ev_charging_pref: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) # EV-specific fields (Phase 7) battery_range_km: Mapped[Optional[float]] = mapped_column(Float, nullable=True) charging_time_minutes: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) created_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, ) updated_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, ) # Relationships daily_stats: Mapped[List["DriverStatsDaily"]] = relationship( "DriverStatsDaily", back_populates="driver", cascade="all, delete-orphan", ) assignments: Mapped[List["Assignment"]] = relationship( "Assignment", back_populates="driver", cascade="all, delete-orphan", ) feedback: Mapped[List["DriverFeedback"]] = relationship( "DriverFeedback", back_populates="driver", cascade="all, delete-orphan", ) @property def is_ev(self) -> bool: """Check if driver uses an electric vehicle.""" return self.vehicle_type == VehicleType.EV def __repr__(self) -> str: return f"<Driver(id={self.id}, name={self.name})>"
class DriverStatsDaily(Base): """ Daily statistics for each driver. Tracks workload, routes, fairness metrics, and recovery state per day. """ __tablename__ = "driver_stats_daily" id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) driver_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("drivers.id", ondelete="CASCADE"), nullable=False, index=True, ) date: Mapped[date] = mapped_column(Date, nullable=False, index=True) avg_workload_score: Mapped[float] = mapped_column(Float, default=0.0) total_routes: Mapped[int] = mapped_column(Integer, default=0) gini_contribution: Mapped[Optional[float]] = mapped_column(Float, nullable=True) reported_stress_level: Mapped[Optional[float]] = mapped_column(Float, nullable=True) reported_fairness_score: Mapped[Optional[float]] = mapped_column(Float, nullable=True) # Recovery tracking fields (Phase 7) is_hard_day: Mapped[bool] = mapped_column(Boolean, default=False) complexity_debt: Mapped[float] = mapped_column(Float, default=0.0) is_recovery_day: Mapped[bool] = mapped_column(Boolean, default=False) # Learning fields (Phase 8) predicted_effort: Mapped[Optional[float]] = mapped_column(Float, nullable=True) actual_effort: Mapped[Optional[float]] = mapped_column(Float, nullable=True) prediction_error: Mapped[Optional[float]] = mapped_column(Float, nullable=True) model_version_used: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) allocation_run_id: Mapped[Optional[uuid.UUID]] = mapped_column( GUID(), ForeignKey("allocation_runs.id", ondelete="SET NULL"), nullable=True, index=True, ) # Relationships driver: Mapped["Driver"] = relationship("Driver", back_populates="daily_stats") def __repr__(self) -> str: return f"<DriverStatsDaily(driver_id={self.driver_id}, date={self.date})>"
class HardestAspect(str, enum.Enum): """Common difficult aspects of delivery work.""" TRAFFIC = "traffic" PARKING = "parking" STAIRS = "stairs" WEATHER = "weather" HEAVY_LOAD = "heavy_load" CUSTOMER = "customer" NAVIGATION = "navigation" OTHER = "other"
class DriverFeedback(Base): """ Feedback submitted by drivers after completing assignments. Used for learning and improving future allocations. """ __tablename__ = "driver_feedback" id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) driver_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("drivers.id", ondelete="CASCADE"), nullable=False, index=True, ) assignment_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("assignments.id", ondelete="CASCADE"), nullable=False, index=True, ) fairness_rating: Mapped[int] = mapped_column(Integer, nullable=False) # 1-5 stress_level: Mapped[int] = mapped_column(Integer, nullable=False) # 1-10 tiredness_level: Mapped[int] = mapped_column(Integer, nullable=False) # 1-5 hardest_aspect: Mapped[Optional[HardestAspect]] = mapped_column( Enum(HardestAspect), nullable=True, ) comments: Mapped[Optional[str]] = mapped_column(Text, nullable=True) # Extended feedback fields (Phase 2) route_difficulty_self_report: Mapped[Optional[int]] = mapped_column( Integer, nullable=True, ) # 1-5 scale would_take_similar_route_again: Mapped[Optional[bool]] = mapped_column( nullable=True, ) most_unfair_aspect: Mapped[Optional[str]] = mapped_column( String(100), nullable=True, ) created_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, ) # Relationships driver: Mapped["Driver"] = relationship("Driver", back_populates="feedback") assignment: Mapped["Assignment"] = relationship("Assignment", back_populates="feedback") def __repr__(self) -> str: return f"<DriverFeedback(id={self.id}, driver_id={self.driver_id})>"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""DriverEffortModel database model.Stores per-driver XGBoost models for personalized effort prediction."""
import uuidfrom datetime import datetimefrom typing import Optional
from sqlalchemy import Boolean, Float, Integer, DateTime, ForeignKey, LargeBinary, JSONfrom sqlalchemy.orm import Mapped, mapped_column
from app.database import Base, GUID
class DriverEffortModel(Base): """ DriverEffortModel stores serialized XGBoost models per driver. Each driver gets their own personalized effort prediction model. """ __tablename__ = "driver_effort_models"
driver_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("drivers.id", ondelete="CASCADE"), primary_key=True, ) model_version: Mapped[int] = mapped_column( Integer, default=1, nullable=False, ) # Serialized XGBoost model (pickle format) model_pickle: Mapped[Optional[bytes]] = mapped_column( LargeBinary, nullable=True, ) # Training metadata training_samples: Mapped[int] = mapped_column( Integer, default=0, ) feature_names: Mapped[Optional[dict]] = mapped_column( JSON, nullable=True, ) # Performance tracking mse_history: Mapped[Optional[dict]] = mapped_column( JSON, nullable=True, default=list, ) # List of last 10 MSE values current_mse: Mapped[Optional[float]] = mapped_column( Float, nullable=True, ) r2_score: Mapped[Optional[float]] = mapped_column( Float, nullable=True, ) # Model state active: Mapped[bool] = mapped_column( Boolean, default=True, index=True, ) last_trained_at: Mapped[Optional[datetime]] = mapped_column( DateTime, nullable=True, ) created_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, nullable=False, ) updated_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, )
def __repr__(self) -> str: return f"<DriverEffortModel(driver_id={self.driver_id}, v{self.model_version})>"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""FairnessConfig database model.Stores fairness engine weights and thresholds."""
import uuidfrom datetime import datetime
from sqlalchemy import Boolean, Float, DateTimefrom sqlalchemy.orm import Mapped, mapped_column
from app.database import Base, GUID
class FairnessConfig(Base): """ FairnessConfig model for storing fairness engine weights and thresholds. Only one config should be active at a time. """ __tablename__ = "fairness_configs"
id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) is_active: Mapped[bool] = mapped_column( Boolean, default=True, nullable=False, index=True, ) # Workload weights workload_weight_packages: Mapped[float] = mapped_column(Float, default=1.0) workload_weight_weight_kg: Mapped[float] = mapped_column(Float, default=0.5) workload_weight_difficulty: Mapped[float] = mapped_column(Float, default=10.0) workload_weight_time: Mapped[float] = mapped_column(Float, default=0.2) # Fairness thresholds gini_threshold: Mapped[float] = mapped_column(Float, default=0.33) stddev_threshold: Mapped[float] = mapped_column(Float, default=25.0) max_gap_threshold: Mapped[float] = mapped_column(Float, default=25.0) # Recovery mode (Phase 7) recovery_mode_enabled: Mapped[bool] = mapped_column(Boolean, default=False) complexity_debt_hard_threshold: Mapped[float] = mapped_column(Float, default=2.0) recovery_lightening_factor: Mapped[float] = mapped_column(Float, default=0.7) recovery_penalty_weight: Mapped[float] = mapped_column(Float, default=3.0) # EV config (Phase 7) ev_charging_penalty_weight: Mapped[float] = mapped_column(Float, default=0.3) ev_safety_margin_pct: Mapped[float] = mapped_column(Float, default=10.0) created_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, nullable=False, ) updated_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, )
def __repr__(self) -> str: return f"<FairnessConfig(id={self.id}, is_active={self.is_active})>"
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""LearningEpisode database model.Tracks bandit learning episodes per allocation run for Thompson Sampling."""
import uuidfrom datetime import datetimefrom typing import Optional
from sqlalchemy import Boolean, Float, Integer, String, DateTime, ForeignKey, Text, JSONfrom sqlalchemy.orm import Mapped, mapped_column
from app.database import Base, GUID
class LearningEpisode(Base): """ LearningEpisode model for tracking bandit learning episodes. Each allocation run creates one episode; reward is computed 24h+ later. """ __tablename__ = "learning_episodes"
id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) allocation_run_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("allocation_runs.id", ondelete="CASCADE"), nullable=False, index=True, unique=True, # One episode per allocation run ) # Bandit arm identification config_hash: Mapped[str] = mapped_column( String(64), nullable=False, index=True, ) fairness_config: Mapped[dict] = mapped_column( JSON, nullable=False, ) arm_idx: Mapped[int] = mapped_column( Integer, nullable=False, default=0, ) # Episode context num_drivers: Mapped[int] = mapped_column(Integer, nullable=False, default=0) num_routes: Mapped[int] = mapped_column(Integer, nullable=False, default=0) # Reward (computed later by cron job) episode_reward: Mapped[Optional[float]] = mapped_column( Float, nullable=True, ) reward_computed_at: Mapped[Optional[datetime]] = mapped_column( DateTime, nullable=True, ) # Thompson Sampling priors at time of selection alpha_prior: Mapped[float] = mapped_column(Float, default=1.0) beta_prior: Mapped[float] = mapped_column(Float, default=1.0) samples_count: Mapped[int] = mapped_column(Integer, default=0) # A/B testing flag is_experimental: Mapped[bool] = mapped_column( Boolean, default=False, index=True, ) # Feedback aggregation (stored for debugging) avg_fairness_rating: Mapped[Optional[float]] = mapped_column(Float, nullable=True) avg_stress_level: Mapped[Optional[float]] = mapped_column(Float, nullable=True) completion_rate: Mapped[Optional[float]] = mapped_column(Float, nullable=True) feedback_count: Mapped[int] = mapped_column(Integer, default=0) created_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, nullable=False, index=True, )
def __repr__(self) -> str: return f"<LearningEpisode(id={self.id}, reward={self.episode_reward})>"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""ManualOverride database model.Captures manual admin interventions in allocations."""
import uuidfrom datetime import datetimefrom typing import Optional, TYPE_CHECKING
from sqlalchemy import Text, DateTime, ForeignKey, JSONfrom sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database import Base, GUID
if TYPE_CHECKING: from app.models.driver import Driver from app.models.route import Route
class ManualOverride(Base): """ ManualOverride model for admin manual interventions. Records route reassignments with before/after fairness metrics. """ __tablename__ = "manual_overrides"
id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) allocation_run_id: Mapped[uuid.UUID] = mapped_column( GUID(), nullable=False, index=True, ) old_driver_id: Mapped[Optional[uuid.UUID]] = mapped_column( GUID(), ForeignKey("drivers.id", ondelete="SET NULL"), nullable=True, ) new_driver_id: Mapped[Optional[uuid.UUID]] = mapped_column( GUID(), ForeignKey("drivers.id", ondelete="SET NULL"), nullable=True, ) route_id: Mapped[Optional[uuid.UUID]] = mapped_column( GUID(), ForeignKey("routes.id", ondelete="SET NULL"), nullable=True, ) reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) before_metrics: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) after_metrics: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) created_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, nullable=False, )
# Relationships old_driver: Mapped[Optional["Driver"]] = relationship( "Driver", foreign_keys=[old_driver_id], ) new_driver: Mapped[Optional["Driver"]] = relationship( "Driver", foreign_keys=[new_driver_id], ) route: Mapped[Optional["Route"]] = relationship("Route")
def __repr__(self) -> str: return f"<ManualOverride(id={self.id}, old_driver={self.old_driver_id}, new_driver={self.new_driver_id})>"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Package database model.Represents delivery packages with location and priority info."""
import enumimport uuidfrom datetime import datetimefrom typing import Optional, List, TYPE_CHECKING
from sqlalchemy import String, Float, Integer, Text, DateTime, Enumfrom sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database import Base, GUID
if TYPE_CHECKING: from app.models.route import RoutePackage
class PackagePriority(str, enum.Enum): """Priority levels for package delivery.""" NORMAL = "NORMAL" HIGH = "HIGH" EXPRESS = "EXPRESS"
class Package(Base): """ Package model representing items to be delivered. Contains weight, fragility, location, and priority information. """ __tablename__ = "packages" id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) external_id: Mapped[str] = mapped_column( String(100), unique=True, nullable=False, index=True, ) weight_kg: Mapped[float] = mapped_column(Float, nullable=False, default=1.0) fragility_level: Mapped[int] = mapped_column(Integer, nullable=False, default=1) # 1-5 address: Mapped[str] = mapped_column(Text, nullable=False) latitude: Mapped[float] = mapped_column(Float, nullable=False) longitude: Mapped[float] = mapped_column(Float, nullable=False) priority: Mapped[PackagePriority] = mapped_column( Enum(PackagePriority), default=PackagePriority.NORMAL, ) created_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, ) # Relationships route_packages: Mapped[List["RoutePackage"]] = relationship( "RoutePackage", back_populates="package", cascade="all, delete-orphan", ) def __repr__(self) -> str: return f"<Package(id={self.id}, external_id={self.external_id})>"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"""Route database models.Includes Route and RoutePackage (association table) models."""
import uuidfrom datetime import datetime, datefrom typing import Optional, List, TYPE_CHECKING
from sqlalchemy import Integer, Float, Date, DateTime, ForeignKeyfrom sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database import Base, GUID
if TYPE_CHECKING: from app.models.package import Package from app.models.assignment import Assignment
class Route(Base): """ Route model representing a delivery route (cluster of packages). Contains aggregated metrics about the route. """ __tablename__ = "routes" id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) date: Mapped[date] = mapped_column(Date, nullable=False, index=True) cluster_id: Mapped[int] = mapped_column(Integer, nullable=False) total_weight_kg: Mapped[float] = mapped_column(Float, default=0.0) num_packages: Mapped[int] = mapped_column(Integer, default=0) num_stops: Mapped[int] = mapped_column(Integer, default=0) route_difficulty_score: Mapped[float] = mapped_column(Float, default=1.0) estimated_time_minutes: Mapped[int] = mapped_column(Integer, default=60) # Distance for EV range calculations (Phase 7) total_distance_km: Mapped[Optional[float]] = mapped_column(Float, nullable=True) # Run scoping - links route to specific allocation run # Nullable for backward compatibility with existing routes allocation_run_id: Mapped[Optional[uuid.UUID]] = mapped_column( GUID(), ForeignKey("allocation_runs.id", ondelete="CASCADE"), nullable=True, index=True, ) created_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, ) # Relationships route_packages: Mapped[List["RoutePackage"]] = relationship( "RoutePackage", back_populates="route", cascade="all, delete-orphan", ) assignments: Mapped[List["Assignment"]] = relationship( "Assignment", back_populates="route", cascade="all, delete-orphan", ) def __repr__(self) -> str: return f"<Route(id={self.id}, cluster_id={self.cluster_id}, packages={self.num_packages})>"
class RoutePackage(Base): """ Association table linking routes to packages with stop order. Represents which packages belong to which route and in what order. """ __tablename__ = "route_packages" route_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("routes.id", ondelete="CASCADE"), primary_key=True, ) package_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("packages.id", ondelete="CASCADE"), primary_key=True, ) stop_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0) # Relationships route: Mapped["Route"] = relationship("Route", back_populates="route_packages") package: Mapped["Package"] = relationship("Package", back_populates="route_packages") def __repr__(self) -> str: return f"<RoutePackage(route_id={self.route_id}, package_id={self.package_id}, order={self.stop_order})>"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""RouteSwapRequest database model.Represents a driver requesting to swap or change a route."""
import enumimport uuidfrom datetime import datetime, datefrom typing import Optional, TYPE_CHECKING
from sqlalchemy import Text, Date, DateTime, ForeignKey, Enumfrom sqlalchemy.orm import Mapped, mapped_column, relationship
from app.database import Base, GUID
if TYPE_CHECKING: from app.models.driver import Driver from app.models.assignment import Assignment
class SwapRequestStatus(str, enum.Enum): """Status of a route swap request.""" PENDING = "PENDING" APPROVED = "APPROVED" REJECTED = "REJECTED" CANCELLED = "CANCELLED"
class RouteSwapRequest(Base): """ RouteSwapRequest model for driver route swap/change requests. Tracks request status and allows drivers to request lighter routes. """ __tablename__ = "route_swap_requests"
id: Mapped[uuid.UUID] = mapped_column( GUID(), primary_key=True, default=uuid.uuid4, ) from_driver_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("drivers.id", ondelete="CASCADE"), nullable=False, index=True, ) to_driver_id: Mapped[Optional[uuid.UUID]] = mapped_column( GUID(), ForeignKey("drivers.id", ondelete="SET NULL"), nullable=True, ) assignment_id: Mapped[uuid.UUID] = mapped_column( GUID(), ForeignKey("assignments.id", ondelete="CASCADE"), nullable=False, index=True, ) reason: Mapped[str] = mapped_column(Text, nullable=False) preferred_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) status: Mapped[SwapRequestStatus] = mapped_column( Enum(SwapRequestStatus), nullable=False, default=SwapRequestStatus.PENDING, ) created_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, nullable=False, ) updated_at: Mapped[datetime] = mapped_column( DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, )
# Relationships from_driver: Mapped["Driver"] = relationship( "Driver", foreign_keys=[from_driver_id], ) to_driver: Mapped[Optional["Driver"]] = relationship( "Driver", foreign_keys=[to_driver_id], ) assignment: Mapped["Assignment"] = relationship("Assignment")
def __repr__(self) -> str: return f"<RouteSwapRequest(id={self.id}, from_driver={self.from_driver_id}, status={self.status})>".gitattributes+1
.gitignoreAdded+75
README.md+630-15
brain/.env.exampleAdded+26
brain/.github/workflows/test.ymlAdded+42
brain/.gitignoreAdded+95
brain/DockerfileAdded+23
brain/MakefileAdded+34
brain/README.mdAdded+484
brain/alembic.iniAdded+114
brain/alembic/env.pyAdded+92
brain/alembic/script.py.makoAdded+26
brain/alembic/versions/001_initial_schema.pyAdded+145
brain/alembic/versions/002_phase2_phase3_models.pyAdded+179
brain/alembic/versions/003_add_pending_status.pyAdded+36
brain/alembic/versions/004_add_explanation_fields.pyAdded+42
brain/alembic/versions/005_phase7_ev_recovery.pyAdded+59
brain/alembic/versions/006_phase8_learning_agent.pyAdded+119
brain/app/__init__.pyAdded+1
brain/app/api/__init__.pyAdded+24
brain/app/api/admin.pyAdded+298
brain/app/api/admin_learning.pyAdded+368
brain/app/api/agent_events.pyAdded+93
brain/app/api/allocation.pyAdded+808
brain/app/api/allocation_langgraph.pyAdded+513
brain/app/api/consolidation.pyAdded+109
brain/app/api/driver_api.pyAdded+175
brain/app/api/drivers.pyAdded+136
brain/app/api/feedback.pyAdded+108
brain/app/api/routes.pyAdded+93
brain/app/api/runs.pyAdded+251
brain/app/config.pyAdded+77
brain/app/core/__init__.pyAdded+1
brain/app/core/events.pyAdded+154
brain/app/database.pyAdded+108
brain/app/main.pyAdded+187
brain/app/models/__init__.pyAdded+49
brain/app/models/allocation_run.pyAdded+64
brain/app/models/appeal.pyAdded+77
brain/app/models/assignment.pyAdded+71
brain/app/models/decision_log.pyAdded+55
brain/app/models/delivery_log.pyAdded+102
brain/app/models/driver.pyAdded+226
brain/app/models/driver_effort_model.pyAdded+90
brain/app/models/fairness_config.pyAdded+69
brain/app/models/learning_episode.pyAdded+92
brain/app/models/manual_override.pyAdded+73
brain/app/models/package.pyAdded+68
brain/app/models/route.pyAdded+97
brain/app/models/route_swap.pyAdded+89