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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
import base64
|
| 4 |
+
import requests
|
| 5 |
+
import mimetypes
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
logging.basicConfig(level=logging.INFO)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class AIService:
|
| 14 |
+
def __init__(self):
|
| 15 |
+
self.api_key = "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"
|
| 16 |
+
self.base_url = "https://openrouter.ai/api/v1/chat/completions"
|
| 17 |
+
|
| 18 |
+
if not self.api_key:
|
| 19 |
+
logger.error("OpenRouter API key missing.")
|
| 20 |
+
self.client_available = False
|
| 21 |
+
else:
|
| 22 |
+
self.client_available = True
|
| 23 |
+
logger.info("OpenRouter client initialized")
|
| 24 |
+
|
| 25 |
+
# Default model from OpenRouter - using Arcee Trinity as requested
|
| 26 |
+
self.model_name = "arcee-ai/trinity-large-preview:free"
|
| 27 |
+
|
| 28 |
+
# reuse connection (faster)
|
| 29 |
+
self.session = requests.Session()
|
| 30 |
+
|
| 31 |
+
# Labels for intent classification (aligned with routes.py)
|
| 32 |
+
self.labels1 = [
|
| 33 |
+
'cancel_order', 'change_order', 'change_shipping_address', 'check_cancellation_fee',
|
| 34 |
+
'check_invoice', 'check_payment_methods', 'check_refund_policy', 'complaint',
|
| 35 |
+
'contact_customer_service', 'contact_human_agent', 'create_account', 'delete_account',
|
| 36 |
+
'delivery_options', 'delivery_period', 'edit_account', 'get_invoice', 'get_refund',
|
| 37 |
+
'newsletter_subscription', 'payment_issue', 'place_order', 'recover_password',
|
| 38 |
+
'registration_problems', 'review', 'set_up_shipping_address', 'switch_account',
|
| 39 |
+
'track_order', 'track_refund'
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
self.labels2 = [
|
| 43 |
+
'ACCOUNT', 'CANCELLATION_FEE', 'CONTACT', 'DELIVERY', 'FEEDBACK',
|
| 44 |
+
'INVOICE', 'NEWSLETTER', 'ORDER', 'PAYMENT', 'REFUND', 'SHIPPING_ADDRESS'
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
# Support system prompt
|
| 48 |
+
self.system_prompt = """
|
| 49 |
+
You are a professional customer support chatbot for an e-commerce service.
|
| 50 |
+
Reply short, helpful, and polite.
|
| 51 |
+
Never say you are an AI model.
|
| 52 |
+
Ask only 1 question if needed.
|
| 53 |
+
""".strip()
|
| 54 |
+
|
| 55 |
+
# ---------------------------
|
| 56 |
+
# OPENROUTER CALL (REUSABLE)
|
| 57 |
+
# ---------------------------
|
| 58 |
+
def _openrouter_generate(self, messages, max_tokens=250, temperature=0.2, enable_reasoning=True, model_override=None):
|
| 59 |
+
headers = {
|
| 60 |
+
"Authorization": f"Bearer {self.api_key}",
|
| 61 |
+
"Content-Type": "application/json",
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
# Filter messages to ensure only valid fields are sent to OpenRouter
|
| 65 |
+
clean_messages = []
|
| 66 |
+
for m in messages:
|
| 67 |
+
clean_msg = {"role": m["role"], "content": m["content"]}
|
| 68 |
+
# Preserve reasoning_details for models that support it (continued reasoning)
|
| 69 |
+
if "reasoning_details" in m:
|
| 70 |
+
clean_msg["reasoning_details"] = m["reasoning_details"]
|
| 71 |
+
clean_messages.append(clean_msg)
|
| 72 |
+
|
| 73 |
+
payload = {
|
| 74 |
+
"model": model_override if model_override else self.model_name,
|
| 75 |
+
"messages": clean_messages,
|
| 76 |
+
"max_tokens": max_tokens,
|
| 77 |
+
"temperature": temperature,
|
| 78 |
+
}
|
| 79 |
+
if enable_reasoning:
|
| 80 |
+
payload["reasoning"] = {"enabled": True}
|
| 81 |
+
|
| 82 |
+
logger.debug(f"OpenRouter Payload: {json.dumps(payload)}")
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
response = self.session.post(self.base_url, headers=headers, data=json.dumps(payload), timeout=30)
|
| 86 |
+
logger.info(f"OpenRouter response status: {response.status_code}")
|
| 87 |
+
response.raise_for_status()
|
| 88 |
+
data = response.json()
|
| 89 |
+
logger.debug(f"OpenRouter response data: {json.dumps(data)}")
|
| 90 |
+
|
| 91 |
+
choice = data['choices'][0]['message']
|
| 92 |
+
content = choice.get('content') or ""
|
| 93 |
+
reasoning_details = choice.get('reasoning_details')
|
| 94 |
+
|
| 95 |
+
# Special case: some models return everything in 'reasoning'
|
| 96 |
+
if not content and 'reasoning' in choice:
|
| 97 |
+
content = choice['reasoning']
|
| 98 |
+
|
| 99 |
+
return content, reasoning_details
|
| 100 |
+
except Exception as e:
|
| 101 |
+
logger.error(f"OpenRouter call failed: {e}")
|
| 102 |
+
return "", None
|
| 103 |
+
|
| 104 |
+
# ---------------------------
|
| 105 |
+
# INTENT DETECTOR (SINGLE WORD + %)
|
| 106 |
+
# ---------------------------
|
| 107 |
+
def detect_intent(self, user_message):
|
| 108 |
+
"""
|
| 109 |
+
Returns dict like:
|
| 110 |
+
{"intent1": "payment_issue", "intent2": "PAYMENT", "confidence1": 0.92, "confidence2": 0.95}
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
prompt = f"""
|
| 114 |
+
Classify the customer message into exactly ONE intent from labels1 and exactly ONE from labels2.
|
| 115 |
+
|
| 116 |
+
labels1: {self.labels1}
|
| 117 |
+
labels2: {self.labels2}
|
| 118 |
+
|
| 119 |
+
Return JSON only in this exact format:
|
| 120 |
+
{{"intent1":"<one_from_labels1>","conf1":0.xx,"intent2":"<one_from_labels2>","conf2":0.xx}}
|
| 121 |
+
|
| 122 |
+
Message: {user_message}
|
| 123 |
+
""".strip()
|
| 124 |
+
|
| 125 |
+
try:
|
| 126 |
+
# Stricter prompt for better JSON compliance
|
| 127 |
+
messages = [{"role": "user", "content": f"TASK: Classify intent into JSON.\n\n{prompt}\n\nIMPORTANT: ONLY JSON. NO TEXT."}]
|
| 128 |
+
|
| 129 |
+
# Use Arcee Trinity for classification as well
|
| 130 |
+
out, _ = self._openrouter_generate(
|
| 131 |
+
messages,
|
| 132 |
+
max_tokens=600,
|
| 133 |
+
temperature=0.0,
|
| 134 |
+
enable_reasoning=False,
|
| 135 |
+
model_override="arcee-ai/trinity-large-preview:free"
|
| 136 |
+
)
|
| 137 |
+
logger.debug(f"Raw intent output: {out}")
|
| 138 |
+
match = re.search(r"\{.*\}", out, re.DOTALL)
|
| 139 |
+
if match:
|
| 140 |
+
obj = json.loads(match.group())
|
| 141 |
+
intent1 = str(obj.get("intent1", "contact_customer_service")).lower().strip()
|
| 142 |
+
intent2 = str(obj.get("intent2", "CONTACT")).upper().strip()
|
| 143 |
+
conf1 = float(obj.get("conf1", 0.50))
|
| 144 |
+
conf2 = float(obj.get("conf2", 0.50))
|
| 145 |
+
|
| 146 |
+
# enforce allowed intents
|
| 147 |
+
if intent1 not in self.labels1:
|
| 148 |
+
intent1 = "contact_customer_service"
|
| 149 |
+
if intent2 not in self.labels2:
|
| 150 |
+
intent2 = "CONTACT"
|
| 151 |
+
|
| 152 |
+
conf1 = max(0.0, min(conf1, 1.0))
|
| 153 |
+
conf2 = max(0.0, min(conf2, 1.0))
|
| 154 |
+
return {
|
| 155 |
+
"intent1": intent1,
|
| 156 |
+
"confidence1": conf1,
|
| 157 |
+
"intent2": intent2,
|
| 158 |
+
"confidence2": conf2
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
except Exception as e:
|
| 162 |
+
logger.error(f"Intent detection error: {e}")
|
| 163 |
+
|
| 164 |
+
return {
|
| 165 |
+
"intent1": "contact_customer_service",
|
| 166 |
+
"confidence1": 0.50,
|
| 167 |
+
"intent2": "CONTACT",
|
| 168 |
+
"confidence2": 0.50
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
# ---------------------------
|
| 172 |
+
# MAIN CHAT RESPONSE
|
| 173 |
+
# ---------------------------
|
| 174 |
+
def generate_response(self, user_message, conversation_history=None):
|
| 175 |
+
logger.info(f"Generating response for message: {user_message}")
|
| 176 |
+
if not self.client_available:
|
| 177 |
+
return self._fallback_response(user_message), {"intent1": "contact_customer_service", "intent2": "CONTACT", "confidence1": 0.5, "confidence2": 0.5}, None
|
| 178 |
+
|
| 179 |
+
# detect intent
|
| 180 |
+
intent_obj = self.detect_intent(user_message)
|
| 181 |
+
logger.info(f"Detected intent object: {intent_obj}")
|
| 182 |
+
|
| 183 |
+
intent1 = intent_obj["intent1"]
|
| 184 |
+
conf1 = intent_obj["confidence1"]
|
| 185 |
+
intent2 = intent_obj["intent2"]
|
| 186 |
+
conf2 = intent_obj["confidence2"]
|
| 187 |
+
|
| 188 |
+
intent1_display = f"{intent1} ({int(conf1*100)}%)"
|
| 189 |
+
intent2_display = f"{intent2} ({int(conf2*100)}%)"
|
| 190 |
+
|
| 191 |
+
# Prepare messages for OpenRouter
|
| 192 |
+
messages = [{"role": "system", "content": self.system_prompt}]
|
| 193 |
+
|
| 194 |
+
if conversation_history:
|
| 195 |
+
for msg in conversation_history:
|
| 196 |
+
role = msg.get('role')
|
| 197 |
+
content = msg.get('content')
|
| 198 |
+
reasoning = msg.get('reasoning_details')
|
| 199 |
+
|
| 200 |
+
msg_obj = {"role": role, "content": content}
|
| 201 |
+
if reasoning:
|
| 202 |
+
msg_obj["reasoning_details"] = reasoning
|
| 203 |
+
messages.append(msg_obj)
|
| 204 |
+
|
| 205 |
+
# Add current user message
|
| 206 |
+
messages.append({"role": "user", "content": user_message})
|
| 207 |
+
|
| 208 |
+
try:
|
| 209 |
+
# For general e-commerce queries, enable reasoning
|
| 210 |
+
enable_r = True
|
| 211 |
+
# For very short greetings, maybe disable to save time/tokens?
|
| 212 |
+
# But let's keep it on for now as requested.
|
| 213 |
+
|
| 214 |
+
reply, reasoning_details = self._openrouter_generate(messages, enable_reasoning=enable_r)
|
| 215 |
+
|
| 216 |
+
if reply:
|
| 217 |
+
return reply, intent_obj, reasoning_details
|
| 218 |
+
|
| 219 |
+
except Exception as e:
|
| 220 |
+
logger.error(f"Response generation error: {e}")
|
| 221 |
+
|
| 222 |
+
return self._fallback_response(user_message), intent_obj, None
|
| 223 |
+
|
| 224 |
+
def _fallback_response(self, user_message):
|
| 225 |
+
return "Please tell me your issue—delivery, payment, refund, account, or feedback."
|
| 226 |
+
|
| 227 |
+
def is_available(self):
|
| 228 |
+
return self.client_available
|