Spaces:
Sleeping
Sleeping
File size: 14,361 Bytes
782bbd9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 |
from pathlib import Path
from datetime import datetime
from typing_extensions import Annotated, List, Literal
import os
import logging
import requests
from typing import Optional, Dict, Any
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure, OperationFailure
from langchain_core.messages import HumanMessage
from langchain_core.tools import tool, InjectedToolArg
from src.llms.groqllm import GroqLLM
# Configure logging
logger = logging.getLogger(__name__)
# Configuration for MongoDB
MONGODB_URI = os.getenv("MONGODB_URI", None)
MONGODB_DATABASE = os.getenv("MONGODB_DATABASE", "parcel_tracking")
MONGODB_COLLECTION = os.getenv("MONGODB_COLLECTION", "parcels")
MONGODB_TIMEOUT = int(os.getenv("MONGODB_TIMEOUT", "5000")) # milliseconds
# Configuration for ETA API
ETA_API_BASE_URL = os.getenv("ETA_API_BASE_URL", "http://localhost:8000")
ETA_API_TIMEOUT = int(os.getenv("ETA_API_TIMEOUT", "10")) # seconds
# MongoDB client singleton
_mongo_client = None
def get_mongo_client():
"""Get or create MongoDB client singleton"""
global _mongo_client
if _mongo_client is None:
if not MONGODB_URI:
raise ValueError("MONGODB_URI environment variable is not set")
try:
_mongo_client = MongoClient(
MONGODB_URI,
serverSelectionTimeoutMS=MONGODB_TIMEOUT,
connectTimeoutMS=MONGODB_TIMEOUT
)
# Test connection
_mongo_client.admin.command('ping')
logger.info("MongoDB connection established successfully")
except Exception as e:
logger.error(f"Failed to connect to MongoDB: {e}")
raise
return _mongo_client
def get_today_str() -> str:
"""Get current data in a human-readable format."""
return datetime.now().strftime("%a %b %d, %Y")
groq = GroqLLM()
@tool
def think_tool(reflection:str) -> str:
"""
Tool for strategic reflection on execution progress and decision-making.
Use this tool after each search to analyze results and plan next steps systematically.
This creates a deliberate pause in customer query execution workflow for quality decision-making.
When to use:
- After receiving search results: What key information did I find?
- Before deciding next steps: Do I have enough to answer comprehensively?
- When assessing execution gaps: What specific execution am I still missing?
- Before concluding execution: Can I provide a complete answer now?
Reflection should address:
1. Analysis of current findings - What concrete information have I gathered?
2. Gap assessment - What crucial execution or information is still missing?
3. Quality evaluation - Do I have sufficient evidence/examples for a good answer?
4. Strategic decision - Should I continue execution or provide my output?
Args:
reflection: Your detailed reflection on the execution progress, findings, gaps, and next steps
Returns:
Confirmation that reflection was recorded for decision-making
"""
return f"Reflection recorded: {reflection}"
@tool(description="Track parcel based on tracking number")
def track_package(tracking_number: str) -> str:
"""
Tool for tracking customer packages/parcels from MongoDB database.
This tool retrieves real-time parcel tracking information from the MongoDB database.
It fetches details such as current status, location, delivery ETA, sender/recipient info,
and tracking history.
Args:
tracking_number(str): The unique tracking number of the parcel
Returns:
A string describing the parcel status, location, history, and other relevant details
"""
logger.info(f"Tracking parcel: {tracking_number}")
try:
# Check if MongoDB is configured
if not MONGODB_URI:
error_msg = "MongoDB is not configured. Please set MONGODB_URI environment variable."
logger.error(error_msg)
return error_msg
# Get MongoDB client and collection
client = get_mongo_client()
db = client[MONGODB_DATABASE]
collection = db[MONGODB_COLLECTION]
# Query for the tracking number
logger.debug(f"Querying MongoDB for tracking_number: {tracking_number}")
parcel = collection.find_one({"tracking_number": tracking_number})
if not parcel:
# Try case-insensitive search
parcel = collection.find_one(
{"tracking_number": {"$regex": f"^{tracking_number}$", "$options": "i"}}
)
if not parcel:
logger.warning(f"Tracking number not found: {tracking_number}")
return f"Tracking number '{tracking_number}' not found in the system. Please verify the tracking number and try again."
# Format the response with all available information
response_parts = []
response_parts.append(f"๐ฆ Parcel Tracking Information for {tracking_number}")
response_parts.append("=" * 50)
# Basic Information
if parcel.get("status"):
response_parts.append(f"\n๐น Status: {parcel['status']}")
if parcel.get("current_location"):
response_parts.append(f"๐น Current Location: {parcel['current_location']}")
# Delivery Information
if parcel.get("estimated_delivery"):
response_parts.append(f"๐น Estimated Delivery: {parcel['estimated_delivery']}")
if parcel.get("actual_delivery_date"):
response_parts.append(f"๐น Delivered On: {parcel['actual_delivery_date']}")
# Sender and Recipient Information
if parcel.get("sender"):
sender = parcel["sender"]
if isinstance(sender, dict):
sender_info = f"{sender.get('name', 'N/A')}"
if sender.get('address'):
sender_info += f" ({sender['address']})"
response_parts.append(f"\n๐น Sender: {sender_info}")
else:
response_parts.append(f"\n๐น Sender: {sender}")
if parcel.get("recipient"):
recipient = parcel["recipient"]
if isinstance(recipient, dict):
recipient_info = f"{recipient.get('name', 'N/A')}"
if recipient.get('address'):
recipient_info += f" ({recipient['address']})"
response_parts.append(f"๐น Recipient: {recipient_info}")
else:
response_parts.append(f"๐น Recipient: {recipient}")
# Package Details
if parcel.get("weight"):
response_parts.append(f"\n๐น Weight: {parcel['weight']}")
if parcel.get("dimensions"):
response_parts.append(f"๐น Dimensions: {parcel['dimensions']}")
if parcel.get("description"):
response_parts.append(f"๐น Description: {parcel['description']}")
# Courier Information
if parcel.get("courier_name"):
response_parts.append(f"\n๐น Courier: {parcel['courier_name']}")
if parcel.get("vehicle_type"):
response_parts.append(f"๐น Vehicle Type: {parcel['vehicle_type']}")
# Tracking History
if parcel.get("tracking_history"):
history = parcel["tracking_history"]
if isinstance(history, list) and len(history) > 0:
response_parts.append(f"\n๐ Tracking History:")
for idx, event in enumerate(history[-5:], 1): # Show last 5 events
if isinstance(event, dict):
timestamp = event.get('timestamp', 'N/A')
location = event.get('location', 'N/A')
status = event.get('status', 'N/A')
response_parts.append(f" {idx}. [{timestamp}] {location} - {status}")
else:
response_parts.append(f" {idx}. {event}")
if len(history) > 5:
response_parts.append(f" ... and {len(history) - 5} more events")
# Additional Notes
if parcel.get("notes"):
response_parts.append(f"\n๐ Notes: {parcel['notes']}")
# Special Instructions
if parcel.get("special_instructions"):
response_parts.append(f"โ ๏ธ Special Instructions: {parcel['special_instructions']}")
# Shipping Method
if parcel.get("shipping_method"):
response_parts.append(f"\n๐น Shipping Method: {parcel['shipping_method']}")
# Cost Information
if parcel.get("shipping_cost"):
response_parts.append(f"๐น Shipping Cost: {parcel['shipping_cost']}")
response_text = "\n".join(response_parts)
logger.info(f"Successfully retrieved tracking info for: {tracking_number}")
return response_text
except ConnectionFailure as e:
error_msg = f"Failed to connect to MongoDB: {str(e)}. Please check your connection."
logger.error(error_msg)
return error_msg
except OperationFailure as e:
error_msg = f"MongoDB operation failed: {str(e)}. Please check your permissions."
logger.error(error_msg)
return error_msg
except Exception as e:
error_msg = f"Error tracking parcel '{tracking_number}': {str(e)}"
logger.error(error_msg, exc_info=True)
return error_msg
@tool(description="Estimate delivery time for a parcel based on delivery parameters.")
def estimated_time_analysis(
distance_km: float,
courier_experience_yrs: float = 2.0,
vehicle_type: str = "Scooter",
weather: str = "Sunny",
time_of_day: str = "Morning",
traffic_level: str = "Medium"
) -> str:
"""
Estimate delivery time for a parcel based on various delivery parameters.
This tool makes an API call to the ETA prediction service which uses a trained ML model
to predict delivery time based on distance, courier experience, vehicle type, weather,
time of day, and traffic conditions.
Args:
distance_km: Distance in kilometers (must be positive, max 1000km)
courier_experience_yrs: Courier experience in years (0-50, default: 2.0)
vehicle_type: Type of vehicle - one of: 'Scooter', 'Pickup Truck', 'Motorcycle' (default: 'Scooter')
weather: Weather condition - one of: 'Sunny', 'Rainy', 'Foggy', 'Snowy', 'Windy' (default: 'Sunny')
time_of_day: Time of day - one of: 'Morning', 'Afternoon', 'Evening', 'Night' (default: 'Morning')
traffic_level: Traffic level - one of: 'Low', 'Medium', 'High' (default: 'Medium')
Returns:
A string describing the estimated delivery time in minutes with the input parameters used.
Example:
estimated_time_analysis(distance_km=15.5, vehicle_type="Motorcycle", traffic_level="High")
"""
logger.info(f"Estimating delivery time: distance={distance_km}km, vehicle={vehicle_type}, traffic={traffic_level}")
try:
# Prepare the request payload matching the API schema
payload = {
"Distance_km": distance_km,
"Courier_Experience_yrs": courier_experience_yrs,
"Vehicle_Type": vehicle_type,
"Weather": weather,
"Time_of_Day": time_of_day,
"Traffic_Level": traffic_level
}
# Make API call to ETA prediction service
api_url = f"{ETA_API_BASE_URL}/predict"
logger.debug(f"Calling ETA API: {api_url} with payload: {payload}")
response = requests.post(
api_url,
json=payload,
timeout=ETA_API_TIMEOUT
)
# Check if request was successful
response.raise_for_status()
# Parse response
result = response.json()
predicted_time = result.get("predicted_delivery_time")
if predicted_time is None:
raise ValueError("No prediction returned from API")
# Format response
hours = int(predicted_time // 60)
minutes = int(predicted_time % 60)
time_str = ""
if hours > 0:
time_str += f"{hours} hour{'s' if hours > 1 else ''}"
if minutes > 0:
if hours > 0:
time_str += " and "
time_str += f"{minutes} minute{'s' if minutes != 1 else ''}"
response_text = f"""Estimated Delivery Time Analysis:
- Predicted Time: {predicted_time:.1f} minutes ({time_str})
- Distance: {distance_km} km
- Vehicle Type: {vehicle_type}
- Courier Experience: {courier_experience_yrs} years
- Weather: {weather}
- Time of Day: {time_of_day}
- Traffic Level: {traffic_level}
This prediction is based on a trained machine learning model considering all the above factors."""
logger.info(f"ETA prediction successful: {predicted_time:.1f} minutes")
return response_text
except requests.exceptions.ConnectionError:
error_msg = f"Unable to connect to ETA prediction service at {ETA_API_BASE_URL}. Please ensure the service is running."
logger.error(error_msg)
return error_msg
except requests.exceptions.Timeout:
error_msg = f"ETA prediction service timed out after {ETA_API_TIMEOUT} seconds."
logger.error(error_msg)
return error_msg
except requests.exceptions.HTTPError as e:
error_msg = f"ETA prediction service returned an error: {e.response.status_code} - {e.response.text}"
logger.error(error_msg)
return error_msg
except Exception as e:
error_msg = f"Error during ETA estimation: {str(e)}"
logger.error(error_msg, exc_info=True)
return error_msg
@tool
def conduct_execution(execution_jobs: str) -> str:
"""
Tool for delegating an execution task to a specialized sub-agent.
"""
return f"Delegated execution job: {execution_jobs}"
@tool
def execution_complete() -> str:
"""
Tool for indicating the execution process is complete.
"""
return "Execution complete." |