Ahmad140 commited on
Commit
8ff13f1
Β·
verified Β·
1 Parent(s): 6d49e80

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +134 -199
app.py CHANGED
@@ -8,12 +8,10 @@ from datetime import datetime
8
  from sentence_transformers import SentenceTransformer, util
9
  import uuid
10
  import re
11
- import torch
12
- from transformers import AutoTokenizer, AutoModelForCausalLM
13
 
14
  app = Flask(__name__)
15
 
16
- # ---------- Firebase Initialization ----------
17
  firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
18
  if not firebase_service_account_json:
19
  raise ValueError("FIREBASE_SERVICE_ACCOUNT secret set karo.")
@@ -24,257 +22,194 @@ firebase_admin.initialize_app(cred, {'databaseURL': database_url})
24
  ref = db.reference('/')
25
  print("βœ… Firebase connected")
26
 
27
- # ---------- Sentence-Transformer Model ----------
28
  print("πŸ”„ Loading sentence-transformers...")
29
  embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
30
  print("βœ… Embedding model loaded")
31
 
32
- # ---------- Local GPT-2 Fallback (with repetition fix) ----------
33
- print("πŸ”„ Loading local GPT-2 model...")
34
- try:
35
- gpt2_tokenizer = AutoTokenizer.from_pretrained("gpt2")
36
- gpt2_model = AutoModelForCausalLM.from_pretrained("gpt2")
37
- gpt2_tokenizer.pad_token = gpt2_tokenizer.eos_token
38
- device = "cuda" if torch.cuda.is_available() else "cpu"
39
- gpt2_model = gpt2_model.to(device)
40
- print(f"βœ… GPT-2 loaded on {device}")
41
- except Exception as e:
42
- print(f"⚠️ GPT-2 load failed: {e}")
43
- gpt2_model = None
44
- gpt2_tokenizer = None
45
-
46
- # ---------- Detailed Service Packages ----------
47
  SERVICE_PACKAGES = {
48
- "basic website": {
49
- "price": "PKR 50,000",
50
- "timeline": "7-10 working days",
51
- "includes": ["5 pages (Home, About, Services, Contact, Gallery)", "Mobile responsive", "Basic SEO", "Contact form", "Social media links"]
52
- },
53
- "standard website": {
54
- "price": "PKR 1,20,000",
55
- "timeline": "15-20 working days",
56
- "includes": ["10 pages", "CMS (WordPress or custom)", "Advanced SEO", "Blog integration", "Chatbot integration", "Performance optimization", "1 month free support"]
57
- },
58
- "premium website": {
59
- "price": "PKR 2,50,000",
60
- "timeline": "25-30 working days",
61
- "includes": ["Unlimited pages", "E-commerce functionality", "Payment gateway", "User accounts", "Custom animations", "Database design", "Advanced security", "6 months free support", "Training session"]
62
- }
63
  }
64
 
65
  EXTRA_FEATURES = {
66
- "additional language": {"price": "+ PKR 15,000", "timeline": "+ 2 days"},
67
- "multi-vendor": {"price": "+ PKR 80,000", "timeline": "+ 10 days"},
68
  "live chat": {"price": "+ PKR 20,000", "timeline": "+ 3 days"},
69
  "booking system": {"price": "+ PKR 35,000", "timeline": "+ 5 days"},
70
- "custom backend": {"price": "+ PKR 1,00,000+", "timeline": "+ 15 days"},
71
- "24/7 support": {"price": "PKR 10,000/month", "timeline": "ongoing"}
72
  }
73
 
74
- ALL_SERVICES = {
75
- "website design & development": "Custom website from scratch, responsive, modern design.",
76
- "e-commerce setup": "Online store with product catalog, cart, checkout, payment integration.",
77
- "SEO optimization": "On-page, off-page, technical SEO to rank higher on Google.",
78
- "chatbot integration": "AI chatbot for customer support (like this one).",
79
- "maintenance & support": "Regular updates, backups, security, 24/7 monitoring.",
80
- "content writing": "Professional copywriting for web pages, blogs, product descriptions.",
81
- "graphic design": "Logos, banners, social media graphics, brochures.",
82
- "digital marketing": "Social media management, Google Ads, email campaigns.",
83
- "custom web application": "Tailored web apps with database, user authentication, dashboards."
84
- }
85
 
