Real-time Email Search and RAG Assistant with PGVector - n8n Workflow

Deploy a powerful Retrieval-Augmented Generation (RAG) system using this advanced n8n workflow. Automatically ingest Gmail emails into PGVector and use an OpenAI agent for smart, conversational querying.

Workflow Preview

Ready to automate?

Download this n8n workflow template and start using it instantly.

Who is this best for?

Professionals or organizations dealing with high volumes of email who need quick, semantic search capabilities.
Users looking for practical n8n templates integrating LangChain components.
Developers building custom AI assistants who require a robust RAG knowledge base for external data.
Anyone interested in leveraging the power of an n8n workflow to automate knowledge management using vector databases.

Overview

Managing high volumes of email often results in crucial information being buried and difficult to retrieve through standard keyword searches. This innovative n8n workflow solves this by implementing a powerful Retrieval-Augmented Generation (RAG) system.

The n8n workflow operates in two phases: ingestion and retrieval. First, it uses an n8n trigger watching Gmail to automatically extract and vectorize new emails, storing them in a dedicated PGVector table. Second, it utilizes an AI agent powered by an OpenAI Chat Model. When a user sends a query via the chat n8n trigger, the agent uses its tool—the PGVector knowledge base—to find semantically relevant email context. This allows users to ask complex questions like, 'What was the delivery timeline mentioned in the email from Vendor X last Tuesday?' The final response is generated using both the user's query and the context retrieved from the database, demonstrating the powerful capabilities of this n8n template for knowledge retrieval.

How it Works

This n8n workflow is divided into two interdependent automation processes: the Data Ingestion Pipeline and the Conversational Query Agent.

1. Data Ingestion (Real-Time Email Indexing)


  1. Gmail Trigger: The n8n workflow starts with the dedicated Gmail trigger node, which constantly watches for new emails in your designated mailbox.

  2. Get Mail Data: Upon detecting a new email ID, this n8n node fetches the full message body, subject, and header information.

  3. Data Loading and Splitting: The email content is formatted using the Enhanced Default Data Loader n8n node, combining the sender, date, subject, and text body into a single document. This document is then processed by the Recursive Character Text Splitter2 to break down large emails into manageable chunks (2000 characters with 200 overlap), suitable for vectorization.

  4. Embedding and Storage: The Embeddings OpenAI3 n8n node generates vector representations (embeddings) for each text chunk. These embeddings, along with the original text and custom metadata (e.g., datasource: gmail), are immediately inserted into the emailsvectorhistory table using the Postgres PGVector Store3 n8n node. This completes the real-time update of the RAG knowledge base.

2. Conversational Query Agent (Retrieval-Augmented Generation)


  1. When chat message received: The retrieval process starts with this n8n trigger, which activates the Agent upon receiving a new chat query.

  2. New RAG Agent: This acts as the brain of the operation. It uses a defined system message to guide its behavior and delegates tasks.

  3. Language Model: The OpenAI Chat Model n8n node provides the reasoning and conversational capabilities.

  4. Vector Store Tool: The agent is equipped with the Postgres PGVector Store n8n node configured in retrieve-as-tool mode. When the agent determines that the user's query requires knowledge retrieval (e.g., 'What did John send me?'), it calls this tool, which performs a similarity search (topK: 5) against the emailsvector_history database using embeddings provided by the secondary Embeddings OpenAI n8n node.

  5. Final Response: The agent receives the relevant text snippets from the vector store tool, uses the OpenAI model to synthesize a coherent answer based on the retrieved context, and sends the final response back to the chat interface.

Installation Guide

To deploy this comprehensive n8n workflow template, follow these steps:


  1. Import the n8n Workflow: Copy the provided JSON data and navigate to your n8n instance. Click 'New' -> 'Import from JSON' and paste the code.

  2. Configure Credentials:

OpenAI API Key: You must provide valid credentials for the OpenAI Chat Model and both Embeddings OpenAI n8n nodes. Update the existing 'OpenAi account' credentials or create a new one.
Gmail Account: Set up the credentials for the Gmail Trigger and Get Mail Data n8n nodes to allow access to your mailbox.
Postgres/PGVector: Ensure you have a Postgres database instance running with the pgvector extension enabled. Configure the credentials for both Postgres PGVector Store n8n nodes, ensuring they point to the same database and schema. The table name emailsvectorhistory must exist or be created.

  1. Activate the Triggers:

Activate the Gmail Trigger to start indexing new emails.
* Activate the When chat message received n8n trigger to generate the public webhook URL needed for the conversational interface.

  1. Customize: Review the system message in the New RAG Agent n8n node and the jsonData expression in the Enhanced Default Data Loader to ensure the structure meets your specific needs. This complete n8n template is now ready for use.

Node Details

This advanced n8n workflow utilizes specialized nodes to create a robust RAG system:

Gmail Trigger
Function: Acts as the initial n8n trigger, monitoring the configured Gmail account for new messages every minute.
Key Configuration: Polling interval set to 'everyMinute'.

Get Mail Data
Function: Retrieves the full body content and necessary metadata of the email identified by the trigger.
Key Configuration: Retrieves the messageId dynamically using the expression: = {{ $json.id }}.

Enhanced Default Data Loader
Function: Structures the raw email data into a consistent document format, making it searchable. It pulls critical fields like subject, sender, date, and text body using an expression.
Key Configuration: Uses jsonMode: expressionData to construct a detailed input string. Adds custom metadata: datasource: gmail and createdat.

Postgres PGVector Store3 (Insert Mode)
Function: The destination for newly embedded email chunks, facilitating the creation of the knowledge base.
Key Configuration: mode: insert, tableName: emailsvectorhistory.

Embeddings OpenAI3
Function: Responsible for converting the text chunks from the splitter into numerical vector embeddings for storage in PGVector.
Key Configuration: Requires OpenAI API credentials.

When chat message received
Function: Serves as the conversational n8n trigger, initializing the AI agent path when an external chat client sends a message.

New RAG Agent
Function: The core orchestrator. It decides whether to use the vector search tool or rely solely on the language model's internal knowledge based on the user's input.
Key Configuration: Defined systemMessage provides guidance and context for the AI assistant.

Postgres PGVector Store (Retrieve-as-Tool Mode)
Function: Configured as a callable tool for the agent. It performs semantic similarity search (RAG) against the email data.
* Key Configuration: mode: retrieve-as-tool, toolName: emailsvectorsearch, topK: 5 (retrieves the 5 most relevant chunks). This node is crucial for the RAG functionality of the n8n workflow.

Related n8n Workflows

Free

Nodes: 10 Nodes
Updated: December 26 2025
View all
Created by

Software Engineer with over 3+ years of experience in full-stack development.

Featured*