Part 5: Connecting OpenAI GPT-4o to n8n — Build Your First Intelligent AI Automation

🗺️ The Ultimate AI Automation Roadmap — Part 5 of 20 | Tier: Foundations | Difficulty: Intermediate | Est. read: 18 min

Part 5: Connecting OpenAI GPT-4o to n8n — Build Your First Intelligent AI Automation Workflow (2026)

Search Intent: Traditional automation follows rigid rules — it can’t understand unstructured text, interpret intent, or handle unexpected inputs. Adding OpenAI GPT-4o to your n8n workflows transforms them from rule-based robots into genuinely intelligent systems. This guide builds an AI email classification and routing system for wholesale inventory management — a workflow that reads, understands, and acts on any email in real time.

OpenAI GPT-4o connected to n8n automation workflow for intelligent email classification
[Image: n8n workflow canvas — Gmail Trigger → OpenAI Node (system prompt visible in sidebar) → Code Node (JSON parse) → Switch Node with 5 output branches leading to Slack, ERP, Zendesk, Sheets]

📋 Table of Components

ComponentToolMonthly Cost (200 emails/day)Purpose
AI ClassificationGPT-4o-mini~$2.70Email category + urgency + extraction
AI Reply DraftingGPT-4o-mini~$4.50Generate reply email drafts
Workflow Enginen8n (self-hosted)$0Orchestrate all nodes
Email SourceGmail / Google Workspace$0–$6Trigger on new emails
DestinationsSlack, Zendesk, ERP API, Sheets$0–variableRoute to correct team/system

🌍 Real-World Scenario: Wholesale Distributor Inbox Intelligence

A wholesale distributor’s operations Gmail receives 200+ emails daily: stock availability updates from suppliers, reorder requests from clients, complaints, shipping inquiries, and payment notifications. A warehouse manager manually reads and routes each — wasting 4 hours daily. After this automation: AI classifies every email in under 3 seconds, routes to the correct team or system, and drafts a reply. The manager only reviews drafts and handles escalations.

⚙️ Step 1: Set Up OpenAI Credential in n8n

In n8n go to Settings → Credentials → New → OpenAI API. Enter your API key from platform.openai.com/api-keys. Best practice: create separate API keys for development and production so you can track costs and revoke independently. Set a spending limit in the OpenAI dashboard to prevent surprise bills during testing.

⚙️ Step 2: OpenAI Node Configuration

Add an OpenAI → Message a Model node. Critical settings: Model: gpt-4o-mini for classification (fast, cheap, accurate for structured tasks), Temperature: 0 (deterministic — same input always gives same output), Response Format: JSON Object (forces valid JSON — never fails to parse), Max Tokens: 400 (sufficient for classification JSON, no wasted tokens). Pass the email content as the user message: Subject + Body combined.

⚙️ Step 3: System Prompt Engineering

SYSTEM PROMPT (OpenAI Node → System Message field):

You are an intelligent inbox router for a wholesale distribution company.
Analyze each email and return ONLY this exact JSON structure (no extra text):

{
  "category": "STOCK_UPDATE|REORDER_REQUEST|COMPLAINT|PAYMENT_NOTIFICATION|INQUIRY|OTHER",
  "urgency": "HIGH|MEDIUM|LOW",
  "supplier_or_client": "supplier|client|unknown",
  "company_name": "extracted company name or null",
  "product_sku": "extracted SKU code or null",
  "quantity": "extracted number or null",
  "monetary_value": "extracted dollar amount or null",
  "action_required": "1-sentence description of next action",
  "reply_tone": "FORMAL|FRIENDLY|APOLOGETIC|URGENT",
  "confidence": 0-100
}

Classification rules:
- STOCK_UPDATE: Supplier announcing product availability or price changes
- REORDER_REQUEST: Client asking to reorder or place new order  
- COMPLAINT: Any dissatisfaction, delay complaint, or quality issue
- PAYMENT_NOTIFICATION: Invoice sent or payment confirmation
- HIGH urgency: Complaint, out-of-stock alert, payment overdue
- Extract numbers exactly as stated, never calculate
n8n OpenAI node system prompt configuration for email classification workflow
[Image: n8n OpenAI node settings panel — Model: gpt-4o-mini, Temperature: 0, Response Format: JSON Object, System message textarea showing classification prompt, User message field mapped to email subject + body]

⚙️ Step 4: Parse and Validate AI Response

// Code Node: Parse, validate, add context
const ai = $input.first().json.message.content;
let parsed;

try {
  parsed = typeof ai === 'string' ? JSON.parse(ai) : ai;
} catch(e) {
  // Fallback for rare malformed responses
  parsed = { category: 'OTHER', urgency: 'MEDIUM', confidence: 0, action_required: 'Manual review needed - AI parse error' };
}

const email = $('Gmail Trigger').first().json;
return [{ json: {
  ...parsed,
  email_id: email.id,
  from: email.from,
  subject: email.subject,
  received_at: new Date().toISOString(),
  routing_key: parsed.category + '_' + parsed.urgency,
  needs_review: parsed.confidence < 70
}}];

⚙️ Step 5: 6-Way Switch Routing

Add a Switch Node routing on routing_key: Route 1 — STOCK_UPDATE_*: Update Google Sheets inventory tracker + notify #warehouse on Slack. Route 2 — REORDER_REQUEST_HIGH: Immediate Slack DM to sales manager + create draft order in ERP. Route 3 — REORDER_REQUEST_MEDIUM: Add to weekly order batch spreadsheet. Route 4 — COMPLAINT_*: Create Zendesk ticket with HIGH priority + alert account manager. Route 5 — PAYMENT_NOTIFICATION: Update accounts receivable Google Sheet. Route 6 — Default: Log to "Manual Review" sheet.

⚙️ Step 6: AI Reply Draft Generation

On every route (except DEFAULT), add a second OpenAI call: Model: gpt-4o-mini, Temperature: 0.3, Prompt: "Write a {{reply_tone}} email reply to {{from}} regarding their {{category}} email: '{{subject}}'. Action we're taking: {{action_required}}. Under 100 words. Sign: 'Warehouse Operations Team'." Then Gmail → Create Draft, so a human reviews and sends with one click — 80% less writing time.

🔁 Automation Logic: Full Email Intelligence Pipeline

StageWhat HappensNode
🟢 TriggerNew email in Gmail label "Operations"Gmail Trigger (5 min poll)
⚡ Action 1GPT-4o-mini classifies + extracts JSONOpenAI Node (JSON mode, temp=0)
⚡ Action 2Parse, validate, add email metadataCode Node
🔍 FilterRoute by category_urgency keySwitch Node (6 routes)
⚡ Action 3Category-specific system updateSlack / Zendesk / Sheets / ERP
⚡ Action 4GPT-4o-mini generates reply draftOpenAI Node (temp=0.3)
📤 OutputSave Gmail draft + label email ProcessedGmail (Draft + Label)

💡 Pro Tip: Reduce Costs with a Pre-Filter

Add an IF node before the OpenAI call to skip automated/marketing emails: check if sender domain is in your known-vendor list, if subject starts with "Re:", or if it's a newsletter. Only send genuinely new operational emails to the AI. This can reduce AI API costs by 40–60% for busy inboxes.

🚀 Next: Part 6 — Mid-Level Workflows Begin

The Foundations tier is complete. Part 6 launches the Mid-Level Workflows tier with an enterprise lead magnet system: AI-personalized landing pages, automated email capture sequences, and real-time lead scoring that feeds directly into your CRM — the most valuable automation any business can build.

Scroll to Top