86
- def get_service_details(service_name):
87
- """Return formatted response for a service inquiry."""
88
- service_name_lower = service_name.lower()
89
- for key in ALL_SERVICES:
90
- if key in service_name_lower:
91
- return f"- βœ… **{key.title()}**: {ALL_SERVICES[key]}\n- πŸ’° Pricing: depends on complexity – starting from PKR 30,000\n- ⏱️ Timeline: 5-20 working days"
92
- return None
93
-
94
- def handle_package_inquiry(package):
95
- for pkg, details in SERVICE_PACKAGES.items():
96
- if pkg in package.lower():
97
- includes = "\n β€’ ".join(details["includes"])
98
- return f"- **{pkg.title()} Package**\n- πŸ’° Price: {details['price']}\n- ⏱️ Timeline: {details['timeline']}\n- βœ… Includes:\n β€’ {includes}"
99
- return None
100
-
101
- def handle_extra_feature(user_message):
102
- text = user_message.lower()
103
- matched_features = []
104
- for feature, details in EXTRA_FEATURES.items():
105
- if feature in text:
106
- matched_features.append(f"- {feature.title()}: {details['price']} (timeline {details['timeline']})")
107
- if matched_features:
108
- return "**Extra features cost additional:**\n" + "\n".join(matched_features) + "\n- πŸ’‘ Kya aap apni exact requirement bata sakte hain? Hum custom quote de sakte hain."
109
- return None
110
 
111
- # ---------- Intent Classification (Enhanced) ----------
112
- def classify_intent(user_text):
113
- text = user_text.lower()
114
- # irrelevant topics
115
- if any(kw in text for kw in ["weather", "cricket", "politics", "imran", "nawaz", "stock", "bitcoin"]):
116
  return "irrelevant"
117
- # contact
118
- if any(x in text for x in ["contact", "phone", "number", "whatsapp", "email", "call", "raabta"]):
119
  return "contact"
120
- # pricing/timeline
121
- if any(x in text for x in ["price", "cost", "rate", "kitne", "quote", "charges", "fee", "timeline", "time", "days", "weeks"]):
122
  return "pricing_timeline"
123
- # package inquiry
124
- if any(x in text for x in ["basic website", "standard website", "premium website", "package"]):
125
  return "package"
126
- # extra features
127
- if any(x in text for x in ["extra", "additional", "also want", "add", "plus", "more features", "custom"]):
128
  return "custom_request"
129
- # service inquiry
130
- if any(x in text for x in ["service", "website design", "ecommerce", "seo", "maintenance", "marketing"]):
131
  return "service_inquiry"
132
- # portfolio
133
- if any(x in text for x in ["portfolio", "sample", "gallery", "kaam dikhao"]):
134
  return "portfolio"
135
- # greeting
136
- if any(x in text for x in ["salam", "hello", "hi", "hey"]):
137
  return "greeting"
138
  return "general"
139
 
140
- # ---------- Smart Response Generation (No GPT-2 fallback, intent-based + LLM) ----------
141
- def intent_based_reply(user_message, intent):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  if intent == "contact":
143
- return "- πŸ“ž Phone: +92 300 1234567\n- βœ‰οΈ Email: hello@elitevisuals.com\n- 🌐 Website: www.elitevisuals.com\n- ⏰ Timings: Mon-Sat, 10am-7pm"
144
  elif intent == "pricing_timeline":
145
- return "**Pricing & Timeline Packages:**\n- Basic Website: PKR 50,000 (7-10 days)\n- Standard Website: PKR 1,20,000 (15-20 days)\n- Premium Website: PKR 2,50,000 (25-30 days)\n- πŸ’‘ Exact quote ke liye apni requirement bhejein."
146
  elif intent == "package":
147
- # Try to detect which package
148
- for pkg in SERVICE_PACKAGES:
149
- if pkg in user_message.lower():
150
- return handle_package_inquiry(pkg)
151
- # else show all packages
152
- response = "**Our Website Packages:**\n"
153
- for name, details in SERVICE_PACKAGES.items():
154
- response += f"\n**{name.title()}**: {details['price']}, {details['timeline']}\n β€’ Includes: {', '.join(details['includes'][:2])}...\n"
155
- return response + "\n- Kya aap kisi specific package ke baare mein jaanna chahenge?"
 
 
156
  elif intent == "custom_request":
157
- extra = handle_extra_feature(user_message)
158
  if extra:
159
- return extra
160
- return "- βœ… Hum custom requirements handle karte hain.\n- πŸ’° Additional features se price aur timeline increase hoti hai.\n- πŸ“ Apni requirement detail mein likh bhejein – hum free quote denge."
 
 
 
 
 
