Skip to content

diegoperea20/evolutionapi-whatsapp-rag-gemini-n8n

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 

Repository files navigation

Implementation of WhatsApp RAG with n8n, Evolution API, OpenRouter, Google Gemini and Supabase

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.

Spanish version

WhatsApp AI Agent Demo
Example of interaction with the RAG agent on WhatsApp.

n8n Workflow for WhatsApp RAG
View of the workflow in n8n.


📋 Prerequisites

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.

Text Embedding Process
The base project handles embedding generation, fundamental for RAG.

Azure for Students (Optional, for zero cost on the VM)

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.


🚀 Steps to Implement WhatsApp RAG with Evolution API

The following are the steps to configure the infrastructure and integration:

Step 1: Create Virtual Machine in Azure

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)

Step 2: Configure Network Rules in Azure

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 firewall rule for HTTPS in Azure
Example of inbound rule configuration in Azure.

Configured firewall rules in Azure
Overview of network rules in Azure.

Step 3: SSH Connection and Easypanel Installation

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 bash

When 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.

Step 4: Accessing Easypanel

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.

Easypanel control panel
Easypanel control panel.

Step 5: Creating the Evolution API Service in Easypanel

  1. Inside Easypanel, create a new Project.
  2. Within the project, click on "+ New" and select "App Service" or search directly for a template.
  3. Look for the "Evolution API" template (usually atendai/evolution-api).

Selecting Evolution API template in Easypanel
Searching for the Evolution API template.

  1. 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

Configuring Docker image for Evolution API
Make sure to use an updated version of the image.

  1. 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).

Evolution API services created in Easypanel
Deployed services: Evolution API, PostgreSQL, and Redis.

Step 6: Accessing the Evolution API Manager

  1. In Easypanel, within your Evolution API service, go to the "Domains" tab (or similar, depending on the Easypanel version). Open the public URL shown.

Domains section of Evolution API service in Easypanel
Accessing the domain configuration.

Open public URL of Evolution API
Open the assigned URL.

  1. 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 of Evolution API Manager
URL to access the API manager.

  1. 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 of Evolution API Manager
Login page of Evolution API manager.

Global API Key in Easypanel environment variables
Locating the Global API Key in Easypanel.

  1. Once authenticated, you will see the main panel of the Evolution API manager.

Dashboard of Evolution API Manager
Main panel of the Evolution API manager.

Step 7: Creating an Instance in Evolution API

  1. In the Evolution API manager, click on "Add Instance" (or similar).
  2. Name your instance (e.g., myRAGbot).
  3. Important: Keep the "Channel" option set to "Baileys".
  4. The "Number" field can be left empty.

Form to create instance in Evolution API
Creating a new instance.

Instance successfully created in Evolution API
Instance created. Note the instance API Key.

  1. Access the newly created instance and navigate to "Configurations" > "Settings".

Instance configuration in Evolution API
Instance settings.

  1. Enable the options according to your needs. For testing, it is common to enable:
  • Reject Calls
  • Ignore Groups
  • Always Online
  • Read Messages
  1. Save the changes.

Step 8: Configuring n8n and Linking with Evolution API

  1. 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.

Webhook Node in n8n
Webhook Node in n8n.

  1. Activate the Workflow: Ensure your n8n workflow is active so it can receive requests.

  2. Webhook URL: Copy the production URL of your Webhook node in n8n.

  3. 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 Webhook in Evolution API Manager
Configuring the n8n webhook URL in Evolution API.

  • In the events list, enable "MESSAGES_UPSERT". You can select other events if needed.

Enable MESSAGES_UPSERT event in Evolution API
Enabling the event for new messages.

  1. 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).

Get QR Code to link WhatsApp
Scanning the QR code to connect WhatsApp.

Step 9: Verifying the Connection between Evolution API and n8n

  1. Send a test message from another WhatsApp number to the number you just connected to Evolution API.
  2. In n8n, go to the "Executions" tab. You should see a new execution triggered by the webhook.
  3. 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.

Data schema of Webhook received in n8n
Checking the message data in n8n.

  1. 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.

Webhook executions in n8n with sample data
Using execution data for the editor.

Step 10: Configuring the "Edit Fields" (or "Set") Node

  1. Return to the "Editor" mode in n8n.
  2. 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 parameters in the Edit Fields node (1)
