Adaptive email auto-responder with GPT-4, RAG and human feedback loop
⚙️ Self Learning Agent: AI-Powered Email Auto-Responder that Improves with Feedback
🧑💻 Author: LeeWei
Overview of the n8n Workflow
This n8n workflow builds a self-improving AI agent for handling email responses. It integrates Gmail for incoming messages, uses an AI agent with a Supabase vector store for knowledge retrieval, drafts replies based on dynamic prompts, and evaluates confidence scores. High-confidence drafts are sent automatically, while low-confidence ones are routed to Google Sheets for human review. Feedback from Sheets triggers updates to the prompt or knowledge base, enabling the agent to learn and refine its responses over time. The workflow supports OpenAI and OpenRouter models, with structured output parsing and conditional routing for efficiency.
How it Works
• Triggers on new Gmail emails, extracts content, and uses an AI agent with company knowledge from Supabase to draft a response.
• Assesses confidence; auto-sends high-confidence replies or saves drafts to Google Sheets for human feedback.
• Monitors Sheets for updates, extracts feedback via AI, and applies changes—either refining the dynamic prompt or adding new info to the vector store.
• Loops back improvements to enhance future responses without manual reconfiguration.
Set Up Steps
Setup takes about 20-30 minutes, focused on credentials and basic resource creation (e.g., Google Sheet and Supabase table). Detailed node-level guidance is in the workflow's sticky notes—clone the JSON for plug-and-play nodes, then edit only essentials like credentials and IDs. No need to rebuild nodes; they're pre-connected and ready.
🚀 Steps to Connect:
-
Gmail Setup
- Set up OAuth2 credentials at console.cloud.google.com with scopes for Gmail (read/send).
- Paste into the Gmail Trigger and Gmail nodes' credentials fields.
- Test by sending a sample email to your connected inbox.
-
OpenAI API Key
- Generate at platform.openai.com.
- Paste into the OpenAI Chat Model and OpenAI Chat Model1 nodes' credentials.
- 💡 Use a model like
gpt-4o-minifor cost efficiency; adjust temperature in options for response creativity.
-
OpenRouter API Key
- Sign up at openrouter.ai and create an API key.
- Paste into the OpenAI Chat Model2 node's credentials (used for feedback extraction).
- Select a model like
gpt-4o-miniin the node for consistency.
-
Supabase Connection
- Create a free account at supabase.com, set up a project, and add a table named
documentswith vector support (enable pgvector extension). - Paste API URL and key into the Supabase Vector Store and Supabase Vector Store1 nodes' credentials.
- Initialize with sample docs via the workflow or dashboard for knowledge base testing.
- Create a free account at supabase.com, set up a project, and add a table named
-
Google Sheets Setup
- Create OAuth2 credentials at console.cloud.google.com with scopes for Sheets (read/write).
- Paste into all Google Sheets nodes' credentials.
- Duplicate the sample sheet (ID:
1YDzwYd5LdTnSQlFM5YrDhhbCnNH7oHVvNg6x3mYu8I4) or create one with tabs: "Dynamic Var" (for prompts) and "Feedback" (columns: Id, Original Email, Draft, Human Feedback, Status). Replace the documentId in nodes with your sheet's ID.
Plug and Play Instructions
Clone the provided JSON directly into n8n—all nodes (triggers, agents, parsers, switches) are pre-wired and functional. No re-setup required beyond the steps above. Key editable fields (detailed in sticky notes):
-
AI Agent Node: System Message
Customize the prompt template for response style (e.g., add rules for tone or specific facts). Default handles factual, concise replies. -
Structured Output Parser Node: JSON Schema
Adjust if adding output fields (e.g., include "suggested_followup" alongside "final_response" and "resolution_score"). -
If Node: Conditions
Tweak the confidence threshold (default: <4 routes to review) based on your risk tolerance. -
Information Extractor Node: Prompt
Refine the feedback analysis (e.g., prioritize certain feedback types like "add facts" vs. "update prompt").
Test with a sample email: Send a query to your Gmail, review in Sheets if low-confidence, provide feedback, and watch the agent improve on the next run.
Potential Customizations
- Switch AI Models: Swap OpenAI/OpenRouter nodes for alternatives like Anthropic via compatible n8n nodes.
- Add Notifications: Insert a Slack or email node post-Sheets save for alerts on low-confidence drafts.
- Expand Knowledge Base: Add a loader node to ingest more docs into Supabase automatically.
- Confidence Routing: Duplicate the If node for multi-tier reviews (e.g., score 1-2 escalates to admin).
Considerations and Improvements
- API Limits: Monitor OpenAI/OpenRouter usage for costs; start with mini models. Supabase free tier handles small knowledge bases—upgrade for scale.
- Data Privacy: Emails and feedback pass through AI providers—ensure compliance for sensitive info.
- Feedback Loop: Test iterations to confirm improvements; initial runs may need manual prompt tweaks.
- Enhancements: Integrate audio transcription for voice feedback or export logs for auditing.
This workflow turns email handling into an adaptive, low-maintenance system—ideal for support teams or busy inboxes. For tweaks, reference the sticky notes or experiment in a test clone!
n8n Adaptive Email Auto-Responder with GPT-4, RAG, and Human Feedback Loop
This n8n workflow creates an intelligent email auto-responder system leveraging AI (GPT-4) for generating responses, a Retrieval Augmented Generation (RAG) system for context, and a human feedback loop to refine the AI's performance. It can be triggered by new emails or new rows in a Google Sheet, processes the input to generate a draft response, and allows for human review and approval before sending.
What it does
- Triggers on new input: The workflow starts either when a new email is received via Gmail or when a new row is added to a Google Sheet.
- Extracts Information (Placeholder): A placeholder "Information Extractor" node is present, suggesting the intent to parse key details from the incoming email/data.
- Prepares Data for AI (Edit Fields): An "Edit Fields (Set)" node likely prepares the extracted information into a format suitable for the AI agent.
- Generates AI Response (AI Agent with RAG):
- It uses an "AI Agent" node, which is configured with an "OpenAI Chat Model" (likely GPT-4 or similar) for generating responses.
- A "Supabase Vector Store" is integrated, suggesting a RAG (Retrieval Augmented Generation) setup. This means the AI can retrieve relevant information from a knowledge base stored in Supabase to inform its responses.
- "Embeddings OpenAI" is used to convert text into numerical vectors for efficient searching in the vector store.
- "Recursive Character Text Splitter" is used to break down documents into manageable chunks for embedding and retrieval.
- "Structured Output Parser" and "Auto-fixing Output Parser" are used to ensure the AI's output adheres to a specific structure, potentially correcting malformed JSON or other structured data.
- A "Default Data Loader" is present, indicating how documents are loaded into the RAG system.
- Human Feedback Loop (Gmail for Approval): The generated AI response is then routed to a "Gmail" node, likely to send a draft email to a human for review and approval.
- Conditional Logic (If/Switch):
- An "If" node allows for conditional branching based on the AI's output or other criteria.
- A "Switch" node provides multiple output paths, enabling different actions based on the human feedback or AI confidence.
- Logs to Google Sheets: A "Google Sheets" node is used, likely to log the incoming requests, AI-generated responses, and human feedback for tracking and further training.
- Formats Output (Markdown): A "Markdown" node is included, potentially to format the final response or log entries for better readability.
- Provides Notes (Sticky Note): A "Sticky Note" node serves as a place for comments or instructions within the workflow.
Prerequisites/Requirements
- n8n Instance: A running n8n instance.
- Gmail Account: For triggering on new emails and sending approval emails.
- Google Sheets Account: For triggering on new rows and logging data.
- OpenAI API Key: For the "OpenAI Chat Model" and "Embeddings OpenAI" nodes (likely for GPT-4 access).
- Supabase Account: Configured as a vector store for the RAG system. This will require a Supabase project with a
pg_vectorextension enabled and a table for storing embeddings. - LangChain Nodes: Ensure the
@n8n/n8n-nodes-langchainpackage is installed and enabled in your n8n instance.
Setup/Usage
- Import the Workflow: Import the provided JSON into your n8n instance.
- Configure Credentials:
- Set up Google OAuth2 credentials for both the Gmail and Google Sheets nodes.
- Configure your OpenAI API key credential.
- Set up your Supabase credentials, including the URL and service role key.
- Configure Trigger Nodes:
- For "Gmail Trigger", specify the mailbox and any filters for incoming emails.
- For "Google Sheets Trigger", specify the spreadsheet ID and sheet name to monitor.
- Configure AI Agent:
- In the "AI Agent" node, ensure the "OpenAI Chat Model" and "Supabase Vector Store" are correctly linked and configured with your credentials and specific model/collection details.
- Define the prompt for the AI agent to guide its response generation.
- Configure Google Sheets (Logging): Specify the spreadsheet ID and sheet name where the workflow should log information.
- Configure Gmail (Human Feedback): Update the "Gmail" node to send approval emails to the appropriate human reviewer(s).
- Activate the Workflow: Once all credentials and node settings are configured, activate the workflow to start processing.
This workflow provides a robust framework for automating email responses with AI, while maintaining a crucial human oversight for quality control and continuous improvement.
Related Templates
Two-way property repair management system with Google Sheets & Drive
This workflow automates the repair request process between tenants and building managers, keeping all updates organized in a single spreadsheet. It is composed of two coordinated workflows, as two separate triggers are required — one for new repair submissions and another for repair updates. A Unique Unit ID that corresponds to individual units is attributed to each request, and timestamps are used to coordinate repair updates with specific requests. General use cases include: Property managers who manage multiple buildings or units. Building owners looking to centralize tenant repair communication. Automation builders who want to learn multi-trigger workflow design in n8n. --- ⚙️ How It Works Workflow 1 – New Repair Requests Behind the Scenes: A tenant fills out a Google Form (“Repair Request Form”), which automatically adds a new row to a linked Google Sheet. Steps: Trigger: Google Sheets rowAdded – runs when a new form entry appears. Extract & Format: Collects all relevant form data (address, unit, urgency, contacts). Generate Unit ID: Creates a standardized identifier (e.g., BUILDING-UNIT) for tracking. Email Notification: Sends the building manager a formatted email summarizing the repair details and including a link to a Repair Update Form (which activates Workflow 2). --- Workflow 2 – Repair Updates Behind the Scenes:\ Triggered when the building manager submits a follow-up form (“Repair Update Form”). Steps: Lookup by UUID: Uses the Unit ID from Workflow 1 to find the existing row in the Google Sheet. Conditional Logic: If photos are uploaded: Saves each image to a Google Drive folder, renames files consistently, and adds URLs to the sheet. If no photos: Skips the upload step and processes textual updates only. Merge & Update: Combines new data with existing repair info in the same spreadsheet row — enabling a full repair history in one place. --- 🧩 Requirements Google Account (for Forms, Sheets, and Drive) Gmail/email node connected for sending notifications n8n credentials configured for Google API access --- ⚡ Setup Instructions (see more detail in workflow) Import both workflows into n8n, then copy one into a second workflow. Change manual trigger in workflow 2 to a n8n Form node. Connect Google credentials to all nodes. Update spreadsheet and folder IDs in the corresponding nodes. Customize email text, sender name, and form links for your organization. Test each workflow with a sample repair request and a repair update submission. --- 🛠️ Customization Ideas Add Slack or Telegram notifications for urgent repairs. Auto-create folders per building or unit for photo uploads. Generate monthly repair summaries using Google Sheets triggers. Add an AI node to create summaries/extract relevant repair data from repair request that include long submissions.
Automate invoice processing with OCR, GPT-4 & Salesforce opportunity creation
PDF Invoice Extractor (AI) End-to-end pipeline: Watch Drive ➜ Download PDF ➜ OCR text ➜ AI normalize to JSON ➜ Upsert Buyer (Account) ➜ Create Opportunity ➜ Map Products ➜ Create OLI via Composite API ➜ Archive to OneDrive. --- Node by node (what it does & key setup) 1) Google Drive Trigger Purpose: Fire when a new file appears in a specific Google Drive folder. Key settings: Event: fileCreated Folder ID: google drive folder id Polling: everyMinute Creds: googleDriveOAuth2Api Output: Metadata { id, name, ... } for the new file. --- 2) Download File From Google Purpose: Get the file binary for processing and archiving. Key settings: Operation: download File ID: ={{ $json.id }} Creds: googleDriveOAuth2Api Output: Binary (default key: data) and original metadata. --- 3) Extract from File Purpose: Extract text from PDF (OCR as needed) for AI parsing. Key settings: Operation: pdf OCR: enable for scanned PDFs (in options) Output: JSON with OCR text at {{ $json.text }}. --- 4) Message a model (AI JSON Extractor) Purpose: Convert OCR text into strict normalized JSON array (invoice schema). Key settings: Node: @n8n/n8n-nodes-langchain.openAi Model: gpt-4.1 (or gpt-4.1-mini) Message role: system (the strict prompt; references {{ $json.text }}) jsonOutput: true Creds: openAiApi Output (per item): $.message.content → the parsed JSON (ensure it’s an array). --- 5) Create or update an account (Salesforce) Purpose: Upsert Buyer as Account using an external ID. Key settings: Resource: account Operation: upsert External Id Field: taxid_c External Id Value: ={{ $json.message.content.buyer.tax_id }} Name: ={{ $json.message.content.buyer.name }} Creds: salesforceOAuth2Api Output: Account record (captures Id) for downstream Opportunity. --- 6) Create an opportunity (Salesforce) Purpose: Create Opportunity linked to the Buyer (Account). Key settings: Resource: opportunity Name: ={{ $('Message a model').item.json.message.content.invoice.code }} Close Date: ={{ $('Message a model').item.json.message.content.invoice.issue_date }} Stage: Closed Won Amount: ={{ $('Message a model').item.json.message.content.summary.grand_total }} AccountId: ={{ $json.id }} (from Upsert Account output) Creds: salesforceOAuth2Api Output: Opportunity Id for OLI creation. --- 7) Build SOQL (Code / JS) Purpose: Collect unique product codes from AI JSON and build a SOQL query for PricebookEntry by Pricebook2Id. Key settings: pricebook2Id (hardcoded in script): e.g., 01sxxxxxxxxxxxxxxx Source lines: $('Message a model').first().json.message.content.products Output: { soql, codes } --- 8) Query PricebookEntries (Salesforce) Purpose: Fetch PricebookEntry.Id for each Product2.ProductCode. Key settings: Resource: search Query: ={{ $json.soql }} Creds: salesforceOAuth2Api Output: Items with Id, Product2.ProductCode (used for mapping). --- 9) Code in JavaScript (Build OLI payloads) Purpose: Join lines with PBE results and Opportunity Id ➜ build OpportunityLineItem payloads. Inputs: OpportunityId: ={{ $('Create an opportunity').first().json.id }} Lines: ={{ $('Message a model').first().json.message.content.products }} PBE rows: from previous node items Output: { body: { allOrNone:false, records:[{ OpportunityLineItem... }] } } Notes: Converts discount_total ➜ per-unit if needed (currently commented for standard pricing). Throws on missing PBE mapping or empty lines. --- 10) Create Opportunity Line Items (HTTP Request) Purpose: Bulk create OLIs via Salesforce Composite API. Key settings: Method: POST URL: https://<your-instance>.my.salesforce.com/services/data/v65.0/composite/sobjects Auth: salesforceOAuth2Api (predefined credential) Body (JSON): ={{ $json.body }} Output: Composite API results (per-record statuses). --- 11) Update File to One Drive Purpose: Archive the original PDF in OneDrive. Key settings: Operation: upload File Name: ={{ $json.name }} Parent Folder ID: onedrive folder id Binary Data: true (from the Download node) Creds: microsoftOneDriveOAuth2Api Output: Uploaded file metadata. --- Data flow (wiring) Google Drive Trigger → Download File From Google Download File From Google → Extract from File → Update File to One Drive Extract from File → Message a model Message a model → Create or update an account Create or update an account → Create an opportunity Create an opportunity → Build SOQL Build SOQL → Query PricebookEntries Query PricebookEntries → Code in JavaScript Code in JavaScript → Create Opportunity Line Items --- Quick setup checklist 🔐 Credentials: Connect Google Drive, OneDrive, Salesforce, OpenAI. 📂 IDs: Drive Folder ID (watch) OneDrive Parent Folder ID (archive) Salesforce Pricebook2Id (in the JS SOQL builder) 🧠 AI Prompt: Use the strict system prompt; jsonOutput = true. 🧾 Field mappings: Buyer tax id/name → Account upsert fields Invoice code/date/amount → Opportunity fields Product name must equal your Product2.ProductCode in SF. ✅ Test: Drop a sample PDF → verify: AI returns array JSON only Account/Opportunity created OLI records created PDF archived to OneDrive --- Notes & best practices If PDFs are scans, enable OCR in Extract from File. If AI returns non-JSON, keep “Return only a JSON array” as the last line of the prompt and keep jsonOutput enabled. Consider adding validation on parsing.warnings to gate Salesforce writes. For discounts/taxes in OLI: Standard OLI fields don’t support per-line discount amounts directly; model them in UnitPrice or custom fields. Replace the Composite API URL with your org’s domain or use the Salesforce node’s Bulk Upsert for simplicity.
AI multi-agent executive team for entrepreneurs with Gemini, Perplexity and WhatsApp
This workflow is an AI-powered multi-agent system built for startup founders and small business owners who want to automate decision-making, accountability, research, and communication, all through WhatsApp. The “virtual executive team,” is designed to help small teams to work smarter. This workflow sends you market analysis, market and sales tips, It can also monitor what your competitors are doing using perplexity (Research agent) and help you stay a head, or make better decisions. And when you feeling stuck with your start-up accountability director is creative enough to break the barrier 🎯 Core Features 🧑💼 1. President (Super Agent) Acts as the main controller that coordinates all sub-agents. Routes messages, assigns tasks, and ensures workflow synchronization between the AI Directors. 📊 2. Sales & Marketing Director Uses SerpAPI to search for market opportunities, leads, and trends. Suggests marketing campaigns, keywords, or outreach ideas. Can analyze current engagement metrics to adjust content strategy. 🕵️♀️ 3. Business Research Director Powered by Perplexity AI for competitive and market analysis. Monitors competitor moves, social media engagement, and product changes. Provides concise insights to help the founder adapt and stay ahead. ⏰ 4. Accountability Director Keeps the founder and executive team on track. Sends motivational nudges, task reminders, and progress reports. Promotes consistency and discipline — key traits for early-stage success. 🗓️ 5. Executive Secretary Handles scheduling, email drafting, and reminders. Connects with Google Calendar, Gmail, and Sheets through OAuth. Automates follow-ups, meeting summaries, and notifications directly via WhatsApp. 💬 WhatsApp as the Main Interface Interact naturally with your AI team through WhatsApp Business API. All responses, updates, and summaries are delivered to your chat. Ideal for founders who want to manage operations on the go. ⚙️ How It Works Trigger: The workflow starts from a WhatsApp Trigger node (via Meta Developer Account). Routing: The President agent analyzes the incoming message and determines which Director should handle it. Processing: Marketing or sales queries go to the Sales & Marketing Director. Research questions are handled by the Business Research Director. Accountability tasks are assigned to the Accountability Director. Scheduling or communication requests are managed by the Secretary. Collaboration: Each sub-agent returns results to the President, who summarizes and sends the reply back via WhatsApp. Memory: Context is maintained between sessions, ensuring personalized and coherent communication. 🧩 Integrations Required Gemini API – for general intelligence and task reasoning Supabase- for RAG and postgres persistent memory Perplexity API – for business and competitor analysis SerpAPI – for market research and opportunity scouting Google OAuth – to connect Sheets, Calendar, and Gmail WhatsApp Business API – for message triggers and responses 🚀 Benefits Acts like a team of tireless employees available 24/7. Saves time by automating research, reminders, and communication. Enhances accountability and strategy consistency for founders. Keeps operations centralized in a simple WhatsApp interface. 🧰 Setup Steps Create API credentials for: WhatsApp (via Meta Developer Account) Gemini, Perplexity, and SerpAPI Google OAuth (Sheets, Calendar, Gmail) Create a supabase account at supabase Add the credentials in the corresponding n8n nodes. Customize the system prompts for each Director based on your startup’s needs. Activate and start interacting with your virtual executive team on WhatsApp. Use Case You are a small organisation or start-up that can not afford hiring; marketing department, research department and secretar office, then this workflow is for you 💡 Need Customization? Want to tailor it for your startup or integrate with CRM tools like Notion or HubSpot? You can easily extend the workflow or contact the creator for personalized support. Consider adjusting the system prompt to suite your business