161
  elif intent == "service_inquiry":
162
- # Check specific service
163
- for service in ALL_SERVICES:
164
- if service in user_message.lower():
165
- return get_service_details(service)
166
- # general services list
167
- bullet = "\n".join([f" β€’ {s.title()}" for s in ALL_SERVICES])
168
- return f"- Main yeh services provide karta hoon:\n{bullet}\n- Kya aap kisi specific ke baare mein jaanna chahenge?"
 
 
 
 
 
 
 
 
 
 
 
169
  elif intent == "portfolio":
170
- return "- πŸ“· Instagram: @elitevisuals\n- πŸ–₯️ Gallery: www.elitevisuals.com/work\n- πŸ“‚ Sample portfolio: email par bhej sakte hain"
171
  elif intent == "greeting":
172
- return "- Wa-Alaikum-Assalam! πŸ‘‹\n- Main Elite Visuals ka assistant hoon.\n- Main aapki in services mein madad kar sakta hoon:\n β€’ Website design & development\n β€’ E-commerce setup\n β€’ SEO optimization\n β€’ Chatbot integration\n β€’ Maintenance & support\n- Kya aap kisi specific ke baare mein poochna chahenge?"
173
  elif intent == "irrelevant":
174
- return "- ❌ Maazrat, yeh sawaal mere scope mein nahi hai.\n- Main sirf Elite Visuals ki services (website, e-commerce, SEO, chatbot, marketing) ke baare mein jaankaari de sakta hoon.\n- Kya aap in mein se kisi ke baare mein poochna chahenge?"
175
  else:
176
- return "- Main aapki kaise madad kar sakta hoon?\n- Humari services: website design, e-commerce, SEO, chatbot integration, maintenance, digital marketing.\n- Packages start from PKR 50,000."
 
 
177
 
178
- # ---------- OpenRouter Setup ----------
179
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
180
  MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
181
-
182
- SYSTEM_PROMPT = """You are "VisionCraft AI" – assistant for "Elite Visuals", a web & digital agency.
183
-
184
- Services: website design & development, e-commerce, SEO, chatbot integration, maintenance, digital marketing, custom web apps.
185
- Packages: Basic (PKR 50k, 7-10 days), Standard (PKR 1.2L, 15-20 days), Premium (PKR 2.5L, 25-30 days).
186
- Extra features cost additional and increase timeline.
187
-
188
- Always answer in bullet points. If user asks for extra features, clearly state price and timeline increase.
189
- Be concise, helpful, and personalized. Never repeat the same list."""
190
 
191
  def call_openrouter(prompt):
192
  if not OPENROUTER_API_KEY:
193
  return None
194
  url = "https://openrouter.ai/api/v1/chat/completions"
195
  headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
196
- payload = {
197
- "model": MODEL,
198
- "messages": [
199
- {"role": "system", "content": SYSTEM_PROMPT},
200
- {"role": "user", "content": prompt}
201
- ],
202
- "temperature": 0.7,
203
- "max_tokens": 400
204
- }
205
  try:
206
- resp = requests.post(url, json=payload, headers=headers, timeout=15)
207
  resp.raise_for_status()
208
  return resp.json()["choices"][0]["message"]["content"]
209
- except Exception as e:
210
- print(f"OpenRouter error: {e}")
211
  return None
212
 
213
- def generate_with_gpt2(prompt):
214
- """GPT-2 fallback (with same enhancements)"""
215
- if gpt2_model is None:
216
- return None
217
- full_prompt = f"""You are assistant for Elite Visuals (web agency). Services: website design, e-commerce, SEO, chatbots, maintenance.
218
- Answer in bullet points. Be specific about pricing and timeline. If extra features requested, mention price increase.
219
-
220
- User: {prompt}
221
- Assistant:"""
222
- inputs = gpt2_tokenizer(full_prompt, return_tensors="pt", truncation=True, max_length=512)
223
- device = next(gpt2_model.parameters()).device
224
- inputs = {k: v.to(device) for k, v in inputs.items()}
225
- with torch.no_grad():
226
- outputs = gpt2_model.generate(
227
- **inputs,
228
- max_new_tokens=120,
229
- temperature=0.7,
230
- do_sample=True,
231
- repetition_penalty=1.5,
232
- no_repeat_ngram_size=3,
233
- pad_token_id=gpt2_tokenizer.eos_token_id
234
- )
235
- response = gpt2_tokenizer.decode(outputs[0], skip_special_tokens=True)
236
- if "Assistant:" in response:
237
- response = response.split("Assistant:")[-1].strip()
238
- else:
239
- response = response[len(full_prompt):].strip()
240
- # remove duplicates
241
- lines = list(dict.fromkeys([line.strip() for line in response.split('\n') if line.strip()]))
242
- response = '\n'.join(lines[:6])
243
- if len(response) < 20:
244
- return None
245
- return response
246
-
247
- def get_ai_response(user_message, intent):
248
- # First try OpenRouter
249
- resp = call_openrouter(user_message)
250
- if resp and len(resp) > 20 and "error" not in resp.lower():
251
- return resp
252
- # Then try GPT-2
253
- gpt_resp = generate_with_gpt2(user_message)
254
- if gpt_resp:
255
- return gpt_resp
256
- # Final intent-based fallback
257
- return intent_based_reply(user_message, intent)
258
-
259
- # ---------- Firebase ----------
260
- def save_message(session_id, role, content, intent=None):
261
- ref.child(f"chats/{session_id}/messages").push().set({
262
- "role": role, "content": content, "timestamp": datetime.now().isoformat(), "intent": intent
263
- })
264
-
265
  @app.route('/api/chat', methods=['POST'])
266
  def chat():
267
- data = request.get_json()
268
- user_message = data.get('message', '')
269
- session_id = data.get('session_id', str(uuid.uuid4()))
270
  if not user_message:
271
  return jsonify({"error": "No message"}), 400
272
  intent = classify_intent(user_message)
273
  print(f"🎯 [{session_id[:8]}] Intent: {intent}")
 
274
  save_message(session_id, "user", user_message, intent)
275
- bot_reply = get_ai_response(user_message, intent)
276
- save_message(session_id, "assistant", bot_reply)
277
- return jsonify({"reply": bot_reply, "intent": intent, "session_id": session_id})
 
 
 
 
 
 
 
 
 
278
 
279
  @app.route('/')
280
  def index():
 
8
  from sentence_transformers import SentenceTransformer, util
9
  import uuid
10
  import re
 
 
11
 
12
  app = Flask(__name__)
13
 
14
+ # ---------- Firebase ----------
15
  firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
16
  if not firebase_service_account_json:
17
  raise ValueError("FIREBASE_SERVICE_ACCOUNT secret set karo.")
 
22
  ref = db.reference('/')
23
  print("βœ… Firebase connected")
24
 
25
+ # ---------- Sentence-Transformer ----------
26
  print("πŸ”„ Loading sentence-transformers...")
27
  embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
28
  print("βœ… Embedding model loaded")
29
 
30
+ # ---------- Static Data ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  SERVICE_PACKAGES = {
32
+ "basic": {"name": "Basic Website", "price": "PKR 50,000", "timeline": "7-10 days",
33
+ "features": ["5 pages", "responsive", "basic SEO", "contact form", "social links"]},
34
+ "standard": {"name": "Standard Website", "price": "PKR 1,20,000", "timeline": "15-20 days",
35
+ "features": ["10 pages", "CMS", "advanced SEO", "blog", "chatbot", "1 month support"]},
36
+ "premium": {"name": "Premium Website", "price": "PKR 2,50,000", "timeline": "25-30 days",
37
+ "features": ["unlimited pages", "e-commerce", "payment gateway", "user accounts", "custom animations", "6 months support"]}
 
 
 
 
 
 
 
 
 
38
  }
39
 
40
  EXTRA_FEATURES = {
 
 
41
  "live chat": {"price": "+ PKR 20,000", "timeline": "+ 3 days"},
42
  "booking system": {"price": "+ PKR 35,000", "timeline": "+ 5 days"},
43
+ "multi-language": {"price": "+ PKR 25,000", "timeline": "+ 4 days"},
44
+ "custom backend": {"price": "+ PKR 1,00,000+", "timeline": "+ 15 days"}
45
  }
46
 
47
+ ALL_SERVICES = ["Website Design", "E-commerce Setup", "SEO Optimization", "Chatbot Integration", "Maintenance", "Content Writing", "Graphic Design", "Digital Marketing"]
 
 
 
 
 
 
 
 
 
 
48
 
