ThinkOV2 / tools.py
Ayush-003's picture
Upload 28 files
9be2851 verified
Raw History Blame Contribute Delete
12.7 kB
"""
Tool implementations for Grocify Chat Agent
Includes product search, order lookup, promotions, sentiment analysis, and CRM query
"""
import json
import random
from typing import List, Dict, Any, Optional
from datetime import datetime, timedelta
import httpx
from schemas import (
ProductSearchInput, OrderLookupInput, PromotionsCheckInput,
SentimentAnalysisInput, CRMQueryInput,
ProductItem, OrderStatus, PromotionValidation, SentimentResult, SentimentType
)
from config import settings
import logging
logger = logging.getLogger(__name__)
class BaseTool:
"""Base class for all tools"""
def __init__(self, name: str, description: str):
self.name = name
self.description = description
async def execute(self, input_data: Any) -> Any:
"""Execute the tool with given input"""
raise NotImplementedError
class ProductSearchTool(BaseTool):
"""Search product catalog"""
def __init__(self):
super().__init__(
name="product_search",
description="Search product catalog with filters like categories, tags, price range. Note: Product data is retrieved from the knowledge base (ecommerce_faq.txt) via RAG retrieval, not from this tool."
)
async def execute(self, input_data: ProductSearchInput) -> Dict[str, Any]:
"""Execute product search"""
# Product search should rely on RAG retrieval from ecommerce_faq.txt
# This tool returns a status message indicating data comes from RAG
return {
"status": "product_search_via_rag",
"message": "Product information is retrieved from the knowledge base. Use the RAG-retrieved context to answer product queries.",
"search_query": input_data.query,
"filters_applied": {
"categories": input_data.categories,
"min_price": input_data.min_price,
"max_price": input_data.max_price,
"sort_by": input_data.sort_by,
"limit": input_data.limit
}
}
class OrderLookupTool(BaseTool):
"""Look up order status"""
def __init__(self):
super().__init__(
name="order_lookup",
description="Retrieve order status, tracking info, and ETA"
)
async def execute(self, input_data: OrderLookupInput) -> OrderStatus:
"""Execute order lookup"""
if settings.USE_MOCK_TOOLS:
return self._mock_lookup(input_data)
else:
return await self._api_lookup(input_data)
def _mock_lookup(self, input_data: OrderLookupInput) -> OrderStatus:
"""Mock order lookup"""
statuses = ["Order Placed", "Processing", "Shipped", "Out for Delivery", "Delivered"]
carriers = ["Delhivery", "BlueDart", "DTDC", "Ecom Express"]
# Generate deterministic data based on order_id
order_num = sum(ord(c) for c in input_data.order_id)
status_idx = order_num % len(statuses)
carrier_idx = order_num % len(carriers)
eta = (datetime.now() + timedelta(days=random.randint(1, 5))).isoformat()
return OrderStatus(
order_id=input_data.order_id,
status=statuses[status_idx],
carrier=carriers[carrier_idx],
tracking_number=f"{carriers[carrier_idx][:3].upper()}{order_num}",
eta=eta,
items=[
{
"product_id": "SKU123",
"title": "Organic Honey 500g",
"qty": 2,
"price": 299
}
],
order_protection_flag=False,
source="oms_api"
)
async def _api_lookup(self, input_data: OrderLookupInput) -> OrderStatus:
"""Real API order lookup"""
try:
async with httpx.AsyncClient() as client:
response = await client.post(
f"{settings.ORDER_API_URL}/lookup",
json=input_data.dict(),
timeout=10.0
)
response.raise_for_status()
data = response.json()
return OrderStatus(**data)
except Exception as e:
logger.error(f"Order API error: {e}")
return self._mock_lookup(input_data)
class PromotionsCheckTool(BaseTool):
"""Validate promotion/coupon codes"""
def __init__(self):
super().__init__(
name="promotions_check",
description="Validate coupon codes and check promotion eligibility"
)
async def execute(self, input_data: PromotionsCheckInput) -> PromotionValidation:
"""Execute promotion check"""
if settings.USE_MOCK_TOOLS:
return self._mock_check(input_data)
else:
return await self._api_check(input_data)
def _mock_check(self, input_data: PromotionsCheckInput) -> PromotionValidation:
"""Mock promotion validation"""
valid_coupons = {
"DIWALI25": {"discount_percent": 25, "applicable_to": ["category:all"], "expires": "2025-10-30"},
"WELCOME10": {"discount_percent": 10, "applicable_to": ["category:all"], "expires": "2025-12-31"},
"GIFT50": {"discount_percent": 50, "applicable_to": ["category:gifts"], "expires": "2025-11-15"},
"FIRSTBUY": {"discount_percent": 15, "applicable_to": ["first_order"], "expires": "2025-12-31"}
}
coupon_upper = input_data.coupon.upper()
if coupon_upper in valid_coupons:
coupon_data = valid_coupons[coupon_upper]
return PromotionValidation(
coupon=input_data.coupon,
valid=True,
discount_percent=coupon_data["discount_percent"],
applicable_to=coupon_data["applicable_to"],
expires=coupon_data["expires"],
reason="Coupon is valid and active"
)
else:
return PromotionValidation(
coupon=input_data.coupon,
valid=False,
reason="Coupon code not found or expired"
)
async def _api_check(self, input_data: PromotionsCheckInput) -> PromotionValidation:
"""Real API promotion check"""
try:
async with httpx.AsyncClient() as client:
response = await client.post(
f"{settings.PROMOTIONS_API_URL}/validate",
json=input_data.dict(),
timeout=10.0
)
response.raise_for_status()
data = response.json()
return PromotionValidation(**data)
except Exception as e:
logger.error(f"Promotions API error: {e}")
return self._mock_check(input_data)
class SentimentAnalysisTool(BaseTool):
"""Analyze sentiment of user messages"""
def __init__(self):
super().__init__(
name="sentiment_analysis",
description="Analyze sentiment and emotion in user messages"
)
async def execute(self, input_data: SentimentAnalysisInput) -> SentimentResult:
"""Execute sentiment analysis"""
# Simple keyword-based sentiment for now
# In production, use a proper sentiment model
text_lower = input_data.text.lower()
negative_keywords = ["angry", "hate", "worst", "terrible", "awful", "horrible", "disappointed", "frustrated", "useless", "pathetic"]
positive_keywords = ["great", "excellent", "awesome", "love", "amazing", "wonderful", "fantastic", "perfect", "happy", "satisfied"]
negative_count = sum(1 for kw in negative_keywords if kw in text_lower)
positive_count = sum(1 for kw in positive_keywords if kw in text_lower)
if negative_count > positive_count:
sentiment = SentimentType.ANGRY if negative_count >= 2 else SentimentType.NEGATIVE
score = min(0.9, 0.5 + (negative_count * 0.15))
elif positive_count > negative_count:
sentiment = SentimentType.POSITIVE
score = min(0.9, 0.5 + (positive_count * 0.15))
else:
sentiment = SentimentType.NEUTRAL
score = 0.5
return SentimentResult(
sentiment=sentiment,
score=score,
confidence=0.7 # Mock confidence
)
class CRMQueryTool(BaseTool):
"""Query CRM for user information"""
def __init__(self):
super().__init__(
name="crm_query",
description="Retrieve user profile and history from CRM"
)
async def execute(self, input_data: CRMQueryInput) -> Dict[str, Any]:
"""Execute CRM query"""
if settings.USE_MOCK_TOOLS:
return self._mock_query(input_data)
else:
return await self._api_query(input_data)
def _mock_query(self, input_data: CRMQueryInput) -> Dict[str, Any]:
"""Mock CRM query"""
return {
"user_id": input_data.user_id,
"name": "Priya Sharma",
"email": "priya****@gmail.com",
"phone": "+91-98****5678",
"tier": "Gold",
"lifetime_value": 45000,
"order_count": 23,
"preferences": ["organic", "skincare", "gifts"],
"last_order_date": "2025-10-01",
"source": "crm"
}
async def _api_query(self, input_data: CRMQueryInput) -> Dict[str, Any]:
"""Real API CRM query"""
try:
async with httpx.AsyncClient() as client:
response = await client.post(
f"{settings.CRM_API_URL}/query",
json=input_data.dict(),
timeout=10.0
)
response.raise_for_status()
return response.json()
except Exception as e:
logger.error(f"CRM API error: {e}")
return self._mock_query(input_data)
# ============ TOOL REGISTRY ============
class ToolRegistry:
"""Central registry for all tools"""
def __init__(self):
self.tools: Dict[str, BaseTool] = {
"product_search": ProductSearchTool(),
"order_lookup": OrderLookupTool(),
"promotions_check": PromotionsCheckTool(),
"sentiment_analysis": SentimentAnalysisTool(),
"crm_query": CRMQueryTool()
}
def get_tool(self, name: str) -> Optional[BaseTool]:
"""Get tool by name"""
return self.tools.get(name)
def get_tool_descriptions(self) -> List[Dict[str, str]]:
"""Get all tool descriptions for LLM"""
return [
{
"name": tool.name,
"description": tool.description
}
for tool in self.tools.values()
]
async def execute_tool(self, tool_name: str, input_data: Any) -> Any:
"""Execute a tool by name"""
tool = self.get_tool(tool_name)
if not tool:
raise ValueError(f"Tool {tool_name} not found")
try:
# Convert dict input to proper Pydantic model
if isinstance(input_data, dict):
input_data = self._convert_to_input_model(tool_name, input_data)
result = await tool.execute(input_data)
logger.info(f"Tool {tool_name} executed successfully")
return result
except Exception as e:
logger.error(f"Tool {tool_name} execution failed: {e}")
raise
def _convert_to_input_model(self, tool_name: str, data: dict) -> Any:
"""Convert dict to appropriate input model based on tool name"""
model_map = {
"product_search": ProductSearchInput,
"order_lookup": OrderLookupInput,
"promotions_check": PromotionsCheckInput,
"sentiment_analysis": SentimentAnalysisInput,
"crm_query": CRMQueryInput
}
model_class = model_map.get(tool_name)
if not model_class:
return data # Return as-is if no mapping
return model_class(**data)
# Global tool registry instance
tool_registry = ToolRegistry()