Implementation of a WhatsApp RAG (Retrieval-Augmented Generation) system using n8n and the Evolution API. The system is designed to interact with WhatsApp users, retrieving relevant information from a database (Supabase) and generating coherent responses using language models (Google Gemini via OpenRouter), focused in this example on an online store.
Example of interaction with the RAG agent on WhatsApp.
Before starting, it is essential to have completed and understood the base project: ➡️ RAG with n8n using OpenRouter, Google Gemini and Supabase
This previous project establishes the RAG pipeline (including embedding generation and vector database setup with Supabase), on which we will build the WhatsApp integration.
The base project handles embedding generation, fundamental for RAG.
To minimize costs during server infrastructure development, you can use an Azure for Students account. This option does not require a credit card for initial registration.
- Register at: Azure for Students
The following are the steps to configure the infrastructure and integration:
A virtual machine (VM) is required with the following minimum specifications:
- RAM: 8 GB
- Hard Disk: 28 GB of storage
- Operating System: Ubuntu (recommended for this guide, e.g., Ubuntu Server 20.04 LTS or higher)
Once the VM is created, it is crucial to configure the inbound rules in the Network Security Group associated with the VM to allow traffic on the following ports:
- Port 3000 (TCP): For the Easypanel dashboard.
- Port 80 (TCP): For HTTP (access to Evolution API if not using HTTPS).
- Port 8080 (TCP): Default port for the Evolution API.
- (Optional) Port 443 (TCP): For HTTPS (if you configure a domain with SSL for Evolution API).
Example of inbound rule configuration in Azure.
Overview of network rules in Azure.
Connect to your VM via SSH:
ssh your-username@YOUR_PUBLIC_IP
# Example: ssh [email protected]Once connected, run the following commands:
# Update package list and install updates
sudo apt update && sudo apt upgrade -y
# Install cURL (if not present)
sudo apt install -y curl
# Install Easypanel
curl -sSL https://get.easypanel.io | sudo bashWhen the Easypanel installation completes successfully, you will see a message like:
Easypanel was installed successfully on your server!
http://YOUR_PUBLIC_IP:3000📌 Note
If you are using an Azure virtual machine, the network rules configured in Step 2 are essential. Without them, you will not be able to access Easypanel or the Evolution API services from the outside.
Open your web browser and go to http://YOUR_PUBLIC_IP:3000 to access the Easypanel dashboard. Complete the initial setup if this is your first time accessing it.
- Inside Easypanel, create a new Project.
- Within the project, click on "+ New" and select "App Service" or search directly for a template.
- Look for the "Evolution API" template (usually atendai/evolution-api).
Searching for the Evolution API template.
- When configuring the service, ensure that the selected Docker image is the latest or a recommended stable version. You can check the available tags at :docker hub evolution api
Make sure to use an updated version of the image.
- Easypanel will automatically deploy the necessary services: the Evolution API, a PostgreSQL database (for internal use of Evolution API), and Redis (for cache and queues).
Deployed services: Evolution API, PostgreSQL, and Redis.
- In Easypanel, within your Evolution API service, go to the "Domains" tab (or similar, depending on the Easypanel version). Open the public URL shown.
Accessing the domain configuration.
- A welcome page will open. You need to copy the manager url and paste it into your browser to access the management portal. Example: http://YOUR_PUBLIC_IP/manager (or the domain/port you have configured).
URL to access the API manager.
- The manager will ask for a Global API Key. This key is found in Easypanel, in the environment variables of your Evolution API service (usually API_KEY or GLOBAL_API_KEY). Copy and paste it.
Login page of Evolution API manager.
Locating the Global API Key in Easypanel.
- Once authenticated, you will see the main panel of the Evolution API manager.
Main panel of the Evolution API manager.
- In the Evolution API manager, click on "Add Instance" (or similar).
- Name your instance (e.g., myRAGbot).
- Important: Keep the "Channel" option set to "Baileys".
- The "Number" field can be left empty.
Instance created. Note the instance API Key.
- Access the newly created instance and navigate to "Configurations" > "Settings".
- Enable the options according to your needs. For testing, it is common to enable:
- Reject Calls
- Ignore Groups
- Always Online
- Read Messages
- Save the changes.
- Webhook in n8n: In your n8n workflow (the one from the base RAG project), make sure you have a "Webhook" node as the entry point.
-
Activate the Workflow: Ensure your n8n workflow is active so it can receive requests.
-
Webhook URL: Copy the production URL of your Webhook node in n8n.
-
Configuration in Evolution API:
- Return to the manager of your Evolution API instance.
- Go to the "Events" > "Webhook" section.
- Paste the production URL of n8n in the "URL" field.
- Enable "Webhook" and "Webhook Base64".
Configuring the n8n webhook URL in Evolution API.
- In the events list, enable "MESSAGES_UPSERT". You can select other events if needed.
Enabling the event for new messages.
- Connect WhatsApp:
- Go to the "Dashboard" of your instance in Evolution API.
- Click on "Get QR Code".
- Scan the QR code with the WhatsApp application of the phone number you want to use as the RAG bot (from WhatsApp Web or the "Linked Devices" section on your mobile).
Scanning the QR code to connect WhatsApp.
- Send a test message from another WhatsApp number to the number you just connected to Evolution API.
- In n8n, go to the "Executions" tab. You should see a new execution triggered by the webhook.
- Click on the execution and then on the Webhook node to inspect the received data. Ensure that the message and sender information (like remoteJid) are present in the "JSON" or "Schema" tab.
Checking the message data in n8n.
- If the data is correct, you can "pin" this execution (use as example data) to facilitate the configuration of the following nodes. Click on the pin icon (Pin) or "Use data for workflow" on the output of the Webhook node in the execution view.
Using execution data for the editor.
- Return to the "Editor" mode in n8n.
- Add an "Edit Fields" (or "Set" in newer versions of n8n) node connected immediately after the Webhook node. Where the parameters should be added with their corresponding value, "chat_id", "instance_name", "apikey", "url_server"
Configuring key fields like chat_id and the user message.
Configuring fields for the connection with Evolution API.
Run this "Edit Fields" node at least once with test data so that its results are available for the following nodes.
- Connect the "AI Agent" node (which you should already have configured from the base RAG project) after the "Edit Fields" node.
- Ensure that the input field of the "AI Agent" is using the user message extracted by the "Edit Fields" node. Input: {{ $('Edit Fields').item.json.user_message }}
Linking the AI Agent input to the user message.
Ensuring the language model processes the correct message.
- The node that manages the chat memory (in the base project, it's a PostgreSQL node for "Chat Memory") should use the chat_id to keep conversation histories separate by user.
- Set the "Session ID" (or "Key") field of the memory node to use the chat_id from the "Edit Fields" node. Session ID: {{ $('Edit Fields').item.json.chat_id }}
Using chat_id to differentiate conversations.
Run this node with test data to ensure it works correctly.
- Add an "HTTP Request" node at the end of your flow, after the "AI Agent" (and after any node that formats the AI response).
- This node will send the response generated by the AI back to the WhatsApp user through the Evolution API. Consult the official documentation of evolution api Send message
Configuring the URL and authentication.
Defining the JSON body to send the message.
✅ Ready to Test!
With all steps completed and the n8n workflow activated: Send a message from WhatsApp to the connected number. Watch the execution in n8n. You should receive a response generated by your RAG system on WhatsApp.
Conversation with the RAG agent via WhatsApp.
💡 These resources will help you understand and implement each part of the process more easily. From creating the WhatsApp RAG to configuring credentials and processes
🔗 Tutorial N8N: ¡Construir Chatbot en WhatsApp! (Método fácil)
Explicación paso a paso para montar un sistema WhatsApp Evolution api con n8n en Easypanel
🔗 Instala n8n en tu Propio VPS en 5 minutos
Explicación paso a paso para montar un
🔗 Curso N8N desde cero, creando un asistente virtual con Whatsapp + Google Calendar + OPENAI
Explicación paso a paso para montar un
Created by Diego Ivan Perea Montealegre
Este repositorio detalla la implementación de un sistema WhatsApp RAG (Retrieval-Augmented Generation) utilizando n8n y la API de Evolution. El sistema está diseñado para interactuar con usuarios de WhatsApp, recuperando información relevante de una base de datos (Supabase) y generando respuestas coherentes mediante modelos de lenguaje (Google Gemini a través de OpenRouter), enfocado en este ejemplo para una tienda online.
Ejemplo de interacción con el agente RAG en WhatsApp.
Vista del flujo de trabajo en n8n.
Antes de comenzar, es esencial haber completado y comprendido el proyecto base: ➡️ RAG with n8n using OpenRouter, Google Gemini and Supabase
Este proyecto previo establece el pipeline RAG (incluyendo la generación de embeddings y la configuración de la base de datos vectorial con Supabase), sobre el cual construiremos la integración con WhatsApp.
El proyecto base se encarga de la generación de embeddings, fundamental para el RAG.
Para minimizar costos durante el desarrollo de la infraestructura de servidor, se puede utilizar una cuenta de Azure for Students. Esta opción no requiere tarjeta de crédito para el registro inicial.
- Regístrate en: Azure for Students
A continuación, se detallan los pasos para configurar la infraestructura y la integración:
Se requiere una máquina virtual (VM) con las siguientes especificaciones mínimas:
- Memoria RAM: 8 GB
- Disco Duro: 28 GB de almacenamiento
- Sistema Operativo: Ubuntu (recomendado para esta guía, ej: Ubuntu Server 20.04 LTS o superior)
Una vez creada la VM, es crucial configurar las reglas de entrada (Inbound rules) en el Grupo de Seguridad de Red (Network Security Group) asociado a la VM para permitir el tráfico en los siguientes puertos:
- Puerto 3000 (TCP): Para el panel de Easypanel.
- Puerto 80 (TCP): Para HTTP (acceso a Evolution API si no se usa HTTPS).
- Puerto 8080 (TCP): Puerto por defecto para la API de Evolution.
- (Opcional) Puerto 443 (TCP): Para HTTPS (si configuras un dominio con SSL para Evolution API).
Ejemplo de configuración de regla de entrada en Azure.
Vista general de las reglas de red en Azure.
Conéctate a tu VM mediante SSH:
ssh tu-usuario@TU_IP_PUBLICA
# Ejemplo: ssh [email protected]Una vez conectado, ejecuta los siguientes comandos:
# Actualizar el listado de paquetes e instalar actualizaciones
sudo apt update && sudo apt upgrade -y
# Instalar cURL (si no está presente)
sudo apt install -y curl
# Instalar Easypanel
curl -sSL https://get.easypanel.io | sudo bashCuando la instalación de Easypanel finalice correctamente, verás un mensaje similar a:
Easypanel was installed successfully on your server!
http://TU_IP_PUBLICA:3000📌 Nota
Si estás utilizando una máquina virtual de Azure, las reglas de red configuradas en el Paso 2 son indispensables. Sin ellas, no podrás acceder a Easypanel ni a los servicios de la API de Evolution desde el exterior.
Abre tu navegador web e ingresa a http://TU_IP_PUBLICA:3000 para acceder al panel de Easypanel. Completa la configuración inicial si es la primera vez que accedes.
Panel de control de Easypanel.
- Dentro de Easypanel, crea un nuevo Proyecto.
- Dentro del proyecto, haz clic en "+ New" y selecciona "App Service" o busca directamente una plantilla.
- Busca la plantilla de "Evolution API" (normalmente atendai/evolution-api).
Buscando la plantilla de Evolution API.
- Al configurar el servicio, verifica que la imagen de Docker seleccionada sea la más reciente o una versión estable recomendada. Puedes consultar las etiquetas disponibles en :docker hub evolution api
Asegúrate de usar una versión actualizada de la imagen.
- Easypanel desplegará automáticamente los servicios necesarios: la API de Evolution, una base de datos PostgreSQL (para uso interno de Evolution API) y Redis (para caché y colas).
Servicios desplegados: Evolution API, PostgreSQL y Redis.
- En Easypanel, dentro de tu servicio de Evolution API, ve a la pestaña "Domains" (o similar, según la versión de Easypanel). Abre la URL pública que se muestra.
Accediendo a la configuración de dominios.
- Se abrirá una página de bienvenida. Debes copiar la url manager y pegala a tu navegador para acceder al portal de gestión. Ejemplo: http://TU_IP_PUBLICA/manager (o el dominio/puerto que hayas configurado).
URL para acceder al gestor de la API.
- El gestor te pedirá una Global API Key. Esta clave se encuentra en Easypanel, en las variables de entorno de tu servicio de Evolution API (generalmente API_KEY o GLOBAL_API_KEY). Cópiala y pégala.
Página de login del gestor de Evolution API.
Localizando la API Key Global en Easypanel.
- Una vez autenticado, verás el panel principal del gestor de Evolution API.
Panel principal del gestor de Evolution API.
- En el gestor de Evolution API, haz clic en "Add Instance" (o similar).
- Asigna un nombre a tu instancia (ej: myRAGbot).
- Importante: Mantén la opción "Channel" en "Baileys".
- El campo "Number" puede dejarse vacío.
Instancia creada. Anota la API Key de la instancia.
- Accede a la instancia recién creada y navega a "Configurations" > "Settings".
- Habilita las opciones según tus necesidades. Para pruebas, es común habilitar:
- Reject Calls
- Ignore Groups
- Always Online
- Read Messages
- Guarda los cambios.
- Webhook en n8n: En tu flujo de trabajo de n8n (el del proyecto RAG base), asegúrate de tener un nodo "Webhook" como punto de entrada.
-
Activa el Workflow: Asegúrate de que tu workflow de n8n esté activo para que pueda recibir peticiones.
-
URL del Webhook: Copia la URL de producción (Production URL) de tu nodo Webhook en n8n.
-
Configuración en Evolution API:
- Regresa al gestor de tu instancia de Evolution API.
- Ve a la sección "Events" > "Webhook".
- Pega la URL de producción de n8n en el campo "URL".
- Habilita "Webhook" y "Webhook Base64".
Configurando la URL del webhook de n8n en Evolution API.
- En la lista de eventos, habilita "MESSAGES_UPSERT". Puedes seleccionar otros eventos si los necesitas.
Habilitando el evento para nuevos mensajes.
- Conectar WhatsApp:
- Ve al "Dashboard" de tu instancia en Evolution API.
- Haz clic en "Get QR Code".
- Escanea el código QR con la aplicación WhatsApp del número de teléfono que deseas utilizar como bot RAG (desde WhatsApp Web o la sección "Dispositivos vinculados" en tu móvil).
Escaneando el código QR para conectar WhatsApp.
- Envía un mensaje de prueba desde otro número de WhatsApp al número que acabas de conectar a Evolution API.
- En n8n, ve a la pestaña "Executions". Deberías ver una nueva ejecución disparada por el webhook.
- Haz clic en la ejecución y luego en el nodo Webhook para inspeccionar los datos recibidos. Verifica que el mensaje y la información del remitente (como remoteJid) estén presentes en la pestaña "JSON" o "Schema".
Verificando los datos del mensaje en n8n.
- Si los datos son correctos, puedes "pinear" esta ejecución (usar como datos de ejemplo) para facilitar la configuración de los nodos siguientes. Haz clic en el icono de chincheta (Pin) o en "Use data for workflow" sobre la salida del nodo Webhook en la vista de ejecución.
Usando los datos de la ejecución para el editor.
- Regresa al modo "Editor" en n8n.
- Añade un nodo "Edit Fields" (o "Set" en versiones más recientes de n8n) conectado inmediatamente después del nodo Webhook. En donde se debe agregar los parametros con su correpondiente valor , "chat_id" ,"instance_name" ,"apikey" ,"url_server"
Configurando campos clave como chat_id y el mensaje del usuario.
Configurando campos para la conexión con Evolution API.
Ejecuta este nodo "Edit Fields" al menos una vez con datos de prueba para que sus resultados estén disponibles para los siguientes nodos.
- Conecta el nodo "AI Agent" (que ya deberías tener configurado del proyecto RAG base) después del nodo "Edit Fields".
- Asegúrate de que el campo de entrada (Input) del "AI Agent" esté utilizando el mensaje del usuario extraído por el nodo "Edit Fields". Input: {{ $('Edit Fields').item.json.user_message }}
Enlazando la entrada del AI Agent al mensaje del usuario.
Asegurando que el modelo de lenguaje procese el mensaje correcto.
- El nodo que gestiona la memoria de chat (en el proyecto base es un nodo PostgreSQL para "Chat Memory") debe utilizar el chat_id para mantener historiales de conversación separados por usuario.
- Configura el campo "Session ID" (o "Key") del nodo de memoria para que use el chat_id del nodo "Edit Fields". Session ID: {{ $('Edit Fields').item.json.chat_id }}
Usando el chat_id para diferenciar conversaciones.
Ejecuta este nodo con datos de prueba para asegurar que funciona correctamente.
- Añade un nodo "HTTP Request" al final de tu flujo, después del "AI Agent" (y después de cualquier nodo que formatee la respuesta del AI).
- Este nodo enviará la respuesta generada por el AI de vuelta al usuario de WhatsApp a través de la API de Evolution. Consulta la documentación oficial deevolution api Send message
Configurando la URL y autenticación.
Definiendo el cuerpo JSON para enviar el mensaje.
✅ ¡Listo para Probar!
Con todos los pasos completados y el workflow de n8n activado: Envía un mensaje desde WhatsApp al número conectado. Observa la ejecución en n8n. Deberías recibir una respuesta generada por tu sistema RAG en WhatsApp.
Conversación con el agente RAG a través de WhatsApp.
💡 Estos recursos te ayudarán a comprender e implementar cada parte del proceso con mayor facilidad. Desde la creación del WhatsApp RAG hasta la configuración de credenciales y procesos
🔗 Tutorial N8N: ¡Construir Chatbot en WhatsApp! (Método fácil)
Explicación paso a paso para montar un sistema WhatsApp Evolution api con n8n en Easypanel
🔗 Instala n8n en tu Propio VPS en 5 minutos
Explicación paso a paso para montar un
🔗 Curso N8N desde cero, creando un asistente virtual con Whatsapp + Google Calendar + OPENAI
Explicación paso a paso para montar un
Created by Diego Ivan Perea Montealegre




