💿 Managing Your Whinself Conversations with mem0
In this tutorial, we'll learn how to store and manage incoming WhatsApp messages from Whinself using mem0. This allows your chatbot to maintain conversation context, retrieve previous messages, and generate context-aware responses using frameworks like LangChain and OpenAI.
Note: This tutorial assumes that you already have a self-hosted Whinself instance running with a webhook endpoint that receives messages in either the Conversation or ExtendedTextMessage format.
Prerequisites​
- Python 3.8+
- A self-hosted Whinself instance with its API running locally
- Basic knowledge of Python and Flask
- mem0 installed (see installation instructions below)
- An OpenAI API key (if you plan to integrate with LangChain)
Step 1: Install mem0​
For this tutorial, we will use mem0
as our in-memory conversation store. Install mem0 via pip:
pip install mem0
Note: If mem0 is not available via pip, you can implement a simple in-memory store using Python dictionaries or any other storage method.
Step 2: Setting Up Your Flask Webhook with mem0 Integration​
Create a file named app.py
and add the following code. This Flask application will:
- Receive incoming messages from Whinself.
- Parse the message (handling both Conversation and ExtendedTextMessage events).
- Store the message in mem0.
- Retrieve previous conversation history to maintain context.
- Process the message with your chatbot.
- Send a response back to WhatsApp via Whinself using a Python function.
from flask import Flask, request, jsonify
import requests
import json
import mem0 # Import mem0 for storing conversation data
app = Flask(__name__)
# Configure your local Whinself API endpoint and target WhatsApp JID
WHINSSELF_API_URL = "http://localhost:8888/wspout" # Adjust as needed
TARGET_WHATSAPP_JID = "[email protected]" # Replace with the target WhatsApp JID
# Initialize mem0 (this creates an in-memory store)
conversation_store = mem0.Store()
def store_message(sender_id: str, message: str):
"""
Stores the message in the conversation store under the sender's ID.
"""
# Retrieve existing conversation history, if any
history = conversation_store.get(sender_id) or []
history.append(message)
conversation_store.set(sender_id, history)
print(f"Stored message for {sender_id}: {message}")
def retrieve_conversation(sender_id: str):
"""
Retrieves the conversation history for the given sender.
"""
return conversation_store.get(sender_id) or []
def process_message_with_chatbot(message: str, history: list) -> str:
"""
Process the incoming message using LangChain and OpenAI.
The history list provides context for the conversation.
For a production system, integrate with LangChain as needed.
This example simply echoes the message along with the history.
"""
# For demonstration, we concatenate the conversation history with the new message.
context = " | ".join(history)
response = f"Context: {context}\nEcho: {message}"
return response
def send_response_to_whatsapp(response_text: str):
"""
Sends the response back to WhatsApp via Whinself using a Python function.
"""
payload = {
"text": response_text,
"jid": TARGET_WHATSAPP_JID
}
headers = {"Content-Type": "application/json"}
try:
r = requests.post(WHINSSELF_API_URL, json=payload, headers=headers)
print("Response sent to WhatsApp:", r.text)
except Exception as e:
print("Error sending response:", e)
@app.route("/webhook", methods=["POST"])
def webhook():
"""
Webhook endpoint to receive messages from Whinself.
"""
try:
payload = request.get_json(force=True)
except Exception as e:
return jsonify({"status": "error", "error": "Invalid JSON"}), 400
print("Received payload:")
print(json.dumps(payload, indent=2))
# Determine the sender ID (this should be extracted from the payload; here we use a dummy value)
# In a real application, extract the sender's WhatsApp JID from the payload.
sender_id = "default_sender"
# Parse the incoming message event
message_text = ""
if "conversation" in payload:
# Conversation Message Event: plain text message
message_text = payload["conversation"]
elif "text" in payload:
# ExtendedTextMessage Event: message with additional metadata
message_text = payload["text"]
else:
return jsonify({"status": "ignored", "reason": "Unknown message format"}), 200
# Store the incoming message
store_message(sender_id, message_text)
# Retrieve conversation history for context
history = retrieve_conversation(sender_id)
# Process the message using the chatbot (LangChain/OpenAI integration)
response_text = process_message_with_chatbot(message_text, history)
# Send the response back to WhatsApp via Whinself
send_response_to_whatsapp(response_text)
return jsonify({"status": "ok"}), 200
if __name__ == "__main__":
# Run the Flask app on port 8000 (or your preferred port)
app.run(host="0.0.0.0", port=8000, debug=True)
Step 3: Configure Whinself​
Ensure your self-hosted Whinself instance is running and that its config.json
file points the nrurl
(the webhook URL) to your Flask server. For example:
{
"slotid": "my-whatsapp-bot",
"nrurl": "http://localhost:8000/webhook",
"portin": 9001,
"devicename": "Linux WhatsApp Bot",
"debuglevel": 0,
"logstdout": true,
"logsse": true
}
Restart Whinself after updating the configuration.
Step 4: Testing Your Setup​
-
Start the Flask Server:
Run the Flask application:python app.py
-
Verify Whinself Configuration:
Make sure thenrurl
in Whinself's configuration points to your Flask endpoint (e.g.,http://localhost:8000/webhook
). -
Send a Message:
Send a WhatsApp message to your bot, or simulate an incoming POST request to your webhook endpoint using a tool like Postman or curl. -
Observe the Console:
The Flask server should log the received payload, store the message using mem0, retrieve the conversation history, process the message with the chatbot function, and finally send the response back to WhatsApp.
Step 5: Enhancing Your ChatBot​
With this setup, you now have a basic framework to:
- Store and manage conversation history using mem0.
- Use that history as context when processing incoming messages.
- Build a more advanced, context-aware chatbot by integrating with LangChain and OpenAI.
You can further enhance this framework by:
- Extracting a unique sender ID from the incoming payload instead of using a default value.
- Implementing persistence (e.g., using a database) for long-term conversation history.
- Adding error handling and logging for robustness.
- Expanding the chatbot logic for more sophisticated conversation flows.
Conclusion​
By following this tutorial, you've learned how to manage your Whinself conversations with mem0. This setup not only helps you store incoming messages but also provides valuable context for your chatbot's responses, enabling more coherent and personalized interactions.
Happy coding!