guide

Implementation Guide: Building Agents with n8n

Build AI agent workflows with n8n. Covers setup, common patterns, and integration with LLMs, databases, and business systems.

Overview

n8n is a visual workflow automation tool that excels at:

  • Connecting AI to business systems
  • Building multi-step agent workflows
  • Self-hosting for data privacy
  • No-code/low-code development

When to Use n8n

Good For Not Ideal For
System integrations Complex reasoning chains
Scheduled workflows Real-time chat interfaces
Data pipelines Heavy computation
Multi-step automations Simple one-off tasks
Self-hosted requirements Quick prototyping

Setup

Cloud (Quickest)

  1. Sign up at n8n.io
  2. Start free trial
  3. Begin building
# Docker Compose
version: "3.8"
services:
  n8n:
    image: n8nio/n8n
    ports:
      - "5678:5678"
    environment:
      - N8N_BASIC_AUTH_ACTIVE=true
      - N8N_BASIC_AUTH_USER=admin
      - N8N_BASIC_AUTH_PASSWORD=your-password
      - N8N_ENCRYPTION_KEY=your-key
    volumes:
      - n8n_data:/home/node/.n8n
volumes:
  n8n_data:

Core Concepts

Nodes

Node Type Purpose Examples
Trigger Starts workflow Webhook, Schedule, Email
Action Does something HTTP Request, OpenAI, Slack
Logic Controls flow IF, Switch, Merge
Transform Modifies data Set, Code, Function

Data Flow

Trigger β†’ Node 1 β†’ Node 2 β†’ Node 3 β†’ Output
           β”‚
           └── Each node receives data from previous
               and passes to next

Common Agent Patterns

Pattern 1: LLM Request

[Trigger] β†’ [Set: Build Prompt] β†’ [OpenAI/Anthropic] β†’ [Output]

OpenAI Node Configuration:

{
  "resource": "chat",
  "operation": "create",
  "model": "gpt-4o",
  "messages": [
    {
      "role": "system",
      "content": "{{ $json.system_prompt }}"
    },
    {
      "role": "user",
      "content": "{{ $json.user_input }}"
    }
  ]
}

Pattern 2: Parallel Data Gathering

[Trigger] ──┬── [HTTP: API 1] ──┐
            β”œβ”€β”€ [HTTP: API 2] ──┼── [Merge] β†’ [OpenAI: Synthesize] β†’ [Output]
            └── [HTTP: API 3] β”€β”€β”˜

Implementation:

  1. Add Trigger node
  2. Connect to multiple HTTP Request nodes (parallel)
  3. Add Merge node (Mode: Combine)
  4. Add OpenAI node with combined context

Pattern 3: Conditional Routing

[Trigger] β†’ [OpenAI: Classify] β†’ [Switch] ──┬── [Path A]
                                            β”œβ”€β”€ [Path B]
                                            └── [Path C]

Switch Node Configuration:

{
  "rules": [
    {
      "value1": "={{ $json.classification }}",
      "operation": "equals",
      "value2": "urgent"
    }
  ]
}

Pattern 4: RAG Workflow

[Trigger] β†’ [Embeddings] β†’ [Vector Search] β†’ [Merge with Query] β†’ [OpenAI] β†’ [Output]

Using Pinecone:

{
  "operation": "query",
  "topK": 5,
  "vector": "={{ $json.embedding }}",
  "namespace": "knowledge-base"
}

Example: Prospect Research Agent

Workflow Structure

[Webhook: New Lead]
        β”‚
        β–Ό
[Set: Extract Lead Data]
        β”‚
        β”œβ”€β”€ [HTTP: LinkedIn API] ────────┐
        β”œβ”€β”€ [HTTP: Company Website] ─────┼── [Merge]
        └── [HTTP: News API] β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜       β”‚
                                                 β–Ό
                                    [OpenAI: Synthesize Research]
                                                 β”‚
                                                 β–Ό
                                    [Salesforce: Update Lead]
                                                 β”‚
                                                 β–Ό
                                    [Slack: Notify Rep]

Node Configurations

