WhatsApp AI bot with Twilio and Python LangChain

Simple POC using LangChain to built a WhatsApp bot chat with.

Requirements

Local Development

User flow

Code

@app.route('/whatsapp/incoming', methods=['POST']) def whatsapp(): incoming_msg = request.values.get('Body', '').strip() # User's WhatsApp message incoming_file_url = request.values.get('MediaUrl0') # File URL if provided response = MessagingResponse() msg = response.message() # Temp config, for prod can ue the incoming number config = {"configurable": {"thread_id": "abc123"}} try: if incoming_file_url: file_name: str = handle_file_download(incoming_file_url) file_content = extract_text_from_file(file_name) # Index the extracted content index_document(file_content) msg.body("File content indexed successfully. Now you can ask questions related to the uploaded document.") else: # Use the LangChain agent to handle the user's message input_messages = [HumanMessage(incoming_msg)] print(f"input_messages: {input_messages}") agent_response = agent.invoke({"messages": input_messages}, config) ai_response = agent_response["messages"][-1] msg.body(str(ai_response.content)) except Exception as e: msg.body(f"Oops! Something went wrong: {e}") return str(response) if __name__ == '__main__': # starting the server at 8080 app.run(port=8080, debug=True)

UI

(Chat) Error