Spaces:
Running
Running
Chandima Prabhath
commited on
Commit
·
b560795
1
Parent(s):
c629376
Refactor route_intent and whatsapp_webhook functions for improved error handling and logging; streamline JSON parsing and payload validation
Browse files
app.py
CHANGED
@@ -408,13 +408,11 @@ def route_intent(user_input: str, chat_id: str, sender: str):
|
|
408 |
try:
|
409 |
raw = generate_llm(prompt)
|
410 |
except LLMBadRequestError:
|
411 |
-
# Clear history on HTTP 400 from the LLM
|
412 |
clear_history(chat_id, sender)
|
413 |
return SendTextIntent(action="send_text", message="Oops, I lost my train of thought—let’s start fresh!")
|
414 |
|
415 |
logger.debug(f"LLM raw response: {raw}")
|
416 |
|
417 |
-
# 1) Strict: try each Pydantic model
|
418 |
try:
|
419 |
parsed = json.loads(raw)
|
420 |
logger.debug(f"Parsed JSON: {parsed}")
|
@@ -431,7 +429,6 @@ def route_intent(user_input: str, chat_id: str, sender: str):
|
|
431 |
|
432 |
logger.warning("Strict parse failed for all models, falling back to lenient")
|
433 |
|
434 |
-
# 2) Lenient JSON get
|
435 |
action = parsed.get("action")
|
436 |
if action in ACTION_HANDLERS:
|
437 |
data = parsed
|
@@ -459,7 +456,6 @@ def route_intent(user_input: str, chat_id: str, sender: str):
|
|
459 |
kwargs["voter"] = sender
|
460 |
kwargs["choice"] = int(data.get("choice",0))
|
461 |
try:
|
462 |
-
# coerce into Pydantic for uniform interface
|
463 |
model = next(
|
464 |
m for m in INTENT_MODELS
|
465 |
if getattr(m, "__fields__", {}).get("action").default == action
|
@@ -493,19 +489,31 @@ help_text = (
|
|
493 |
@app.post("/whatsapp")
|
494 |
async def whatsapp_webhook(request: Request):
|
495 |
data = await request.json()
|
|
|
|
|
496 |
if request.headers.get("Authorization") != f"Bearer {BotConfig.WEBHOOK_AUTH_TOKEN}":
|
497 |
raise HTTPException(403, "Unauthorized")
|
498 |
|
499 |
-
|
500 |
-
|
501 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
502 |
set_thread_context(chat_id, sender, mid)
|
503 |
logger.debug(f"Received webhook for message {mid} from {sender}")
|
504 |
|
505 |
-
if chat_id != BotConfig.BOT_GROUP_CHAT or data
|
506 |
return {"success": True}
|
507 |
|
508 |
-
md = data
|
509 |
tmd = md.get("textMessageData") or md.get("extendedTextMessageData")
|
510 |
if not tmd:
|
511 |
return {"success": True}
|
@@ -515,7 +523,6 @@ async def whatsapp_webhook(request: Request):
|
|
515 |
logger.debug(f"User message: {body}")
|
516 |
|
517 |
low = body.lower()
|
518 |
-
# Slash commands...
|
519 |
if low == "/help":
|
520 |
_fn_send_text(mid, chat_id, help_text)
|
521 |
return {"success": True}
|
@@ -569,11 +576,9 @@ async def whatsapp_webhook(request: Request):
|
|
569 |
})
|
570 |
return {"success": True}
|
571 |
|
572 |
-
# Skip mentions
|
573 |
if tmd.get("contextInfo", {}).get("mentionedJidList"):
|
574 |
return {"success": True}
|
575 |
|
576 |
-
# Handle quoted replies to the bot
|
577 |
if md.get("typeMessage") == "quotedMessage":
|
578 |
ext = md["extendedTextMessageData"]
|
579 |
quoted = md["quotedMessage"]
|
@@ -587,7 +592,6 @@ async def whatsapp_webhook(request: Request):
|
|
587 |
else:
|
588 |
effective = body
|
589 |
|
590 |
-
# Route intent & dispatch
|
591 |
intent = route_intent(effective, chat_id, sender)
|
592 |
logger.debug(f"Final intent: {intent}")
|
593 |
handler = ACTION_HANDLERS.get(intent.action)
|
|
|
408 |
try:
|
409 |
raw = generate_llm(prompt)
|
410 |
except LLMBadRequestError:
|
|
|
411 |
clear_history(chat_id, sender)
|
412 |
return SendTextIntent(action="send_text", message="Oops, I lost my train of thought—let’s start fresh!")
|
413 |
|
414 |
logger.debug(f"LLM raw response: {raw}")
|
415 |
|
|
|
416 |
try:
|
417 |
parsed = json.loads(raw)
|
418 |
logger.debug(f"Parsed JSON: {parsed}")
|
|
|
429 |
|
430 |
logger.warning("Strict parse failed for all models, falling back to lenient")
|
431 |
|
|
|
432 |
action = parsed.get("action")
|
433 |
if action in ACTION_HANDLERS:
|
434 |
data = parsed
|
|
|
456 |
kwargs["voter"] = sender
|
457 |
kwargs["choice"] = int(data.get("choice",0))
|
458 |
try:
|
|
|
459 |
model = next(
|
460 |
m for m in INTENT_MODELS
|
461 |
if getattr(m, "__fields__", {}).get("action").default == action
|
|
|
489 |
@app.post("/whatsapp")
|
490 |
async def whatsapp_webhook(request: Request):
|
491 |
data = await request.json()
|
492 |
+
logger.debug(f"Incoming webhook payload: {json.dumps(data)}")
|
493 |
+
|
494 |
if request.headers.get("Authorization") != f"Bearer {BotConfig.WEBHOOK_AUTH_TOKEN}":
|
495 |
raise HTTPException(403, "Unauthorized")
|
496 |
|
497 |
+
try:
|
498 |
+
chat_id = data["senderData"]["chatId"]
|
499 |
+
sender = data["senderData"]["sender"]
|
500 |
+
mid = data["idMessage"]
|
501 |
+
except KeyError:
|
502 |
+
try:
|
503 |
+
chat_id = data["chatId"]
|
504 |
+
sender = data["sender"]
|
505 |
+
mid = data["messageId"]
|
506 |
+
except KeyError:
|
507 |
+
logger.error("Cannot find chat_id/sender/message_id in payload")
|
508 |
+
return {"success": False, "error": "bad payload"}
|
509 |
+
|
510 |
set_thread_context(chat_id, sender, mid)
|
511 |
logger.debug(f"Received webhook for message {mid} from {sender}")
|
512 |
|
513 |
+
if chat_id != BotConfig.BOT_GROUP_CHAT or data.get("typeWebhook") != "incomingMessageReceived":
|
514 |
return {"success": True}
|
515 |
|
516 |
+
md = data.get("messageData", {})
|
517 |
tmd = md.get("textMessageData") or md.get("extendedTextMessageData")
|
518 |
if not tmd:
|
519 |
return {"success": True}
|
|
|
523 |
logger.debug(f"User message: {body}")
|
524 |
|
525 |
low = body.lower()
|
|
|
526 |
if low == "/help":
|
527 |
_fn_send_text(mid, chat_id, help_text)
|
528 |
return {"success": True}
|
|
|
576 |
})
|
577 |
return {"success": True}
|
578 |
|
|
|
579 |
if tmd.get("contextInfo", {}).get("mentionedJidList"):
|
580 |
return {"success": True}
|
581 |
|
|
|
582 |
if md.get("typeMessage") == "quotedMessage":
|
583 |
ext = md["extendedTextMessageData"]
|
584 |
quoted = md["quotedMessage"]
|
|
|
592 |
else:
|
593 |
effective = body
|
594 |
|
|
|
595 |
intent = route_intent(effective, chat_id, sender)
|
596 |
logger.debug(f"Final intent: {intent}")
|
597 |
handler = ACTION_HANDLERS.get(intent.action)
|