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|
| 4 |
+
from typing import Dict, List, Optional
|
| 5 |
+
import json
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
import os
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
|
| 10 |
+
# Load environment variables
|
| 11 |
+
load_dotenv()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass
|
| 15 |
+
class IntentResponse:
|
| 16 |
+
intent: str
|
| 17 |
+
confidence: float
|
| 18 |
+
entities: Dict
|
| 19 |
+
suggested_action: str
|
| 20 |
+
explanation: str
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class EcommerceLLMIntentRecognizer:
|
| 24 |
+
def __init__(self):
|
| 25 |
+
# Get API key from environment variable
|
| 26 |
+
api_key = os.getenv('COHERE_API_KEY')
|
| 27 |
+
if not api_key:
|
| 28 |
+
raise ValueError("Please set COHERE_API_KEY environment variable")
|
| 29 |
+
|
| 30 |
+
self.co = cohere.Client(api_key)
|
| 31 |
+
|
| 32 |
+
# Define our intent taxonomy
|
| 33 |
+
self.valid_intents = {
|
| 34 |
+
'product_search': 'SEARCH_CATALOG',
|
| 35 |
+
'price_inquiry': 'FETCH_PRICE',
|
| 36 |
+
'order_status': 'CHECK_ORDER_STATUS',
|
| 37 |
+
'return_request': 'INITIATE_RETURN',
|
| 38 |
+
'cart_management': 'MODIFY_CART',
|
| 39 |
+
'availability_check': 'CHECK_INVENTORY',
|
| 40 |
+
'checkout_help': 'ASSIST_CHECKOUT',
|
| 41 |
+
'shipping_info': 'PROVIDE_SHIPPING_INFO',
|
| 42 |
+
'product_comparison': 'COMPARE_PRODUCTS',
|
| 43 |
+
'size_guide': 'SHOW_SIZE_GUIDE',
|
| 44 |
+
'warranty_info': 'PROVIDE_WARRANTY_INFO',
|
| 45 |
+
'cancel_order': 'PROCESS_CANCELLATION'
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
def _generate_prompt(self, query: str) -> str:
|
| 49 |
+
return f"""As an e-commerce AI assistant, analyze the following customer query and extract the shopping intent, relevant entities, and determine the appropriate action.
|
| 50 |
+
|
| 51 |
+
Valid intents are: {', '.join(self.valid_intents.keys())}
|
| 52 |
+
|
| 53 |
+
Customer Query: "{query}"
|
| 54 |
+
|
| 55 |
+
Provide your analysis in the following JSON format:
|
| 56 |
+
{{
|
| 57 |
+
"intent": "the_identified_intent",
|
| 58 |
+
"confidence": 0.XX,
|
| 59 |
+
"entities": {{
|
| 60 |
+
"product": "identified_product",
|
| 61 |
+
"category": "product_category",
|
| 62 |
+
"specifications": ["any", "relevant", "specs"],
|
| 63 |
+
"quantity": "if_mentioned",
|
| 64 |
+
"order_id": "if_mentioned",
|
| 65 |
+
"price_range": {{
|
| 66 |
+
"min": "if_mentioned",
|
| 67 |
+
"max": "if_mentioned"
|
| 68 |
+
}}
|
| 69 |
+
}},
|
| 70 |
+
"explanation": "Brief explanation of why this intent was chosen"
|
| 71 |
+
}}
|
| 72 |
+
|
| 73 |
+
JSON Response:"""
|
| 74 |
+
|
| 75 |
+
def recognize_intent(self, query: str) -> IntentResponse:
|
| 76 |
+
# Generate LLM response
|
| 77 |
+
response = self.co.generate(
|
| 78 |
+
model='command',
|
| 79 |
+
prompt=self._generate_prompt(query),
|
| 80 |
+
max_tokens=500,
|
| 81 |
+
temperature=0.2,
|
| 82 |
+
k=0,
|
| 83 |
+
stop_sequences=["\n\n"],
|
| 84 |
+
return_likelihoods='NONE'
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
try:
|
| 88 |
+
# Parse the LLM's response
|
| 89 |
+
result = json.loads(response.generations[0].text)
|
| 90 |
+
|
| 91 |
+
# Map to our action system
|
| 92 |
+
suggested_action = self.valid_intents.get(
|
| 93 |
+
result['intent'],
|
| 94 |
+
'UNKNOWN_ACTION'
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
return IntentResponse(
|
| 98 |
+
intent=result['intent'],
|
| 99 |
+
confidence=result['confidence'],
|
| 100 |
+
entities=result['entities'],
|
| 101 |
+
suggested_action=suggested_action,
|
| 102 |
+
explanation=result['explanation']
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
except json.JSONDecodeError:
|
| 106 |
+
return IntentResponse(
|
| 107 |
+
intent='parse_error',
|
| 108 |
+
confidence=0.0,
|
| 109 |
+
entities={},
|
| 110 |
+
suggested_action='HANDLE_ERROR',
|
| 111 |
+
explanation='Failed to parse LLM response'
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def process_query(user_query: str) -> str:
|
| 116 |
+
try:
|
| 117 |
+
recognizer = EcommerceLLMIntentRecognizer()
|
| 118 |
+
response = recognizer.recognize_intent(user_query)
|
| 119 |
+
|
| 120 |
+
return json.dumps({
|
| 121 |
+
'timestamp': datetime.now().isoformat(),
|
| 122 |
+
'query': user_query,
|
| 123 |
+
'intent': response.intent,
|
| 124 |
+
'confidence': response.confidence,
|
| 125 |
+
'entities': response.entities,
|
| 126 |
+
'suggested_action': response.suggested_action,
|
| 127 |
+
'explanation': response.explanation
|
| 128 |
+
}, indent=2)
|
| 129 |
+
except ValueError as e:
|
| 130 |
+
return json.dumps({
|
| 131 |
+
'error': str(e),
|
| 132 |
+
'hint': 'Please ensure COHERE_API_KEY is set in your .env file'
|
| 133 |
+
}, indent=2)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# Create Gradio interface
|
| 137 |
+
iface = gr.Interface(
|
| 138 |
+
fn=process_query,
|
| 139 |
+
inputs=gr.Textbox(label="Enter customer query"),
|
| 140 |
+
outputs=gr.JSON(label="Intent Analysis"),
|
| 141 |
+
title="E-commerce LLM Intent Recognition System",
|
| 142 |
+
description="""This system uses Cohere's Command model to understand customer intentions in an e-commerce context.
|
| 143 |
+
Enter your query to see the detailed intent analysis.""",
|
| 144 |
+
examples=[
|
| 145 |
+
["I'm looking for a waterproof smart watch under $300"],
|
| 146 |
+
["Can you compare the iPhone 13 and iPhone 14 Pro?"],
|
| 147 |
+
["Need to return my order #ABC123, it's the wrong size"],
|
| 148 |
+
["Do you have this dress in size medium and in red?"],
|
| 149 |
+
["What's your shipping time to California?"]
|
| 150 |
+
]
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
iface.launch()
|