Introduction
n8n has evolved from a general-purpose automation tool into a powerful platform for building AI-powered workflows. With native AI nodes, LangChain integration, and connections to major LLM providers, n8n makes it possible to build sophisticated AI automations without writing extensive code.
This guide walks through building practical AI workflows with n8n, from basic LLM integrations to complex document processing pipelines.
n8n’s AI Capabilities
n8n provides several categories of AI nodes:
Basic AI Nodes
- OpenAI Node: Direct integration with GPT models for text generation, classification, and more
- Anthropic Node: Connect to Claude models for advanced reasoning tasks
- AI Agent Node: Build autonomous agents that can use tools and reason through tasks
- Language Model Node: Generic interface supporting multiple providers
Advanced AI Nodes
- Vector Store Node: Store and retrieve embeddings for RAG applications
- Embeddings Node: Generate vector embeddings from text
- Document Loader Node: Load documents from various sources
- Text Splitter Node: Chunk documents for processing
- Memory Node: Maintain conversation context for chat applications
Setting Up AI Credentials
Before building AI workflows, configure your API credentials in n8n:
- Go to Settings > Credentials
- Add a new credential for your LLM provider
- For OpenAI: Enter your API key from platform.openai.com
- For Anthropic: Enter your API key from console.anthropic.com
- Test the connection
Credentials are encrypted at rest and can be reused across workflows.
Building a Document Processing Workflow
Let’s build a workflow that processes incoming documents, extracts key information, and routes it based on content.
Workflow Overview
- Trigger: Watch for new files in a folder or cloud storage
- Load: Read the document content
- Extract: Use AI to extract structured information
- Classify: Categorize the document
- Route: Send to appropriate destination based on category
- Store: Save processed results to a database
Step 1: File Trigger
Use a file trigger node to watch for new documents:
[Watch Folder Node]
Path: /documents/incoming
File Type: *.pdf, *.docx, *.txt
Step 2: Document Loading and Text Extraction
// Code node to extract text from different file types
const fileType = items[0].json.fileExtension;
const filePath = items[0].json.filePath;
let textContent = '';
if (fileType === 'txt') {
const fs = require('fs');
textContent = fs.readFileSync(filePath, 'utf-8');
} else if (fileType === 'pdf') {
// Use PDF extraction library
const pdfData = await this.helpers.httpRequest({
method: 'POST',
url: 'https://api.example.com/extract-pdf',
body: { file: filePath }
});
textContent = pdfData.text;
}
return [{ json: { ...items[0].json, textContent }];
Step 3: AI Information Extraction
Use the OpenAI node to extract structured data:
[OpenAI Node]
Model: gpt-4o
Operation: Message
System Message: "You are a document analysis assistant. Extract the following
information from the document and return as JSON: document_type, date,
key_entities, summary, action_items."
User Message: "={{ $json.textContent }}"
Response Format: json_object
Step 4: Classification and Routing
// Code node for routing based on classification
const extractedData = items[0].json;
const documentType = extractedData.document_type;
let routeTo = '';
switch (documentType) {
case 'invoice':
routeTo = 'accounting-system';
break;
case 'contract':
routeTo = 'legal-review';
break;
case 'support_request':
routeTo = 'ticketing-system';
break;
default:
routeTo = 'general-archive';
}
return [{
json: {
...extractedData,
routeTo: routeTo,
processedAt: new Date().toISOString()
}
}];
Step 5: Conditional Routing
Use the Switch node to route based on the routeTo field:
[Switch Node]
Mode: Rules
Rules:
- Equal to "accounting-system" → [Accounting API Node]
- Equal to "legal-review" → [Email Notification Node]
- Equal to "ticketing-system" → [Ticketing API Node]
- Default → [Archive Node]
Building an AI Agent in n8n
n8n’s AI Agent node lets you build autonomous agents that can use tools and reason through multi-step tasks.
Agent Configuration
[AI Agent Node]
Agent Type: Conversational Agent
Language Model: OpenAI (gpt-4o)
Memory: Window Buffer Memory (memory size: 10)
Tools:
- HTTP Request Tool (for API calls)
- Calculator Tool
- Custom Code Tool
Adding Custom Tools
// Custom tool: Database query
const customTool = {
name: "query_database",
description: "Query the company database for customer information",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "Natural language query about customers"
}
},
required: ["query"]
},
execute: async function(params) {
// Convert natural language to SQL or use a search API
const results = await this.helpers.httpRequest({
method: 'POST',
url: 'http://internal-api:3000/search',
body: { query: params.query }
});
return JSON.stringify(results);
}
};
Agent Workflow Example
Build a customer support agent that:
- Receives a customer message via webhook
- Looks up customer information in the database
- Searches the knowledge base for relevant articles
- Generates a response using the retrieved context
- Sends the response back to the customer
[Webhook Trigger]
→ [AI Agent Node with tools: DB Query, Knowledge Search]
→ [HTTP Response Node]
Building a RAG Workflow in n8n
Retrieval-Augmented Generation in n8n combines vector stores, embeddings, and LLMs:
Step 1: Document Ingestion Pipeline
[Schedule Trigger: Daily]
→ [Google Drive Node: List new files]
→ [Document Loader Node]
→ [Text Splitter Node: chunk_size=500, overlap=50]
→ [Embeddings Node: OpenAI text-embedding-3-small]
→ [Vector Store Node: Pinecone upsert]
Step 2: Query Pipeline
[Webhook Trigger: POST /ask]
→ [Embeddings Node: Embed query]
→ [Vector Store Node: Pinecone similarity search, top_k=5]
→ [OpenAI Node: Generate answer with retrieved context]
→ [HTTP Response Node]
Vector Store Configuration
[Vector Store Node]
Operation: Retrieve
Vector Store: Pinecone
Index: knowledge-base
Embedding Model: OpenAI text-embedding-3-small
Top K: 5
Filter: { "source": "documentation" }
Connecting to Multiple LLM Providers
n8n supports routing to different models based on the task:
// Route based on task complexity
const taskComplexity = items[0].json.complexity;
const tokenBudget = items[0].json.tokenBudget;
let model = 'gpt-4o-mini'; // Default to fast, cheap model
if (taskComplexity === 'high' && tokenBudget > 2000) {
model = 'gpt-4o'; // Use powerful model for complex tasks
} else if (taskComplexity === 'medium') {
model = 'claude-3-5-sonnet'; // Use Anthropic for medium tasks
}
return [{
json: {
...items[0].json,
selectedModel: model
}
}];
Error Handling in AI Workflows
AI workflows need special error handling because LLMs can fail in unexpected ways:
// Validate AI output before using it
function validateAIOutput(output) {
try {
const parsed = JSON.parse(output);
// Check required fields
if (!parsed.document_type || !parsed.summary) {
throw new Error('Missing required fields in AI output');
}
// Check for hallucination indicators
if (parsed.summary.includes('I cannot') ||
parsed.summary.includes('I don\'t have access')) {
throw new Error('AI refused to process document');
}
return parsed;
} catch (error) {
// Fallback: use simpler prompt or different model
return {
document_type: 'unknown',
summary: 'Processing failed, manual review required',
error: error.message
};
}
}
Cost Optimization
AI workflows can get expensive. Here are strategies to manage costs:
- Cache responses: Store AI outputs and check for similar queries before calling the LLM
- Use smaller models for simple tasks: Route classification and extraction to gpt-4o-mini
- Batch processing: Process multiple items in a single LLM call when possible
- Limit context: Only include relevant context in prompts, not entire documents
- Monitor token usage: Track tokens consumed per workflow execution
// Track and log token usage
const tokenUsage = {
inputTokens: items[0].json.usage.prompt_tokens,
outputTokens: items[0].json.usage.completion_tokens,
model: items[0].json.model,
cost: calculateCost(
items[0].json.usage.prompt_tokens,
items[0].json.usage.completion_tokens,
items[0].json.model
)
};
// Send to monitoring
await this.helpers.httpRequest({
method: 'POST',
url: 'http://monitoring:3000/api/tokens',
body: tokenUsage
});
Conclusion
n8n’s AI capabilities make it a powerful platform for building AI-powered automations without extensive coding. The combination of visual workflow building, native AI nodes, and integration with major LLM providers enables everything from simple text processing to complex multi-agent systems.
Start with a simple workflow—like document classification or email summarization—and gradually add complexity as you become comfortable with the AI nodes. The key to success is iterative development: build, test, measure costs, and refine. With proper error handling and cost monitoring, n8n AI workflows can run reliably in production and deliver significant value.