Webhook Node:

{
  "httpMethod": "POST",
  "path": "new-lead",
  "responseMode": "onReceived"
}

Set Node (Extract Data):

{
  "values": {
    "company_name": "={{ $json.body.company }}",
    "contact_name": "={{ $json.body.name }}",
    "linkedin_url": "={{ $json.body.linkedin }}"
  }
}

OpenAI Node (Synthesis):

{
  "model": "gpt-4o",
  "messages": [
    {
      "role": "system",
      "content": "You are a sales research assistant. Synthesize the following data into a 200-word prospect briefing..."
    },
    {
      "role": "user",
      "content": "LinkedIn: {{ $node['LinkedIn'].json }}\nWebsite: {{ $node['Website'].json }}\nNews: {{ $node['News'].json }}"
    }
  ]
}

Example: Account Health Monitor

Workflow Structure

[Schedule: Daily 8am]
        β”‚
        β–Ό
[Salesforce: Get Accounts]
        β”‚
        β–Ό
[Loop: For Each Account]
        β”‚
        β”œβ”€β”€ [HTTP: Usage API]
        β”œβ”€β”€ [Zendesk: Get Tickets]
        └── [Calculate Health Score]
                β”‚
                β–Ό
        [Switch: Risk Level]
                β”‚
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”
        β–Ό       β–Ό       β–Ό
    [Red]   [Yellow]  [Green]
        β”‚       β”‚       β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜
                β”‚
                β–Ό
        [Aggregate Results]
                β”‚
                β–Ό
        [OpenAI: Generate Digest]
                β”‚
                β–Ό
        [Slack: Send to CSM]

Code Node (Health Score)

// Calculate health score from inputs
const usage = $input.first().json.usage;
const tickets = $input.first().json.tickets;

// Scoring logic
let usageScore = Math.min(100, (usage.active_users / usage.total_seats) * 100);
let ticketScore = Math.max(0, 100 - (tickets.open_count * 10));

let healthScore = (usageScore * 0.6) + (ticketScore * 0.4);

let riskLevel;
if (healthScore < 40) riskLevel = 'red';
else if (healthScore < 70) riskLevel = 'yellow';
else riskLevel = 'green';

return [{
  json: {
    account_id: $input.first().json.account_id,
    health_score: healthScore,
    risk_level: riskLevel,
    usage_score: usageScore,
    ticket_score: ticketScore
  }
}];

Best Practices

Error Handling

[Main Flow] β†’ [Error Trigger] β†’ [Slack: Alert] β†’ [Log to DB]

Always include:

  • Error trigger workflow
  • Retry logic for transient failures
  • Alerting for persistent failures
  • Logging for debugging

Credentials Management

Settings β†’ Credentials β†’ Add New
- Store API keys securely
- Use environment variables for sensitive data
- Never hardcode credentials in nodes

Testing

  1. Manual execution: Click "Execute Workflow"
  2. Test data: Use "Execute with Test Data"
  3. Webhook testing: Use webhook.site for mock triggers

Performance

Tip Why
Batch operations Reduce API calls
Use Wait node Respect rate limits
Cache responses Avoid redundant calls
Limit loop iterations Prevent runaway costs

Integrations Reference

LLM Nodes

Node Configuration
OpenAI API key, model, messages
Anthropic API key, model, messages
Ollama Local URL, model

Business Systems

System Common Operations
Salesforce Get/Update records, SOQL query
HubSpot Contacts, deals, companies
Slack Send message, post to channel
Gmail Send, read, search
Google Sheets Read/write rows
Notion Pages, databases

Data & Storage

System Use Case
Postgres Structured data
Pinecone Vector search
Redis Caching
Supabase Backend as a service

Troubleshooting

"Workflow doesn't trigger"

  • Check webhook URL is correct
  • Verify credentials are valid
  • Check trigger conditions
  • Review execution logs

"Data not passing between nodes"

  • Use expression editor to debug
  • Check data structure with Code node
  • Verify property names match

"API rate limits"

  • Add Wait node between calls
  • Implement batching
  • Use caching where possible