🏠 Home / Hub

n8n 07 — AI Agents & LLM Integration

n8n has first-class support for AI through a built-in LangChain integration. You can build chat agents, document Q&A systems, email summarizers, and more — all visually.

1. AI Nodes in n8n

n8n's AI capabilities are built on LangChain. The relevant node categories are:

CategoryNodesPurpose
Chat ModelsOpenAI, Anthropic, Ollama, Azure OpenAI, MistralGenerate text responses
EmbeddingsOpenAI Embeddings, CohereConvert text to vectors for search
Vector StoresPinecone, Qdrant, Supabase, In-MemoryStore and retrieve embeddings
MemoryWindow Buffer Memory, Postgres MemoryKeep conversation history
ToolsCalculator, Code Exec, HTTP Request, SearchActions the agent can take
Document LoadersPDF, CSV, JSON, HTML, Google DriveLoad data for RAG pipelines
Text SplittersRecursive Character, TokenChunk documents for embedding

2. OpenAI Chat Model Setup

# 1. Create OpenAI credential:
Settings → Credentials → New → "OpenAI API"
API Key: sk-proj-your-key-here

# 2. Add "OpenAI Chat Model" node (under AI → Chat Models)
Credential: (select the one you created)
Model: gpt-4o           # or gpt-4o-mini, gpt-3.5-turbo
Temperature: 0.7        # 0=deterministic, 1=creative
Max Tokens: 1000        # limit response length
Timeout: 60000ms
Use gpt-4o-mini for high-volume, lower-cost tasks like classification. Use gpt-4o for complex reasoning or generation where quality matters.

3. Basic AI Chat Workflow

# Simplest AI chat workflow:
When Chat Message Received (trigger)
   └─► AI Agent node
         - Chat Model: OpenAI gpt-4o-mini
         - System Prompt: "You are a helpful assistant."
               └─► (respond automatically via chat interface)

# To expose as a public chat:
# The "When Chat Message Received" trigger gives you
# a chat URL you can embed or share directly.
The AI Agent node handles the conversation loop automatically. It can call tools, receive results, and respond — all in one node.

4. AI Agent Node with Tools

The AI Agent node can use tools to take real actions. Connect tool nodes to the "Tools" input of the AI Agent.

# AI Agent node settings:
System Message: |
  You are a product support agent.
  Use the search tool to find product info.
  Use the calculator for pricing questions.
  Always cite your sources.

# Connected tools (attach to Tools input):
- Calculator tool    → handles math
- HTTP Request tool  → can call your internal API
- SerpAPI tool       → web search capability
- Code execution     → run small scripts

# Example agent reasoning trace:
User: "What's the price of 5 units of SKU-123 with 10% discount?"
Agent: [calls Calculator] → 5 × $49.99 × 0.9 = $224.95
Agent: "That would be $224.95 for 5 units with 10% discount."

5. Document Q&A Workflow (RAG)

# Phase 1: Ingest documents (run once)
HTTP Request / Google Drive → load PDF
   └─► Default Data Loader (extract text)
         └─► Recursive Character Text Splitter
               (Chunk Size: 1000, Overlap: 100)
               └─► OpenAI Embeddings
                     └─► Pinecone Vector Store (Insert)

# Phase 2: Query (on each user question)
When Chat Message Received
   └─► AI Agent
         - Chat Model: OpenAI gpt-4o
         - System: "Answer only from the provided context."
         - Tool: Vector Store Retriever
                 (connects to Pinecone, returns top 5 chunks)
               └─► Reply with answer + source references
Set a strict system prompt like "Only answer from the provided context. If the answer isn't there, say so." This prevents hallucination.

6. Memory Nodes

Memory TypeStorageBest for
Window Buffer MemoryIn-memory (lost on restart)Short sessions, testing
Postgres Chat MemoryPostgres databasePersistent multi-session conversations
Redis Chat MemoryRedisFast, scalable session memory
# Postgres Chat Memory setup:
1. Add "Postgres Chat Memory" node
2. Connect it to the "Memory" input of the AI Agent
3. Set Session ID: {{ $sessionId }}  (auto from chat trigger)
4. Set Table Name: n8n_chat_memory
5. Connect your Postgres credential

# The agent now remembers the full conversation history
# across multiple messages in the same session

7. AI-Powered Automation Examples

Email Summarizer

Gmail Trigger (new email arrives)
   └─► OpenAI Chat Model (Basic LLM Chain)
         System: "Summarize this email in 2 sentences.
                  Extract: sender, action needed, urgency (low/med/high)"
         User: {{ $json.text }}
               └─► Set Node (store summary + urgency)
                     └─► IF urgency = high
                           └─► Slack: alert team

Support Ticket Classifier

Webhook (new ticket) └─► Basic LLM Chain Prompt: "Classify this support ticket into one of: billing, technical, feature-request, other. Reply with JSON: {category, priority}" Input: {{ $json.message }} └─► Code Node (parse JSON response) └─► Switch (route by category)

8. LLM Chaining

Chain multiple AI nodes to build multi-step reasoning pipelines:

# Step 1: Extract structured data from raw text
LLM Chain 1:
  Prompt: "Extract name, company, budget from: {{ $json.email_body }}"
  Output: { name: "Alice", company: "Acme", budget: "$5000" }

# Step 2: Score the lead based on extracted data
LLM Chain 2:
  Prompt: "Given this lead: {{ $json }}
           Rate their likelihood to buy (1-10) and explain why."
  Output: { score: 8, reason: "Budget matches, clear intent" }

# Step 3: Draft a personalized outreach email
LLM Chain 3:
  Prompt: "Write a personalized intro email to {{ $json.name }}
           at {{ $json.company }} referencing their interest."
Pass the full output JSON from one LLM chain to the next using {{ JSON.stringify($json) }} in the prompt for maximum context.

📌 Study Checklist