This workflow creates a multi-modal (Text, Audio, Image) WhatsApp Chatbot for <Business Name> that uses OpenAI to understand customer queries and Supabase as a Vector Store to recommend products.
1. Prerequisites & Database Configuration
Before configuring n8n, you must set up the database tables to handle the AI's "Long Term Knowledge" (Product Catalog) and "Short Term Memory" (Chat History).
A. PostgreSQL Setup (Chat Memory)
This workflow uses a standard Postgres database to remember conversation history so the bot knows what the user said previously.
- Connect to your PostgreSQL database (this can be the same database instance as your Supabase project).
- Run the following SQL to create the necessary table:
SQL
CREATE TABLE IF NOT EXISTS chat_messages (
id SERIAL PRIMARY KEY,
session_id VARCHAR(255) NOT NULL,
message JSONB NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
B. Supabase Setup (Vector Store)
Here is the step-by-step actionable guide to setting up a RAG agent using n8n and Supabase, based on the transcript provided.
Phase 1: Supabase Setup & Database Creation
- Log in to Supabase: Go to the Supabase website and sign in (e.g., via GitHub).
- Create Organization: If you haven't already, create a new organization.
- Create Project:
- Click "New Project".
- Password: Create a strong password and copy/save it immediately (you will need this for the connection string).
- Leave Region and other settings as default.
- Click "Create new project".
- Wait approx. 2-3 minutes for the project status to turn green (Live).
Phase 2: Connect Postgres Chat Memory (for Conversation History)
- Get Connection Details from Supabase:
- In your Supabase project dashboard, click the "Connect" button (usually at the top of the interface).
- Select "Transaction Pooler" (do not use Session for this setup).
- Ensure "pgbouncer" or similar compatible mode is selected if visible.
- Copy the following values displayed:
- Host URL
- User
- Port (Note: Standard is 5432, but for Transaction Pooler it is often 6543—check carefully).
- Database Name (usually postgres).
- Configure n8n Postgres Node:
- In n8n, add a Postgres Chat Memory node (attached to your Agent's memory input).
- Click to create New Credentials.
- Paste the Host, User, Database, and Port you copied.
- Paste the Password you saved during Phase 1.
- SSL: Ignore/Default.
- Click Save.
- Finalize Memory Node:
- Table Name: Enter anytime_chat_history (or your preferred name).
- Context Window Length: Leave as default.
Phase 3: Set Up Vector Store (The RAG Knowledge Base)
- Get API Credentials from Supabase:
- In Supabase, go to Settings (gear icon) -> Data API.
- Copy the Project URL.
- Copy the service_role secret key (Note: Do not use the anon key; use service_role for admin rights to write vectors).
- Create Vector Table via SQL:
- Go to the SQL Editor in the Supabase left sidebar.
- Copy the LangChain/Vector Store setup SQL script (available in Supabase docs or n8n docs for Supabase Vector Store). Basically, it enables the vector extension and creates a documents table.
- Paste the SQL into the editor.
- Click Run.
- Verify: Go to Table Editor (left sidebar) to ensure a table named documents has been created.
- Configure n8n Vector Store Node:
- In n8n, add a Supabase Vector Store node.
- Credentials: Create new credentials using the Project URL and Service Role Key retrieved in Step 1.
- Operation Mode: Select "Use as Tool" (this connects it to the AI Agent).
- Name: Give it a name (e.g., Legion_Man_Docs).
- Description: Describe what is in it (e.g., "Valuable data storage for Legion Company").
- Table Name: Enter documents (matching the table created in SQL).
Phase 4: Uploading Files to Vector Store (Data Ingestion)
To upload files, you need a temporary workflow setup.
- Add Tools to n8n Canvas:
- Add a Supabase Vector Store node (independent, not the tool version yet).
- Set Operation to "Add Documents" (or Insert).
- Table: documents.
- Connect Helper Nodes to Vector Store:
- Embeddings: Connect an OpenAI Embeddings node to the Vector Store's "Embeddings" input.
- Text Splitter: Connect a Recursive Character Text Splitter node to the "Text Splitter" input.
- Settings: Chunk Size 1000, Overlap 200.
- Data Loader: Connect a Default Data Loader node to the "Document" input.
- Settings: Data Format: Automatically Detect by MimeType.
- Set Up Trigger for Upload:
- Add a Chat Trigger node.
- Open the node settings and enable "Allow File Uploads".
- Connect the Chat Trigger to the Supabase Vector Store node.
- Execute Upload:
- Click "Execute Workflow" (or Test Workflow).
- Open the Chat Interface in n8n.
- Click the Paperclip/Upload icon.
- Select your file (PDF, CSV, JSON, etc.).
- Wait for the "Success" message.
- Verify: Check your Supabase Table Editor; the documents table should now contain rows of vector data.
Phase 5: Final Agent Assembly
- Connect Tool: Connect the Supabase Vector Store node (configured as "Use as Tool" in Phase 3) to the Tools input of your AI Agent node.
- Update Prompt: Open your AI Agent node parameters. In the System Prompt, explicitly instruct the agent:
"Use the Supabase vector store tool to retrieve external data when asked about [specific topic/company info]." - Test: Open the chat in n8n and ask a question related to the uploaded document to verify the agent retrieves the correct answer.
Once your Supabase project is ready, run the following SQL query in the Supabase SQL Editor to enable vector search for your products:
SQL
-- Enable the pgvector extension to work with embeddings
create extension vector;
-- Create a table to store your product catalog
create table documents (
id bigserial primary key,
content text, -- This stores the product description/details
metadata jsonb, -- Stores price, image links, SKU, etc.
embedding vector(1536) -- OpenAI embedding dimension
);
-- Create a function to search for products
create function match_documents (
query_embedding vector(1536),
match_threshold float,
match_count int
) returns table (
id bigint,
content text,
metadata jsonb,
similarity float
) language plpgsql stable as $$
begin
return query select
documents.id,
documents.content,
documents.metadata,
1 - (documents.embedding <=> query_embedding) as similarity
from documents
where 1 - (documents.embedding <=> query_embedding) > match_threshold
order by similarity desc
limit match_count;
end;
$$;
2. Workflow Configuration in n8n
A. Credentials Setup
Ensure the following credentials are setup in n8n:
- OpenAI API: Used for the Chat Model (GPT-4), Transcription (Whisper), and Embeddings.
- Postgres: Used for the Postgres Chat Memory node.
- Supabase: Used for the Supabase Vector Store nodes.
B. WhatsApp Connection
Phase 1: Set Up Meta App & Business Portfolio
- Go to business.facebook.com.
- Create Business Portfolio (if none exists):
- Click Create Business Portfolio.
- Fill in business details and click Next.
- Access Settings:
- Click the Settings icon (gear) for your portfolio.
- Create App:
- In the sidebar, click Apps.
- Click the Add button -> Create a new app.
- Select Other -> Click Next.
- Select Business -> Click Next.
- App Name: Enter a name (e.g., n8n Test).
- Contact Email: Enter your email.
- Business Portfolio: Select your portfolio from the dropdown.
- Click Create app and enter your password.
Phase 2: Configure WhatsApp Product
- Add Product:
- On the App dashboard, scroll to WhatsApp.
- Click Set up.
- Start API:
- Click Start using the API (sidebar or main button).
- Add Recipient Number:
- Locate the To field (Step 2 on the screen).
- Click Manage phone number list.
- Add your personal phone number to receive OTP.
- Verify the OTP to add the number to the allowed testing list.
- Send Test Message:
- Click the Send message button on the API setup page to verify the connection.
Phase 3: Set Up n8n Trigger (Incoming Messages)
- Add Trigger Node:
- In n8n, click the + icon.
- Search WhatsApp.
- Select WhatsApp Business Cloud -> Trigger.
- Event: On Message.
- Create Credentials (Client ID/Secret):
- In the n8n node, click Create New Credentials.
- Get Client ID: Go to Meta App Dashboard -> App settings -> Basic. Copy App ID.
- Get Client Secret: On the same Meta page, click Show next to App Secret. Copy it.
- Paste both into n8n and click Save.
Phase 4: Generate Permanent Token (Critical Step)
The default token expires in 24 hours. Do this for a non-expiring token.
- Create System User:
- Go to Business Settings (business.facebook.com/settings).
- Sidebar: Users -> System users.
- Click Add.
- Name: e.g., "n8n Admin".
- Role: Admin.
- Click Create System User.
- Assign App Asset:
- Select the new System User.
- Click Assign Assets.
- Select Apps -> Select your specific App.
- Toggle Full Control (Manage App).
- Click Save Changes.
- Assign WhatsApp Asset:
- Click Assign Assets again.
- Select WhatsApp Accounts.
- Select your Business Account.
- Toggle Full Control.
- Click Save Changes.
- Generate Token:
- Click Generate New Token.
- Select App: Choose your App.
- Token Expiration: Select Never.
- Permissions: Check whatsapp_business_messaging and whatsapp_business_management.
- Click Generate Token.
- Copy this token immediately (you won't see it again).
Phase 5: Set Up n8n Action (Sending Messages)
- Add Action Node:
- In n8n, click + -> Search WhatsApp.
- Select WhatsApp Business Cloud -> Send Message.
- Create Credentials (Permanent Token):
- Click Create New Credentials.
- Access Token: Paste the Permanent Token created in Phase 4.
- Business Account ID: Go to Meta App Dashboard -> WhatsApp -> API Setup. Copy the Business Account ID (not Phone Number ID).
- Paste into n8n and click Save.
- Configure Node:
- Recipient Phone Number: Enter your verified number (with country code, no +).
- Body: Enter text (e.g., "Success").
- Test:
- Connect the Trigger node to the Send Message node.
- Click Execute Workflow.
- Send a message ("Hey") from your phone to the test business number.
- Check if you receive the "Success" reply.
C. Node Specific Configurations
You need to ensure specific nodes map to the tables created in Step 1.
- Postgres Chat Memory Node:
- Credential: Select your Postgres credential.
- Table Name: Ensure this is set to chat_messages (or whatever you named the table in Step 1A).
- Session Key: The workflow is pre-configured to use {{ $('WhatsApp Trigger').item.json.contacts[0].wa_id }}. This ensures every unique WhatsApp number has its own chat history.
- Supabase Vector Store (Retrieve-as-tool) Node:
- Table Name: The JSON uses s by default. Change this to documents (created in Step 1B).
- Search Function: Ensure this matches the function name created in SQL (e.g., match_documents).
- AI Agent Node (The Brain):
- Action Required: Open this node and scroll to Options -> System Message.
- The current prompt contains the old business name. You must manually edit the text to replace it with <Business Name> and describe your actual products (e.g., "We specialize in electronics..." vs "We specialize in jewelry...").
3. Ingesting Your Product Data
The workflow contains a disconnected section on the far right (nodes: Supabase Vector Store1, Embeddings OpenAI1, Default Data Loader). This is your Knowledge Base Uploader.
To load your products into the AI's brain:
- Prepare your Data: You can use a CSV or JSON file containing your products (Name, Description, Price, Image URL).
- Connect a Trigger: Add a Manual Trigger or File Trigger node before the Character Text Splitter or Data Loader.
- Run Once: Execute this specific chain once.
- It will read your product list.
- Convert the text into numbers (Embeddings).
- Save them into the Supabase documents table.
- Once this is done, the Main AI Agent can search this table to recommend products.
4. Understanding the Flow Logic
- Switch Node: Detects the incoming media type.
- Text: Passes directly to the AI Agent.
- Audio: Uses OpenAI Whisper to transcribe the voice note into text, then passes it to the Agent.
- Image: Uses GPT-4 Vision to describe the image (e.g., "A customer sent a photo of a specific dress style"). This description is passed to the Agent so it can recommend matching items from your store.
- AI Response:
- The Agent uses the Supabase Tool to look up products.
- It formulates a response based on the persona defined in the System Message.
- Output:
- If the user sent Text or Image, the bot replies with Text.
- If the user sent Audio, the bot generates an Audio reply (TTS) to maintain a natural conversation flow.