AI Automation·12 min read

AI Automation with n8n Workflows

Lyubo
Lyubo·
AI Automation with n8n Workflows

Learn how to automate smart workflows using AI tools with n8n. This guide covers OpenAI integration, sentiment analysis, and more.

AI Automation with n8n Workflows 🚀

TL;DR – In this tutorial you'll learn how to add smart, AI‑powered steps to your n8n workflows. We'll build three practical automations (email summarisation, tweet generation, sentiment‑based routing), sprinkle in best‑practice tips, and finish with a troubleshooting checklist. By the end you'll know how to make your automations think as well as do.


Table of Contents

  1. Why n8n + AI?
  2. Prerequisites
  3. Installing & Configuring n8n
  4. Storing API Credentials
  5. Workflow 1 – Summarise Emails
  6. Workflow 2 – Generate Tweets
  7. Workflow 3 – Sentiment Routing
  8. Best Practices & Tips
  9. Troubleshooting Guide
  10. Key Takeaways

Why n8n + AI?

n8n already excels at connecting services: email ➜ CRM ➜ database ➜ messaging apps.
Adding AI turns those pipes into a brain. 🧠

Examples

  • Auto‑summarise a 2 000‑word email into three bullet points.
  • Generate fresh social‑media content every morning.
  • Detect negative customer feedback and create a priority ticket.

With built‑in OpenAI nodes and the generic HTTP Request node for anything else (Hugging Face, Cohere, local LLMs), you can drop intelligence anywhere in a flow—no custom servers, no glue code.


Prerequisites

RequirementNotes
n8nSelf‑host, Docker, or n8n Cloud
OpenAI API keyFree tier is enough for testing
(Optional) Hugging Face tokenNeeded for hosted inference API
Basic JavaScriptFor tiny snippets in Function nodes

Installing & Configuring n8n

1 – Quick Docker spin‑up

1docker run -it --rm \
2 -p 5678:5678 \
3 -e N8N_BASIC_AUTH_ACTIVE=true \
4 -e N8N_BASIC_AUTH_USER=admin \
5 -e N8N_BASIC_AUTH_PASSWORD=changeme \
6 n8nio/n8n

Open http://localhost:5678 – you'll land in the visual editor.

2 – Alternative installs

  • npm global: npm i -g n8n
  • n8n Cloud: zero‑config, starts free.

Storing API Credentials

  1. In the top nav click Credentials → New.
  2. Choose OpenAI ➜ paste your sk-… key ➜ give it a friendly name ("OpenAI Prod").
  3. For Hugging Face, pick Generic Credential ➜ select "HTTP Header Auth" ➜ key =Authorization, value =Bearer <token>.

n8n encrypts creds at rest, so keys aren't exposed in workflow JSON. 🔐


Workflow 1 – Summarise Emails

Goal

Every time a new Gmail message arrives, post a three‑sentence summary to Slack.

Step‑by‑step

  1. Gmail Trigger – event: "New Email" (optionally filter by label).

  2. OpenAI (Chat Completion)

    • Model: gpt-3.5-turbo

    • System message: You are a helpful assistant that writes concise summaries.

    • User message (expression):

      1Summarise the following email in 3 sentences:
      2
      3{{$json["snippet"]}}
  3. Slack – channel message:

    *New email summary* ✉️
    {{$node["OpenAI"].json["choices"][0]["message"]["content"]}}
    

Visual snapshot

<!-- Replace with actual screenshot -->

Pro tip – set Max Tokens to ~120 and Temperature to 0.3 for crisp summaries.


Workflow 2 – Generate Tweets

Goal

Create five daily tech tweets and store them in Airtable for review.

Steps

  1. Cron – schedule: every day at 09:00.

  2. Function Item – pick a random hashtag:

    1const tags = ["#AI", "#n8n", "#WebDev", "#OpenSource"];
    2return [{ topic: tags[Math.floor(Math.random()*tags.length)] }];
  3. OpenAI (Completion)

    1Write an engaging tweet about {{$json["topic"]}}.
    2Keep it under 240 characters and include the hashtag {{$json["topic"]}}.
  4. Set – map fields:

    FieldValue
    text{{$json["choices"][0]["text"]}}
    topic{{$json["topic"]}}
    createdAt={{$now}}
  5. Airtable – base Social Queue, table TweetsCreate Record.

Result

Your Airtable becomes a queue of AI‑generated tweets waiting for approval – no more writer's block! 🎉


Workflow 3 – Sentiment Routing

Goal

Classify incoming user feedback (Positive / Negative / Question) and route to the right Slack channel.

Two AI options

OptionNodeProsCons
OpenAIOpenAI ChatSimple, one callHigher latency + cost
Hugging FaceHTTP RequestCheap / self‑hostableYou parse JSON manually

Implementation (OpenAI route)

  1. Webhook – POST feedback JSON:

    1{ "message": "Your app keeps crashing when I click export." }
  2. OpenAI Chat

    1Categorise the following feedback as POSITIVE, NEGATIVE, or QUESTION.
    2Respond with just the category.
    3
    4{{$json["message"]}}
  3. Switch

    • If NEGATIVE ➜ Slack #support-urgent
    • If QUESTION ➜ Slack #support-faq
    • Else ➜ Slack #praise
  4. Slack – send original message + category.

Implementation (Hugging Face route)

1POST https://api-inference.huggingface.co/models/facebook/bart-large-mnli
2Authorization: Bearer <HF_TOKEN>
3Content-Type: application/json
4
5{
6 "inputs": "Your app keeps crashing when I click export.",
7 "parameters": {
8 "candidate_labels": ["Positive", "Negative", "Question"]
9 }
10}

Parse the highest‑score label in a Function node, then use the same Switch logic.


Best Practices & Tips

  • Prompt like a pro: be explicit about format, tone, and length.
  • Watch token usage: large inputs → big bills. Summarise first if needed.
  • Handle rate limits: enable Retry on Fail with exponential back‑off.
  • Add human review: auto‑posting publicly? Queue drafts for safety.
  • Secure keys: store in n8n Credentials, not in Function code.
  • Document flows: use Sticky Notes and clear node names for future you.

Troubleshooting Guide

SymptomLikely CauseFix
429 Too Many RequestsHit OpenAI rate‑limitAdd Wait node, lower concurrency
Empty AI responsePrompt unclear / exceeds max tokensSimplify prompt, raise Max Tokens
401 UnauthorizedWrong or revoked keyRe‑paste key in Credentials
Workflow halts mid‑runNode received zero itemsCheck previous node output; guard with IF
Unexpected AI answerModel misunderstood contextRefine prompt, add examples

Key Takeaways

  • n8n + AI = super‑charged automations that read, write, and decide.
  • Built‑in OpenAI nodes make text tasks trivial; HTTP Request opens every other AI door.
  • Start small (one AI step), iterate quickly, and layer on error handling before going production.
  • Keep prompts precise, manage tokens, and secure your API keys.
  • The best workflow is the one you ship—go build something awesome today! 💪

Questions or feedback? Drop a comment on the blog – I'd love to hear what you automate! 😊

Share:
AIn8nAutomationWorkflowsOpenAI