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)
- Sign up at n8n.io
- Start free trial
- Begin building
Self-Hosted (Recommended for Production)
# 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:
- Add Trigger node
- Connect to multiple HTTP Request nodes (parallel)
- Add Merge node (Mode: Combine)
- 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
- Manual execution: Click "Execute Workflow"
- Test data: Use "Execute with Test Data"
- 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
Related Documents
- Pattern: Agent Chaining & Orchestration - Chaining concepts
- Implementation Guide: Building Agents with LangChain - Code-based alternative
- Sales AI Agents - Sales agent examples
- Customer Success AI Agents - CS agent examples