How to Build AI-Powered Automations with n8n (Summarize, Classify, and Route with LLMs)
Add AI to your n8n workflows — summarize documents, classify text, score leads, and route decisions using OpenAI. Step-by-step with real node logic and templates.
Your Automations Can Think Now
Most automation tools move data. n8n can also reason about it.
When you add an LLM node to a workflow, the pipeline gains a new capability: it can read unstructured text — emails, support tickets, form responses, call transcripts — and turn them into structured decisions. No regex. No keyword lists. No fragile rule trees.
The pattern is simple: trigger → read data → call AI → act on the result. This post shows you exactly how to build it.
What You Can Automate with AI Nodes
Every workflow that involves reading, interpreting, or categorizing text is a candidate:
- Support ticket classification — detect topic, urgency, and sentiment before the ticket reaches a human
- Lead scoring — let an LLM analyze the prospect's message and assign a fit score based on your ICP
- Document summarization — condense long emails, PDFs, or meeting notes into a 3-bullet summary
- Smart email routing — read the intent of inbound emails and forward them to the right department
- Content moderation — screen user-generated content for policy violations before it's published
- Data extraction — pull structured fields (name, date, amount) out of unstructured invoice text
- Sentiment monitoring — classify reviews, survey responses, or Slack messages as positive/negative/neutral
Keyword-based routing breaks the moment a user phrases something unexpectedly. An LLM understands intent — "I was charged twice" and "there's a duplicate transaction on my card" both route to billing without you writing a rule for every phrasing.
The AI Automation Pipeline
Every AI-powered n8n workflow follows this shape:
Trigger (Webhook / Gmail / Schedule)
→ Fetch Data (HTTP Request / Google Sheets / Gmail)
→ Prepare Prompt (Code node — build the message array)
→ OpenAI node (call the model, capture structured output)
→ Parse Output (Code node — extract label, score, or summary)
→ Switch / IF (branch on AI result)
→ Path A: Slack alert + Sheets log
→ Path B: Gmail reply + CRM update
→ Path C: Discard / archive
The AI node sits in the middle — it does not trigger anything on its own. The workflow feeds it data, it returns a judgment, and the rest of the workflow acts on it.
Try the AI Lead Scoring and Email Routing template →1. Collect — Bring in Unstructured Data
Use whichever trigger makes sense for your source: Webhook for real-time form submissions, Gmail Trigger for inbound email, Schedule Trigger + HTTP Request for batched API data.
The goal at this stage is a single item with the raw text you want the AI to process:
// Code node: normalize whatever the trigger gives you
const raw = items[0].json;
return [{
json: {
source_id: raw.id || raw.ticket_id || String(Date.now()),
text: raw.body || raw.message || raw.description || '',
sender: raw.from || raw.email || 'unknown',
received_at: new Date().toISOString(),
}
}];
Keep the text field clean — strip HTML, remove quoted email threads, trim whitespace. Garbage in, garbage out applies doubly with LLMs.
2. Process — Build the Prompt
A Code node constructs the message array that the OpenAI node expects. Being explicit in the system prompt about output format saves you a parsing step later:
const item = items[0].json;
const systemPrompt = `You are a support ticket classifier.
Respond with a JSON object only — no prose. Format:
{"category": "billing|bug|feature_request|general", "urgency": "low|medium|high", "summary": "<one sentence>"}`;
const userMessage = `Classify this support ticket:\n\n${item.text}`;
return [{
json: {
...item,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userMessage }
]
}
}];
Asking for JSON output with a fixed schema means you can reliably parse the response — no need for fuzzy string matching.
3. Route — Send to the Model and Parse the Result
The OpenAI node (type: @n8n/n8n-nodes-langchain.openAi) takes your messages array and returns the model's response. Use gpt-4o-mini for classification tasks — it's fast and cheap.
After the OpenAI node, a Code node extracts the structured fields:
const raw = items[0].json;
// The model output lives at: output[0].content[0].text
const responseText = raw.output[0].content[0].text;
let parsed;
try {
parsed = JSON.parse(responseText);
} catch {
parsed = { category: 'general', urgency: 'low', summary: responseText };
}
return [{
json: {
...raw,
ai_category: parsed.category,
ai_urgency: parsed.urgency,
ai_summary: parsed.summary,
}
}];
4. Act — Branch on the AI Result
A Switch node reads ai_category and sends the item down the correct path. Each path can trigger entirely different actions:
Switch on ai_category:
billing → Slack #billing-team + Gmail (acknowledge with billing FAQ)
bug → Jira (create issue) + Slack #engineering
feature_req → Notion (add to roadmap) + Gmail (thank you reply)
general → Google Sheets (log) + Gmail (generic acknowledgment)
A second IF node on ai_urgency === 'high' fires a pager alert before any of the above — regardless of category.
5. Follow Up — Log and Confirm
Every branch writes to the same Google Sheets log:
| Column | Value |
|---|---|
| ticket_id | source_id |
| category | ai_category |
| urgency | ai_urgency |
| summary | ai_summary |
| routed_to | channel or team name |
| timestamp | received_at |
This gives you a full audit trail and lets a second workflow query open high-urgency items on a schedule to check for SLA breaches.
Version your system prompts. When you change the prompt, the model behavior changes — and old logs may have been classified differently. Store the prompt version alongside each classification row so you can compare before and after.
Implementation Patterns
Pattern 1 — Zero-Shot Classification
Use this when you want a quick label and have enough examples in the prompt for the model to understand the taxonomy:
const systemPrompt = `Classify the email below into exactly one category.
Categories: sales_inquiry, support_request, partnership, spam, other.
Respond with the category name only — no other text.`;
Best for: simple routing with 3–6 categories, high throughput, cost-sensitive workloads.
Pattern 2 — Structured Extraction
Use this when you need to pull specific fields out of free-form text (invoices, contracts, emails):
const systemPrompt = `Extract the following fields from the invoice text.
Return a JSON object with these keys exactly:
{"vendor_name": "", "invoice_number": "", "total_amount": 0, "due_date": "YYYY-MM-DD"}
If a field is not present, use null.`;
Best for: document processing, data entry automation, contract analysis.
Pattern 3 — Scored Evaluation
Use this when you need a numeric signal to filter or rank items — like lead scoring or content quality:
const systemPrompt = `You are a B2B lead evaluator.
Score the lead's message from 0–100 based on:
- Fit with a B2B SaaS product (0–40 pts)
- Purchase intent signal (0–40 pts)
- Completeness of information (0–20 pts)
Respond with JSON only: {"score": 0, "reason": "<one sentence>"}`;
Best for: lead prioritization, content moderation thresholds, risk assessment.
Automate follow-up sequences with the Email Followup Automator template →n8n Nodes You'll Use Most
| Node | Purpose |
|---|---|
| Webhook | Real-time trigger from forms, apps, or external services |
| Gmail Trigger | Watch an inbox for inbound emails to process |
| Schedule Trigger | Run batch AI jobs on a timed interval |
| Code | Build prompts, parse JSON responses, transform data |
OpenAI (@n8n/n8n-nodes-langchain.openAi) | Call GPT-4o or GPT-4o mini for text tasks |
| HTTP Request | Call Anthropic, Mistral, or any other LLM REST API |
| Switch | Branch the workflow based on AI classification output |
| IF | Filter items that cross a score threshold |
| Google Sheets | Log AI results; read reference data for prompts |
| Slack | Send alerts and summaries to team channels |
| Gmail | Send AI-generated or AI-triggered email replies |
Getting Started
- Pick one high-volume manual task that involves reading text and making a decision — support triage, lead scoring, or email routing are good starting points.
- Create a Webhook trigger (or Gmail Trigger) to capture the raw data in real time.
- Add a Code node to clean the text and build the message array with a clear system prompt.
- Wire in the OpenAI node — use
gpt-4o-miniand request JSON output in your system prompt. - Add a Code node after OpenAI to parse the response and attach the AI fields to the item.
- Add a Switch node to route based on the classification, then wire each branch to its destination (Slack, Gmail, Sheets, CRM).
- Test with a sample payload, inspect the OpenAI output in the execution log, and adjust the prompt until the classification is accurate.
Build your first AI workflow for a single inbox or a single ticket source. Once it runs cleanly for a week, duplicate the workflow and point it at the next source. You'll catch prompt edge cases faster with lower volume.
If you're combining AI classification with outreach sequences, the approach in How to Automate Lead Generation and Outreach with n8n covers how to feed scored leads into multi-step email sequences.
For workflows that need to report on AI-classified data over time, the patterns in How to Automate Your Marketing with n8n Workflows show how to aggregate and summarize results in Google Sheets on a schedule.
The Decision Support System template pairs well with this pattern — it routes AI-analyzed inputs to the right team and logs every decision for review.
For lead-specific AI scoring, the AI Lead Scoring and Email Routing template implements the Pattern 3 scored evaluation approach above, ready to connect to your existing CRM or inbox.
Browse all n8n automation templates →Common questions
Which AI models can n8n connect to out of the box?
Can n8n use AI output to make routing decisions in the same workflow?
How do I keep AI API costs low inside n8n workflows?
Get the workflow templates this guide is built on
Import-ready n8n JSON, step-by-step setup, and tested end-to-end. One-time payment, own it forever.
More automation guides

How to Automate Airtable with n8n (Sync, Update, and Trigger Workflows from Your Database)
Airtable Is Your Database. n8n Makes It Behave Like a Full Automation Platform. Airtable is where teams store structured data — project trackers, CRM records, content calendars, inventory, hiring pipe…

How to Automate Your Email Inbox with n8n (Triage, Route, and Auto-Reply)
Your Inbox Is a Queue. n8n Can Run It for You. Most knowledge workers spend 2–4 hours a day on email. Sorting, reading, deciding who to forward to, writing the same replies again and again. That is op…

How to Automate Notion Workflows with n8n (Databases, Pages, and Syncs)
Notion Is Your Team's Source of Truth. n8n Keeps It Accurate Without the Manual Work. Notion is where teams track projects, log decisions, manage content pipelines, and maintain wikis. The problem is…