Skip to main content
Lifetime license included with every purchase
n8n workflowsAI automationOpenAI integrationworkflow AI

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.

Nn8n Marketplace Team·May 4, 2026·9 min read

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
AI nodes vs. keyword rules

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:

ColumnValue
ticket_idsource_id
categoryai_category
urgencyai_urgency
summaryai_summary
routed_tochannel or team name
timestampreceived_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.

Prompt stability tip

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

NodePurpose
WebhookReal-time trigger from forms, apps, or external services
Gmail TriggerWatch an inbox for inbound emails to process
Schedule TriggerRun batch AI jobs on a timed interval
CodeBuild prompts, parse JSON responses, transform data
OpenAI (@n8n/n8n-nodes-langchain.openAi)Call GPT-4o or GPT-4o mini for text tasks
HTTP RequestCall Anthropic, Mistral, or any other LLM REST API
SwitchBranch the workflow based on AI classification output
IFFilter items that cross a score threshold
Google SheetsLog AI results; read reference data for prompts
SlackSend alerts and summaries to team channels
GmailSend AI-generated or AI-triggered email replies

Getting Started

  1. 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.
  2. Create a Webhook trigger (or Gmail Trigger) to capture the raw data in real time.
  3. Add a Code node to clean the text and build the message array with a clear system prompt.
  4. Wire in the OpenAI node — use gpt-4o-mini and request JSON output in your system prompt.
  5. Add a Code node after OpenAI to parse the response and attach the AI fields to the item.
  6. Add a Switch node to route based on the classification, then wire each branch to its destination (Slack, Gmail, Sheets, CRM).
  7. Test with a sample payload, inspect the OpenAI output in the execution log, and adjust the prompt until the classification is accurate.
Start narrow, expand later

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
FAQ

Common questions

Which AI models can n8n connect to out of the box?
n8n has native nodes for OpenAI (GPT-4o, GPT-4 Turbo, Whisper, DALL-E), Anthropic Claude, Google Gemini, and Hugging Face. For any other model, the HTTP Request node can call any REST-based API — Mistral, Cohere, Together AI, and others all work the same way.
Can n8n use AI output to make routing decisions in the same workflow?
Yes. An OpenAI node returns structured JSON or plain text. A Code node parses that output, and a Switch or IF node branches the workflow based on the classification — for example, routing a support ticket to the billing team if the AI labels it 'payment issue', or to engineering if it labels it 'bug'.
How do I keep AI API costs low inside n8n workflows?
Use smaller, faster models (GPT-4o mini, Claude Haiku) for classification and summarization tasks where precision matters less. Reserve larger models for tasks that need nuanced reasoning. Cache frequently repeated prompts in Google Sheets or a database node so the same content is not re-sent to the API on each run.
Stop reading. Start running.

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.