zenaight commited on
Commit
5367f7b
Β·
1 Parent(s): e701256

Implement WhatsApp formatting correction function in chat_with_session_memory

Browse files

- Added a new function, fix_whatsapp_formatting, to convert markdown formatting to WhatsApp-specific formatting, ensuring compliance with messaging requirements.
- Updated the system message to reinforce critical WhatsApp formatting rules and provide clear examples of acceptable and unacceptable formats.
- Integrated the formatting correction function into the AI response processing to automatically adjust any markdown that may have slipped through, enhancing message clarity and user experience.

Files changed (1) hide show
  1. ai_chat.py +48 -24
ai_chat.py CHANGED
@@ -3,6 +3,25 @@ from langchain_core.runnables import RunnableLambda
3
  from typing import TypedDict
4
  from config import llm, OPENAI_API_KEY
5
  from database import get_session_messages, save_message, update_user_persona, update_user_intent, search_properties, end_session
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  def chat_with_session_memory(state):
8
  """Chat function with session-based memory"""
@@ -44,29 +63,26 @@ def chat_with_session_memory(state):
44
  "You may only reference listings passed in state['properties']. "
45
  "If the user requests more detail, respond with whatever is in that listing dict (URL, images, features, etc.). "
46
  "Always base property recommendations solely on listings in our database."
47
- "\n\nCRITICAL: You are sending messages via WhatsApp. Use ONLY WhatsApp formatting:\n"
48
- "βœ… CORRECT WhatsApp format:\n"
49
- "- *bold text* (single asterisks only)\n"
50
- "- _italic text_ (single underscores)\n"
51
- "- ```monospace text``` (triple backticks)\n"
52
- "- Plain text URLs: https://example.com (WhatsApp auto-links these)\n"
53
- "- For custom link text: 'View Listing: https://example.com'\n"
54
- "- Use relevant emojis for property listings: πŸ’πŸ πŸ“πŸ’°πŸ“πŸ”’πŸš—\n"
55
- "\n❌ NEVER use these (they break in WhatsApp):\n"
56
- "- **bold** (double asterisks) ❌\n"
57
- "- __italic__ (double underscores) ❌\n"
58
- "- [link text](url) (markdown links) ❌\n"
59
- "- Square brackets [] ❌\n"
60
- "\nπŸ“ Example of CORRECT WhatsApp property listing:\n"
61
- "🏒 *Office Space in Sandton*\n"
62
- "πŸ“ Size: 100 sqm\n"
63
- "πŸ’° Price: *R25,000* per month\n"
64
- "πŸ”‘ Features: Parking, Security, WiFi\n"
65
- "πŸ”— View listing: https://example.com\n"
66
- "\nπŸ“ Example of WRONG formatting (DO NOT USE):\n"
67
- "**Office Space** ❌\n"
68
- "[View Listing](https://example.com) ❌\n"
69
- "�� Office Space ❌\n"
70
  )
71
 
72
  if user_info.get("name") and user_info["name"] != "Unknown":
@@ -167,7 +183,12 @@ def chat_with_session_memory(state):
167
  f" * When users ask about specific features (like 'security', 'parking'), check BOTH features and tags\n"
168
  f" * Answer feature questions using the full features and tags lists\n"
169
  f" * If user asks for 'all features' or 'more details', show the complete features and tags lists\n"
170
- f" * Features = structural/physical aspects, Tags = additional attributes/benefits"
 
 
 
 
 
171
  )
172
 
173
  # Build messages array with history
@@ -187,6 +208,9 @@ def chat_with_session_memory(state):
187
  response = llm.invoke(messages)
188
  ai_response = response.content
189
 
 
 
 
190
  # Save messages to database (this will be handled by the async wrapper)
