n8n AI Agent Tutorial: Build 5 Real Workflows (Step-by-Step 2026)

TutorialsBy Ivern AI Team14 min read

n8n AI Agent Tutorial: Build 5 Real Workflows Step-by-Step (2026)

TL;DR: This tutorial walks through building 5 production-ready n8n AI agent workflows: an email classifier, data extractor, content summarizer, customer support router, and automated report generator. Each workflow includes the exact n8n node configuration, prompt templates, and real cost data ($0.02-0.15 per task). We also cover where n8n AI agents hit limits and when multi-agent squads produce better results.

n8n's AI Agent node lets you add AI reasoning to any automated workflow. You connect a language model (GPT-4o, Claude, Gemini), give it tools, and it processes data within your automation flow. This tutorial goes beyond basic setup -- we build 5 real workflows you can deploy today.

Related guides: Ivern vs n8n AI Agent Comparison · Best n8n Alternatives for AI Workflows · AI Workflow Automation Tools 2026 · Build an AI Agent Pipeline · AI Agent Orchestration Guide · Enterprise AI Agent Platform Comparison · AI Agents vs Chatbots · No-Code AI Agent Guide

Prerequisites and Setup

Before building workflows, you need n8n running and connected to an AI model provider.

Option 1: Self-Hosted n8n (Free)

docker run -it --rm \
  --name n8n \
  -p 5678:5678 \
  -v n8n_data:/home/node/.n8n \
  docker.n8n.io/n8nio/n8n

Open http://localhost:5678 and create your admin account.

Option 2: n8n Cloud ($20/month Starter)

Sign up at n8n.cloud. The Starter plan includes 2,500 executions/month, which covers roughly 500-1,000 AI agent tasks depending on workflow complexity.

Connect Your AI Model

In n8n, go to Credentials and add your model provider:

Scroll to see full table

ProviderCredential TypeCost (per 1M tokens)Best For
OpenAI GPT-4oAPI Key$2.50 input / $10 outputGeneral reasoning, classification
Anthropic Claude SonnetAPI Key$3.00 input / $15 outputAnalysis, long documents
Google Gemini 1.5 FlashAPI Key$0.075 input / $0.30 outputHigh-volume, low-cost tasks
Ollama (local)NoneFree (uses your GPU)Private/air-gapped environments

For this tutorial, we use GPT-4o as the default model. Cost estimates assume GPT-4o pricing.

Workflow 1: AI Email Classifier

Goal: Automatically classify incoming emails by intent (support request, sales inquiry, spam, feedback) and route them to the right team.

Cost: ~$0.02 per email classified.

Step-by-Step Setup

  1. Add a Trigger node: Use IMAP Trigger or Gmail Trigger to watch for new emails.
  2. Add an AI Agent node: Connect it to your GPT-4o credential.
  3. Configure the system prompt:
You are an email classifier. Classify each email into exactly one category:
- SUPPORT: Technical issues, bug reports, account problems
- SALES: Pricing questions, demo requests, partnership inquiries
- SPAM: Promotional, irrelevant, or suspicious content
- FEEDBACK: Product feedback, feature requests, reviews
- OTHER: Anything that doesn't fit the above

Respond with ONLY the category name in uppercase. No explanation needed.
  1. Add output routing: Use a Switch node after the AI Agent to route based on the classification:

    • SUPPORT → Send to Zendesk / Slack #support channel
    • SALES → Send to Hubspot / Slack #sales channel
    • SPAM → Archive or delete
    • FEEDBACK → Send to Notion database / Slack #product channel
    • OTHER → Send to general inbox
  2. Add error handling: Use an If node to check if the AI response matches a valid category. If not, route to manual review.

Cost Breakdown

Scroll to see full table

ComponentTokensCost
System prompt~80 tokens$0.0002
Average email body~300 tokens$0.0008
Classification output~3 tokens$0.00003
Total per email~383 tokens~$0.001

At scale (1,000 emails/day): ~$1/day or ~$30/month in API costs.

Limitations

This workflow classifies one email at a time. If you need an agent that reads the email, looks up the customer's history in your CRM, drafts a personalized response, and gets approval before sending -- that requires multi-step agent coordination that n8n's single-agent model doesn't handle well. See Workflow 5 for a more complex example.

Workflow 2: AI Data Extractor

Goal: Extract structured data from unstructured text (invoices, receipts, contact info) into a structured format.

Cost: ~$0.03-0.05 per document.