Configuring key fields like chat_id and the user message.

Configuring parameters in the Edit Fields node (2)
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.

Step 11: Configuring the "AI Agent" Node

  1. Connect the "AI Agent" node (which you should already have configured from the base RAG project) after the "Edit Fields" node.
  2. 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 }}

Configuring AI Agent input (1)
Linking the AI Agent input to the user message.

Configuring AI Agent input (2)
Ensuring the language model processes the correct message.

Step 12: Editing the Chat Memory Node (PostgreSQL)

  1. 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.
  2. 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 }}

Chat memory configuration in PostgreSQL
Chat memory node.

Using chat_id as Session ID in PostgreSQL memory
Using chat_id to differentiate conversations.

Run this node with test data to ensure it works correctly.

Step 13: Configuring the "HTTP Request" Node to Send Responses

  1. Add an "HTTP Request" node at the end of your flow, after the "AI Agent" (and after any node that formats the AI response).
  2. 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 HTTP Request node to send message (1)
Configuring the URL and authentication.

Configuring HTTP Request node to send message (2)
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.

Complete n8n flow for WhatsApp RAG
Flow completed in n8n.

Result of interaction with AI Agent on WhatsApp
Conversation with the RAG agent via WhatsApp.

🎥 Support Videos to Implement WhatsApp RAG with n8n

💡 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


1️⃣ WhatsApp Evolution api n8n

🔗 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

2️⃣ Instala n8n en Propio VPS con Easypanel

🔗 Instala n8n en tu Propio VPS en 5 minutos
Explicación paso a paso para montar un

3️⃣ Instala n8n en Propio VPS con Easypanel, uso evolution api , whatsap con audio

🔗 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



Spanish

Implementación de WhatsApp RAG con n8n, Evolution API, OpenRouter, Google Gemini y Supabase

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.

Demostración del Agente IA en WhatsApp
Ejemplo de interacción con el agente RAG en WhatsApp.

Flujo de n8n para WhatsApp RAG
Vista del flujo de trabajo en n8n.


📋 Prerrequisitos

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.

Proceso de Embedding de Texto
El proyecto base se encarga de la generación de embeddings, fundamental para el RAG.

Azure for Students (Opcional, para coste cero en la VM)

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.


🚀 Pasos para Implementar WhatsApp RAG con Evolution API

A continuación, se detallan los pasos para configurar la infraestructura y la integración:

Paso 1: Creación de Máquina Virtual en Azure

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)

Paso 2: Configuración de Reglas de Red en Azure

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 regla de firewall para HTTPS en Azure
Ejemplo de configuración de regla de entrada en Azure.

Reglas de firewall configuradas en Azure
Vista general de las reglas de red en Azure.

Paso 3: Conexión SSH e Instalación de Easypanel

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 bash

Cuando 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.

Paso 4: Acceso a Easypanel

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
Panel de control de Easypanel.

Paso 5: Creación del Servicio de Evolution API en Easypanel

  1. Dentro de Easypanel, crea un nuevo Proyecto.
  2. Dentro del proyecto, haz clic en "+ New" y selecciona "App Service" o busca directamente una plantilla.
  3. Busca la plantilla de "Evolution API" (normalmente atendai/evolution-api).

Selección de plantilla de Evolution API en Easypanel
Buscando la plantilla de Evolution API.

  1. 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

Configuración de la imagen de Docker para Evolution API
Asegúrate de usar una versión actualizada de la imagen.

  1. 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 de Evolution API creados en Easypanel
Servicios desplegados: Evolution API, PostgreSQL y Redis.

Paso 6: Acceso al Gestor de Evolution API

  1. 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.

Sección Dominios del servicio Evolution API en Easypanel
Accediendo a la configuración de dominios.

Abrir URL pública de Evolution API
Abrir la URL asignada.

  1. 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 del Manager de Evolution API
URL para acceder al gestor de la API.

  1. 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.

Login del Manager de Evolution API
Página de login del gestor de Evolution API.

API Key Global en variables de entorno de Easypanel
Localizando la API Key Global en Easypanel.

  1. Una vez autenticado, verás el panel principal del gestor de Evolution API.

Dashboard del Manager de Evolution API
Panel principal del gestor de Evolution API.

