Shanmuganathan75 commited on
Commit
6fdb40e
·
verified ·
1 Parent(s): b361fe8

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +72 -25
app.py CHANGED
@@ -276,32 +276,53 @@ def handle_cancellation(user_query: str, raw_orders: str, order_status: str) ->
276
 
277
  else:
278
  return "Your order cannot be canceled. We hope to serve you again!"
279
-
280
- # Order chatbot tool
281
  def order_chatbot(input_string: str) -> str:
282
- """Fetch order details from database"""
 
 
 
 
283
  try:
 
284
  data = ast.literal_eval(input_string)
 
 
285
  cust_id = data.get("cust_id")
286
  user_message = data.get("user_message")
287
  except Exception:
 
288
  return "⚠️ Invalid input format for OrderQueryTool."
289
 
 
290
  try:
 
291
  order_result = db_agent.invoke(f"SELECT * FROM orders WHERE cust_id = '{cust_id}';")
 
 
292
  raw_orders = order_result.get("output") if order_result else None
293
  except Exception:
 
294
  return "🚫 Sorry, we cannot fetch your order details right now. Please try again later."
295
 
 
 
 
 
 
296
  return str({
297
  "cust_id": cust_id,
298
  "user_query": user_message,
299
  "raw_orders": raw_orders
300
  })
301
 
302
- # Format customer response
303
  def format_customer_response(input_string: str) -> str:
304
- """Generate final friendly message for customer"""
 
 
 
305
  try:
306
  data = ast.literal_eval(input_string)
307
  cust_id = data.get("cust_id", "Unknown")
@@ -311,28 +332,35 @@ def format_customer_response(input_string: str) -> str:
311
  return "⚠️ Error: Could not parse order data properly."
312
 
313
  order_status = None
 
 
 
314
 
 
315
  for line in raw_orders.splitlines():
316
  if "Order Status" in line:
317
  order_status = line.split(":", 1)[1].strip()
318
- elif "order_status" in line.lower():
319
- try:
320
- order_status = line.split(":", 1)[1].strip().rstrip(",")
321
- except:
322
- pass
323
 
 
324
  escalation_var = detect_escalation(user_query)
325
  if escalation_var == "Escalated":
326
  return (
327
- f"Present status of your order is : {order_status.lower() if order_status else 'processing'}. "
328
- "⚠️ Your issue requires immediate attention. "
329
  "We have escalated your query to a human agent who will contact you shortly."
330
  )
331
 
332
- cancel_response = handle_cancellation(user_query, raw_orders, order_status if order_status else "")
333
- if cancel_response:
 
334
  return cancel_response
335
 
 
 
336
  system_prompt = f"""
337
  You are a friendly customer support assistant for FoodHub.
338
 
@@ -340,34 +368,51 @@ def format_customer_response(input_string: str) -> str:
340
  Here is the customer's order data from the database:
341
  {raw_orders}
342
 
 
 
 
 
 
 
 
 
 
 
 
 
343
  Instructions:
344
  1. Respond naturally and conversationally in a very short response.
345
- 2. Use only raw_orders data to answer the user's query.
346
- 3. Interpret the raw_orders into polite, concise, and customer-friendly responses.
347
- 4. If order_status = 'preparing food', include ETA from 'preparing_eta' and also include ETA from 'delivery_eta'.
348
  - If 'delivery_eta' is missing or None, say: "Your order is being prepared, and Delivery ETA will be available soon."
349
- 5. If order_status = 'delivered', mention 'delivery_time'.
350
- 6. If order_status = 'canceled', explain politely.
351
- 7. If order_status = 'picked up', include ETA from 'delivery_eta'.
352
  - If 'delivery_eta' is missing or None, say: "Your order has been picked up, delivery ETA will be available soon."
353
- 8. If user_query contains 'Where is my order' then provide the order_status from the raw_orders.
354
- 9. If user_query contains 'How many items' then provide the 'Items in Order' from the raw_orders and return only that number in a friendly way.
 
355
  """
356
 
 
357
  user_prompt = f"User Query: {user_query}"
358
 
 
359
  response_msg = llm.predict_messages([
360
  SystemMessage(content=system_prompt),
361
  HumanMessage(content=user_prompt)
362
  ])
363
 
 
364
  response = response_msg.content.strip()
365
 
 
366
  if not response:
367
  return "Sorry, we could not retrieve your order details at this time."
368
-
369
  return response
370
 
 
371
  # Register Tools
