πŸ“– Build a support knowledge base from historical Gmail emails with OpenAI and PostgreSQL

⚑ 114 views Β· πŸ“– Internal Wiki & Knowledge Base

Description

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 β€” kb_data for clean Q&A pairs, scenario_patterns 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: kb_data, scenario_patterns, and corrections.


🧩 Prerequisites


πŸ—„οΈ Database Schema

Table: kb_data

FieldTypeNotes
idSERIAL PRIMARY KEYAuto-increment
thread_idTEXTGmail thread ID
subjectTEXTEmail subject
categoryTEXTAI-assigned scenario type
questionTEXTCustomer issue / question
answerTEXTSupport resolution
entitiesTEXTKey entities extracted by AI
sentimentTEXTCustomer sentiment
resolution_statusTEXTResolved / Unresolved
embeddingvector(1536)OpenAI embedding for similarity search
sourceTEXThistorical_import
created_atTIMESTAMPInsert timestamp

Table: scenario_patterns

FieldTypeNotes
idSERIAL PRIMARY KEYAuto-increment
categoryTEXTScenario type
pattern_descriptionTEXTHandling logic summary
example_subjectTEXTRepresentative subject line
embeddingvector(1536)OpenAI embedding
sourceTEXThistorical_import
created_atTIMESTAMPInsert timestamp

Table: corrections

FieldTypeNotes
idSERIAL PRIMARY KEYAuto-increment
gmail_thread_idTEXTGmail thread ID
original_email_bodyTEXTCustomer’s original message
human_sent_textTEXTActual support reply sent
ai_draft_textTEXTNULL for historical imports
diff_summaryTEXTImport note or live diff
classificationTEXTScenario category
embeddingvector(1536)OpenAI embedding
sourceTEXThistorical_import
created_atTIMESTAMPInsert timestamp

πŸ’° Cost Estimate

ItemEstimated Cost
Gmail OAuth2Free
GPT-4o-mini (100 threads classification)~$0.20–0.50
text-embedding-3-small (100 records Γ— 2 embeddings)~$0.02
PostgreSQL + pgvector (self-hosted)~$5–15/mo
n8n self-hosted (AWS t3.small)~$10–15/mo
Total per 100-email import run~$0.25–0.75

βš™οΈ Setup Instructions

  1. Gmail β€” Connect your Gmail account in n8n using OAuth2. Ensure the account is the support inbox. Grant read permissions for messages and threads.

  2. PostgreSQL β€” Create a new database, enable the pgvector extension (CREATE EXTENSION IF NOT EXISTS vector), then create the three tables using the schema above.

  3. OpenAI β€” Add your OpenAI API key as an n8n credential. Used for both the chat completion node (classification) and the HTTP Request node (embeddings).

  4. Customise the AI prompt β€” Open the AI Classification node and update the system prompt to reflect your business type, support tone, and the scenario categories relevant to your domain (e.g. Refund Request, Order Status, Technical Issue, Billing Query).

  5. Set your domain filter β€” In the Parse & Filter node, update the YOUR_DOMAIN variable to your support team’s email domain so outbound replies are correctly excluded from customer email processing.

  6. Set fetch limit β€” In the Fetch Emails node, set the limit parameter to the number of historical emails you want to import per run. Start with 5–10 to validate the pipeline before running at scale.

  7. Run manually β€” Click Execute Workflow. Monitor the output of each node to verify parsing, classification, and DB inserts are working correctly.


πŸ’‘ Key Benefits

βœ” Converts your inbox into a structured KB β€” no manual tagging or categorisation required
βœ” AI classification assigns scenario types and extracts Q&A pairs automatically
βœ” Vector embeddings enable semantic similarity search in downstream draft workflows
βœ” Smart deduplication keeps KB and scenario tables clean β€” no near-duplicate entries
βœ” Corrections table accumulates diverse examples β€” improves AI draft quality over time
βœ” Thread-aware β€” reconstructs full conversations, not just individual emails
βœ” Modular AI node β€” swap GPT-4o-mini for Claude or any other model with minimal changes
βœ” One-time historical import feeds directly into live draft-generation workflows


πŸ‘₯ Perfect For


This workflow is Step 1 in a two-workflow system:

πŸ”— Nodes Used

Postgres, Gmail, AI Agent, OpenAI Chat Model

πŸ“₯ Import

Download workflow.json and import into n8n: Workflow menu β†’ Import from File

πŸ“– Importing guide Β· πŸ”‘ Credential setup