Step-by-Step Setup

  1. Add a Trigger node: Use Webhook Trigger to receive documents via API call.
  2. Add a Set node to define the extraction schema:
{
  "schema": {
    "vendor_name": "string",
    "total_amount": "number",
    "date": "YYYY-MM-DD",
    "line_items": [
      {
        "description": "string",
        "quantity": "number",
        "unit_price": "number"
      }
    ],
    "tax_amount": "number"
  }
}
  1. Add an AI Agent node with this system prompt:
You are a data extraction specialist. Extract structured data from the provided document.
Return ONLY valid JSON matching this schema. If a field is not found, use null.
Do not include any text outside the JSON object.
  1. Add an Error Trigger node to catch malformed AI output.
  2. Add a Function node to validate the JSON against your schema:
const data = JSON.parse($input.first().json.text);
if (!data.vendor_name || !data.total_amount) {
  throw new Error('Missing required fields');
}
return [{ json: data }];
  1. Add a destination node: Write to Google Sheets, Airtable, PostgreSQL, or send via webhook to your app.

Cost Breakdown

Scroll to see full table

Document TypeAvg TokensCost
Short receipt~200 tokens~$0.001
Standard invoice~500 tokens~$0.002
Multi-page contract~2,000 tokens~$0.01
Average~500 tokens~$0.002

At scale (500 documents/day): ~$1/day or ~$30/month.

Workflow 3: Content Summarizer Pipeline

Goal: Watch an RSS feed or bookmarking service, summarize new articles, and save summaries to Notion or a database.

Cost: ~$0.03-0.08 per article.

Step-by-Step Setup

  1. Add an RSS Feed Trigger node: Point it at any RSS feed (or use the Pocket/Readwise trigger).
  2. Add a Function node to extract article text from HTML:
const html = $input.first().json.content;
const text = html.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
return [{ json: { ...$input.first().json, plainText: text.substring(0, 8000) } }];
  1. Add an AI Agent node with this system prompt:
Summarize the following article in 3-5 bullet points. Include:
1. Main thesis or argument
2. Key data points or statistics mentioned
3. Actionable takeaways
4. Any notable tools, products, or companies mentioned

Keep each bullet point to 1-2 sentences.
  1. Add a Notion node (or Google Sheets, Airtable) to save the summary.
  2. Optional: Add a Slack node to post summaries to a team channel.

Cost Breakdown

Get AI agent tips in your inbox

Multi-agent workflows, BYOK tips, and product updates. No spam.

Scroll to see full table

Article LengthInput TokensOutput TokensCost
Short (~500 words)~700~150~$0.003
Medium (~1,500 words)~2,000~200~$0.007
Long (~3,000 words)~4,000~250~$0.013

At scale (50 articles/day): ~$0.35/day or ~$10/month.

Extending This Workflow

If you want the summarizer to also categorize articles, tag them by topic, extract key quotes, and draft a weekly newsletter -- you need multiple AI calls chained together. n8n handles this with sequential AI Agent nodes, but each node operates independently without shared context. For workflows where agents need to share understanding and collaborate, a multi-agent platform like Ivern AI produces more coherent results because agents share a common task context.

Workflow 4: Customer Support Router

Goal: Analyze incoming support tickets, determine urgency, categorize the issue, search your knowledge base for relevant articles, and draft a response for human review.

Cost: ~$0.05-0.15 per ticket.

Step-by-Step Setup

  1. Add a Trigger node: Use a Zendesk Trigger, Intercom Trigger, or Webhook Trigger.
  2. Add an AI Agent node for classification:
Analyze this support ticket and provide:
1. URGENCY: critical/high/medium/low
2. CATEGORY: billing/technical/account/feature_request/bug
3. SENTIMENT: frustrated/neutral/satisfied
4. SUGGESTED_ACTION: one sentence describing what should happen next
5. KNOWLEDGE_BASE_QUERY: 3-5 search terms to find relevant help articles

Respond in this exact JSON format.
  1. Add an HTTP Request node to search your knowledge base using the extracted query terms.
  2. Add a second AI Agent node for response drafting:
You are a customer support agent. Based on the ticket and the following knowledge base articles, draft a helpful response.
Rules:
- Be empathetic and professional
- Include specific steps from the knowledge base
- If the issue requires escalation, say so clearly
- Keep the response under 200 words
- Do not make up information not found in the knowledge base
  1. Add a Slack node to send the draft to a human reviewer channel.
  2. Add a Wait node for manual approval, then send the approved response to the customer.

Cost Breakdown

Scroll to see full table

StepTokensCost
Classification~400~$0.002
Knowledge base search~1,000~$0.004
Response drafting~1,500~$0.006
Total per ticket~2,900~$0.012

At scale (200 tickets/day): ~$2.40/day or ~$72/month.

Where n8n Hits Limits Here

This workflow has 3 separate AI calls, but they don't share context. The classification agent doesn't know what the drafting agent wrote. If the customer replies with a follow-up question, you need to build a separate workflow for handling the conversation loop. n8n's AI agents are stateless within a workflow execution -- they don't maintain conversation history across runs.

For support scenarios that require multi-turn conversations with context persistence, platforms with built-in agent memory (like Ivern AI's agent squads) handle this more naturally because agents maintain shared context across the entire task lifecycle.

Workflow 5: Automated Report Generator

Goal: Collect data from multiple sources, analyze it with AI, and generate a formatted weekly report.

Cost: ~$0.10-0.25 per report.

Step-by-Step Setup

  1. Add a Schedule Trigger (every Monday at 9 AM).
  2. Add multiple data source nodes:
    • HTTP Request node: Pull analytics data from your analytics API
    • Google Sheets node: Read sales pipeline data
    • PostgreSQL node: Query user activity metrics
  3. Add a Merge node to combine all data sources.
  4. Add an AI Agent node for analysis:
You are a business analyst. Analyze the following data and write a weekly report covering:

## Executive Summary
2-3 sentences on overall performance this week.

## Key Metrics
Present the most important metrics with week-over-week changes.

## Trends and Patterns
Identify 2-3 notable trends in the data.

## Recommendations
Based on the data, suggest 1-2 actions the team should take this week.

## Risks
Flag any metrics that are trending negatively.

Use specific numbers from the data. Do not hedge or be vague.
  1. Add a Markdown to HTML conversion node.
  2. Add destination nodes:
    • Email node: Send to stakeholders
    • Slack node: Post to team channel
    • Google Docs node: Save for archival

Cost Breakdown

Scroll to see full table

ComponentTokensCost
Data input (typical)~3,000~$0.008
Analysis output~800~$0.008
Total per report~3,800~$0.016

At scale (4 reports/week): ~$0.064/week or ~$0.25/month.

n8n AI Agent Limits: When to Use Multi-Agent Squads

After building these 5 workflows, here are the practical limits we hit:

Limit 1: Single-Agent Constraint

Each n8n AI Agent node is a single agent. It receives input, reasons, and produces output. It cannot decompose a complex task into subtasks and assign them to specialized agents. The report generator workflow (Workflow 5) works because the analysis is done by one agent in one pass. If you wanted separate agents for data gathering, trend analysis, chart generation, and executive summary writing -- n8n cannot coordinate that.

Limit 2: No Cross-Workflow Memory

n8n agents are stateless between workflow executions. Workflow 4 (Support Router) cannot remember that a customer wrote in yesterday about the same issue. Each execution starts from scratch. For support workflows that need conversation history, you must build your own memory layer using a database node.

Limit 3: No Agent-to-Agent Communication

In n8n, agents communicate by passing JSON through nodes. Agent A writes output to a field, Agent B reads that field. This works for simple pipelines but breaks down when agents need to negotiate, ask each other questions, or iterate on a shared output.

When Multi-Agent Squads Are Better

Scroll to see full table

Scenarion8n AI AgentMulti-Agent Squad
Single-step classificationBest choiceOverkill
Data extraction to databaseBest choiceOverkill
Multi-step research + writingPossible (chained nodes)Better (shared context)
Customer support with follow-upsLimited (no memory)Better (conversation memory)
Complex report with multiple analystsWorkaround (sequential calls)Better (parallel specialist agents)
Code review + fix + testNot supportedRequired

For workflows that need multiple specialized agents working together with shared context, Ivern AI provides purpose-built multi-agent squads where a Researcher, Writer, Coder, and Reviewer coordinate on tasks. The BYOK model means you pay wholesale API rates ($3-8/month for typical usage) with no platform markup.

n8n AI Agent Pricing at Scale

Self-Hosted n8n Cost

Scroll to see full table

ComponentMonthly Cost
n8n software$0 (open source)
Server (2 vCPU, 4GB RAM)~$20-40
AI model API (GPT-4o, 1,000 tasks/day)~$30-60
DevOps time (maintenance, updates)~$500-1,000
Total~$550-1,100/month

n8n Cloud Cost

Scroll to see full table

PlanPriceExecutionsBest For
Starter$20/mo2,500Individuals, testing
Pro$50/mo10,000Small teams
EnterpriseCustomUnlimitedOrganizations

Cloud pricing does not include AI model costs -- you still bring your own API keys for the AI Agent node.

n8n vs Ivern AI Cost Comparison

Scroll to see full table

Cost Factorn8n Self-Hostedn8n Cloud (Pro)Ivern AI (BYOK)
Platform fee$0$50/mo$0 (free tier) or $29/mo (Pro)
AI model costs~$30-60/mo~$30-60/mo~$3-8/mo (BYOK, same models)
Infrastructure~$20-40/mo$0$0
DevOps overhead~$500-1,000/mo$0$0
Total (1 user)~$550-1,100/mo~$80-110/mo~$3-8/mo (free tier)

For AI-agent-specific workflows (not general automation), Ivern AI's BYOK model is significantly cheaper because there is no infrastructure to manage and no platform markup on API costs. See our BYOK Cost Comparison for the full breakdown.

Quick Reference: n8n AI Agent Node Configuration

Required Sub-Nodes

Every AI Agent node needs at least two sub-nodes:

  1. AI Model -- Connects to your LLM provider
  2. AI Tool (optional) -- Gives the agent external capabilities

Available AI Model Connectors

Scroll to see full table

ConnectorProviderKey Requirement
OpenAI ModelOpenAIAPI key from platform.openai.com
Anthropic Chat ModelAnthropicAPI key from console.anthropic.com
Google Gemini Chat ModelGoogleAPI key from aistudio.google.com
Azure OpenAI ModelAzureAzure endpoint + API key
Ollama Chat ModelLocalRunning Ollama server

Available AI Tools

Scroll to see full table

ToolWhat It Does
SerpAPIWeb search
CalculatorMath operations
HTTP RequestCall external APIs
CodeExecute JavaScript/Python
Vector StoreQuery embeddings
WikipediaLook up Wikipedia articles

Tips for Better n8n AI Agent Results

  1. Be specific in system prompts. "Classify into exactly one of: SUPPORT, SALES, SPAM" works better than "classify this email."
  2. Use the Code tool for complex logic. If the AI needs to do math, give it a Calculator tool instead of asking it to compute in text.
  3. Add error handling after every AI node. AI output is non-deterministic. Always validate with a Function node.
  4. Limit output length. Add "Keep your response under 200 words" to prompts. This reduces cost and improves consistency.
  5. Test with real data. Synthetic test data rarely matches the edge cases you will see in production.

Frequently Asked Questions

Can n8n AI agents work with multiple models in the same workflow?

Yes. You can use different model providers in different AI Agent nodes within the same workflow. For example, use GPT-4o for classification and Claude for response drafting. Each node connects to its own model credential.

How much does an n8n AI agent workflow cost to run?

Cost depends on the model and task complexity. Simple classifications cost ~$0.001-0.003 per execution. Complex multi-step workflows with long inputs cost ~$0.01-0.05 per execution. At typical usage (100-500 tasks/day), expect $3-30/month in AI API costs.

Can n8n AI agents access external APIs and databases?

Yes, through the Tool sub-node. You can give an AI agent HTTP Request tools to call APIs, Database tools to query PostgreSQL/MySQL, and custom Function tools for any logic. The agent decides when to use each tool based on the task.

What is the difference between n8n AI agents and multi-agent platforms?

n8n AI agents operate as single agents within individual workflow nodes. They cannot collaborate, share context, or decompose tasks across specialized roles. Multi-agent platforms like Ivern AI create teams of specialized agents (Researcher, Writer, Coder, Reviewer) that coordinate on complex tasks with shared memory and context. See our n8n vs Ivern comparison for details.

Is n8n good for building AI agent workflows?

n8n is excellent for single-step AI tasks within automated workflows: classifying data, extracting information, generating text, routing requests. It is not designed for multi-agent coordination, complex reasoning chains, or workflows that require agents to maintain conversation memory across executions.


Building AI agent workflows? Try Ivern AI free to create multi-agent squads that handle complex tasks with shared context. Bring your own API keys -- no markup, no infrastructure to manage. Start with 15 free tasks.

Related guides: Ivern vs n8n AI Agent Comparison · Best n8n Alternatives for AI Workflows · AI Workflow Automation Tools 2026 · Build an AI Agent Pipeline · AI Agent Orchestration Guide · Enterprise AI Agent Platform Comparison · BYOK Cost Comparison · AI Agents vs Chatbots · No-Code AI Agent Guide · AI Presentation Generator

Want to try multi-agent AI for free?

Generate a blog post, Twitter thread, LinkedIn post, and newsletter from one prompt. No signup required.

Try the Free Demo

AI Agent Squads -- Free to Start

One prompt generates blog posts, social media, and emails. Free tier, BYOK, zero markup.

No spam. Unsubscribe anytime.