372
  Order_Query_Tool = Tool(
373
  name="OrderQueryTool",
@@ -390,9 +435,11 @@ agent = initialize_agent(
390
  verbose=False
391
  )
392
 
393
- # Agent tool response
394
  def agent_tool_response(cust_id: str, user_query: str) -> str:
395
- """Execute tools in correct sequence"""
 
 
396
  agent_prompt = f"""
397
  You are FoodHub's Order Assistant.
398
 
 
276
 
277
  else:
278
  return "Your order cannot be canceled. We hope to serve you again!"
279
+ #________________________________________________________________________________________________________________________
280
+ # --- TOOL 1: Order Query Tool ---
281
  def order_chatbot(input_string: str) -> str:
282
+ """
283
+ Accepts a stringified dict input like:
284
+ "{'cust_id': 'C1016', 'user_message': 'Where is my order?'}"
285
+ Parses it, authenticates, fetches data, and returns structured info.
286
+ """
287
  try:
288
+ # Safely parse the input string into a Python dictionary
289
  data = ast.literal_eval(input_string)
290
+
291
+ # Extract customer ID and user message from the parsed data
292
  cust_id = data.get("cust_id")
293
  user_message = data.get("user_message")
294
  except Exception:
295
+ # If parsing fails, return a formatted error message
296
  return "⚠️ Invalid input format for OrderQueryTool."
297
 
298
+ # Step 1: Fetch order details from the database
299
  try:
300
+ # Query the database for all orders related to the given customer ID
301
  order_result = db_agent.invoke(f"SELECT * FROM orders WHERE cust_id = '{cust_id}';")
302
+
303
+ # Extract the output (raw order data) from the query result
304
  raw_orders = order_result.get("output") if order_result else None
305
  except Exception:
306
+ # Handle any database or query execution errors gracefully
307
  return "🚫 Sorry, we cannot fetch your order details right now. Please try again later."
308
 
309
+ # ✅ Return structured dictionary string for next tool
310
+ # Print raw orders for debugging/logging
311
+ #print(raw_orders)
312
+
313
+ # Return a stringified dictionary containing customer ID, query, and order data
314
  return str({
315
  "cust_id": cust_id,
316
  "user_query": user_message,
317
  "raw_orders": raw_orders
318
  })
319
 
320
+ #---------------------------------------------------------------------------------------------------------------------------
321
  def format_customer_response(input_string: str) -> str:
322
+ """
323
+ Receives the output from OrderQueryTool as stringified dict,
324
+ parses it, and generates the final friendly message.
325
+ """
326
  try:
327
  data = ast.literal_eval(input_string)
328
  cust_id = data.get("cust_id", "Unknown")
 
332
  return "⚠️ Error: Could not parse order data properly."
333
 
334
  order_status = None
335
+ item_in_order = None
336
+ preparing_eta = None
337
+ delivery_time = None
338
 
339
+ # 🔹 Parse the raw order details line by line
340
  for line in raw_orders.splitlines():
341
  if "Order Status" in line:
342
  order_status = line.split(":", 1)[1].strip()
343
+ elif "Preparing ETA" in line:
344
+ preparing_eta = line.split(":", 1)[1].strip()
345
+ elif "Delivery Time" in line:
346
+ delivery_time = line.split(":", 1)[1].strip()
 
347
 
348
+ # 🔹 Check if user query needs escalation (e.g., delayed order or major issue)
349
  escalation_var = detect_escalation(user_query)
350
  if escalation_var == "Escalated":
351
  return (
352
+ f"Present status of your order is : {order_status.lower()}." +
353
+ "⚠️ Your issue requires immediate attention. " +
354
  "We have escalated your query to a human agent who will contact you shortly."
355
  )
356
 
357
+ # 🔹 Handle cancellation requests (calls the function)
358
+ cancel_response = handle_cancellation(user_query, raw_orders, order_status)
359
+ if cancel_response: # If function returns a valid message
360
  return cancel_response
361
 
362
+
363
+ # 🔹 Format normal order response using LLM
364
  system_prompt = f"""
365
  You are a friendly customer support assistant for FoodHub.
366
 
 
368
  Here is the customer's order data from the database:
369
  {raw_orders}
370
 
371
+ Sample of raw_orders :
372
+ order_id: O12501,
373
+ cust_id: C1026,
374
+ order_time: 12:59,
375
+ order_status: preparing food,
376
+ payment_status: COD,
377
+ item_in_order: Burger, Fries, Soda,
378
+ preparing_eta: 13:14,
379
+ prepared_time: None,
380
+ delivery_eta: None,
381
+ delivery_time: None
382
+
383
  Instructions:
384
  1. Respond naturally and conversationally in a very short response.
385
+ 2. Use only raw_oreders data to answer the user's query.
386
+ 2. Interpret the raw_orders into polite, concise, and customer-friendly responses.
387
+ 3. If order_status = 'preparing food', include ETA from 'preparing_eta' and also include ETA from 'delivery_eta'.
388
  - If 'delivery_eta' is missing or None, say: "Your order is being prepared, and Delivery ETA will be available soon."
389
+ 4. If order_status = 'delivered', mention 'delivery_time'.
390
+ 5. If order_status = 'canceled', explain politely.
391
+ 6. If order_status = 'picked up', include ETA from 'delivery_eta'.
392
  - If 'delivery_eta' is missing or None, say: "Your order has been picked up, delivery ETA will be available soon."
393
+ 7. If user_query contains 'Where is my order' then provide the order_status from the raw_orders.
394
+ 8. If user_query contains 'How many items' then provide the 'Items in Order' from the raw_orders and return only that number in a friendly way (e.g., “Your order contains 3 items.”).
395
+
396
  """
397
 
398
+ # Build user-specific prompt
399
  user_prompt = f"User Query: {user_query}"
400
 
401
+ # 🔹 Generate response using LLM (system + user messages)
402
  response_msg = llm.predict_messages([
403
  SystemMessage(content=system_prompt),
404
  HumanMessage(content=user_prompt)
405
  ])
406
 
407
+ # Clean and return the final LLM response
408
  response = response_msg.content.strip()
409
 
410
+ # Return fallback message if no response is generated
411
  if not response:
412
  return "Sorry, we could not retrieve your order details at this time."
 
413
  return response
414
 
415
+ #------------------------------------------------------------------------------------------------------------------------------
416
  # Register Tools
417
  Order_Query_Tool = Tool(
418
  name="OrderQueryTool",
 
435
  verbose=False
436
  )
437
 
438
+ # --- AGENT CONTROLLER ---
439
  def agent_tool_response(cust_id: str, user_query: str) -> str:
440
+ """
441
+ Executes tools in correct sequence: OrderQueryTool → AnswerTool.
442
+ """
443
  agent_prompt = f"""
444
  You are FoodHub's Order Assistant.
445