Commit
·
c86bca5
1
Parent(s):
96042a2
Remove GeminiProvider implementation from chat providers
Browse files- chat/__init__.py +5 -5
- chat/chat_engine.py +0 -108
- chat/conversation.py +0 -85
- chat/providers/__init__.py +0 -10
- chat/providers/base_provider.py +0 -53
- chat/providers/claude_provider.py +0 -373
- chat/providers/gemini_provider.py +0 -983
chat/__init__.py
CHANGED
|
@@ -1,9 +1,9 @@
|
|
| 1 |
"""
|
| 2 |
-
Chat package for FleetMind MCP
|
| 3 |
-
|
| 4 |
"""
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
|
| 9 |
-
__all__ = [
|
|
|
|
| 1 |
"""
|
| 2 |
+
Chat package for FleetMind MCP Server (Track 1)
|
| 3 |
+
Contains geocoding service and tool handlers for MCP server
|
| 4 |
"""
|
| 5 |
|
| 6 |
+
# Only tools and geocoding are needed for MCP server
|
| 7 |
+
# ChatEngine and ConversationManager are archived (were for Gradio UI)
|
| 8 |
|
| 9 |
+
__all__ = []
|
chat/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 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
chat/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
chat/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']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
chat/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
chat/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?"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
chat/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?"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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