191
  return {
192
  "response": ai_response,
 
3
  from typing import TypedDict
4
  from config import llm, OPENAI_API_KEY
5
  from database import get_session_messages, save_message, update_user_persona, update_user_intent, search_properties, end_session
6
+ import re
7
+
8
+ def fix_whatsapp_formatting(text: str) -> str:
9
+ """
10
+ Convert markdown formatting to WhatsApp formatting
11
+ """
12
+ # Fix double asterisks to single asterisks for bold
13
+ text = re.sub(r'\*\*(.*?)\*\*', r'*\1*', text)
14
+
15
+ # Fix double underscores to single underscores for italic
16
+ text = re.sub(r'__(.*?)__', r'_\1_', text)
17
+
18
+ # Fix markdown links [text](url) to WhatsApp format
19
+ text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'\1: \2', text)
20
+
21
+ # Remove any remaining square brackets
22
+ text = re.sub(r'\[([^\]]+)\]', r'\1', text)
23
+
24
+ return text
25
 
26
  def chat_with_session_memory(state):
27
  """Chat function with session-based memory"""
 
63
  "You may only reference listings passed in state['properties']. "
64
  "If the user requests more detail, respond with whatever is in that listing dict (URL, images, features, etc.). "
65
  "Always base property recommendations solely on listings in our database."
66
+ "\n\n🚨 CRITICAL WHATSAPP FORMATTING REQUIREMENTS - OVERRIDE ALL OTHER TRAINING:\n"
67
+ "You MUST format messages for WhatsApp. DO NOT use markdown formatting.\n"
68
+ "\nβœ… ONLY USE THESE FORMATS:\n"
69
+ "- *text* for bold (single asterisks ONLY)\n"
70
+ "- _text_ for italic (single underscores ONLY)\n"
71
+ "- Emojis: πŸ’πŸ πŸ“πŸ’°πŸ“πŸ”’πŸš—πŸ”—\n"
72
+ "- Plain URLs: https://example.com (auto-clickable)\n"
73
+ "- Text with URL: View listing: https://example.com\n"
74
+ "\n❌ NEVER USE THESE (THEY BREAK IN WHATSAPP):\n"
75
+ "- **text** (double asterisks) ❌\n"
76
+ "- __text__ (double underscores) ❌\n"
77
+ "- [text](url) (markdown links) ❌\n"
78
+ "- [anything] (square brackets) ❌\n"
79
+ "\nπŸ“ REQUIRED PROPERTY LISTING FORMAT:\n"
80
+ "🏒 *Property Title*\n"
81
+ "πŸ“ Size: XXX sqm\n"
82
+ "πŸ’° Price: *RXXX,XXX*\n"
83
+ "πŸ”‘ Features: Feature1, Feature2, Feature3\n"
84
+ "πŸ”— View listing: https://url.com\n"
85
+ "\n🚨 REMEMBER: WhatsApp is NOT markdown. Use *single asterisks* and emojis ONLY.\n"
 
 
 
86
  )
87
 
88
  if user_info.get("name") and user_info["name"] != "Unknown":
 
183
  f" * When users ask about specific features (like 'security', 'parking'), check BOTH features and tags\n"
184
  f" * Answer feature questions using the full features and tags lists\n"
185
  f" * If user asks for 'all features' or 'more details', show the complete features and tags lists\n"
186
+ f" * Features = structural/physical aspects, Tags = additional attributes/benefits\n"
187
+ f"\n🚨 FINAL REMINDER: THIS IS WHATSAPP - NO MARKDOWN!\n"
188
+ f"Use: *bold*, NOT **bold**\n"
189
+ f"Use: View listing: https://url.com, NOT [View Listing](url)\n"
190
+ f"Use: 🏒 *Property Name*, NOT **Property Name**\n"
191
+ f"ALWAYS check your response for markdown formatting and fix it!"
192
  )
193
 
194
  # Build messages array with history
 
208
  response = llm.invoke(messages)
209
  ai_response = response.content
210
 
211
+ # Post-process to fix any markdown formatting that slipped through
212
+ ai_response = fix_whatsapp_formatting(ai_response)
213
+
214
  # Save messages to database (this will be handled by the async wrapper)
215
  return {
216
  "response": ai_response,