Listen to this Post

Introduction:
Restaurants lose customers daily because they cannot respond quickly to inquiries and orders. Manual order-taking and customer support are time-consuming, error-prone, and impossible to scale. By building an AI-powered automation system using n8n, Retrieval-Augmented Generation (RAG), and Supabase Vector Database, restaurants can handle customer conversations from start to finish—answering FAQs, taking orders, and sending notifications—all without human intervention. RAG is a technique that improves AI responses by combining language models with external data sources, grounding responses in up-to-date, domain-specific knowledge rather than relying solely on the model’s internal training data.
Learning Objectives:
- Understand how to build a multi-agent AI automation system using n8n’s visual workflow builder
- Learn to implement RAG (Retrieval-Augmented Generation) with Supabase pgvector for dynamic knowledge retrieval
- Master Telegram bot integration for customer messaging and order processing
- Implement AI agent classification and routing for intent-based conversation handling
- Deploy a production-ready restaurant automation workflow with proper security hardening
- Setting Up the Telegram Bot Trigger and Message Reception
The workflow begins when a customer sends a message via Telegram. You need to create a Telegram bot and configure n8n to receive updates.
Step-by-step guide:
First, create your Telegram bot by chatting with @BotFather on Telegram. Copy the bot token provided. In n8n, add a Telegram Trigger node and configure it with your bot credentials to receive “Updates: message”. This node acts as the entry point for every customer interaction, outputting a message object that includes the user’s text, chat ID, and sender information.
Telegram Bot Creation Commands:
1. Open Telegram and search for @BotFather 2. Send /newbot and follow the prompts 3. Copy the bot token (e.g., 1234567890:ABCdefGHIjklMNOpqrsTUVwxyz) 4. In n8n: Settings → Credentials → Add Credential → Telegram Bot API 5. Paste your bot token and save
The Telegram Trigger node should be configured with the following parameters:
– Resource: Message
– Operation: Get Updates (or use Webhook for production)
– Credential: Your saved Telegram credential
For production deployments, configure a webhook URL instead of polling: set the webhook to `https://your-18n-domain.com/webhook-telegram/`.
- Configuring the AI Classification Agent for Intent Routing
Once the message is received, an AI Classification Agent analyzes the customer’s intent and routes the conversation to the appropriate specialized agent—either the General AI Agent (for FAQs) or the Order AI Agent (for menu browsing and ordering).
Step-by-step guide:
Add an AI Agent node and configure it as a classifier. The agent uses a system prompt that instructs it to categorize incoming messages. Connect a Chat OpenAI model node (or any LangChain-compatible LLM) to the agent.
System Prompt for Classification Agent:
You are a restaurant conversation classifier. Analyze the user's message and classify it into one of these categories: - "faq": Questions about opening hours, location, reservations, policies, or general information - "order": Requests to browse the menu, ask about dishes, build an order, or place an order - "other": Anything else Return only the category name in lowercase.
The AI Agent node implements LangChain’s tool calling interface, allowing it to decide which tools (or in this case, which routing path) to invoke. Use a Switch node after the classification to route the message to the appropriate workflow branch.
Configuration Tips:
- Use a Window Buffer Memory node to maintain short-term conversation context
- Set the AI Agent’s System Prompt to clearly define its classification role
- For higher accuracy, use Output Schema to enforce structured responses
3. Implementing RAG with Supabase Vector Database
Both AI agents use a RAG system powered by a Supabase Vector Database to ensure responses always use the latest menu, prices, ingredients, opening hours, and restaurant policies. This eliminates hallucinations and keeps information current.
Step-by-step guide:
First, set up Supabase with pgvector extension:
-- Enable the pgvector extension CREATE EXTENSION IF NOT EXISTS vector WITH SCHEMA extensions; -- Create the documents table for storing embeddings CREATE TABLE documents ( id BIGSERIAL PRIMARY KEY, content TEXT, embedding VECTOR(1536), -- 1536 for OpenAI embeddings metadata JSONB, created_at TIMESTAMP DEFAULT NOW() ); -- Create a function for similarity search CREATE OR REPLACE 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 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 documents.embedding <=> query_embedding LIMIT match_count; END; $$;
Ingestion Pipeline (Knowledge Base Population):
Create a separate ingestion workflow that:
- Fetches restaurant data from Google Drive or a CMS
- Splits content into chunks using a Recursive Character Text Splitter
3. Generates embeddings using OpenAI’s `text-embedding-3-small` model
- Stores embeddings in Supabase using the Supabase Vector Store node
Ingestion Workflow Nodes:
- Google Drive Trigger → Watches for new/modified files
- Default Data Loader → Extracts text from documents
- Recursive Character Text Splitter → Chunks text (recommended: chunk_size=1000, chunk_overlap=200)
- OpenAI Embeddings → Converts chunks to vectors
- Supabase Vector Store (Insert) → Stores embeddings in pgvector
Querying the Vector Store in the AI Agent:
In the RAG Agent workflow, add the Supabase Vector Store node as a tool with the Retrieve operation. Configure it with:
– Embedding Model: Same as used for ingestion
– Limit: 3-5 chunks to return
– Include Metadata: Enable for richer context
The AI Agent will automatically query the vector store when it needs information about menu items, prices, or policies. This is the “open book” mode for your chatbot.
- Building the Order AI Agent with Tool Integration
The Order AI Agent helps customers browse the menu, answers questions about dishes, builds orders naturally, and collects customer details before confirmation.
Step-by-step guide:
Create a dedicated Order AI Agent with the following tools:
Tool 1: Get Menu (HTTP GET)
Endpoint: GET /api/menu Description: Retrieves the current menu with items, prices, and descriptions
Tool 2: Add to Order (HTTP POST)
Endpoint: POST /api/order/add
Body: { "item_id": "string", "quantity": number, "special_instructions": "string" }
Description: Adds an item to the current order
Tool 3: View Order (HTTP GET)
Endpoint: GET /api/order/current Description: Returns the current order summary with items and total
Tool 4: Confirm Order (HTTP POST)
Endpoint: POST /api/order/confirm
Body: { "customer_name": "string", "phone": "string", "address": "string" }
Description: Finalizes the order and saves it
System Prompt for Order AI Agent:
You are a friendly restaurant ordering assistant. Your role is to help customers browse the menu, answer questions about dishes, build their order, and collect delivery details. Rules: - Always confirm the order before finalizing - Ask for customer name, phone, and address before confirmation - Be helpful and conversational - If an item is unavailable, suggest alternatives - Use the tools provided to access menu data and manage orders
The AI Agent node orchestrates the conversation, deciding which tool to call based on the user’s message and the system instructions. It maintains context across multiple turns using the Window Buffer Memory node.
5. Implementing General AI Agent for FAQs
The General AI Agent answers questions about opening hours, restaurant location, reservations, policies, and other frequently asked questions.
Step-by-step guide:
This agent is simpler than the Order Agent—it primarily uses the RAG system to retrieve answers from the knowledge base.
System Prompt for General AI Agent:
You are a helpful restaurant information assistant. Answer customer questions about: - Opening hours and operating days - Restaurant location and directions - Reservation policies and booking - Dietary restrictions and allergen information - Payment methods and policies Always use the RAG tool to retrieve the most current information from the knowledge base. If you don't know the answer, politely say so and offer to connect the customer with a human staff member.
Tools for General AI Agent:
- Supabase Vector Store (Retrieve) → Queries the knowledge base for relevant information
- Optional: Check Opening Hours (HTTP GET) → Verifies if the restaurant is currently open
Opening Hours Check Logic:
Add an HTTP Request node that checks current time against the restaurant’s operating hours. If the restaurant is closed, the workflow automatically prevents new orders and informs the customer.
// Example logic in a Code node
const currentTime = new Date();
const dayOfWeek = currentTime.getDay(); // 0=Sunday, 6=Saturday
const hours = {
monday: { open: 11, close: 22 },
tuesday: { open: 11, close: 22 },
// ... etc
};
// Compare current hour against operating hours
const isOpen = currentTime.getHours() >= hours[bash].open &&
currentTime.getHours() < hours[bash].close;
return { isOpen };
6. Order Confirmation, Storage, and Notification
Once an order is confirmed, the workflow saves order details automatically and sends an instant notification to the restaurant owner.
Step-by-step guide:
Order Storage (Google Sheets Example):
Create a Google Sheet with the following headers:
| Column | Header Name | Description |
|–|-|-|
| A | Queue Number | Auto-generated (e.g., 4582) |
| B | Chat ID | Customer’s Telegram ID |
| C | Name | Customer’s first name |
| D | Order | Items ordered — parsed by AI |
| E | Status | Dropdown: Pending, Preparing, Ready, Completed, Cancelled |
| F | Order Time | Timestamp |
| G | Order Date | Date of order |
Google Sheets Node Configuration:
- Google Sheets OAuth2 API credential required
- Append Row operation to add new orders
- Update Row operation for status changes
Notification Workflow:
When staff update the order status in Google Sheets (e.g., from “Pending” to “Ready”), a separate workflow triggers and sends a notification to the customer via Telegram.
Notification Workflow Nodes:
- Google Sheets Trigger → Watches for row updates
- If Node → Checks if status has changed
- Telegram Send Message → Sends status update to customer’s chat ID
Telegram Notification Example:
🍕 Your order 4582 is now READY for pickup! Thank you for ordering from [Restaurant Name].
7. Security Hardening and Production Deployment
When deploying this system to production, security is paramount. n8n workflows handle sensitive data including customer information, API keys, and order details.
Critical Security Measures:
1. Encryption Key Configuration:
Configure a persistent encryption key so credentials remain secure across restarts:
Set in environment variables N8N_ENCRYPTION_KEY=your-secure-encryption-key
2. Webhook Authentication:
Secure your webhooks by requiring an API key in the request header:
– In n8n, configure Webhook node with Header Auth
– Set header name: `X-API-Key`
– Set expected value: Your secret API key
3. Data Redaction:
Redact execution data to hide sensitive input and output data from workflow executions:
– Navigate to Settings → Security → Data redaction
– Enable enforcement for production workflows
4. Network Security:
- Set up SSL/TLS for encrypted data in transit
- Restrict public access to the n8n UI/API
- Configure task runners to run as unprivileged user
5. Docker Deployment with Environment Variables:
docker-compose.yaml
version: '3.8'
services:
n8n:
image: n8nio/n8n:latest
restart: unless-stopped
ports:
- "5678:5678"
environment:
- N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY}
- N8N_USER_FOLDER=/home/node/.n8n
- N8N_PROTOCOL=https
- N8N_SSL_KEY=/ssl/private.key
- N8N_SSL_CERT=/ssl/certificate.crt
- WEBHOOK_URL=https://your-domain.com/
volumes:
- ./n8n_data:/home/node/.n8n
- ./ssl:/ssl
6. SSRF Protection:
Protect against Server-Side Request Forgery by restricting which hosts and IP ranges workflow nodes can connect to.
7. Credential Management:
Store all API keys (OpenAI, Supabase, Telegram) as n8n credentials rather than hardcoding them in workflows.
What Undercode Say:
- Key Takeaway 1: The combination of n8n’s visual workflow automation with RAG and Supabase vector storage creates a powerful, production-ready AI customer service system that can be deployed in days, not months. The modular architecture allows easy customization for different restaurants or food businesses.
-
Key Takeaway 2: Multi-agent systems with intent classification dramatically improve customer experience by routing inquiries to specialized agents. This reduces response times, eliminates manual work, and ensures customers never miss placing an order—even outside business hours.
Analysis:
This AI-powered restaurant automation system represents a significant shift in how small to medium businesses can leverage AI without extensive development resources. The n8n platform provides a visual, auditable workflow that non-developers can understand and modify. The RAG implementation ensures that responses are always grounded in current data—menu changes, price updates, and policy modifications are reflected instantly without retraining models.
The system addresses the critical pain point of customer service scalability: restaurants can handle unlimited concurrent conversations, respond instantly 24/7, and never miss an order. The modular design means businesses can start with basic FAQ automation and gradually add ordering, payment processing, and loyalty program integration.
From a security perspective, proper hardening—encryption, webhook authentication, data redaction, and SSRF protection—ensures that customer data and business operations remain protected. The use of environment variables for sensitive credentials follows DevOps best practices.
Prediction:
+1 The democratization of AI automation through platforms like n8n will enable millions of small businesses to deploy enterprise-grade customer service systems within the next 12-18 months, fundamentally changing how local businesses compete with larger chains.
+1 RAG-powered systems will become the standard for AI customer interactions, with vector databases like Supabase pgvector serving as the backbone for knowledge retrieval in production environments.
-1 The security landscape for AI automation workflows will face increased scrutiny as attackers target misconfigured webhooks and exposed API endpoints. Organizations must prioritize security auditing and regular vulnerability assessments.
+1 The integration of voice capabilities (Telegram voice notes, WhatsApp voice messages) will be the next frontier, expanding accessibility and user adoption.
-1 Over-reliance on AI agents without proper human fallback mechanisms could lead to customer frustration when edge cases arise. Implementing human-in-the-loop workflows for complex or unresolved queries is essential.
▶️ Related Video (76% Match):
🎯Let’s Practice For Free:
🎓 Live Courses & Certifications:
Join Undercode Academy for Verified Certifications
🚀 Request a Custom Project:
Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[email protected]
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands
IT/Security Reporter URL:
Reported By: Muhammad Eitasam – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