Paso 7: Creación de una Instancia en Evolution API

  1. En el gestor de Evolution API, haz clic en "Add Instance" (o similar).
  2. Asigna un nombre a tu instancia (ej: myRAGbot).
  3. Importante: Mantén la opción "Channel" en "Baileys".
  4. El campo "Number" puede dejarse vacío.

Formulario para crear instancia en Evolution API
Creando una nueva instancia.

Instancia creada exitosamente en Evolution API
Instancia creada. Anota la API Key de la instancia.

  1. Accede a la instancia recién creada y navega a "Configurations" > "Settings".

Configuración de la instancia en Evolution API
Ajustes de la instancia.

  1. Habilita las opciones según tus necesidades. Para pruebas, es común habilitar:
  • Reject Calls
  • Ignore Groups
  • Always Online
  • Read Messages
  1. Guarda los cambios.

Paso 8: Configuración de n8n y Vinculación con Evolution API

  1. 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.

Nodo Webhook en n8n
Nodo Webhook en n8n.

  1. Activa el Workflow: Asegúrate de que tu workflow de n8n esté activo para que pueda recibir peticiones.

  2. URL del Webhook: Copia la URL de producción (Production URL) de tu nodo Webhook en n8n.

  3. 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".

Configuración de Webhook en Evolution API Manager
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.

Habilitar evento MESSAGES_UPSERT en Evolution API
Habilitando el evento para nuevos mensajes.

  1. 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).

Obtener código QR para vincular WhatsApp
Escaneando el código QR para conectar WhatsApp.

Paso 9: Verificación de la Conexión Evolution API y n8n

  1. Envía un mensaje de prueba desde otro número de WhatsApp al número que acabas de conectar a Evolution API.
  2. En n8n, ve a la pestaña "Executions". Deberías ver una nueva ejecución disparada por el webhook.
  3. 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".

Esquema de datos del Webhook recibido en n8n
Verificando los datos del mensaje en n8n.

  1. 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.

Ejecuciones del Webhook en n8n con datos de muestra
Usando los datos de la ejecución para el editor.

Paso 10: Configuración del Nodo "Edit Fields" (o "Set")

  1. Regresa al modo "Editor" en n8n.
  2. 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"

Configuración de parámetros en el nodo Edit Fields (1)
Configurando campos clave como chat_id y el mensaje del usuario.

Configuración de parámetros en el nodo Edit Fields (2)
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.

Paso 11: Configuración del Nodo "AI Agent"

  1. Conecta el nodo "AI Agent" (que ya deberías tener configurado del proyecto RAG base) después del nodo "Edit Fields".
  2. 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 }}

Configuración del input del AI Agent (1)
Enlazando la entrada del AI Agent al mensaje del usuario.

Configuración del input del AI Agent (2)
Asegurando que el modelo de lenguaje procese el mensaje correcto.

Paso 12: Edición del Nodo de Memoria de Chat (PostgreSQL)

  1. 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.
  2. 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 }}

Configuración de memoria de chat en PostgreSQL
Nodo de memoria de chat.

Uso de chat_id como Session ID en memoria de PostgreSQL
Usando el chat_id para diferenciar conversaciones.

Ejecuta este nodo con datos de prueba para asegurar que funciona correctamente.

Paso 13: Configuración del Nodo "HTTP Request" para Enviar Respuestas

  1. 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).
  2. 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

Configuración del nodo HTTP Request para enviar mensaje (1)
Configurando la URL y autenticación.

Configuración del nodo HTTP Request para enviar mensaje (2)
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.

Flujo completo de n8n para WhatsApp RAG
Flujo finalizado en n8n.

Resultado de la interacción con el Agente IA en WhatsApp
Conversación con el agente RAG a través de WhatsApp.

🎥 Videos de Apoyo para Implementar WhatsApp RAG con n8n

💡 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


1️⃣ WhatsApp Evolution api n8n

🔗 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

2️⃣ Instala n8n en Propio VPS con Easypanel

🔗 Instala n8n en tu Propio VPS en 5 minutos
Explicación paso a paso para montar un

3️⃣ Instala n8n en Propio VPS con Easypanel, uso evolution api , whatsap con audio

🔗 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


About

WhatsApp RAG system implementation using n8n & Evolution API. It queries Supabase for info & uses Google Gemini (via OpenRouter) to generate responses for an online store context.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors