Templates / Build a support knowledge base from historical Gmail emails with OpenAI and PostgreSQL

Build a support knowledge base from historical Gmail emails with OpenAI and PostgreSQL

Ready for 3.0

by Vivekanand M βœ“ Β· 113 views Β· created 2026-04-24 Β· Internal Wiki, AI RAG

Ready for 3.0. This template uses no nodes that n8n 3.0 removes. No removed nodes, versions or helpers found. Static check, last run 2026-10-19.

Nodes used (7)

GmailPostgresOpenAI Chat ModelAI Agent

What it does

KB Builder β€” Historical Emails n8n Workflow Template --- πŸ“˜ Description This workflow automates the process of building a structured Knowledge Base (KB) from your existing Gmail inbox by processing historical email threads, extracting customer-support conversation pairs, classifying them with AI, generating vector embeddings, and storing everything in a PostgreSQL database β€” ready to power AI-assisted draft generation in downstream workflows. The workflow is triggered manually and fetches the last N emails from your connected Gmail account. Each email is parsed, filtered, and deduplicated before being processed. A thread-level fetch retrieves the full conversation context, separating customer messages from support replies. An AI classification step categorises each thread into a defined scenario type. Vector embeddings are generated for semantic similarity search. Qualified threads are inserted into three database tables β€” kbdata for clean Q&A pairs, scenariopatterns for reusable handling logic, and corrections for diverse real-world examples β€” with strict deduplication to keep the KB clean and non-redundant. --- βš™οΈ What This Workflow Does (Step-by-Step) πŸ“₯ Manual Trigger β€” Run on demand whenever you want to import a batch of historical emails into the KB. No scheduling required. πŸ“¬ Fetch Emails from Gmail β€” Pulls the last N emails (configurable, default 100) from your Gmail account using OAuth2. Returns full email metadata including thread IDs, sender, subject, labels, and body. πŸ” Parse & Filter β€” Extracts structured fields from each email: sender address, subject, body (cleaned of links and quoted history), date, and thread ID. Filters out emails from your own domain (outbound support replies) and auto-generated emails (no-reply, notifications, newsletters). Only genuine inbound customer emails proceed. 🧡 Fetch Full Thread β€” For each qualified email, fetches the entire Gmail thread using the thread ID. Retrieves all messages in the conversation to identify the original customer message and the latest support reply. πŸ—‚οΈ Assemble Thread Context β€” Reconstructs the conversation by separating customer messages from support replies. Builds a clean conversationText block used as AI input. Flags threads with no support reply for conditional handling. πŸ€– AI Classification β€” Calls GPT-4o-mini (or Claude) with the assembled conversation. Returns a structured JSON output containing: scenario category, a concise Q&A pair, a handling pattern description, key entities, sentiment, resolution status, and a summary. πŸ”’ Generate Embeddings β€” Calls the OpenAI Embeddings API to generate a 1536-dimension vector for both the KB entry and the correction record. Used for semantic similarity search in the downstream draft-generation workflow. πŸ” Duplicate Detection & DB Insert β€” Performs cosine similarity checks against existing records before inserting. KB entries and scenario patterns are blocked if a match exceeds 92% similarity. Corrections are inserted freely (deduped at 92%) since diverse examples improve AI draft quality. New records are written to three tables: kbdata, scenariopatterns, and corrections. --- 🧩 Prerequisites - Gmail account β€” OAuth2 credentials connected in n8n. The account must be the support inbox you want to import from. - OpenAI API key β€” Used for GPT-4o-mini classification (~$0.002–0.005 per thread) and text-embedding-3-small for vector generation (~$0.0001 per record). - PostgreSQL database β€” With the pgvector extension enabled. Must have the three tables set up per the schema below. - n8n instance β€” Self-hosted or cloud. Requires the PostgreSQL and OpenAI nodes. --- πŸ—„οΈ Database Schema Table: kbdata | Field | Type | Notes | |---|---|---| | id | SERIAL PRIMARY KEY | Auto-increment | | threadid | TEXT | Gmail thread ID | | subject | TEXT | Email subject | | category | TEXT | AI-assigned scenario type | | question | TEXT | Customer issue / question | | answer | TEXT | Support resolution | | entities | TEXT | Key entities

View the original on n8n.io β†’ Check your own copy

Get the weekly β€œwhat broke” email

New templates, newly broken ones, and n8n release changes. One short email a week.

Form not loading? Subscribe here.