mashrur950 commited on
Commit
6313678
·
1 Parent(s): c2b773b

Remove deprecated conversation management and UI components from the archive

Browse files
DHAKA_ROUTE_VERIFICATION.md DELETED
@@ -1,150 +0,0 @@
1
- # Dhaka Route Verification: Ahsanullah University → Tejgaon College
2
-
3
- ## Your Route Details
4
-
5
- **Origin:** Ahsanullah University of Science and Technology (141, &142 Love Rd, Dhaka 1208)
6
- **Destination:** Tejgaon College (16 Indira Rd, Dhaka 1215)
7
- **Distance:** 2.5 km
8
- **Vehicle:** Car
9
-
10
- ### Your Algorithm's Estimate
11
- - **Base Duration:** 19 minutes (at 8 km/h)
12
- - **With Traffic:** 57 minutes
13
- - **Traffic Delay:** +200% (Severe)
14
- - **Traffic Status:** 🔴 SEVERE - Heavy congestion
15
-
16
- ## Real-World Data from Research Studies
17
-
18
- ### Current Dhaka Traffic Speeds (2023-2025 Studies)
19
-
20
- According to recent traffic studies and research papers:
21
-
22
- 1. **Average speed in Dhaka (2023):** **4.8 km/h**
23
- - Source: Business Standard, April 2023
24
-
25
- 2. **Peak hour speeds:** **5 km/h or less**
26
- - Some areas drop below 10 km/h during rush hours
27
- - Source: BUET Accident Research Institute
28
-
29
- 3. **Historical comparison:**
30
- - 1990s: 25 km/h average
31
- - 2005: 21 km/h average
32
- - 2025: **4.8 km/h average** (slower than walking speed!)
33
-
34
- ### Tejgaon Area Specific Information
35
-
36
- **Critical Finding:** Tejgaon is specifically mentioned as a **major congestion hotspot** in Dhaka.
37
-
38
- From research studies:
39
- - "Traffic has increased at Bijoy Sarani, **Tejgaon**, Shat Rasta and adjacent areas"
40
- - "The pressure of traffic at **Farmgate**, Bijoy Sarani and Tejgaon is not likely to lessen"
41
- - Tejgaon College is located at **Farmgate** - one of Dhaka's worst congestion points
42
-
43
- ## Calculated Real-World Time
44
-
45
- For 2.5 km in Tejgaon/Farmgate area:
46
-
47
- **At 4.8 km/h (current Dhaka average):**
48
- 2.5 km ÷ 4.8 km/h = **31 minutes**
49
-
50
- **At 5 km/h (peak hours):**
51
- 2.5 km ÷ 5 km/h = **30 minutes**
52
-
53
- ## Comparison
54
-
55
- | Method | Time Estimate | Accuracy |
56
- |--------|---------------|----------|
57
- | **Your Algorithm** | 57 minutes | ⚠️ 2x too slow |
58
- | **Real-World Data** | 30-31 minutes | ✅ Based on studies |
59
- | **Walking Speed** | ~30 minutes | (at 5 km/h) |
60
-
61
- ## Analysis
62
-
63
- ### Why the Discrepancy?
64
-
65
- Your algorithm is **conservative but over-estimates** by about 2x. Here's why:
66
-
67
- 1. **Base Speed Issue:**
68
- - Your algorithm: 8 km/h base speed
69
- - Reality: 4.8 km/h actual average
70
- - Your base is actually FASTER than reality!
71
-
72
- 2. **But Then You Add Too Many Delays:**
73
- - Traffic signals: +11 minutes
74
- - Intersections: +1.4 minutes
75
- - Congestion multiplier: +31 minutes (150% extra)
76
- - **Total delays: +43 minutes**
77
-
78
- 3. **The Problem:**
79
- - Real Dhaka traffic (4.8 km/h) already includes all these factors
80
- - Your algorithm applies them AGAIN on top of 8 km/h base
81
- - This double-counts the delays
82
-
83
- ### What This Means
84
-
85
- **Real Dhaka drivers experience:**
86
- - Constant crawling at 4.8 km/h
87
- - This already includes stopped time at signals, intersections, congestion
88
- - The 4.8 km/h is the "all-in" effective speed
89
-
90
- **Your algorithm assumes:**
91
- - 8 km/h when moving
92
- - PLUS separate time stopped at signals
93
- - PLUS separate congestion delays
94
- - Result: Double-counting leads to 2x estimate
95
-
96
- ## Verdict
97
-
98
- ### ✅ Your Algorithm is **Directionally Correct** but **Too Conservative**
99
-
100
- **Positive:**
101
- - Correctly identified Dhaka as heavy traffic city
102
- - Correctly detected peak hours
103
- - Better to over-estimate than under-estimate for delivery planning
104
-
105
- **Needs Adjustment:**
106
- - Your 57-minute estimate vs real 30-31 minutes
107
- - Off by about **26 minutes (2x)**
108
-
109
- ### Recommendation for Calibration
110
-
111
- For Dhaka peak hours, instead of:
112
- ```
113
- Base speed: 8 km/h
114
- + Signal delays
115
- + Intersection delays
116
- + Congestion multiplier (2.5x)
117
- = 57 minutes
118
- ```
119
-
120
- Should be:
121
- ```
122
- Effective all-in speed: 5 km/h
123
- (No additional multipliers - they're already baked in)
124
- = 30 minutes
125
- ```
126
-
127
- ## Conclusion
128
-
129
- **Your estimate: 57 minutes ⚠️**
130
- **Real-world: 30-31 minutes ✅**
131
- **Accuracy: Over-estimated by 85% (almost 2x)**
132
-
133
- However, this is actually **safer for delivery operations** than under-estimating. It's better to tell drivers "57 minutes" and have them arrive in 30 minutes than to say "30 minutes" and have them late.
134
-
135
- For **operational planning** (not real-time navigation), your conservative estimate provides a buffer for:
136
- - Unexpected delays
137
- - Accidents or road closures
138
- - Worst-case scenarios
139
-
140
- **Bottom line:** Your algorithm works, but could be fine-tuned to be more accurate. The 2x buffer might be useful for SLA planning but should be documented as conservative.
141
-
142
- ---
143
-
144
- ## Sources
145
-
146
- 1. "City speed drops to 4.5kmph from 21kmph in a decade" - The Business Standard
147
- 2. "Dhaka traffic at 4.0km per hour!" - The Financial Express
148
- 3. "Real Time Traffic Congestion Analyzer of Dhaka City" - BUET Study
149
- 4. "Dhaka's Farmgate: The new hub of traffic congestion" - Prothom Alo
150
- 5. Traffic in Dhaka - Numbeo (crowd-sourced traffic data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ROUTING_VERIFICATION_RESULTS.md DELETED
@@ -1,174 +0,0 @@
1
- # Enhanced Routing Algorithm - Verification Results
2
-
3
- ## Summary
4
- Successfully enhanced the routing algorithm with realistic urban traffic modeling and tested with two real-world routes.
5
-
6
- ## Enhancement Details
7
-
8
- ### Changes Made to `_calculate_route_mock()` in `chat/tools.py`
9
-
10
- 1. **Added City-Specific Traffic Profiles**
11
- - Dhaka profile: Heavy congestion (8-25 km/h speeds, 4 signals/km)
12
- - Default profile: Moderate traffic (20-40 km/h speeds, 2 signals/km)
13
-
14
- 2. **Time-of-Day Awareness**
15
- - Peak hours: 7-10 AM, 5-9 PM (slowest speeds)
16
- - Off-peak hours: 10 AM-5 PM (moderate speeds)
17
- - Night hours: 10 PM-6 AM (fastest speeds)
18
-
19
- 3. **Realistic Urban Delays**
20
- - Traffic signal delays: 45-50 seconds per signal
21
- - Intersection delays: 20-30 seconds per km
22
- - Congestion multipliers: 1.5x-2.5x during peak hours
23
- - Minimum 2-minute travel time
24
-
25
- ## Test Results
26
-
27
- ### Test 1: Dhaka Route (Heavy Traffic City)
28
-
29
- **Route:** Ahsanullah University → Bashundhara City Shopping Complex
30
- - **Origin:** 141, &142 Love Rd, Dhaka 1208, Bangladesh
31
- - **Destination:** 3 No, West Panthapath, Dhaka 1215, Bangladesh
32
- - **Distance:** 2.8 km
33
-
34
- **Algorithm Estimates:**
35
- - Base Duration: 21 minutes (at 8 km/h peak speed)
36
- - With Traffic: **63 minutes** (1 hour 3 minutes)
37
- - Traffic Delay: +200% (+42 minutes)
38
- - Breakdown:
39
- - Traffic signals: 550s (9.2 min) - 11 signals × 50s each
40
- - Intersections: 84s (1.4 min)
41
- - Congestion: 1896s (31.6 min) - 150% congestion multiplier
42
-
43
- **Comparison to Original Algorithm:**
44
- - **Before Enhancement:** 3 minutes (UNREALISTIC - 56 km/h average)
45
- - **After Enhancement:** 63 minutes
46
- - **Improvement:** 21x more realistic
47
-
48
- **Real-World Verification:**
49
- - Could not find exact Google Maps data for this specific route
50
- - Both locations are in Tejgaon area of central Dhaka
51
- - Based on 2.8 km distance in heavy Dhaka traffic, realistic estimate would be:
52
- - Off-peak: 10-15 minutes
53
- - Peak traffic: 15-25 minutes
54
-
55
- **Analysis:**
56
- - **Current estimate may be too conservative (2-3x too slow)**
57
- - Possible reasons:
58
- - Congestion multiplier (2.5x) might be too aggressive
59
- - Traffic signal count (4 per km) might be too high
60
- - All delays are additive, which may over-estimate total time
61
-
62
- ### Test 2: San Francisco Route (Moderate Traffic)
63
-
64
- **Route:** San Francisco City Hall → Oakland International Airport
65
- - **Origin:** 1 Dr Carlton B Goodlett Pl, San Francisco, CA 94102, USA
66
- - **Destination:** Oakland International Airport (OAK), 1 Airport Dr, Oakland, CA 94621, USA
67
- - **Distance:** 24.4 km (15.2 miles)
68
-
69
- **Algorithm Estimates:**
70
- - Base Duration: 73 minutes (at 20 km/h peak speed)
71
- - With Traffic: **154 minutes** (2 hours 34 minutes)
72
- - Traffic Delay: +110% (+81 minutes)
73
- - Breakdown:
74
- - Traffic signals: 2160s (36 min) - 48 signals × 45s each
75
- - Intersections: 488s (8.1 min)
76
- - Congestion: 2198s (36.6 min) - 50% congestion multiplier
77
-
78
- **Comparison to Original Algorithm:**
79
- - **Before Enhancement:** Would have been ~30 minutes (unrealistic constant speed)
80
- - **After Enhancement:** 154 minutes
81
-
82
- **Real-World Verification (from Rome2Rio and forums):**
83
- - **Distance:** ~20 miles (32 km) - our estimate: 24.4 km (close)
84
- - **Baseline time:** 27 minutes (without traffic)
85
- - **With peak traffic:** 27-87 minutes (adding 30-60 minutes delay)
86
- - **BART alternative:** 47 minutes
87
-
88
- **Analysis:**
89
- - **Current estimate is 2-3x too slow**
90
- - Real-world: 27-87 minutes
91
- - Our estimate: 154 minutes
92
- - Possible reasons:
93
- - Distance estimate is slightly low (24.4 km vs 32 km actual)
94
- - Base speed (20 km/h) is too conservative for highway segments
95
- - Too many traffic signals assumed (48 signals for highway route)
96
- - Congestion multiplier applied on top of already-slow speeds
97
-
98
- ## Observations & Recommendations
99
-
100
- ### What Works Well
101
-
102
- 1. **City Detection:** Successfully identified Dhaka from address
103
- 2. **Time-of-Day Detection:** Correctly identified peak hours
104
- 3. **Directional Improvement:** Algorithm is now 21x more realistic than before
105
- 4. **Structured Approach:** Clear breakdown of delays (signals, intersections, congestion)
106
-
107
- ### Areas for Improvement
108
-
109
- 1. **Congestion Multiplier is Too Aggressive**
110
- - Current: Adds 150% of base time for Dhaka peak
111
- - Suggestion: Reduce to 50-75% for peak hours
112
- - Reason: Other delays (signals, intersections) already slow things down
113
-
114
- 2. **Traffic Signal Count Needs Route Type Awareness**
115
- - Current: Assumes all routes have uniform signal density
116
- - Issue: Highway routes have fewer signals than urban streets
117
- - Suggestion: Reduce signal count for longer routes (>10 km)
118
-
119
- 3. **Base Speeds May Be Too Conservative**
120
- - Current: 8 km/h (Dhaka peak), 20 km/h (default peak)
121
- - Reality: Routes include highway segments with higher speeds
122
- - Suggestion: Use mixed speeds based on distance (urban vs highway)
123
-
124
- 4. **Minimum Travel Time (2 minutes)**
125
- - Good for preventing unrealistic short trips
126
- - May not be necessary for longer routes
127
-
128
- ### Suggested Tuning
129
-
130
- ```python
131
- # For Dhaka
132
- "peak_speed_kmh": 12, # Increase from 8 → 12 km/h
133
- "congestion_multiplier": 1.5, # Reduce from 2.5 → 1.5
134
-
135
- # For Default
136
- "peak_speed_kmh": 30, # Increase from 20 → 30 km/h
137
- "congestion_multiplier": 1.2, # Reduce from 1.5 → 1.2
138
-
139
- # Add route type detection
140
- if distance_km > 10:
141
- # Highway route - fewer signals
142
- signals_per_km /= 2
143
- speed_kmh *= 1.5 # Allow higher speeds for highway segments
144
- ```
145
-
146
- ## Conclusion
147
-
148
- ### Before Enhancement
149
- - **Dhaka (2.8 km):** 3 minutes ❌ (3-8x too fast)
150
- - Completely unrealistic for urban traffic
151
-
152
- ### After Enhancement
153
- - **Dhaka (2.8 km):** 63 minutes ⚠️ (2-3x too slow)
154
- - **San Francisco (24.4 km):** 154 minutes ⚠️ (2-3x too slow)
155
-
156
- ### Overall Assessment
157
-
158
- **Major Improvement Achieved:**
159
- - Algorithm went from being 3-8x too FAST to 2-3x too SLOW
160
- - This is a significant step in the right direction
161
- - Now accounts for realistic urban traffic factors
162
-
163
- **Current Status:**
164
- - ✅ City detection working
165
- - ✅ Time-of-day awareness working
166
- - ✅ Urban delay modeling implemented
167
- - ⚠️ Needs tuning to reduce over-conservative estimates
168
-
169
- **Recommended Next Step:**
170
- - Fine-tune congestion multipliers and base speeds
171
- - Add route type detection (urban vs highway)
172
- - Test again with adjusted parameters
173
-
174
- The enhanced algorithm is a major improvement over the original constant-speed calculation and provides a solid foundation for realistic routing. With parameter tuning, it can achieve accuracy within 10-20% of real-world times.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
archive/chat_engine.py DELETED
@@ -1,108 +0,0 @@
1
- """
2
- Chat engine for FleetMind
3
- Main orchestrator for AI-powered conversations with multi-provider support
4
- """
5
-
6
- import os
7
- import logging
8
- from typing import Tuple, List, Dict
9
-
10
- from chat.providers import ClaudeProvider, GeminiProvider
11
-
12
- logger = logging.getLogger(__name__)
13
-
14
-
15
- class ChatEngine:
16
- """Main orchestrator for AI chat conversations with multi-provider support"""
17
-
18
- def __init__(self):
19
- # Get provider selection from environment
20
- provider_name = os.getenv("AI_PROVIDER", "anthropic").lower()
21
-
22
- logger.info(f"ChatEngine: Selected provider: {provider_name}")
23
-
24
- # Initialize the selected provider
25
- if provider_name == "gemini":
26
- self.provider = GeminiProvider()
27
- logger.info("ChatEngine: Using Gemini provider")
28
- elif provider_name == "anthropic":
29
- self.provider = ClaudeProvider()
30
- logger.info("ChatEngine: Using Claude provider")
31
- else:
32
- # Default to Claude if unknown provider
33
- logger.warning(f"ChatEngine: Unknown provider '{provider_name}', defaulting to Claude")
34
- self.provider = ClaudeProvider()
35
-
36
- # Store provider name for UI
37
- self.selected_provider = provider_name
38
-
39
- def is_available(self) -> bool:
40
- """Check if the chat engine is available"""
41
- return self.provider.is_available()
42
-
43
- def get_status(self) -> str:
44
- """Get status message for UI"""
45
- provider_status = self.provider.get_status()
46
- provider_name = self.provider.get_provider_name()
47
-
48
- return f"**{provider_name}:** {provider_status}"
49
-
50
- def get_provider_name(self) -> str:
51
- """Get the active provider name"""
52
- return self.provider.get_provider_name()
53
-
54
- def get_model_name(self) -> str:
55
- """Get the active model name"""
56
- return self.provider.get_model_name()
57
-
58
- def process_message(
59
- self,
60
- user_message: str,
61
- conversation
62
- ) -> Tuple[str, List[Dict]]:
63
- """
64
- Process user message and return AI response
65
-
66
- Args:
67
- user_message: User's message
68
- conversation: ConversationManager instance
69
-
70
- Returns:
71
- Tuple of (assistant_response, tool_calls_made)
72
- """
73
- return self.provider.process_message(user_message, conversation)
74
-
75
- def get_welcome_message(self) -> str:
76
- """Get welcome message for new conversations"""
77
- return self.provider.get_welcome_message()
78
-
79
- def get_full_status(self) -> Dict[str, str]:
80
- """
81
- Get detailed status for all providers
82
-
83
- Returns:
84
- Dict with status for each provider
85
- """
86
- # Get status without creating new instances (avoid API calls)
87
- claude_key = os.getenv("ANTHROPIC_API_KEY", "")
88
- gemini_key = os.getenv("GOOGLE_API_KEY", "")
89
-
90
- claude_available = bool(claude_key and not claude_key.startswith("your_"))
91
- gemini_available = bool(gemini_key and not gemini_key.startswith("your_"))
92
-
93
- claude_status = "✅ Connected - Model: claude-3-5-sonnet-20241022" if claude_available else "⚠️ Not configured (add ANTHROPIC_API_KEY)"
94
- gemini_status = f"✅ Connected - Model: {self.provider.get_model_name()}" if (self.selected_provider == "gemini" and gemini_available) else "⚠️ Not configured (add GOOGLE_API_KEY)" if not gemini_available else "✅ Configured"
95
-
96
- return {
97
- "selected": self.selected_provider,
98
- "claude": {
99
- "name": "Claude (Anthropic)",
100
- "status": claude_status,
101
- "available": claude_available
102
- },
103
- "gemini": {
104
- "name": "Gemini (Google)",
105
- "status": gemini_status,
106
- "available": gemini_available
107
- }
108
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
archive/chat_providers/providers/__init__.py DELETED
@@ -1,10 +0,0 @@
1
- """
2
- AI Provider implementations for FleetMind chat
3
- Supports multiple AI providers (Anthropic Claude, Google Gemini)
4
- """
5
-
6
- from .base_provider import AIProvider
7
- from .claude_provider import ClaudeProvider
8
- from .gemini_provider import GeminiProvider
9
-
10
- __all__ = ['AIProvider', 'ClaudeProvider', 'GeminiProvider']
 
 
 
 
 
 
 
 
 
 
 
archive/chat_providers/providers/base_provider.py DELETED
@@ -1,53 +0,0 @@
1
- """
2
- Base provider interface for AI providers
3
- """
4
-
5
- from abc import ABC, abstractmethod
6
- from typing import Tuple, List, Dict
7
-
8
-
9
- class AIProvider(ABC):
10
- """Abstract base class for AI providers"""
11
-
12
- @abstractmethod
13
- def is_available(self) -> bool:
14
- """Check if the provider is available (API key configured)"""
15
- pass
16
-
17
- @abstractmethod
18
- def get_status(self) -> str:
19
- """Get status message for UI"""
20
- pass
21
-
22
- @abstractmethod
23
- def get_provider_name(self) -> str:
24
- """Get provider name (e.g., 'Claude', 'Gemini')"""
25
- pass
26
-
27
- @abstractmethod
28
- def get_model_name(self) -> str:
29
- """Get model name (e.g., 'claude-3-5-sonnet-20241022')"""
30
- pass
31
-
32
- @abstractmethod
33
- def process_message(
34
- self,
35
- user_message: str,
36
- conversation
37
- ) -> Tuple[str, List[Dict]]:
38
- """
39
- Process user message and return AI response
40
-
41
- Args:
42
- user_message: User's message
43
- conversation: ConversationManager instance
44
-
45
- Returns:
46
- Tuple of (assistant_response, tool_calls_made)
47
- """
48
- pass
49
-
50
- @abstractmethod
51
- def get_welcome_message(self) -> str:
52
- """Get welcome message for new conversations"""
53
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
archive/chat_providers/providers/claude_provider.py DELETED
@@ -1,373 +0,0 @@
1
- """
2
- Anthropic Claude provider for FleetMind chat
3
- """
4
-
5
- import os
6
- import logging
7
- from typing import Tuple, List, Dict
8
- from anthropic import Anthropic, APIError, APIConnectionError, AuthenticationError
9
-
10
- from chat.providers.base_provider import AIProvider
11
- from chat.tools import TOOLS_SCHEMA, execute_tool
12
-
13
- logger = logging.getLogger(__name__)
14
-
15
-
16
- class ClaudeProvider(AIProvider):
17
- """Anthropic Claude AI provider"""
18
-
19
- def __init__(self):
20
- self.api_key = os.getenv("ANTHROPIC_API_KEY", "")
21
- self.api_available = bool(self.api_key and not self.api_key.startswith("your_"))
22
-
23
- # Debug logging
24
- key_status = "not set" if not self.api_key else f"set ({len(self.api_key)} chars)"
25
- logger.info(f"ClaudeProvider init: ANTHROPIC_API_KEY {key_status}")
26
-
27
- if self.api_available:
28
- try:
29
- self.client = Anthropic(api_key=self.api_key)
30
- logger.info("ClaudeProvider: Initialized successfully")
31
- except Exception as e:
32
- logger.error(f"ClaudeProvider: Failed to initialize: {e}")
33
- self.api_available = False
34
- else:
35
- self.client = None
36
- logger.warning("ClaudeProvider: ANTHROPIC_API_KEY not configured")
37
-
38
- self.model = "claude-3-5-sonnet-20241022"
39
- self.system_prompt = self._get_system_prompt()
40
-
41
- def _get_system_prompt(self) -> str:
42
- """Get the system prompt for Claude"""
43
- return """You are an AI assistant for FleetMind, a delivery dispatch system. Your job is to help coordinators create and query delivery orders efficiently.
44
-
45
- **IMPORTANT: When a user wants to create an order, FIRST show them this order form:**
46
-
47
- 📋 **Order Information Form**
48
- Please provide the following details:
49
-
50
- **Required Fields:**
51
- • Customer Name: [Full name]
52
- • Delivery Address: [Street address, city, state, zip]
53
- • Contact: [Phone number OR email address]
54
-
55
- **Optional Fields:**
56
- • Delivery Deadline: [Date/time, or "ASAP" - default: 6 hours from now]
57
- • Priority: [standard/express/urgent - default: standard]
58
- • Special Instructions: [Any special notes]
59
- • Package Weight: [In kg - default: 5.0 kg]
60
-
61
- **Example:**
62
- "Customer: John Doe, Address: 123 Main St, San Francisco, CA 94103, Phone: 555-1234, Deliver by 5 PM today"
63
-
64
- ---
65
-
66
- **Your Workflow for ORDER CREATION:**
67
- 1. **If user says "create order" or similar:** Show the form above and ask them to provide the information
68
- 2. **If they provide all/most info:** Proceed immediately with geocoding and order creation
69
- 3. **If information is missing:** Show what's missing from the form and ask for those specific fields
70
- 4. **After collecting required fields:**
71
- - Use `geocode_address` tool to validate the address
72
- - Use `create_order` tool to save the order
73
- - Provide a clear confirmation with order ID
74
-
75
- **Your Workflow for ORDER QUERYING (INTERACTIVE):**
76
-
77
- When user asks to "fetch orders", "show orders", or "get orders":
78
- 1. First call `count_orders` (with any filters user mentioned)
79
- 2. Tell user: "I found X orders. How many would you like to see?"
80
- 3. Wait for user response
81
- 4. Call `fetch_orders` with the limit they specify
82
- 5. Display the results clearly
83
-
84
- When user asks "which orders are incomplete/not complete/pending":
85
- - Call `get_incomplete_orders` directly
86
- - Show results with priority and deadline
87
-
88
- When user asks about a specific order ID:
89
- - Call `get_order_details` with the order_id
90
- - Display all 26 fields clearly organized
91
-
92
- **Available Tools:**
93
-
94
- **Order Creation:**
95
- - geocode_address: Convert address to GPS coordinates
96
- - create_order: Create customer delivery order (REQUIRES geocoded address)
97
-
98
- **Order Querying:**
99
- - count_orders: Count orders with optional filters
100
- - fetch_orders: Fetch N orders with pagination and filters
101
- - get_order_details: Get complete info about specific order by ID
102
- - search_orders: Search by customer name/email/phone/order ID
103
- - get_incomplete_orders: Get all pending/assigned/in_transit orders
104
-
105
- **Driver Creation:**
106
- - create_driver: Add new driver to fleet
107
-
108
- **Driver Querying:**
109
- - count_drivers: Count drivers with optional filters
110
- - fetch_drivers: Fetch N drivers with pagination and filters
111
- - get_driver_details: Get complete info about specific driver by ID
112
- - search_drivers: Search by name/email/phone/plate/driver ID
113
- - get_available_drivers: Get all active/offline drivers
114
-
115
- **Available Order Filters:**
116
- - Status: pending, assigned, in_transit, delivered, failed, cancelled
117
- - Priority: standard, express, urgent
118
- - Payment: pending, paid, cod
119
- - Booleans: is_fragile, requires_signature, requires_cold_storage
120
- - Driver: assigned_driver_id
121
-
122
- **Available Driver Filters:**
123
- - Status: active, busy, offline, unavailable
124
- - Vehicle Type: van, truck, car, motorcycle, etc.
125
-
126
- **Your Workflow for DRIVER QUERYING (INTERACTIVE):**
127
-
128
- When user asks to "show drivers", "fetch drivers", or "get drivers":
129
- 1. First call `count_drivers` (with any filters user mentioned)
130
- 2. Tell user: "I found X drivers. How many would you like to see?"
131
- 3. Wait for user response
132
- 4. Call `fetch_drivers` with the limit they specify
133
- 5. Display the results clearly
134
-
135
- When user asks "which drivers are available/free":
136
- - Call `get_available_drivers` directly
137
- - Show results with status and vehicle info
138
-
139
- When user asks about a specific driver ID:
140
- - Call `get_driver_details` with the driver_id
141
- - Display all 15 fields clearly organized
142
-
143
- **Important Rules:**
144
- - ALWAYS geocode the address BEFORE creating an order
145
- - Be efficient - don't ask questions one at a time
146
- - Accept information in any format (natural language, bullet points, etc.)
147
- - Keep responses concise and professional
148
- - Show enthusiasm when orders/drivers are successfully created
149
- - For order/driver queries, be interactive and helpful with summaries
150
-
151
- Remember: Dispatch coordinators are busy - help them work efficiently!"""
152
-
153
- def is_available(self) -> bool:
154
- return self.api_available
155
-
156
- def get_status(self) -> str:
157
- if self.api_available:
158
- return f"✅ Connected - Model: {self.model}"
159
- return "⚠️ Not configured (add ANTHROPIC_API_KEY)"
160
-
161
- def get_provider_name(self) -> str:
162
- return "Claude (Anthropic)"
163
-
164
- def get_model_name(self) -> str:
165
- return self.model
166
-
167
- def process_message(
168
- self,
169
- user_message: str,
170
- conversation
171
- ) -> Tuple[str, List[Dict]]:
172
- """Process user message with Claude"""
173
- if not self.api_available:
174
- return self._handle_no_api(), []
175
-
176
- # Add user message to history
177
- conversation.add_message("user", user_message)
178
-
179
- try:
180
- # Make API call to Claude
181
- response = self.client.messages.create(
182
- model=self.model,
183
- max_tokens=4096,
184
- system=self.system_prompt,
185
- tools=TOOLS_SCHEMA,
186
- messages=conversation.get_history()
187
- )
188
-
189
- # Process response and handle tool calls
190
- return self._process_response(response, conversation)
191
-
192
- except AuthenticationError:
193
- error_msg = "⚠️ Invalid API key. Please check your ANTHROPIC_API_KEY in .env file."
194
- logger.error("Authentication error with Anthropic API")
195
- return error_msg, []
196
-
197
- except APIConnectionError:
198
- error_msg = "⚠️ Cannot connect to Anthropic API. Please check your internet connection."
199
- logger.error("Connection error with Anthropic API")
200
- return error_msg, []
201
-
202
- except APIError as e:
203
- error_msg = f"⚠️ API error: {str(e)}"
204
- logger.error(f"Anthropic API error: {e}")
205
- return error_msg, []
206
-
207
- except Exception as e:
208
- error_msg = f"⚠️ Unexpected error: {str(e)}"
209
- logger.error(f"Claude provider error: {e}")
210
- return error_msg, []
211
-
212
- def _process_response(
213
- self,
214
- response,
215
- conversation
216
- ) -> Tuple[str, List[Dict]]:
217
- """Process Claude's response and handle tool calls"""
218
- tool_calls_made = []
219
-
220
- # Check if Claude wants to use tools
221
- if response.stop_reason == "tool_use":
222
- # Execute tools
223
- tool_results = []
224
-
225
- for content_block in response.content:
226
- if content_block.type == "tool_use":
227
- tool_name = content_block.name
228
- tool_input = content_block.input
229
-
230
- logger.info(f"Claude executing tool: {tool_name}")
231
-
232
- # Execute the tool
233
- tool_result = execute_tool(tool_name, tool_input)
234
-
235
- # Track for transparency
236
- tool_calls_made.append({
237
- "tool": tool_name,
238
- "input": tool_input,
239
- "result": tool_result
240
- })
241
-
242
- conversation.add_tool_result(tool_name, tool_input, tool_result)
243
-
244
- # Prepare result for Claude
245
- tool_results.append({
246
- "type": "tool_result",
247
- "tool_use_id": content_block.id,
248
- "content": str(tool_result)
249
- })
250
-
251
- # Add assistant's tool use to history
252
- conversation.add_message("assistant", response.content)
253
-
254
- # Add tool results to history
255
- conversation.add_message("user", tool_results)
256
-
257
- # Continue conversation with tool results
258
- followup_response = self.client.messages.create(
259
- model=self.model,
260
- max_tokens=4096,
261
- system=self.system_prompt,
262
- tools=TOOLS_SCHEMA,
263
- messages=conversation.get_history()
264
- )
265
-
266
- # Extract final text response
267
- final_text = self._extract_text_response(followup_response)
268
- conversation.add_message("assistant", final_text)
269
-
270
- return final_text, tool_calls_made
271
-
272
- else:
273
- # No tool use, just text response
274
- text_response = self._extract_text_response(response)
275
- conversation.add_message("assistant", text_response)
276
- return text_response, tool_calls_made
277
-
278
- def _extract_text_response(self, response) -> str:
279
- """Extract text content from Claude's response"""
280
- text_parts = []
281
- for block in response.content:
282
- if hasattr(block, 'text'):
283
- text_parts.append(block.text)
284
- elif block.type == "text":
285
- text_parts.append(block.text if hasattr(block, 'text') else str(block))
286
-
287
- return "\n".join(text_parts) if text_parts else "I apologize, but I couldn't generate a response."
288
-
289
- def _handle_no_api(self) -> str:
290
- """Return error message when API is not available"""
291
- return """⚠️ **Claude API requires Anthropic API key**
292
-
293
- To use Claude:
294
-
295
- 1. Get an API key from: https://console.anthropic.com/
296
- - Sign up for free ($5 credit available)
297
- - Or use hackathon credits
298
-
299
- 2. Add to your `.env` file:
300
- ```
301
- ANTHROPIC_API_KEY=sk-ant-your-key-here
302
- ```
303
-
304
- 3. Restart the application
305
-
306
- **Alternative:** Switch to Gemini by setting `AI_PROVIDER=gemini` in .env
307
- """
308
-
309
- def get_welcome_message(self) -> str:
310
- if not self.api_available:
311
- return self._handle_no_api()
312
-
313
- return """👋 Hello! I'm your AI dispatch assistant powered by **Claude Sonnet 3.5**.
314
-
315
- I can help you create and query delivery orders and drivers quickly and efficiently!
316
-
317
- ---
318
-
319
- 📋 **To Create an Order, Provide:**
320
-
321
- **Required:**
322
- • Customer Name
323
- • Delivery Address
324
- • Contact (Phone OR Email)
325
-
326
- **Optional:**
327
- • Delivery Deadline (default: 6 hours)
328
- • Priority: standard/express/urgent (default: standard)
329
- • Special Instructions
330
- • Package Weight in kg (default: 5.0)
331
-
332
- ---
333
-
334
- 🔍 **To Query Orders:**
335
-
336
- • "Fetch orders" or "Show orders" - I'll ask how many
337
- • "Which orders are incomplete?" - See all pending/in-progress orders
338
- • "Tell me about order ORD-XXX" - Get complete order details
339
- • "Show me 10 urgent orders" - Filter by priority
340
- • "Search for orders from John" - Find by customer name
341
-
342
- ---
343
-
344
- 🚚 **To Create a Driver:**
345
-
346
- **Required:** Driver Name
347
- **Optional:** Phone, Email, Vehicle Type, Plate, Capacity, Skills
348
-
349
- ---
350
-
351
- 👥 **To Query Drivers:**
352
-
353
- • "Show me drivers" or "Fetch drivers" - I'll ask how many
354
- • "Which drivers are available?" - See all active/offline drivers
355
- • "Tell me about driver DRV-XXX" - Get complete driver details
356
- • "Show 5 active drivers with vans" - Filter by status and vehicle
357
- • "Search for Tom" - Find by driver name
358
-
359
- ---
360
-
361
- **Quick Start Examples:**
362
-
363
- ✅ **Create Order:** "Create order for John Doe, 123 Main St San Francisco CA, phone 555-1234, deliver by 5 PM"
364
-
365
- ✅ **Query Orders:** "Fetch the orders" or "Show me incomplete orders"
366
-
367
- ✅ **Create Driver:** "Add driver Tom Wilson, phone 555-0101, drives a van, plate ABC-123"
368
-
369
- ✅ **Query Drivers:** "Show me drivers" or "Which drivers are available?"
370
-
371
- ---
372
-
373
- What would you like to do?"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
archive/chat_providers/providers/gemini_provider.py DELETED
@@ -1,983 +0,0 @@
1
- """
2
- Google Gemini provider for FleetMind chat
3
- """
4
-
5
- import os
6
- import logging
7
- from typing import Tuple, List, Dict
8
- import google.generativeai as genai
9
- from google.generativeai.types import HarmCategory, HarmBlockThreshold
10
-
11
- from chat.providers.base_provider import AIProvider
12
- from chat.tools import execute_tool
13
-
14
- logger = logging.getLogger(__name__)
15
-
16
-
17
- class GeminiProvider(AIProvider):
18
- """Google Gemini AI provider"""
19
-
20
- def __init__(self):
21
- self.api_key = os.getenv("GOOGLE_API_KEY", "")
22
- self.api_available = bool(self.api_key and not self.api_key.startswith("your_"))
23
- self.model_name = "gemini-2.0-flash"
24
- self.model = None
25
- self._initialized = False
26
-
27
- # Debug logging
28
- key_status = "not set" if not self.api_key else f"set ({len(self.api_key)} chars)"
29
- logger.info(f"GeminiProvider init: GOOGLE_API_KEY {key_status}")
30
-
31
- if not self.api_available:
32
- logger.warning("GeminiProvider: GOOGLE_API_KEY not configured")
33
- else:
34
- logger.info("GeminiProvider: Ready (will initialize on first use)")
35
-
36
- def _get_system_prompt(self) -> str:
37
- """Get the system prompt for Gemini"""
38
- return """You are an AI assistant for FleetMind, a delivery dispatch system.
39
-
40
- **🚨 CRITICAL RULES - READ CAREFULLY:**
41
-
42
- 1. **NEVER return text in the middle of tool calls**
43
- - If you need to call multiple tools, call them ALL in sequence
44
- - Only return text AFTER all tools are complete
45
-
46
- 2. **Order Creation MUST be a single automated flow:**
47
- - Step 1: Call geocode_address (get coordinates)
48
- - Step 2: IMMEDIATELY call create_order (save to database)
49
- - Step 3: ONLY THEN return success message
50
- - DO NOT stop between Step 1 and Step 2
51
- - DO NOT say "Now creating order..." - just DO it!
52
-
53
- 3. **Driver Creation is a SINGLE tool call:**
54
- - When user wants to create a driver, call create_driver immediately
55
- - NO geocoding needed for drivers
56
- - Just call create_driver → confirm
57
-
58
- 4. **If user provides required info, START IMMEDIATELY:**
59
- - For Orders: Customer name, address, contact (phone OR email)
60
- - For Drivers: Driver name (phone/email optional)
61
- - If all present → execute → confirm
62
- - If missing → ask ONCE for all missing fields
63
-
64
- **Example of CORRECT behavior:**
65
-
66
- ORDER:
67
- User: "Create order for John Doe, 123 Main St SF, phone 555-1234"
68
- You: [geocode_address] → [create_order] → "✅ Order ORD-123 created!"
69
- (ALL in one response, no intermediate text)
70
-
71
- DRIVER:
72
- User: "Add new driver Mike Johnson, phone 555-0101, drives a van"
73
- You: [create_driver] → "✅ Driver DRV-123 (Mike Johnson) added to fleet!"
74
- (Single tool call, immediate response)
75
-
76
- **Example of WRONG behavior (DO NOT DO THIS):**
77
- User: "Create order for John Doe..."
78
- You: [geocode_address] → "OK geocoded, now creating..." ❌ WRONG!
79
-
80
- **Available Tools:**
81
-
82
- **Order Creation:**
83
- - geocode_address: Convert address to GPS coordinates
84
- - create_order: Create customer delivery order (REQUIRES geocoded address)
85
-
86
- **Order Management:**
87
- - update_order: Update existing order's details (status, priority, address, etc.)
88
- - delete_order: Permanently delete an order (requires confirm=true)
89
-
90
- **Order Querying (INTERACTIVE):**
91
- - count_orders: Count orders with optional filters
92
- - fetch_orders: Fetch N orders with pagination and filters
93
- - get_order_details: Get complete info about specific order by ID
94
- - search_orders: Search by customer name/email/phone/order ID
95
- - get_incomplete_orders: Get all pending/assigned/in_transit orders
96
-
97
- **Driver Creation:**
98
- - create_driver: Add new driver/delivery man to fleet
99
-
100
- **Driver Management:**
101
- - update_driver: Update existing driver's details (name, status, vehicle, location, etc.)
102
- - delete_driver: Permanently delete a driver (requires confirm=true)
103
-
104
- **Driver Querying (INTERACTIVE):**
105
- - count_drivers: Count drivers with optional filters
106
- - fetch_drivers: Fetch N drivers with pagination and filters
107
- - get_driver_details: Get complete info about specific driver by ID (includes current location with latitude, longitude, and human-readable address)
108
- - search_drivers: Search by name/email/phone/plate/driver ID
109
- - get_available_drivers: Get all active/offline drivers ready for dispatch
110
-
111
- **Order Fields:**
112
- Required: customer_name, delivery_address, contact
113
- Optional: time_window_end, priority (standard/express/urgent), special_instructions, weight_kg
114
-
115
- **Driver Fields:**
116
- Required: name
117
- Optional: phone, email, vehicle_type (van/truck/car/motorcycle), vehicle_plate, capacity_kg, capacity_m3, skills (list), status (active/busy/offline)
118
-
119
- **Order Query Workflow (INTERACTIVE - this is DIFFERENT from creation):**
120
-
121
- When user asks to "fetch orders", "show orders", or "get orders":
122
- 1. First call count_orders (with any filters user mentioned)
123
- 2. Tell user: "I found X orders. How many would you like to see?"
124
- 3. Wait for user response
125
- 4. Call fetch_orders with the limit they specify
126
- 5. Display the results clearly
127
-
128
- When user asks "which orders are incomplete/not complete/pending":
129
- - Call get_incomplete_orders directly
130
- - Show results with priority and deadline
131
-
132
- When user asks about a specific order ID:
133
- - Call get_order_details with the order_id
134
- - Display all 26 fields clearly organized
135
-
136
- **Available Filters (use when user specifies):**
137
- - Status: pending, assigned, in_transit, delivered, failed, cancelled
138
- - Priority: standard, express, urgent
139
- - Payment: pending, paid, cod
140
- - Booleans: is_fragile, requires_signature, requires_cold_storage
141
- - Driver: assigned_driver_id
142
-
143
- **Example Interactions:**
144
-
145
- User: "Fetch the orders"
146
- You: [count_orders] → "I found 45 orders in the database. How many would you like to see? (I can also filter by status, priority, etc.)"
147
-
148
- User: "Show me 10 urgent ones"
149
- You: [fetch_orders with limit=10, priority=urgent] → [Display 10 urgent orders]
150
-
151
- User: "Which orders are incomplete?"
152
- You: [get_incomplete_orders] → [Display all pending/assigned/in_transit orders]
153
-
154
- User: "Tell me about order ORD-20251114120000"
155
- You: [get_order_details with order_id=ORD-20251114120000] → [Display complete order details]
156
-
157
- **Driver Query Workflow (INTERACTIVE - same as orders):**
158
-
159
- When user asks to "show drivers", "fetch drivers", or "get drivers":
160
- 1. First call count_drivers (with any filters user mentioned)
161
- 2. Tell user: "I found X drivers. How many would you like to see?"
162
- 3. Wait for user response
163
- 4. Call fetch_drivers with the limit they specify
164
- 5. Display the results clearly
165
-
166
- When user asks "which drivers are available/free":
167
- - Call get_available_drivers directly
168
- - Show results with status and vehicle info
169
-
170
- When user asks about a specific driver ID:
171
- - Call get_driver_details with the driver_id
172
- - Display all 15 fields clearly organized
173
-
174
- **Available Driver Filters:**
175
- - Status: active, busy, offline, unavailable (4 values)
176
- - Vehicle Type: van, truck, car, motorcycle, etc.
177
- - Sorting: name, status, created_at, last_location_update
178
-
179
- **Example Driver Interactions:**
180
-
181
- User: "Show me drivers"
182
- You: [count_drivers] → "I found 15 drivers. How many would you like to see?"
183
-
184
- User: "Show 5 active ones with vans"
185
- You: [fetch_drivers with limit=5, status=active, vehicle_type=van] → [Display 5 drivers]
186
-
187
- User: "Which drivers are available?"
188
- You: [get_available_drivers] → [Display all active/offline drivers]
189
-
190
- User: "Tell me about driver DRV-20251114163800"
191
- You: [get_driver_details with driver_id=DRV-20251114163800] → [Display complete driver details]
192
-
193
- **Your goal:**
194
- - Order CREATION: Execute in ONE smooth automated flow (no stopping!)
195
- - Order QUERYING: Be interactive, ask user for preferences, provide helpful summaries
196
- - Driver CREATION: Single tool call, immediate response
197
- - Driver QUERYING: Be interactive, ask how many, provide helpful summaries"""
198
-
199
- def _get_gemini_tools(self) -> list:
200
- """Convert tool schemas to Gemini function calling format"""
201
- # Gemini expects tools wrapped in function_declarations
202
- return [
203
- genai.protos.Tool(
204
- function_declarations=[
205
- genai.protos.FunctionDeclaration(
206
- name="geocode_address",
207
- description="Convert a delivery address to GPS coordinates and validate the address format. Use this before creating an order to ensure the address is valid.",
208
- parameters=genai.protos.Schema(
209
- type=genai.protos.Type.OBJECT,
210
- properties={
211
- "address": genai.protos.Schema(
212
- type=genai.protos.Type.STRING,
213
- description="The full delivery address to geocode (e.g., '123 Main St, San Francisco, CA')"
214
- )
215
- },
216
- required=["address"]
217
- )
218
- ),
219
- genai.protos.FunctionDeclaration(
220
- name="create_order",
221
- description="Create a new delivery order in the database. Only call this after geocoding the address successfully.",
222
- parameters=genai.protos.Schema(
223
- type=genai.protos.Type.OBJECT,
224
- properties={
225
- "customer_name": genai.protos.Schema(
226
- type=genai.protos.Type.STRING,
227
- description="Full name of the customer"
228
- ),
229
- "customer_phone": genai.protos.Schema(
230
- type=genai.protos.Type.STRING,
231
- description="Customer phone number (optional)"
232
- ),
233
- "customer_email": genai.protos.Schema(
234
- type=genai.protos.Type.STRING,
235
- description="Customer email address (optional)"
236
- ),
237
- "delivery_address": genai.protos.Schema(
238
- type=genai.protos.Type.STRING,
239
- description="Full delivery address"
240
- ),
241
- "delivery_lat": genai.protos.Schema(
242
- type=genai.protos.Type.NUMBER,
243
- description="Latitude from geocoding"
244
- ),
245
- "delivery_lng": genai.protos.Schema(
246
- type=genai.protos.Type.NUMBER,
247
- description="Longitude from geocoding"
248
- ),
249
- "time_window_end": genai.protos.Schema(
250
- type=genai.protos.Type.STRING,
251
- description="Delivery deadline in ISO format (e.g., '2025-11-13T17:00:00'). If not specified by user, default to 6 hours from now."
252
- ),
253
- "priority": genai.protos.Schema(
254
- type=genai.protos.Type.STRING,
255
- description="Delivery priority. Default to 'standard' unless user specifies urgent/express."
256
- ),
257
- "special_instructions": genai.protos.Schema(
258
- type=genai.protos.Type.STRING,
259
- description="Any special delivery instructions (optional)"
260
- ),
261
- "weight_kg": genai.protos.Schema(
262
- type=genai.protos.Type.NUMBER,
263
- description="Package weight in kilograms (optional, default to 5.0)"
264
- )
265
- },
266
- required=["customer_name", "delivery_address", "delivery_lat", "delivery_lng"]
267
- )
268
- ),
269
- genai.protos.FunctionDeclaration(
270
- name="create_driver",
271
- description="Create a new delivery driver/delivery man in the database. Use this to onboard new drivers to the fleet.",
272
- parameters=genai.protos.Schema(
273
- type=genai.protos.Type.OBJECT,
274
- properties={
275
- "name": genai.protos.Schema(
276
- type=genai.protos.Type.STRING,
277
- description="Full name of the driver"
278
- ),
279
- "phone": genai.protos.Schema(
280
- type=genai.protos.Type.STRING,
281
- description="Driver phone number"
282
- ),
283
- "email": genai.protos.Schema(
284
- type=genai.protos.Type.STRING,
285
- description="Driver email address (optional)"
286
- ),
287
- "vehicle_type": genai.protos.Schema(
288
- type=genai.protos.Type.STRING,
289
- description="Type of vehicle: van, truck, car, motorcycle (default: van)"
290
- ),
291
- "vehicle_plate": genai.protos.Schema(
292
- type=genai.protos.Type.STRING,
293
- description="Vehicle license plate number"
294
- ),
295
- "capacity_kg": genai.protos.Schema(
296
- type=genai.protos.Type.NUMBER,
297
- description="Vehicle cargo capacity in kilograms (default: 1000.0)"
298
- ),
299
- "capacity_m3": genai.protos.Schema(
300
- type=genai.protos.Type.NUMBER,
301
- description="Vehicle cargo volume in cubic meters (default: 12.0)"
302
- ),
303
- "skills": genai.protos.Schema(
304
- type=genai.protos.Type.ARRAY,
305
- description="List of driver skills/certifications: refrigerated, medical_certified, fragile_handler, overnight, express_delivery",
306
- items=genai.protos.Schema(type=genai.protos.Type.STRING)
307
- ),
308
- "status": genai.protos.Schema(
309
- type=genai.protos.Type.STRING,
310
- description="Driver status: active, busy, offline, unavailable (default: active)"
311
- )
312
- },
313
- required=["name"]
314
- )
315
- ),
316
- genai.protos.FunctionDeclaration(
317
- name="count_orders",
318
- description="Count total orders in the database with optional filters. Use this when user asks 'how many orders', 'fetch orders', or wants to know order statistics.",
319
- parameters=genai.protos.Schema(
320
- type=genai.protos.Type.OBJECT,
321
- properties={
322
- "status": genai.protos.Schema(
323
- type=genai.protos.Type.STRING,
324
- description="Filter by order status: pending, assigned, in_transit, delivered, failed, cancelled (optional)"
325
- ),
326
- "priority": genai.protos.Schema(
327
- type=genai.protos.Type.STRING,
328
- description="Filter by priority level: standard, express, urgent (optional)"
329
- ),
330
- "payment_status": genai.protos.Schema(
331
- type=genai.protos.Type.STRING,
332
- description="Filter by payment status: pending, paid, cod (optional)"
333
- ),
334
- "assigned_driver_id": genai.protos.Schema(
335
- type=genai.protos.Type.STRING,
336
- description="Filter by assigned driver ID (optional)"
337
- ),
338
- "is_fragile": genai.protos.Schema(
339
- type=genai.protos.Type.BOOLEAN,
340
- description="Filter fragile packages only (optional)"
341
- ),
342
- "requires_signature": genai.protos.Schema(
343
- type=genai.protos.Type.BOOLEAN,
344
- description="Filter orders requiring signature (optional)"
345
- ),
346
- "requires_cold_storage": genai.protos.Schema(
347
- type=genai.protos.Type.BOOLEAN,
348
- description="Filter orders requiring cold storage (optional)"
349
- )
350
- },
351
- required=[]
352
- )
353
- ),
354
- genai.protos.FunctionDeclaration(
355
- name="fetch_orders",
356
- description="Fetch orders from the database with optional filters, pagination, and sorting. Use after counting to show specific number of orders.",
357
- parameters=genai.protos.Schema(
358
- type=genai.protos.Type.OBJECT,
359
- properties={
360
- "limit": genai.protos.Schema(
361
- type=genai.protos.Type.INTEGER,
362
- description="Number of orders to fetch (default: 10, max: 100)"
363
- ),
364
- "offset": genai.protos.Schema(
365
- type=genai.protos.Type.INTEGER,
366
- description="Number of orders to skip for pagination (default: 0)"
367
- ),
368
- "status": genai.protos.Schema(
369
- type=genai.protos.Type.STRING,
370
- description="Filter by order status: pending, assigned, in_transit, delivered, failed, cancelled (optional)"
371
- ),
372
- "priority": genai.protos.Schema(
373
- type=genai.protos.Type.STRING,
374
- description="Filter by priority level: standard, express, urgent (optional)"
375
- ),
376
- "payment_status": genai.protos.Schema(
377
- type=genai.protos.Type.STRING,
378
- description="Filter by payment status: pending, paid, cod (optional)"
379
- ),
380
- "assigned_driver_id": genai.protos.Schema(
381
- type=genai.protos.Type.STRING,
382
- description="Filter by assigned driver ID (optional)"
383
- ),
384
- "is_fragile": genai.protos.Schema(
385
- type=genai.protos.Type.BOOLEAN,
386
- description="Filter fragile packages only (optional)"
387
- ),
388
- "requires_signature": genai.protos.Schema(
389
- type=genai.protos.Type.BOOLEAN,
390
- description="Filter orders requiring signature (optional)"
391
- ),
392
- "requires_cold_storage": genai.protos.Schema(
393
- type=genai.protos.Type.BOOLEAN,
394
- description="Filter orders requiring cold storage (optional)"
395
- ),
396
- "sort_by": genai.protos.Schema(
397
- type=genai.protos.Type.STRING,
398
- description="Field to sort by: created_at, priority, time_window_start (default: created_at)"
399
- ),
400
- "sort_order": genai.protos.Schema(
401
- type=genai.protos.Type.STRING,
402
- description="Sort order: ASC, DESC (default: DESC for newest first)"
403
- )
404
- },
405
- required=[]
406
- )
407
- ),
408
- genai.protos.FunctionDeclaration(
409
- name="get_order_details",
410
- description="Get complete details of a specific order by order ID. Use when user asks 'tell me about order X' or wants detailed information about a specific order.",
411
- parameters=genai.protos.Schema(
412
- type=genai.protos.Type.OBJECT,
413
- properties={
414
- "order_id": genai.protos.Schema(
415
- type=genai.protos.Type.STRING,
416
- description="The order ID to fetch details for (e.g., 'ORD-20251114163800')"
417
- )
418
- },
419
- required=["order_id"]
420
- )
421
- ),
422
- genai.protos.FunctionDeclaration(
423
- name="search_orders",
424
- description="Search for orders by customer name, email, phone, or order ID pattern. Use when user provides partial information to find orders.",
425
- parameters=genai.protos.Schema(
426
- type=genai.protos.Type.OBJECT,
427
- properties={
428
- "search_term": genai.protos.Schema(
429
- type=genai.protos.Type.STRING,
430
- description="Search term to match against customer_name, customer_email, customer_phone, or order_id"
431
- )
432
- },
433
- required=["search_term"]
434
- )
435
- ),
436
- genai.protos.FunctionDeclaration(
437
- name="get_incomplete_orders",
438
- description="Get all orders that are not yet completed (excludes delivered and cancelled orders). Shortcut for finding orders in progress (pending, assigned, in_transit).",
439
- parameters=genai.protos.Schema(
440
- type=genai.protos.Type.OBJECT,
441
- properties={
442
- "limit": genai.protos.Schema(
443
- type=genai.protos.Type.INTEGER,
444
- description="Number of orders to fetch (default: 20)"
445
- )
446
- },
447
- required=[]
448
- )
449
- ),
450
- genai.protos.FunctionDeclaration(
451
- name="count_drivers",
452
- description="Count total drivers in the database with optional filters. Use this when user asks 'how many drivers', 'show drivers', or wants driver statistics.",
453
- parameters=genai.protos.Schema(
454
- type=genai.protos.Type.OBJECT,
455
- properties={
456
- "status": genai.protos.Schema(
457
- type=genai.protos.Type.STRING,
458
- description="Filter by driver status: active, busy, offline, unavailable (optional)"
459
- ),
460
- "vehicle_type": genai.protos.Schema(
461
- type=genai.protos.Type.STRING,
462
- description="Filter by vehicle type: van, truck, car, motorcycle, etc. (optional)"
463
- )
464
- },
465
- required=[]
466
- )
467
- ),
468
- genai.protos.FunctionDeclaration(
469
- name="fetch_drivers",
470
- description="Fetch drivers from the database with optional filters, pagination, and sorting. Use after counting to show specific number of drivers.",
471
- parameters=genai.protos.Schema(
472
- type=genai.protos.Type.OBJECT,
473
- properties={
474
- "limit": genai.protos.Schema(
475
- type=genai.protos.Type.INTEGER,
476
- description="Number of drivers to fetch (default: 10, max: 100)"
477
- ),
478
- "offset": genai.protos.Schema(
479
- type=genai.protos.Type.INTEGER,
480
- description="Number of drivers to skip for pagination (default: 0)"
481
- ),
482
- "status": genai.protos.Schema(
483
- type=genai.protos.Type.STRING,
484
- description="Filter by driver status: active, busy, offline, unavailable (optional)"
485
- ),
486
- "vehicle_type": genai.protos.Schema(
487
- type=genai.protos.Type.STRING,
488
- description="Filter by vehicle type: van, truck, car, motorcycle, etc. (optional)"
489
- ),
490
- "sort_by": genai.protos.Schema(
491
- type=genai.protos.Type.STRING,
492
- description="Field to sort by: name, status, created_at, last_location_update (default: name)"
493
- ),
494
- "sort_order": genai.protos.Schema(
495
- type=genai.protos.Type.STRING,
496
- description="Sort order: ASC, DESC (default: ASC for alphabetical)"
497
- )
498
- },
499
- required=[]
500
- )
501
- ),
502
- genai.protos.FunctionDeclaration(
503
- name="get_driver_details",
504
- description="Get complete details of a specific driver by driver ID, including current location (latitude, longitude, and human-readable address), contact info, vehicle details, status, and skills. Use when user asks about a driver's location, coordinates, position, or any other driver information.",
505
- parameters=genai.protos.Schema(
506
- type=genai.protos.Type.OBJECT,
507
- properties={
508
- "driver_id": genai.protos.Schema(
509
- type=genai.protos.Type.STRING,
510
- description="The driver ID to fetch details for (e.g., 'DRV-20251114163800')"
511
- )
512
- },
513
- required=["driver_id"]
514
- )
515
- ),
516
- genai.protos.FunctionDeclaration(
517
- name="search_drivers",
518
- description="Search for drivers by name, email, phone, vehicle plate, or driver ID pattern. Use when user provides partial information to find drivers.",
519
- parameters=genai.protos.Schema(
520
- type=genai.protos.Type.OBJECT,
521
- properties={
522
- "search_term": genai.protos.Schema(
523
- type=genai.protos.Type.STRING,
524
- description="Search term to match against name, email, phone, vehicle_plate, or driver_id"
525
- )
526
- },
527
- required=["search_term"]
528
- )
529
- ),
530
- genai.protos.FunctionDeclaration(
531
- name="get_available_drivers",
532
- description="Get all drivers that are available for assignment (active or offline status, excludes busy and unavailable). Shortcut for finding drivers ready for dispatch.",
533
- parameters=genai.protos.Schema(
534
- type=genai.protos.Type.OBJECT,
535
- properties={
536
- "limit": genai.protos.Schema(
537
- type=genai.protos.Type.INTEGER,
538
- description="Number of drivers to fetch (default: 20)"
539
- )
540
- },
541
- required=[]
542
- )
543
- ),
544
- genai.protos.FunctionDeclaration(
545
- name="update_order",
546
- description="Update an existing order's details. You can update any combination of fields. Only provide the fields you want to change.",
547
- parameters=genai.protos.Schema(
548
- type=genai.protos.Type.OBJECT,
549
- properties={
550
- "order_id": genai.protos.Schema(type=genai.protos.Type.STRING, description="Order ID to update"),
551
- "customer_name": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated customer name"),
552
- "customer_phone": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated customer phone"),
553
- "customer_email": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated customer email"),
554
- "delivery_address": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated delivery address"),
555
- "delivery_lat": genai.protos.Schema(type=genai.protos.Type.NUMBER, description="Updated delivery latitude"),
556
- "delivery_lng": genai.protos.Schema(type=genai.protos.Type.NUMBER, description="Updated delivery longitude"),
557
- "status": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated order status (pending/assigned/in_transit/delivered/failed/cancelled)"),
558
- "priority": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated priority (standard/express/urgent)"),
559
- "special_instructions": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated special instructions"),
560
- "time_window_end": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated delivery deadline"),
561
- "payment_status": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated payment status (pending/paid/cod)"),
562
- "weight_kg": genai.protos.Schema(type=genai.protos.Type.NUMBER, description="Updated weight in kg"),
563
- "order_value": genai.protos.Schema(type=genai.protos.Type.NUMBER, description="Updated order value")
564
- },
565
- required=["order_id"]
566
- )
567
- ),
568
- genai.protos.FunctionDeclaration(
569
- name="delete_order",
570
- description="Permanently delete an order from the database. This action cannot be undone. Use with caution.",
571
- parameters=genai.protos.Schema(
572
- type=genai.protos.Type.OBJECT,
573
- properties={
574
- "order_id": genai.protos.Schema(type=genai.protos.Type.STRING, description="Order ID to delete"),
575
- "confirm": genai.protos.Schema(type=genai.protos.Type.BOOLEAN, description="Must be true to confirm deletion")
576
- },
577
- required=["order_id", "confirm"]
578
- )
579
- ),
580
- genai.protos.FunctionDeclaration(
581
- name="update_driver",
582
- description="Update an existing driver's details. You can update any combination of fields. Only provide the fields you want to change.",
583
- parameters=genai.protos.Schema(
584
- type=genai.protos.Type.OBJECT,
585
- properties={
586
- "driver_id": genai.protos.Schema(type=genai.protos.Type.STRING, description="Driver ID to update"),
587
- "name": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated driver name"),
588
- "phone": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated phone"),
589
- "email": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated email"),
590
- "status": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated status (active/busy/offline/unavailable)"),
591
- "vehicle_type": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated vehicle type"),
592
- "vehicle_plate": genai.protos.Schema(type=genai.protos.Type.STRING, description="Updated vehicle plate"),
593
- "capacity_kg": genai.protos.Schema(type=genai.protos.Type.NUMBER, description="Updated capacity in kg"),
594
- "capacity_m3": genai.protos.Schema(type=genai.protos.Type.NUMBER, description="Updated capacity in m³"),
595
- "current_lat": genai.protos.Schema(type=genai.protos.Type.NUMBER, description="Updated current latitude"),
596
- "current_lng": genai.protos.Schema(type=genai.protos.Type.NUMBER, description="Updated current longitude")
597
- },
598
- required=["driver_id"]
599
- )
600
- ),
601
- genai.protos.FunctionDeclaration(
602
- name="delete_driver",
603
- description="Permanently delete a driver from the database. This action cannot be undone. Use with caution.",
604
- parameters=genai.protos.Schema(
605
- type=genai.protos.Type.OBJECT,
606
- properties={
607
- "driver_id": genai.protos.Schema(type=genai.protos.Type.STRING, description="Driver ID to delete"),
608
- "confirm": genai.protos.Schema(type=genai.protos.Type.BOOLEAN, description="Must be true to confirm deletion")
609
- },
610
- required=["driver_id", "confirm"]
611
- )
612
- )
613
- ]
614
- )
615
- ]
616
-
617
- def _ensure_initialized(self):
618
- """Lazy initialization - only create model when first needed"""
619
- if self._initialized or not self.api_available:
620
- return
621
-
622
- try:
623
- genai.configure(api_key=self.api_key)
624
- self.model = genai.GenerativeModel(
625
- model_name=self.model_name,
626
- tools=self._get_gemini_tools(),
627
- system_instruction=self._get_system_prompt()
628
- )
629
- self._initialized = True
630
- logger.info(f"GeminiProvider: Model initialized ({self.model_name})")
631
- except Exception as e:
632
- logger.error(f"GeminiProvider: Failed to initialize: {e}")
633
- self.api_available = False
634
- self.model = None
635
-
636
- def is_available(self) -> bool:
637
- return self.api_available
638
-
639
- def get_status(self) -> str:
640
- if self.api_available:
641
- return f"✅ Connected - Model: {self.model_name}"
642
- return "⚠️ Not configured (add GOOGLE_API_KEY)"
643
-
644
- def get_provider_name(self) -> str:
645
- return "Gemini (Google)"
646
-
647
- def get_model_name(self) -> str:
648
- return self.model_name if self.api_available else "gemini-2.0-flash"
649
-
650
- def process_message(
651
- self,
652
- user_message: str,
653
- conversation
654
- ) -> Tuple[str, List[Dict]]:
655
- """Process user message with Gemini"""
656
- if not self.api_available:
657
- return self._handle_no_api(), []
658
-
659
- # Lazy initialization on first use
660
- self._ensure_initialized()
661
-
662
- if not self._initialized:
663
- return "⚠️ Failed to initialize Gemini model. Please check your API key and try again.", []
664
-
665
- try:
666
- # Build conversation history for Gemini
667
- chat = self.model.start_chat(history=self._convert_history(conversation))
668
-
669
- # Send message and get response
670
- response = chat.send_message(
671
- user_message,
672
- safety_settings={
673
- HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
674
- HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
675
- HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
676
- HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
677
- }
678
- )
679
-
680
- # Add user message to conversation
681
- conversation.add_message("user", user_message)
682
-
683
- # Process response and handle function calls
684
- return self._process_response(response, conversation, chat)
685
-
686
- except Exception as e:
687
- error_msg = f"⚠️ Gemini API error: {str(e)}"
688
- logger.error(f"Gemini provider error: {e}")
689
- return error_msg, []
690
-
691
- def _convert_history(self, conversation) -> list:
692
- """Convert conversation history to Gemini format"""
693
- history = []
694
- # Get all messages from conversation (history is built before adding current message)
695
- for msg in conversation.get_history():
696
- role = "user" if msg["role"] == "user" else "model"
697
- history.append({
698
- "role": role,
699
- "parts": [{"text": str(msg["content"])}]
700
- })
701
- return history
702
-
703
- def _process_response(
704
- self,
705
- response,
706
- conversation,
707
- chat
708
- ) -> Tuple[str, List[Dict]]:
709
- """Process Gemini's response and handle function calls"""
710
- tool_calls_made = []
711
-
712
- # Check if Gemini wants to call functions
713
- try:
714
- # Check ALL parts for function calls (not just first)
715
- has_function_call = False
716
- parts = response.candidates[0].content.parts
717
- logger.info(f"Processing response with {len(parts)} part(s)")
718
-
719
- for part in parts:
720
- if hasattr(part, 'function_call'):
721
- fc = part.function_call
722
- # More robust check
723
- if fc is not None:
724
- try:
725
- if hasattr(fc, 'name') and fc.name:
726
- has_function_call = True
727
- logger.info(f"Detected function call: {fc.name}")
728
- break
729
- except Exception as e:
730
- logger.warning(f"Error checking function call: {e}")
731
-
732
- if has_function_call:
733
- # Handle function calls (potentially multiple in sequence)
734
- current_response = response
735
- max_iterations = 3 # Prevent rate limit errors (Gemini free tier: 15 req/min)
736
-
737
- for iteration in range(max_iterations):
738
- # Check if current response has a function call
739
- try:
740
- parts = current_response.candidates[0].content.parts
741
- logger.info(f"Iteration {iteration + 1}: Response has {len(parts)} part(s)")
742
- except (IndexError, AttributeError) as e:
743
- logger.error(f"Cannot access response parts: {e}")
744
- break
745
-
746
- # Check ALL parts for function calls (some responses have text + function_call)
747
- has_fc = False
748
- fc_part = None
749
-
750
- for idx, part in enumerate(parts):
751
- if hasattr(part, 'function_call'):
752
- fc = part.function_call
753
- if fc and hasattr(fc, 'name') and fc.name:
754
- has_fc = True
755
- fc_part = part
756
- logger.info(f"Iteration {iteration + 1}: Found function_call in part {idx}: {fc.name}")
757
- break
758
-
759
- # Also check if there's text (indicates Gemini wants to respond instead of continuing)
760
- if hasattr(part, 'text') and part.text:
761
- logger.warning(f"Iteration {iteration + 1}: Part {idx} has text: {part.text[:100]}")
762
-
763
- if not has_fc:
764
- # No more function calls, break and extract text
765
- logger.info(f"No more function calls after iteration {iteration + 1}")
766
- break
767
-
768
- # Use the part with function_call
769
- first_part = fc_part
770
-
771
- # Extract function call details
772
- function_call = first_part.function_call
773
- function_name = function_call.name
774
- function_args = dict(function_call.args) if function_call.args else {}
775
-
776
- logger.info(f"Gemini executing function: {function_name} (iteration {iteration + 1})")
777
-
778
- # Execute the tool
779
- tool_result = execute_tool(function_name, function_args)
780
-
781
- # Track for transparency
782
- tool_calls_made.append({
783
- "tool": function_name,
784
- "input": function_args,
785
- "result": tool_result
786
- })
787
-
788
- conversation.add_tool_result(function_name, function_args, tool_result)
789
-
790
- # Send function result back to Gemini
791
- try:
792
- current_response = chat.send_message(
793
- genai.protos.Content(
794
- parts=[genai.protos.Part(
795
- function_response=genai.protos.FunctionResponse(
796
- name=function_name,
797
- response={"result": tool_result}
798
- )
799
- )]
800
- )
801
- )
802
- except Exception as e:
803
- logger.error(f"Error sending function response: {e}")
804
- break
805
-
806
- # Now extract text from the final response
807
- # NEVER use .text property directly - always check parts
808
- final_text = ""
809
- try:
810
- parts = current_response.candidates[0].content.parts
811
- logger.info(f"Extracting text from {len(parts)} parts")
812
-
813
- for idx, part in enumerate(parts):
814
- # Check if this part has a function call
815
- if hasattr(part, 'function_call') and part.function_call:
816
- fc = part.function_call
817
- if hasattr(fc, 'name') and fc.name:
818
- logger.warning(f"Part {idx} still has function call: {fc.name}. Skipping.")
819
- continue
820
-
821
- # Extract text from this part
822
- if hasattr(part, 'text') and part.text:
823
- logger.info(f"Part {idx} has text: {part.text[:50]}...")
824
- final_text += part.text
825
-
826
- except (AttributeError, IndexError) as e:
827
- logger.error(f"Error extracting text from parts: {e}")
828
-
829
- # Generate fallback message if still no text
830
- if not final_text:
831
- logger.warning("No text extracted from response, generating fallback")
832
- if tool_calls_made:
833
- # Create a summary of what was done
834
- tool_names = [t["tool"] for t in tool_calls_made]
835
- if "create_order" in tool_names:
836
- # Check if order was created successfully
837
- create_result = next((t["result"] for t in tool_calls_made if t["tool"] == "create_order"), {})
838
- if create_result.get("success"):
839
- order_id = create_result.get("order_id", "")
840
- final_text = f"✅ Order {order_id} created successfully!"
841
- else:
842
- final_text = "⚠️ There was an issue creating the order."
843
- else:
844
- final_text = f"✅ Executed {len(tool_calls_made)} tool(s) successfully!"
845
- else:
846
- final_text = "✅ Task completed!"
847
-
848
- logger.info(f"Returning response: {final_text[:100]}")
849
- conversation.add_message("assistant", final_text)
850
- return final_text, tool_calls_made
851
-
852
- else:
853
- # No function call detected, extract text from parts
854
- text_response = ""
855
- try:
856
- parts = response.candidates[0].content.parts
857
- logger.info(f"Extracting text from {len(parts)} parts (no function call)")
858
-
859
- for idx, part in enumerate(parts):
860
- # Double-check no function call in this part
861
- if hasattr(part, 'function_call') and part.function_call:
862
- fc = part.function_call
863
- if hasattr(fc, 'name') and fc.name:
864
- logger.error(f"Part {idx} has function call {fc.name} but was not detected earlier!")
865
- # We missed a function call - handle it now
866
- logger.info("Re-processing response with function call handling")
867
- return self._process_response(response, conversation, chat)
868
-
869
- # Extract text
870
- if hasattr(part, 'text') and part.text:
871
- logger.info(f"Part {idx} has text: {part.text[:50]}...")
872
- text_response += part.text
873
-
874
- except (ValueError, AttributeError, IndexError) as e:
875
- logger.error(f"Error extracting text from response: {e}")
876
-
877
- # Fallback if no text extracted
878
- if not text_response:
879
- logger.warning("No text in response, using fallback")
880
- text_response = "I'm ready to help! What would you like me to do?"
881
-
882
- conversation.add_message("assistant", text_response)
883
- return text_response, tool_calls_made
884
-
885
- except Exception as e:
886
- logger.error(f"Error processing Gemini response: {e}")
887
- error_msg = f"⚠️ Error processing response: {str(e)}"
888
- conversation.add_message("assistant", error_msg)
889
- return error_msg, tool_calls_made
890
-
891
- def _handle_no_api(self) -> str:
892
- """Return error message when API is not available"""
893
- return """⚠️ **Gemini API requires Google API key**
894
-
895
- To use Gemini:
896
-
897
- 1. Get an API key from: https://aistudio.google.com/app/apikey
898
- - Free tier: 15 requests/min, 1500/day
899
- - Or use hackathon credits
900
-
901
- 2. Add to your `.env` file:
902
- ```
903
- GOOGLE_API_KEY=your-gemini-key-here
904
- ```
905
-
906
- 3. Restart the application
907
-
908
- **Alternative:** Switch to Claude by setting `AI_PROVIDER=anthropic` in .env
909
- """
910
-
911
- def get_welcome_message(self) -> str:
912
- if not self.api_available:
913
- return self._handle_no_api()
914
-
915
- # Don't initialize model yet - wait for first actual message
916
- # This allows the welcome message to load instantly
917
-
918
- return """👋 Hello! I'm your AI dispatch assistant powered by **Google Gemini 2.0 Flash**.
919
-
920
- I can help you manage your delivery fleet!
921
-
922
- ---
923
-
924
- 📋 **What I Can Do:**
925
-
926
- **1. Create Delivery Orders:**
927
- • Customer Name
928
- • Delivery Address
929
- • Contact (Phone OR Email)
930
- • Optional: Deadline, Priority, Special Instructions
931
-
932
- **2. Query & Search Orders:**
933
- • Fetch orders with filters (status, priority, payment, etc.)
934
- • Get complete details of specific orders
935
- • Search by customer name, phone, email, or order ID
936
- • Find incomplete/pending orders
937
-
938
- **3. Create New Drivers:**
939
- • Driver Name (required)
940
- • Optional: Phone, Email, Vehicle Type, License Plate, Skills
941
-
942
- **4. Query & Search Drivers:**
943
- • Fetch drivers with filters (status, vehicle type)
944
- • Get complete details of specific drivers
945
- • Search by name, phone, email, plate, or driver ID
946
- • Find available/active drivers
947
-
948
- ---
949
-
950
- **Examples - Just Type Naturally:**
951
-
952
- 📦 **Create Orders:**
953
- 💬 "Create order for John Doe, 123 Main St San Francisco CA, phone 555-1234, deliver by 5 PM"
954
- 💬 "New urgent delivery to Sarah at 456 Oak Ave NYC, email [email protected]"
955
-
956
- 🔍 **Query Orders:**
957
- 💬 "Fetch the orders" or "Show me orders"
958
- 💬 "Which orders are incomplete?"
959
- 💬 "Tell me about order ORD-20251114120000"
960
- 💬 "Show me 10 urgent orders"
961
- 💬 "Search for orders from John"
962
-
963
- 🚚 **Create Drivers:**
964
- 💬 "Add new driver Tom Wilson, phone 555-0101, drives a van, plate ABC-123"
965
- 💬 "Create driver Sarah Martinez with refrigerated truck, phone 555-0202"
966
- 💬 "New driver: Mike Chen, email [email protected], motorcycle delivery"
967
-
968
- 👥 **Query Drivers:**
969
- 💬 "Show me drivers" or "Fetch the drivers"
970
- 💬 "Which drivers are available?"
971
- 💬 "Tell me about driver DRV-20251114163800"
972
- 💬 "Show 5 active drivers with vans"
973
- 💬 "Search for Tom"
974
-
975
- ---
976
-
977
- 🚀 **I'll automatically:**
978
- • Geocode addresses for orders
979
- • Generate unique IDs
980
- • Save everything to the database
981
- • Filter and search across all order fields
982
-
983
- What would you like to do?"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
archive/conversation.py DELETED
@@ -1,85 +0,0 @@
1
- """
2
- Conversation manager for FleetMind chat
3
- Handles conversation state and history
4
- """
5
-
6
- import logging
7
- from typing import List, Dict
8
-
9
- logger = logging.getLogger(__name__)
10
-
11
-
12
- class ConversationManager:
13
- """Manage conversation state and history"""
14
-
15
- def __init__(self):
16
- self.history = []
17
- self.tool_calls = [] # Track all tool calls for transparency
18
- self.order_context = {} # Accumulated order details
19
-
20
- def add_message(self, role: str, content: str):
21
- """
22
- Add message to conversation history
23
-
24
- Args:
25
- role: "user" or "assistant"
26
- content: Message content
27
- """
28
- self.history.append({
29
- "role": role,
30
- "content": content
31
- })
32
-
33
- def add_tool_result(self, tool_name: str, tool_input: dict, tool_result: dict):
34
- """
35
- Track tool usage for transparency
36
-
37
- Args:
38
- tool_name: Name of the tool called
39
- tool_input: Input parameters
40
- tool_result: Result from tool execution
41
- """
42
- self.tool_calls.append({
43
- "tool": tool_name,
44
- "input": tool_input,
45
- "result": tool_result
46
- })
47
-
48
- def get_history(self) -> List[Dict]:
49
- """Get full conversation history"""
50
- return self.history
51
-
52
- def get_tool_calls(self) -> List[Dict]:
53
- """Get all tool calls made in this conversation"""
54
- return self.tool_calls
55
-
56
- def get_last_tool_call(self) -> Dict:
57
- """Get the most recent tool call"""
58
- if self.tool_calls:
59
- return self.tool_calls[-1]
60
- return {}
61
-
62
- def clear_tool_calls(self):
63
- """Clear tool call history"""
64
- self.tool_calls = []
65
-
66
- def reset(self):
67
- """Start a new conversation"""
68
- self.history = []
69
- self.tool_calls = []
70
- self.order_context = {}
71
- logger.info("Conversation reset")
72
-
73
- def get_message_count(self) -> int:
74
- """Get number of messages in conversation"""
75
- return len(self.history)
76
-
77
- def get_formatted_history(self) -> List[Dict]:
78
- """
79
- Get history formatted for Gradio chatbot (messages format)
80
-
81
- Returns:
82
- List of message dictionaries with 'role' and 'content' keys
83
- """
84
- # For Gradio type="messages", return list of dicts with role/content
85
- return self.history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
archive/old_app.py DELETED
@@ -1,28 +0,0 @@
1
- """
2
- FleetMind MCP - Hugging Face Spaces Entry Point
3
- This is the main entry point for the HF Space deployment
4
- """
5
-
6
- import sys
7
- from pathlib import Path
8
-
9
- # Add current directory to path
10
- sys.path.insert(0, str(Path(__file__).parent))
11
-
12
- # Import and launch the Gradio app
13
- from ui.app import create_interface
14
-
15
- if __name__ == "__main__":
16
- print("=" * 60)
17
- print("FleetMind MCP - Starting on Hugging Face Spaces")
18
- print("=" * 60)
19
-
20
- # Create and launch the interface
21
- app = create_interface()
22
- app.launch(
23
- server_name="0.0.0.0",
24
- server_port=7860,
25
- share=False,
26
- show_error=True,
27
- show_api=False # Disable API docs to avoid schema parsing bug
28
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
archive/ui/ui/__init__.py DELETED
@@ -1,4 +0,0 @@
1
- """
2
- UI package for FleetMind
3
- Contains Gradio interface components
4
- """
 
 
 
 
 
archive/ui/ui/app.py DELETED
@@ -1,1127 +0,0 @@
1
- """
2
- FleetMind MCP - Gradio Web Interface
3
- Enhanced 3-tab dashboard: Chat, Orders, Drivers
4
- """
5
-
6
- import sys
7
- from pathlib import Path
8
-
9
- # Add parent directory to path
10
- sys.path.insert(0, str(Path(__file__).parent.parent))
11
-
12
- import gradio as gr
13
- from database.connection import execute_query, execute_write, test_connection
14
- from datetime import datetime, timedelta
15
- import json
16
-
17
- # Import chat functionality
18
- from chat.chat_engine import ChatEngine
19
- from chat.conversation import ConversationManager
20
- from chat.geocoding import GeocodingService
21
- import uuid
22
-
23
- # Global session storage
24
- SESSIONS = {}
25
-
26
- # Initialize chat engine and geocoding service
27
- chat_engine = ChatEngine()
28
- geocoding_service = GeocodingService()
29
-
30
- # ============================================
31
- # STATISTICS FUNCTIONS
32
- # ============================================
33
-
34
- def get_orders_stats():
35
- """Get order statistics by status"""
36
- try:
37
- query = """
38
- SELECT
39
- COUNT(*) as total,
40
- COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending,
41
- COUNT(CASE WHEN status = 'assigned' THEN 1 END) as assigned,
42
- COUNT(CASE WHEN status = 'in_transit' THEN 1 END) as in_transit,
43
- COUNT(CASE WHEN status = 'delivered' THEN 1 END) as delivered,
44
- COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed,
45
- COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled
46
- FROM orders
47
- """
48
- result = execute_query(query)
49
- if result:
50
- return result[0]
51
- return {"total": 0, "pending": 0, "assigned": 0, "in_transit": 0, "delivered": 0, "failed": 0, "cancelled": 0}
52
- except Exception as e:
53
- print(f"Error getting order stats: {e}")
54
- return {"total": 0, "pending": 0, "assigned": 0, "in_transit": 0, "delivered": 0, "failed": 0, "cancelled": 0}
55
-
56
-
57
- def get_drivers_stats():
58
- """Get driver statistics by status"""
59
- try:
60
- query = """
61
- SELECT
62
- COUNT(*) as total,
63
- COUNT(CASE WHEN status = 'active' THEN 1 END) as active,
64
- COUNT(CASE WHEN status = 'busy' THEN 1 END) as busy,
65
- COUNT(CASE WHEN status = 'offline' THEN 1 END) as offline,
66
- COUNT(CASE WHEN status = 'unavailable' THEN 1 END) as unavailable
67
- FROM drivers
68
- """
69
- result = execute_query(query)
70
- if result:
71
- return result[0]
72
- return {"total": 0, "active": 0, "busy": 0, "offline": 0, "unavailable": 0}
73
- except Exception as e:
74
- print(f"Error getting driver stats: {e}")
75
- return {"total": 0, "active": 0, "busy": 0, "offline": 0, "unavailable": 0}
76
-
77
-
78
- # ============================================
79
- # ORDERS FUNCTIONS
80
- # ============================================
81
-
82
- def get_all_orders(status_filter="all", priority_filter="all", payment_filter="all", search_term=""):
83
- """Get orders with filters"""
84
- try:
85
- where_clauses = []
86
- params = []
87
-
88
- if status_filter and status_filter != "all":
89
- where_clauses.append("status = %s")
90
- params.append(status_filter)
91
-
92
- if priority_filter and priority_filter != "all":
93
- where_clauses.append("priority = %s")
94
- params.append(priority_filter)
95
-
96
- if payment_filter and payment_filter != "all":
97
- where_clauses.append("payment_status = %s")
98
- params.append(payment_filter)
99
-
100
- if search_term:
101
- where_clauses.append("(order_id ILIKE %s OR customer_name ILIKE %s OR customer_phone ILIKE %s)")
102
- search_pattern = f"%{search_term}%"
103
- params.extend([search_pattern, search_pattern, search_pattern])
104
-
105
- where_sql = " WHERE " + " AND ".join(where_clauses) if where_clauses else ""
106
-
107
- query = f"""
108
- SELECT
109
- order_id,
110
- customer_name,
111
- delivery_address,
112
- status,
113
- priority,
114
- assigned_driver_id,
115
- time_window_end,
116
- created_at
117
- FROM orders
118
- {where_sql}
119
- ORDER BY created_at DESC
120
- LIMIT 100
121
- """
122
-
123
- results = execute_query(query, tuple(params) if params else ())
124
-
125
- if not results:
126
- return [["-", "-", "-", "-", "-", "-", "-"]]
127
-
128
- # Format data for table
129
- data = []
130
- for row in results:
131
- # Truncate address if too long
132
- address = row['delivery_address']
133
- if len(address) > 40:
134
- address = address[:37] + "..."
135
-
136
- # Format deadline
137
- deadline = row['time_window_end'].strftime("%Y-%m-%d %H:%M") if row['time_window_end'] else "No deadline"
138
-
139
- # Driver ID or "Unassigned"
140
- driver = row['assigned_driver_id'] if row['assigned_driver_id'] else "Unassigned"
141
-
142
- data.append([
143
- row['order_id'],
144
- row['customer_name'],
145
- address,
146
- row['status'],
147
- row['priority'],
148
- driver,
149
- deadline
150
- ])
151
-
152
- return data
153
- except Exception as e:
154
- print(f"Error fetching orders: {e}")
155
- return [[f"Error: {str(e)}", "", "", "", "", "", ""]]
156
-
157
-
158
- def get_order_details(order_id):
159
- """Get complete order details"""
160
- if not order_id or order_id == "-":
161
- return "Select an order from the table to view details"
162
-
163
- try:
164
- query = """
165
- SELECT * FROM orders WHERE order_id = %s
166
- """
167
- results = execute_query(query, (order_id,))
168
-
169
- if not results:
170
- return f"Order {order_id} not found"
171
-
172
- order = results[0]
173
-
174
- # Format the details nicely
175
- details = f"""
176
- # Order Details: {order_id}
177
-
178
- ## Customer Information
179
- - **Name:** {order['customer_name']}
180
- - **Phone:** {order['customer_phone'] or 'N/A'}
181
- - **Email:** {order['customer_email'] or 'N/A'}
182
-
183
- ## Delivery Information
184
- - **Address:** {order['delivery_address']}
185
- - **Coordinates:** ({order['delivery_lat']}, {order['delivery_lng']})
186
- - **Time Window:** {order['time_window_start']} to {order['time_window_end']}
187
-
188
- ## Package Details
189
- - **Weight:** {order['weight_kg'] or 'N/A'} kg
190
- - **Volume:** {order['volume_m3'] or 'N/A'} m³
191
- - **Is Fragile:** {"Yes" if order['is_fragile'] else "No"}
192
- - **Requires Signature:** {"Yes" if order['requires_signature'] else "No"}
193
- - **Requires Cold Storage:** {"Yes" if order['requires_cold_storage'] else "No"}
194
-
195
- ## Order Status
196
- - **Status:** {order['status']}
197
- - **Priority:** {order['priority']}
198
- - **Assigned Driver:** {order['assigned_driver_id'] or 'Unassigned'}
199
-
200
- ## Payment
201
- - **Order Value:** ${order['order_value'] or '0.00'}
202
- - **Payment Status:** {order['payment_status']}
203
-
204
- ## Special Instructions
205
- {order['special_instructions'] or 'None'}
206
-
207
- ## Timestamps
208
- - **Created:** {order['created_at']}
209
- - **Updated:** {order['updated_at']}
210
- - **Delivered:** {order['delivered_at'] or 'Not delivered yet'}
211
- """
212
- return details
213
-
214
- except Exception as e:
215
- return f"Error fetching order details: {str(e)}"
216
-
217
-
218
- # ============================================
219
- # DRIVERS FUNCTIONS
220
- # ============================================
221
-
222
- def get_all_drivers(status_filter="all", vehicle_filter="all", search_term=""):
223
- """Get drivers with filters"""
224
- try:
225
- where_clauses = []
226
- params = []
227
-
228
- if status_filter and status_filter != "all":
229
- where_clauses.append("status = %s")
230
- params.append(status_filter)
231
-
232
- if vehicle_filter and vehicle_filter != "all":
233
- where_clauses.append("vehicle_type = %s")
234
- params.append(vehicle_filter)
235
-
236
- if search_term:
237
- where_clauses.append("(driver_id ILIKE %s OR name ILIKE %s OR phone ILIKE %s OR vehicle_plate ILIKE %s)")
238
- search_pattern = f"%{search_term}%"
239
- params.extend([search_pattern, search_pattern, search_pattern, search_pattern])
240
-
241
- where_sql = " WHERE " + " AND ".join(where_clauses) if where_clauses else ""
242
-
243
- query = f"""
244
- SELECT
245
- driver_id,
246
- name,
247
- phone,
248
- status,
249
- vehicle_type,
250
- vehicle_plate,
251
- current_lat,
252
- current_lng,
253
- last_location_update
254
- FROM drivers
255
- {where_sql}
256
- ORDER BY name ASC
257
- LIMIT 100
258
- """
259
-
260
- results = execute_query(query, tuple(params) if params else ())
261
-
262
- if not results:
263
- return [["-", "-", "-", "-", "-", "-", "-"]]
264
-
265
- # Format data for table
266
- data = []
267
- for row in results:
268
- # Format location
269
- if row['current_lat'] and row['current_lng']:
270
- location = f"{row['current_lat']:.4f}, {row['current_lng']:.4f}"
271
- else:
272
- location = "No location"
273
-
274
- # Format last update
275
- last_update = row['last_location_update'].strftime("%Y-%m-%d %H:%M") if row['last_location_update'] else "Never"
276
-
277
- data.append([
278
- row['driver_id'],
279
- row['name'],
280
- row['phone'] or "N/A",
281
- row['status'],
282
- f"{row['vehicle_type']} - {row['vehicle_plate'] or 'N/A'}",
283
- location,
284
- last_update
285
- ])
286
-
287
- return data
288
- except Exception as e:
289
- print(f"Error fetching drivers: {e}")
290
- return [[f"Error: {str(e)}", "", "", "", "", "", ""]]
291
-
292
-
293
- def get_driver_details(driver_id):
294
- """Get complete driver details"""
295
- if not driver_id or driver_id == "-":
296
- return "Select a driver from the table to view details"
297
-
298
- try:
299
- query = """
300
- SELECT * FROM drivers WHERE driver_id = %s
301
- """
302
- results = execute_query(query, (driver_id,))
303
-
304
- if not results:
305
- return f"Driver {driver_id} not found"
306
-
307
- driver = results[0]
308
-
309
- # Parse skills (handle both list and JSON string)
310
- if driver['skills']:
311
- if isinstance(driver['skills'], list):
312
- skills = driver['skills']
313
- else:
314
- skills = json.loads(driver['skills'])
315
- else:
316
- skills = []
317
- skills_str = ", ".join(skills) if skills else "None"
318
-
319
- # Format the details nicely
320
- details = f"""
321
- # Driver Details: {driver_id}
322
-
323
- ## Personal Information
324
- - **Name:** {driver['name']}
325
- - **Phone:** {driver['phone'] or 'N/A'}
326
- - **Email:** {driver['email'] or 'N/A'}
327
-
328
- ## Current Location
329
- - **Coordinates:** ({driver['current_lat']}, {driver['current_lng']})
330
- - **Last Update:** {driver['last_location_update'] or 'Never updated'}
331
-
332
- ## Status
333
- - **Status:** {driver['status']}
334
-
335
- ## Vehicle Information
336
- - **Type:** {driver['vehicle_type']}
337
- - **Plate:** {driver['vehicle_plate'] or 'N/A'}
338
- - **Capacity (kg):** {driver['capacity_kg'] or 'N/A'}
339
- - **Capacity (m³):** {driver['capacity_m3'] or 'N/A'}
340
-
341
- ## Skills & Certifications
342
- {skills_str}
343
-
344
- ## Timestamps
345
- - **Created:** {driver['created_at']}
346
- - **Updated:** {driver['updated_at']}
347
- """
348
- return details
349
-
350
- except Exception as e:
351
- return f"Error fetching driver details: {str(e)}"
352
-
353
-
354
- def update_order_ui(order_id, **fields):
355
- """Update order via UI"""
356
- from chat.tools import execute_tool
357
-
358
- if not order_id:
359
- return {"success": False, "message": "Order ID is required"}
360
-
361
- # Build tool input
362
- tool_input = {"order_id": order_id}
363
- tool_input.update(fields)
364
-
365
- # Call update tool
366
- result = execute_tool("update_order", tool_input)
367
-
368
- return result
369
-
370
-
371
- def delete_order_ui(order_id):
372
- """Delete order via UI"""
373
- from chat.tools import execute_tool
374
-
375
- if not order_id:
376
- return {"success": False, "message": "Order ID is required"}
377
-
378
- # Call delete tool with confirmation
379
- result = execute_tool("delete_order", {"order_id": order_id, "confirm": True})
380
-
381
- return result
382
-
383
-
384
- def update_driver_ui(driver_id, **fields):
385
- """Update driver via UI"""
386
- from chat.tools import execute_tool
387
-
388
- if not driver_id:
389
- return {"success": False, "message": "Driver ID is required"}
390
-
391
- # Build tool input
392
- tool_input = {"driver_id": driver_id}
393
- tool_input.update(fields)
394
-
395
- # Call update tool
396
- result = execute_tool("update_driver", tool_input)
397
-
398
- return result
399
-
400
-
401
- def delete_driver_ui(driver_id):
402
- """Delete driver via UI"""
403
- from chat.tools import execute_tool
404
-
405
- if not driver_id:
406
- return {"success": False, "message": "Driver ID is required"}
407
-
408
- # Call delete tool with confirmation
409
- result = execute_tool("delete_driver", {"driver_id": driver_id, "confirm": True})
410
-
411
- return result
412
-
413
-
414
- # ============================================
415
- # CHAT FUNCTIONS
416
- # ============================================
417
-
418
- def get_api_status():
419
- """Get API status for chat"""
420
- full_status = chat_engine.get_full_status()
421
- selected = full_status["selected"]
422
- claude_status = full_status["claude"]["status"]
423
- gemini_status = full_status["gemini"]["status"]
424
- geocoding_status = geocoding_service.get_status()
425
-
426
- claude_marker = "🎯 **ACTIVE** - " if selected == "anthropic" else ""
427
- gemini_marker = "🎯 **ACTIVE** - " if selected == "gemini" else ""
428
-
429
- return f"""**AI Provider:**
430
-
431
- **Claude:** {claude_marker}{claude_status}
432
- **Gemini:** {gemini_marker}{gemini_status}
433
-
434
- **Geocoding:** {geocoding_status}
435
- """
436
-
437
-
438
- def handle_chat_message(message, session_id):
439
- """Handle chat message from user"""
440
- if session_id not in SESSIONS:
441
- SESSIONS[session_id] = ConversationManager()
442
- welcome = chat_engine.get_welcome_message()
443
- SESSIONS[session_id].add_message("assistant", welcome)
444
-
445
- conversation = SESSIONS[session_id]
446
-
447
- if not message.strip():
448
- return conversation.get_formatted_history(), conversation.get_tool_calls(), session_id
449
-
450
- response, tool_calls = chat_engine.process_message(message, conversation)
451
- return conversation.get_formatted_history(), conversation.get_tool_calls(), session_id
452
-
453
-
454
- def reset_conversation(session_id):
455
- """Reset conversation to start fresh"""
456
- new_session_id = str(uuid.uuid4())
457
- new_conversation = ConversationManager()
458
- welcome = chat_engine.get_welcome_message()
459
- new_conversation.add_message("assistant", welcome)
460
- SESSIONS[new_session_id] = new_conversation
461
-
462
- return (
463
- new_conversation.get_formatted_history(),
464
- [],
465
- new_session_id
466
- )
467
-
468
-
469
- def get_initial_chat():
470
- """Get initial chat state with welcome message"""
471
- session_id = str(uuid.uuid4())
472
- conversation = ConversationManager()
473
- welcome = chat_engine.get_welcome_message()
474
- conversation.add_message("assistant", welcome)
475
- SESSIONS[session_id] = conversation
476
-
477
- return conversation.get_formatted_history(), [], session_id
478
-
479
-
480
- # ============================================
481
- # GRADIO INTERFACE
482
- # ============================================
483
-
484
- def create_interface():
485
- """Create the Gradio interface with 3 enhanced tabs"""
486
-
487
- with gr.Blocks(theme=gr.themes.Soft(), title="FleetMind Dispatch System") as app:
488
-
489
- gr.Markdown("# 🚚 FleetMind Dispatch System")
490
- gr.Markdown("*AI-Powered Delivery Coordination*")
491
-
492
- with gr.Tabs():
493
-
494
- # ==========================================
495
- # TAB 1: CHAT
496
- # ==========================================
497
- with gr.Tab("💬 Chat Assistant"):
498
- provider_name = chat_engine.get_provider_name()
499
- model_name = chat_engine.get_model_name()
500
-
501
- gr.Markdown(f"### AI Dispatch Assistant")
502
- gr.Markdown(f"*Powered by {provider_name} ({model_name})*")
503
-
504
- # Quick Action Buttons
505
- gr.Markdown("**Quick Actions:**")
506
-
507
- # Row 1: Create and View
508
- with gr.Row():
509
- quick_create_order = gr.Button("📦 Create Order", size="sm")
510
- quick_view_orders = gr.Button("📋 View Orders", size="sm")
511
- quick_view_drivers = gr.Button("👥 View Drivers", size="sm")
512
- quick_check_status = gr.Button("📊 Check Status", size="sm")
513
-
514
- # Row 2: Order Management
515
- with gr.Row():
516
- quick_update_order = gr.Button("✏️ Update Order", size="sm", variant="secondary")
517
- quick_delete_order = gr.Button("🗑️ Delete Order", size="sm", variant="secondary")
518
- quick_update_driver = gr.Button("✏️ Update Driver", size="sm", variant="secondary")
519
- quick_delete_driver = gr.Button("🗑️ Delete Driver", size="sm", variant="secondary")
520
-
521
- # Chat interface
522
- chatbot = gr.Chatbot(
523
- label="Chat with AI Assistant",
524
- height=600,
525
- type="messages",
526
- show_copy_button=True,
527
- avatar_images=("👤", "🤖")
528
- )
529
-
530
- msg_input = gr.Textbox(
531
- placeholder="Type your message here... (e.g., 'Create order for John at 123 Main St' or 'Show me available drivers')",
532
- label="Your Message",
533
- lines=3
534
- )
535
-
536
- with gr.Row():
537
- send_btn = gr.Button("📤 Send Message", variant="primary", scale=3)
538
- clear_btn = gr.Button("🗑️ Clear Chat", scale=1)
539
-
540
- # API Status in accordion
541
- with gr.Accordion("🔧 System Status", open=False):
542
- api_status = gr.Markdown(get_api_status())
543
-
544
- # Tool usage display
545
- with gr.Accordion("🛠️ Tool Usage Log", open=False):
546
- gr.Markdown("*See what tools the AI is using behind the scenes*")
547
- tool_display = gr.JSON(label="Tools Called", value=[])
548
-
549
- # Session state
550
- session_id_state = gr.State(value=None)
551
-
552
- # Event handlers
553
- def send_message(message, sess_id):
554
- if sess_id is None:
555
- sess_id = str(uuid.uuid4())
556
- SESSIONS[sess_id] = ConversationManager()
557
- welcome = chat_engine.get_welcome_message()
558
- SESSIONS[sess_id].add_message("assistant", welcome)
559
-
560
- chat_history, tools, new_sess_id = handle_chat_message(message, sess_id)
561
- return chat_history, tools, new_sess_id, ""
562
-
563
- # Quick action functions
564
- def quick_action(prompt):
565
- return prompt
566
-
567
- quick_create_order.click(
568
- fn=lambda: "Create a new order",
569
- outputs=msg_input
570
- )
571
-
572
- quick_view_orders.click(
573
- fn=lambda: "Show me all orders",
574
- outputs=msg_input
575
- )
576
-
577
- quick_view_drivers.click(
578
- fn=lambda: "Show me all available drivers",
579
- outputs=msg_input
580
- )
581
-
582
- quick_check_status.click(
583
- fn=lambda: "What is the current status of orders and drivers?",
584
- outputs=msg_input
585
- )
586
-
587
- quick_update_order.click(
588
- fn=lambda: "Update order [ORDER_ID] - change status to [STATUS]",
589
- outputs=msg_input
590
- )
591
-
592
- quick_delete_order.click(
593
- fn=lambda: "Delete order [ORDER_ID]",
594
- outputs=msg_input
595
- )
596
-
597
- quick_update_driver.click(
598
- fn=lambda: "Update driver [DRIVER_ID] - change status to [STATUS]",
599
- outputs=msg_input
600
- )
601
-
602
- quick_delete_driver.click(
603
- fn=lambda: "Delete driver [DRIVER_ID]",
604
- outputs=msg_input
605
- )
606
-
607
- send_btn.click(
608
- fn=send_message,
609
- inputs=[msg_input, session_id_state],
610
- outputs=[chatbot, tool_display, session_id_state, msg_input]
611
- )
612
-
613
- msg_input.submit(
614
- fn=send_message,
615
- inputs=[msg_input, session_id_state],
616
- outputs=[chatbot, tool_display, session_id_state, msg_input]
617
- )
618
-
619
- clear_btn.click(
620
- fn=reset_conversation,
621
- inputs=[session_id_state],
622
- outputs=[chatbot, tool_display, session_id_state]
623
- )
624
-
625
- # ==========================================
626
- # TAB 2: ORDERS
627
- # ==========================================
628
- with gr.Tab("📦 Orders Management"):
629
- gr.Markdown("### Orders Dashboard")
630
-
631
- # Statistics Cards
632
- def update_order_stats():
633
- stats = get_orders_stats()
634
- return (
635
- f"**Total:** {stats['total']}",
636
- f"**Pending:** {stats['pending']}",
637
- f"**In Transit:** {stats['in_transit']}",
638
- f"**Delivered:** {stats['delivered']}"
639
- )
640
-
641
- with gr.Row():
642
- stat_total = gr.Markdown("**Total:** 0")
643
- stat_pending = gr.Markdown("**Pending:** 0")
644
- stat_transit = gr.Markdown("**In Transit:** 0")
645
- stat_delivered = gr.Markdown("**Delivered:** 0")
646
-
647
- gr.Markdown("---")
648
-
649
- # Filters
650
- gr.Markdown("**Filters:**")
651
- with gr.Row():
652
- status_filter = gr.Dropdown(
653
- choices=["all", "pending", "assigned", "in_transit", "delivered", "failed", "cancelled"],
654
- value="all",
655
- label="Status",
656
- scale=1
657
- )
658
- priority_filter = gr.Dropdown(
659
- choices=["all", "standard", "express", "urgent"],
660
- value="all",
661
- label="Priority",
662
- scale=1
663
- )
664
- payment_filter = gr.Dropdown(
665
- choices=["all", "pending", "paid", "cod"],
666
- value="all",
667
- label="Payment",
668
- scale=1
669
- )
670
- search_orders = gr.Textbox(
671
- placeholder="Search by Order ID, Customer, Phone...",
672
- label="Search",
673
- scale=2
674
- )
675
-
676
- with gr.Row():
677
- apply_filters_btn = gr.Button("🔍 Apply Filters", variant="primary", scale=1)
678
- refresh_orders_btn = gr.Button("🔄 Refresh", scale=1)
679
-
680
- # Orders Table
681
- orders_table = gr.Dataframe(
682
- headers=["Order ID", "Customer", "Address", "Status", "Priority", "Driver", "Deadline"],
683
- datatype=["str", "str", "str", "str", "str", "str", "str"],
684
- label="Orders List (Click row to view details)",
685
- value=get_all_orders(),
686
- interactive=False,
687
- wrap=True
688
- )
689
-
690
- # Order Details
691
- gr.Markdown("---")
692
- gr.Markdown("**Order Details:**")
693
- order_details = gr.Markdown("*Select an order from the table above to view full details*")
694
-
695
- # Edit/Delete Actions
696
- gr.Markdown("---")
697
- gr.Markdown("**Order Actions:**")
698
-
699
- with gr.Row():
700
- selected_order_id_edit = gr.Textbox(label="Order ID to Edit", placeholder="ORD-XXXXXXXX", scale=2)
701
- edit_order_btn = gr.Button("✏️ Edit Order", variant="secondary", scale=1)
702
- delete_order_btn = gr.Button("🗑️ Delete Order", variant="stop", scale=1)
703
-
704
- # Edit Form (in accordion)
705
- with gr.Accordion("Edit Order Form", open=False) as edit_accordion:
706
- with gr.Row():
707
- edit_customer_name = gr.Textbox(label="Customer Name")
708
- edit_customer_phone = gr.Textbox(label="Customer Phone")
709
- with gr.Row():
710
- edit_status = gr.Dropdown(
711
- choices=["pending", "assigned", "in_transit", "delivered", "failed", "cancelled"],
712
- label="Status"
713
- )
714
- edit_priority = gr.Dropdown(
715
- choices=["standard", "express", "urgent"],
716
- label="Priority"
717
- )
718
- with gr.Row():
719
- edit_payment_status = gr.Dropdown(
720
- choices=["pending", "paid", "cod"],
721
- label="Payment Status"
722
- )
723
- edit_weight_kg = gr.Number(label="Weight (kg)")
724
- edit_special_instructions = gr.Textbox(label="Special Instructions", lines=2)
725
-
726
- save_order_btn = gr.Button("💾 Save Changes", variant="primary")
727
-
728
- # Action Results
729
- action_result = gr.Markdown("")
730
-
731
- # Event handlers
732
- def filter_and_update_orders(status, priority, payment, search):
733
- return get_all_orders(status, priority, payment, search)
734
-
735
- def refresh_orders_and_stats(status, priority, payment, search):
736
- stats = update_order_stats()
737
- table = get_all_orders(status, priority, payment, search)
738
- return stats[0], stats[1], stats[2], stats[3], table
739
-
740
- def show_order_details(evt: gr.SelectData, table_data):
741
- try:
742
- # table_data is a pandas DataFrame from Gradio
743
- if hasattr(table_data, 'iloc'):
744
- # DataFrame - use iloc to access row and column
745
- order_id = table_data.iloc[evt.index[0], 0]
746
- else:
747
- # List of lists - use standard indexing
748
- order_id = table_data[evt.index[0]][0]
749
- return get_order_details(order_id)
750
- except Exception as e:
751
- return f"Error: {str(e)}"
752
-
753
- apply_filters_btn.click(
754
- fn=filter_and_update_orders,
755
- inputs=[status_filter, priority_filter, payment_filter, search_orders],
756
- outputs=orders_table
757
- )
758
-
759
- refresh_orders_btn.click(
760
- fn=refresh_orders_and_stats,
761
- inputs=[status_filter, priority_filter, payment_filter, search_orders],
762
- outputs=[stat_total, stat_pending, stat_transit, stat_delivered, orders_table]
763
- )
764
-
765
- orders_table.select(
766
- fn=show_order_details,
767
- inputs=[orders_table],
768
- outputs=order_details
769
- )
770
-
771
- # Edit/Delete handlers
772
- def handle_edit_order(order_id):
773
- if not order_id:
774
- return "Please enter an Order ID"
775
- # Fetch order details and populate form
776
- query = "SELECT * FROM orders WHERE order_id = %s"
777
- from database.connection import execute_query
778
- results = execute_query(query, (order_id,))
779
- if not results:
780
- return "Order not found"
781
- order = results[0]
782
- return (
783
- order.get('customer_name', ''),
784
- order.get('customer_phone', ''),
785
- order.get('status', ''),
786
- order.get('priority', ''),
787
- order.get('payment_status', ''),
788
- order.get('weight_kg', 0),
789
- order.get('special_instructions', ''),
790
- "Order loaded. Update fields and click Save Changes."
791
- )
792
-
793
- def handle_save_order(order_id, name, phone, status, priority, payment, weight, instructions, status_f, priority_f, payment_f, search):
794
- if not order_id:
795
- return "Please enter an Order ID", get_all_orders(status_f, priority_f, payment_f, search)
796
-
797
- fields = {}
798
- if name:
799
- fields['customer_name'] = name
800
- if phone:
801
- fields['customer_phone'] = phone
802
- if status:
803
- fields['status'] = status
804
- if priority:
805
- fields['priority'] = priority
806
- if payment:
807
- fields['payment_status'] = payment
808
- if weight:
809
- fields['weight_kg'] = float(weight)
810
- if instructions:
811
- fields['special_instructions'] = instructions
812
-
813
- result = update_order_ui(order_id, **fields)
814
-
815
- # Refresh table
816
- refreshed_table = get_all_orders(status_f, priority_f, payment_f, search)
817
-
818
- if result['success']:
819
- return f"✅ {result['message']}", refreshed_table
820
- else:
821
- return f"❌ {result.get('error', 'Update failed')}", refreshed_table
822
-
823
- def handle_delete_order(order_id, status_f, priority_f, payment_f, search):
824
- if not order_id:
825
- return "Please enter an Order ID", get_all_orders(status_f, priority_f, payment_f, search)
826
-
827
- result = delete_order_ui(order_id)
828
-
829
- # Refresh table
830
- refreshed_table = get_all_orders(status_f, priority_f, payment_f, search)
831
-
832
- if result['success']:
833
- return f"✅ {result['message']}", refreshed_table
834
- else:
835
- return f"❌ {result.get('error', 'Deletion failed')}", refreshed_table
836
-
837
- edit_order_btn.click(
838
- fn=handle_edit_order,
839
- inputs=[selected_order_id_edit],
840
- outputs=[edit_customer_name, edit_customer_phone, edit_status, edit_priority,
841
- edit_payment_status, edit_weight_kg, edit_special_instructions, action_result]
842
- )
843
-
844
- save_order_btn.click(
845
- fn=handle_save_order,
846
- inputs=[selected_order_id_edit, edit_customer_name, edit_customer_phone, edit_status,
847
- edit_priority, edit_payment_status, edit_weight_kg, edit_special_instructions,
848
- status_filter, priority_filter, payment_filter, search_orders],
849
- outputs=[action_result, orders_table]
850
- )
851
-
852
- delete_order_btn.click(
853
- fn=handle_delete_order,
854
- inputs=[selected_order_id_edit, status_filter, priority_filter, payment_filter, search_orders],
855
- outputs=[action_result, orders_table]
856
- )
857
-
858
- # ==========================================
859
- # TAB 3: DRIVERS
860
- # ==========================================
861
- with gr.Tab("👥 Drivers Management"):
862
- gr.Markdown("### Drivers Dashboard")
863
-
864
- # Statistics Cards
865
- def update_driver_stats():
866
- stats = get_drivers_stats()
867
- return (
868
- f"**Total:** {stats['total']}",
869
- f"**Active:** {stats['active']}",
870
- f"**Busy:** {stats['busy']}",
871
- f"**Offline:** {stats['offline']}"
872
- )
873
-
874
- with gr.Row():
875
- driver_stat_total = gr.Markdown("**Total:** 0")
876
- driver_stat_active = gr.Markdown("**Active:** 0")
877
- driver_stat_busy = gr.Markdown("**Busy:** 0")
878
- driver_stat_offline = gr.Markdown("**Offline:** 0")
879
-
880
- gr.Markdown("---")
881
-
882
- # Filters
883
- gr.Markdown("**Filters:**")
884
- with gr.Row():
885
- driver_status_filter = gr.Dropdown(
886
- choices=["all", "active", "busy", "offline", "unavailable"],
887
- value="all",
888
- label="Status",
889
- scale=1
890
- )
891
- vehicle_filter = gr.Dropdown(
892
- choices=["all", "van", "truck", "car", "motorcycle"],
893
- value="all",
894
- label="Vehicle Type",
895
- scale=1
896
- )
897
- search_drivers = gr.Textbox(
898
- placeholder="Search by Driver ID, Name, Phone, Plate...",
899
- label="Search",
900
- scale=2
901
- )
902
-
903
- with gr.Row():
904
- apply_driver_filters_btn = gr.Button("🔍 Apply Filters", variant="primary", scale=1)
905
- refresh_drivers_btn = gr.Button("🔄 Refresh", scale=1)
906
-
907
- # Drivers Table
908
- drivers_table = gr.Dataframe(
909
- headers=["Driver ID", "Name", "Phone", "Status", "Vehicle", "Location", "Last Update"],
910
- datatype=["str", "str", "str", "str", "str", "str", "str"],
911
- label="Drivers List (Click row to view details)",
912
- value=get_all_drivers(),
913
- interactive=False,
914
- wrap=True
915
- )
916
-
917
- # Driver Details
918
- gr.Markdown("---")
919
- gr.Markdown("**Driver Details:**")
920
- driver_details = gr.Markdown("*Select a driver from the table above to view full details*")
921
-
922
- # Edit/Delete Actions
923
- gr.Markdown("---")
924
- gr.Markdown("**Driver Actions:**")
925
-
926
- with gr.Row():
927
- selected_driver_id_edit = gr.Textbox(label="Driver ID to Edit", placeholder="DRV-XXXXXXXX", scale=2)
928
- edit_driver_btn = gr.Button("✏️ Edit Driver", variant="secondary", scale=1)
929
- delete_driver_btn = gr.Button("🗑️ Delete Driver", variant="stop", scale=1)
930
-
931
- # Edit Form (in accordion)
932
- with gr.Accordion("Edit Driver Form", open=False) as driver_edit_accordion:
933
- with gr.Row():
934
- edit_driver_name = gr.Textbox(label="Driver Name")
935
- edit_driver_phone = gr.Textbox(label="Phone")
936
- with gr.Row():
937
- edit_driver_email = gr.Textbox(label="Email")
938
- edit_driver_status = gr.Dropdown(
939
- choices=["active", "busy", "offline", "unavailable"],
940
- label="Status"
941
- )
942
- with gr.Row():
943
- edit_vehicle_type = gr.Textbox(label="Vehicle Type")
944
- edit_vehicle_plate = gr.Textbox(label="Vehicle Plate")
945
- with gr.Row():
946
- edit_capacity_kg = gr.Number(label="Capacity (kg)")
947
- edit_capacity_m3 = gr.Number(label="Capacity (m³)")
948
-
949
- save_driver_btn = gr.Button("💾 Save Changes", variant="primary")
950
-
951
- # Action Results
952
- driver_action_result = gr.Markdown("")
953
-
954
- # Event handlers
955
- def filter_and_update_drivers(status, vehicle, search):
956
- return get_all_drivers(status, vehicle, search)
957
-
958
- def refresh_drivers_and_stats(status, vehicle, search):
959
- stats = update_driver_stats()
960
- table = get_all_drivers(status, vehicle, search)
961
- return stats[0], stats[1], stats[2], stats[3], table
962
-
963
- def show_driver_details(evt: gr.SelectData, table_data):
964
- try:
965
- # table_data is a pandas DataFrame from Gradio
966
- if hasattr(table_data, 'iloc'):
967
- # DataFrame - use iloc to access row and column
968
- driver_id = table_data.iloc[evt.index[0], 0]
969
- else:
970
- # List of lists - use standard indexing
971
- driver_id = table_data[evt.index[0]][0]
972
- return get_driver_details(driver_id)
973
- except Exception as e:
974
- return f"Error: {str(e)}"
975
-
976
- apply_driver_filters_btn.click(
977
- fn=filter_and_update_drivers,
978
- inputs=[driver_status_filter, vehicle_filter, search_drivers],
979
- outputs=drivers_table
980
- )
981
-
982
- refresh_drivers_btn.click(
983
- fn=refresh_drivers_and_stats,
984
- inputs=[driver_status_filter, vehicle_filter, search_drivers],
985
- outputs=[driver_stat_total, driver_stat_active, driver_stat_busy, driver_stat_offline, drivers_table]
986
- )
987
-
988
- drivers_table.select(
989
- fn=show_driver_details,
990
- inputs=[drivers_table],
991
- outputs=driver_details
992
- )
993
-
994
- # Edit/Delete handlers
995
- def handle_edit_driver(driver_id):
996
- if not driver_id:
997
- return "Please enter a Driver ID"
998
- # Fetch driver details and populate form
999
- query = "SELECT * FROM drivers WHERE driver_id = %s"
1000
- from database.connection import execute_query
1001
- results = execute_query(query, (driver_id,))
1002
- if not results:
1003
- return "Driver not found"
1004
- driver = results[0]
1005
- return (
1006
- driver.get('name', ''),
1007
- driver.get('phone', ''),
1008
- driver.get('email', ''),
1009
- driver.get('status', ''),
1010
- driver.get('vehicle_type', ''),
1011
- driver.get('vehicle_plate', ''),
1012
- driver.get('capacity_kg', 0),
1013
- driver.get('capacity_m3', 0),
1014
- "Driver loaded. Update fields and click Save Changes."
1015
- )
1016
-
1017
- def handle_save_driver(driver_id, name, phone, email, status, vehicle_type, vehicle_plate, capacity_kg, capacity_m3, status_f, vehicle_f, search):
1018
- if not driver_id:
1019
- return "Please enter a Driver ID", get_all_drivers(status_f, vehicle_f, search)
1020
-
1021
- fields = {}
1022
- if name:
1023
- fields['name'] = name
1024
- if phone:
1025
- fields['phone'] = phone
1026
- if email:
1027
- fields['email'] = email
1028
- if status:
1029
- fields['status'] = status
1030
- if vehicle_type:
1031
- fields['vehicle_type'] = vehicle_type
1032
- if vehicle_plate:
1033
- fields['vehicle_plate'] = vehicle_plate
1034
- if capacity_kg:
1035
- fields['capacity_kg'] = float(capacity_kg)
1036
- if capacity_m3:
1037
- fields['capacity_m3'] = float(capacity_m3)
1038
-
1039
- result = update_driver_ui(driver_id, **fields)
1040
-
1041
- # Refresh table
1042
- refreshed_table = get_all_drivers(status_f, vehicle_f, search)
1043
-
1044
- if result['success']:
1045
- return f"✅ {result['message']}", refreshed_table
1046
- else:
1047
- return f"❌ {result.get('error', 'Update failed')}", refreshed_table
1048
-
1049
- def handle_delete_driver(driver_id, status_f, vehicle_f, search):
1050
- if not driver_id:
1051
- return "Please enter a Driver ID", get_all_drivers(status_f, vehicle_f, search)
1052
-
1053
- result = delete_driver_ui(driver_id)
1054
-
1055
- # Refresh table
1056
- refreshed_table = get_all_drivers(status_f, vehicle_f, search)
1057
-
1058
- if result['success']:
1059
- return f"✅ {result['message']}", refreshed_table
1060
- else:
1061
- return f"❌ {result.get('error', 'Deletion failed')}", refreshed_table
1062
-
1063
- edit_driver_btn.click(
1064
- fn=handle_edit_driver,
1065
- inputs=[selected_driver_id_edit],
1066
- outputs=[edit_driver_name, edit_driver_phone, edit_driver_email, edit_driver_status,
1067
- edit_vehicle_type, edit_vehicle_plate, edit_capacity_kg, edit_capacity_m3, driver_action_result]
1068
- )
1069
-
1070
- save_driver_btn.click(
1071
- fn=handle_save_driver,
1072
- inputs=[selected_driver_id_edit, edit_driver_name, edit_driver_phone, edit_driver_email,
1073
- edit_driver_status, edit_vehicle_type, edit_vehicle_plate, edit_capacity_kg, edit_capacity_m3,
1074
- driver_status_filter, vehicle_filter, search_drivers],
1075
- outputs=[driver_action_result, drivers_table]
1076
- )
1077
-
1078
- delete_driver_btn.click(
1079
- fn=handle_delete_driver,
1080
- inputs=[selected_driver_id_edit, driver_status_filter, vehicle_filter, search_drivers],
1081
- outputs=[driver_action_result, drivers_table]
1082
- )
1083
-
1084
- gr.Markdown("---")
1085
- gr.Markdown("*FleetMind v1.0 - AI-Powered Dispatch Coordination*")
1086
-
1087
- # Initialize chat and stats on load
1088
- app.load(
1089
- fn=get_initial_chat,
1090
- outputs=[chatbot, tool_display, session_id_state]
1091
- ).then(
1092
- fn=update_order_stats,
1093
- outputs=[stat_total, stat_pending, stat_transit, stat_delivered]
1094
- ).then(
1095
- fn=update_driver_stats,
1096
- outputs=[driver_stat_total, driver_stat_active, driver_stat_busy, driver_stat_offline]
1097
- )
1098
-
1099
- return app
1100
-
1101
-
1102
- # ============================================
1103
- # MAIN
1104
- # ============================================
1105
-
1106
- if __name__ == "__main__":
1107
- print("=" * 60)
1108
- print("FleetMind - Starting Enhanced UI")
1109
- print("=" * 60)
1110
-
1111
- print("\nChecking database connection...")
1112
- if test_connection():
1113
- print("✅ Database connected")
1114
- else:
1115
- print("❌ Database connection failed")
1116
-
1117
- print("\nStarting Gradio interface...")
1118
- print("=" * 60)
1119
-
1120
- app = create_interface()
1121
- app.launch(
1122
- server_name="0.0.0.0",
1123
- server_port=7860,
1124
- share=False,
1125
- show_error=True,
1126
- show_api=False
1127
- )