49
+ # ---------- Intent Classification ----------
50
+ IRRELEVANT = ["weather", "cricket", "politics", "imran", "nawaz", "stock", "bitcoin", "covid"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
+ def classify_intent(text):
53
+ t = text.lower()
54
+ if any(k in t for k in IRRELEVANT):
 
 
55
  return "irrelevant"
56
+ if any(x in t for x in ["contact", "phone", "number", "whatsapp", "email", "call"]):
 
57
  return "contact"
58
+ if any(x in t for x in ["price", "cost", "rate", "kitne", "quote", "charges", "fee", "timeline", "time", "days"]):
 
59
  return "pricing_timeline"
60
+ if any(x in t for x in ["basic", "standard", "premium", "package"]):
 
61
  return "package"
62
+ if any(x in t for x in ["extra", "additional", "also want", "add", "more", "custom", "live chat", "booking", "multi-language"]):
 
63
  return "custom_request"
64
+ if any(x in t for x in ["service", "ecommerce", "seo", "chatbot", "maintenance", "marketing", "design"]):
 
65
  return "service_inquiry"
66
+ if any(x in t for x in ["portfolio", "sample", "gallery"]):
 
67
  return "portfolio"
68
+ if any(x in t for x in ["salam", "hello", "hi", "hey"]):
 
69
  return "greeting"
70
  return "general"
71
 
72
+ def detect_package(text):
73
+ t = text.lower()
74
+ if "basic" in t:
75
+ return "basic"
76
+ if "standard" in t:
77
+ return "standard"
78
+ if "premium" in t:
79
+ return "premium"
80
+ return None
81
+
82
+ def detect_extra_feature(text):
83
+ t = text.lower()
84
+ for feat in EXTRA_FEATURES:
85
+ if feat in t:
86
+ return feat
87
+ return None
88
+
89
+ # ---------- Response Generator (with structured data) ----------
90
+ def get_response_and_data(user_message, intent):
91
+ data = {
92
+ "package": None,
93
+ "price": None,
94
+ "timeline": None,
95
+ "features": None,
96
+ "extra_feature": None,
97
+ "extra_cost": None,
98
+ "extra_timeline": None,
99
+ "service": None
100
+ }
101
+
102
  if intent == "contact":
103
+ reply = "- πŸ“ž Phone: +92 300 1234567\n- βœ‰οΈ Email: hello@elitevisuals.com\n- 🌐 Website: www.elitevisuals.com"
104
  elif intent == "pricing_timeline":
105
+ reply = "**Packages:**\n- Basic: PKR 50,000 (7-10 days)\n- Standard: PKR 1,20,000 (15-20 days)\n- Premium: PKR 2,50,000 (25-30 days)"
106
  elif intent == "package":
107
+ pkg = detect_package(user_message)
108
+ if pkg and pkg in SERVICE_PACKAGES:
109
+ p = SERVICE_PACKAGES[pkg]
110
+ data["package"] = p["name"]
111
+ data["price"] = p["price"]
112
+ data["timeline"] = p["timeline"]
113
+ data["features"] = p["features"]
114
+ features = "\n β€’ ".join(p["features"])
115
+ reply = f"**{p['name']}** – {p['price']}, {p['timeline']}\nβœ… Includes:\n β€’ {features}"
116
+ else:
117
+ reply = "**Our Packages:**\n- Basic: PKR 50,000 (7-10 days)\n- Standard: PKR 1,20,000 (15-20 days)\n- Premium: PKR 2,50,000 (25-30 days)"
118
  elif intent == "custom_request":
119
+ extra = detect_extra_feature(user_message)
120
  if extra:
121
+ info = EXTRA_FEATURES[extra]
122
+ data["extra_feature"] = extra
123
+ data["extra_cost"] = info["price"]
124
+ data["extra_timeline"] = info["timeline"]
125
+ reply = f"- βœ… {extra.title()} feature available.\n- πŸ’° Additional cost: {info['price']}\n- ⏱️ Timeline increase: {info['timeline']}\n- πŸ’‘ Custom quote possible."
126
+ else:
127
+ reply = "- βœ… Custom requirements handled.\n- πŸ’° Extra features increase price/timeline.\n- πŸ“ Send your requirement for free quote."
128
  elif intent == "service_inquiry":
129
+ if "ecommerce" in user_message.lower():
130
+ data["service"] = "E-commerce Website"
131
+ data["price"] = "Starting PKR 1,50,000"
132
+ data["timeline"] = "20-30 days"
133
+ reply = "- βœ… E-commerce websites with payment gateway.\n- πŸ’° Starting PKR 1,50,000\n- ⏱️ 20-30 days"
134
+ elif "seo" in user_message.lower():
135
+ data["service"] = "SEO Optimization"
136
+ data["price"] = "PKR 25,000/month"
137
+ data["timeline"] = "ongoing"
138
+ reply = "- βœ… SEO (on-page, off-page, technical).\n- πŸ’° PKR 25,000/month\n- ⏱️ Results in 2-3 months"
139
+ elif "chatbot" in user_message.lower():
140
+ data["service"] = "Chatbot Integration"
141
+ data["price"] = "PKR 30,000 one-time + PKR 5,000/month"
142
+ data["timeline"] = "7-10 days"
143
+ reply = "- βœ… Custom AI chatbot integration.\n- πŸ’° PKR 30,000 setup + PKR 5,000/month\n- ⏱️ 7-10 days"
144
+ else:
145
+ services = "\n β€’ ".join(ALL_SERVICES)
146
+ reply = f"- Services:\n β€’ {services}\n- Ask about specific service."
147
  elif intent == "portfolio":
148
+ reply = "- πŸ“· Instagram: @elitevisuals\n- πŸ–₯️ Gallery: www.elitevisuals.com/work"
149
  elif intent == "greeting":
150
+ reply = "- Wa-Alaikum-Assalam! πŸ‘‹\n- I help with websites, e-commerce, SEO, chatbots.\n- Ask about packages or extra features."
151
  elif intent == "irrelevant":
152
+ reply = "- ❌ Out of scope. I only answer web & digital services."
153
  else:
154
+ reply = "- How can I help? Services: website design, e-commerce, SEO, chatbots, maintenance."
155
+
156
+ return reply, data
157
 
158
+ # ---------- OpenRouter (optional) ----------
159
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
160
  MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
161
+ SYSTEM_PROMPT = """You are Elite Visuals AI assistant. Answer in bullet points. Include price and timeline when relevant."""
 
 
 
 
 
 
 
 
162
 
163
  def call_openrouter(prompt):
164
  if not OPENROUTER_API_KEY:
165
  return None
166
  url = "https://openrouter.ai/api/v1/chat/completions"
167
  headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
168
+ payload = {"model": MODEL, "messages": [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}], "temperature": 0.7, "max_tokens": 300}
 
 
 
 
 
 
 
 
169
  try:
170
+ resp = requests.post(url, json=payload, headers=headers, timeout=10)
171
  resp.raise_for_status()
172
  return resp.json()["choices"][0]["message"]["content"]
173
+ except Exception:
 
174
  return None
175
 
176
+ def get_final_response(user_message, intent):
177
+ # Try OpenRouter
178
+ if OPENROUTER_API_KEY:
179
+ ai_reply = call_openrouter(user_message)
180
+ if ai_reply and len(ai_reply) > 20:
181
+ # For dynamic widget, we can't parse AI output easily, so fallback to structured data as well.
182
+ # But we still need data. We'll also generate structured data from intent as backup.
183
+ reply, data = get_response_and_data(user_message, intent)
184
+ # If AI reply is good, use it but keep data from intent.
185
+ return ai_reply, data
186
+ # Fallback to rule-based
187
+ return get_response_and_data(user_message, intent)
188
+
189
+ # ---------- API ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  @app.route('/api/chat', methods=['POST'])
191
  def chat():
192
+ data_req = request.get_json()
193
+ user_message = data_req.get('message', '')
194
+ session_id = data_req.get('session_id', str(uuid.uuid4()))
195
  if not user_message:
196
  return jsonify({"error": "No message"}), 400
197
  intent = classify_intent(user_message)
198
  print(f"🎯 [{session_id[:8]}] Intent: {intent}")
199
+ reply, structured = get_final_response(user_message, intent)
200
  save_message(session_id, "user", user_message, intent)
201
+ save_message(session_id, "assistant", reply)
202
+ return jsonify({
203
+ "reply": reply,
204
+ "intent": intent,
205
+ "session_id": session_id,
206
+ "widget": structured # send structured data to frontend
207
+ })
208
+
209
+ def save_message(session_id, role, content, intent=None):
210
+ ref.child(f"chats/{session_id}/messages").push().set({
211
+ "role": role, "content": content, "timestamp": datetime.now().isoformat(), "intent": intent
212
+ })
213
 
214
  @app.route('/')
215
  def index():