To connect WhatsApp with your local LLM, you'll need to use a WhatsApp Web automation library and integrate it with your LLM. Here's a step-by-step approach:
Prerequisites
A local LLM running (like Ollama, LM Studio, or text-generation-webui)
Ensure your local LLM has an API endpoint. For example:
Ollama: Usually runs on http://localhost:11434
LM Studio: Default is http://localhost:1234/v1
Text-generation-webui: Typically http://localhost:5000
3. Create the Integration Script
python
import requests
from whatsapp_web import WhatsApp
import time
# Initialize WhatsApp Web
whatsapp = WhatsApp()
# LLM API configuration
LLM_API_URL = "http://localhost:11434/api/generate" # Adjust for your LLM
MODEL_NAME = "llama2" # Your model name
def query_llm(prompt):
payload = {
"model": MODEL_NAME,
"prompt": prompt,
"stream": False
}
response = requests.post(LLM_API_URL, json=payload)
return response.json()["response"]
def process_message(message):
# Send message to LLM
llm_response = query_llm(message)
return llm_response
# Main loop
whatsapp.open()
time.sleep(10) # Wait for QR code scan
while True:
unread_messages = whatsapp.get_unread_messages()
for msg in unread_messages:
response = process_message(msg.text)
whatsapp.send_message(msg.sender, response)
time.sleep(5)
4. Alternative: Using Selenium-based Approach
python
from selenium import webdriver
from selenium.webdriver.common.by import By
import requests
import time
driver = webdriver.Chrome()
driver.get('https://web.whatsapp.com')
# Wait for QR code scan
input("Scan QR code and press Enter...")
# Your message processing logic here
5. Run Your Bot
Start your local LLM server
Run your Python script
Scan the WhatsApp Web QR code when prompted
The bot will now respond to messages using your local LLM
Important Considerations
Rate Limiting: Add delays between messages to avoid being flagged
Error Handling: Implement try-catch blocks for network issues
Message Filtering: Consider filtering which messages to respond to
Privacy: Only use this for personal or authorized conversations
Advanced Features
You can enhance this by:
Adding context memory for conversations
Implementing specific commands (e.g., "/help", "/reset")
Creating message templates
Adding multimedia support
Would you like me to elaborate on any specific part of this setup or help you troubleshoot a particular issue?
User
How about whatsapp mcp
Assistant
Ah, you're asking about using WhatsApp with MCP (Model Context Protocol)! This is a more sophisticated approach that allows your LLM to interact with WhatsApp as a tool. Here's how to set it up:
import subprocess
import json
from mcp import ClientSession, StdioClientTransport
async def setup_whatsapp_mcp():
# Start MCP server
process = subprocess.Popen(
["node", "whatsapp-mcp-server.js"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# Create MCP client
transport = StdioClientTransport(process.stdout, process.stdin)
async with ClientSession(transport) as session:
# Initialize
await session.initialize()
# List available tools
tools = await session.list_tools()
print("Available tools:", tools)
# Send a message
result = await session.call_tool(
"send_whatsapp_message",
{
"number": "+1234567890",
"message": "Hello from MCP!"
}
)
return session
# Use with your LLM
async def process_with_llm(prompt):
# Your LLM logic here
# Can now use WhatsApp tools through MCP
pass
6. Integration with Popular Local LLMs
For Ollama:
python
import ollama
from mcp import ClientSession
async def ollama_with_whatsapp(prompt):
# Get LLM response
response = ollama.chat(model='llama2', messages=[
{'role': 'user', 'content': prompt}
])
# If response indicates sending WhatsApp
if "send whatsapp" in response['message']['content'].lower():
await session.call_tool("send_whatsapp_message", {...})