Skip to content
Back to blog

Building AI-Powered Workflows with n8n

Learn how to build AI-powered workflows with n8n using AI nodes, LangChain integration, document processing, and connections to OpenAI and Anthropic models.

MH
Mahmoud Hashem
· October 10, 2024 · 7 min read
AI workflow automation interface on a computer screen

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:

  1. Go to Settings > Credentials
  2. Add a new credential for your LLM provider
  3. For OpenAI: Enter your API key from platform.openai.com
  4. For Anthropic: Enter your API key from console.anthropic.com
  5. 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

  1. Trigger: Watch for new files in a folder or cloud storage
  2. Load: Read the document content
  3. Extract: Use AI to extract structured information
  4. Classify: Categorize the document
  5. Route: Send to appropriate destination based on category
  6. 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:

  1. Receives a customer message via webhook
  2. Looks up customer information in the database
  3. Searches the knowledge base for relevant articles
  4. Generates a response using the retrieved context
  5. 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:

  1. Cache responses: Store AI outputs and check for similar queries before calling the LLM
  2. Use smaller models for simple tasks: Route classification and extraction to gpt-4o-mini
  3. Batch processing: Process multiple items in a single LLM call when possible
  4. Limit context: Only include relevant context in prompts, not entire documents
  5. 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.

#n8n #AI #Automation

Related articles

Let's build something great together

Ready to automate your business processes and save hundreds of hours every month? Let's talk about your project.