How to Build an AI Agent with n8n? Complete Beginner Tutorial 2026
If you want to build AI agents that search the web, read emails, query databases, and make decisions autonomously — without writing hundreds of lines of code — n8n gives you a visual drag-and-drop editor. This tutorial takes you from zero to a production-ready agent with LLM integration, multi-tool orchestration, persistent memory, and RAG document Q&A in 60 minutes.
入门 · 60 分钟 · 2026年6月25日
TL;DR
If you want to build an AI agent that can search the web, read your emails, query databases, and make decisions — without writing hundreds of lines of code — n8n gives you a visual drag-and-drop editor to connect LLMs (OpenAI, Claude, Gemini) with real-world tools. In this tutorial, you'll go from zero to a working AI agent in under 60 minutes, including a RAG-powered document Q&A bot and a multi-tool research assistant.
What You'll Learn
- How to install n8n locally with Docker in 5 minutes
- How to connect OpenAI, Claude, or Ollama models to the AI Agent node
- How to give your agent tools: web search, calculator, HTTP requests, code execution
- How to add memory so your agent remembers conversation context
- How to build a RAG (Retrieval-Augmented Generation) agent that answers questions from your documents
- How to trigger your agent via webhook, schedule, or chat interface
- Common pitfalls and how to fix them
Prerequisites
- A computer with Docker installed (or Node.js 18+ for npm install)
- An API key from at least one LLM provider (OpenAI, Anthropic, or Google AI Studio — all have free tiers)
- Basic familiarity with the concept of APIs (you don't need to write code)
- 10-15 minutes of uninterrupted focus per section
Step 1: Install n8n with Docker
The fastest way to get n8n running locally is Docker. Open your terminal and run:
docker run -it --rm \
--name n8n \
-p 5678:5678 \
-v ~/.n8n:/home/node/.n8n \
docker.n8n.io/n8nio/n8nThis command:
- Downloads the official n8n image
- Maps port 5678 so you can access the editor at
http://localhost:5678 - Persists your workflows and credentials in
~/.n8nso they survive container restarts
Once you see n8n ready on ::, port 5678, open http://localhost:5678 in your browser. Create an account (email + password) — this is your local instance, so data stays on your machine.
Alternative: n8n Cloud. If you don't want to self-host, sign up at n8n.cloud for a free trial. The editor is identical; you just skip the Docker step.
Alternative: npm. If you have Node.js 18+:
npx n8nStep 2: Understand the n8n Editor
Before building an agent, get familiar with the interface:
- Canvas (center): The visual workflow builder. You drag nodes onto it and connect them.
- Nodes Panel (left): All available nodes grouped by category — AI, Triggers, Actions, etc.
- Node Settings (right, after clicking a node): Configure parameters, credentials, and options.
- Executions Tab (left sidebar): See past workflow runs, inspect inputs/outputs, and debug errors.
Key concept: Every workflow starts with a Trigger node. This is what kicks off the agent — a webhook call, a schedule, a chat message, or a manual click. From the trigger, data flows through Action nodes connected by arrows.
Your first mini-workflow: Drag a "Manual Trigger" onto the canvas. Add a "Code" node, paste return [{ json: { message: "Hello from n8n!" } }];, connect them, and click "Execute Workflow." You'll see the output in the Executions tab. This is the basic pattern: trigger → process → output.
Step 3: Connect Your First LLM
Your AI agent needs a brain. n8n supports multiple LLM providers through credential-based connections.
Add OpenAI credentials:
- Click your profile icon (bottom-left) → Credentials → Add Credential
- Search "OpenAI API" and select it
- Paste your API key (get one from platform.openai.com/api-keys)
- Click Save
Add Anthropic (Claude) credentials:
- Same path: Credentials → Add Credential → search "Anthropic API"
- Paste your Anthropic API key (from console.anthropic.com)
- Save
Add Google AI (Gemini) credentials:
- Credentials → Add Credential → search "Google Gemini(PaLM) API"
- Paste your API key from aistudio.google.com
- Save
Test the connection: Drag an "AI Agent" node onto a new workflow canvas. Click it, and in the Model dropdown, select "OpenAI Chat Model." Under Credential, choose the OpenAI credential you just created. Set Model to gpt-4o. This confirms your LLM connection works — we'll build the full agent in the next step.
Step 4: Build Your First AI Agent — Email Summarizer
Now let's build something useful: an agent that reads an email (simulated) and summarizes it.
Workflow setup:
- Trigger: Drag a "Webhook" node onto the canvas. This generates a unique URL; we'll use it to send emails to our agent.
- AI Agent node: Drag the "AI Agent" node and connect it after the webhook.
- Configure the AI Agent:
- Model: OpenAI Chat Model → gpt-4o
- System Prompt:
You are an email assistant. Summarize emails concisely. Return: (1) sender, (2) main request, (3) urgency level (low/medium/high), (4) suggested reply draft. Keep summaries under 150 words. - Leave Tools and Memory empty for now.
- Output: Add a "Respond to Webhook" node at the end. This sends the agent's summary back to whoever called the webhook.
Test it: Click "Listen for Test Event" on the webhook node, then in another terminal:
curl -X POST http://localhost:5678/webhook-test/YOUR-WEBHOOK-ID \
-H "Content-Type: application/json" \
-d '{"from":"boss@company.com","subject":"Q3 Report Due Friday","body":"Hi, just a reminder that Q3 reports are due this Friday by 5pm. Please send me your draft by Thursday EOD for review. Thanks."}'The agent receives the email JSON, processes it through GPT-4o with your instructions, and returns a structured summary with urgency level and a suggested reply. In the Executions tab, you can see exactly what the LLM received (input) and returned (output).
Step 5: Give Your Agent Tools
A plain LLM can only think. To act, it needs tools. n8n's AI Agent node lets you attach sub-workflows as tools that the agent can call autonomously.
Add a Web Search tool:
- Add a "SerpAPI" (or "Google Custom Search") credential in Credentials
- In the AI Agent node settings, click + Add Tool
- Select "SerpAPI" → set it to return top 3 results
- The agent can now search the web when asked
Add a Calculator tool:
- In the AI Agent node, + Add Tool → select "Calculator"
- The agent can now do math — useful for calculations inside research workflows
Add an HTTP Request tool:
- + Add Tool → select "HTTP Request Tool"
- Configure allowed domains (e.g.,
api.github.com,weather.com) - The agent can now call any REST API to fetch live data
Build a Research Agent: With web search + HTTP + calculator, your agent becomes a research assistant. Update the system prompt:
You are a research assistant. When asked a question:
1. Search the web for relevant information
2. If numerical calculations are needed, use the calculator
3. If you need live data, use the HTTP request tool
4. Synthesize findings into a clear answer with sourcesNow test it by asking: "What's the current Bitcoin price, and if I invested $1,000 at the start of 2024, what would it be worth today?" The agent will web-search the price, use the calculator, and return a complete answer.
Important: n8n limits agent tool calls to prevent infinite loops. Set Max Iterations in the AI Agent node to 10-15 for research tasks (higher = more thorough but slower and more expensive).
Step 6: Add Memory to Your Agent
Without memory, every message is treated as a brand-new conversation. Memory lets your agent remember what you discussed earlier.
Simple Memory (Window Buffer): In the AI Agent node settings, find the Memory section and add a "Window Buffer Memory" node. Set Context Window Length to 10 (remembers last 10 messages). This is perfect for chat-style agents.
Advanced Memory (Postgres with Chat Memory): For persistent memory across sessions:
- Install the Postgres node (already included in n8n)
- Add a "Postgres Chat Memory" node to the agent's Memory section
- Configure your Postgres connection string
- The agent now stores conversation history in a database — close your browser, come back tomorrow, and it remembers
Session-based memory: Add a "Session ID" field to your webhook input, and configure memory to use it. Different users get separate conversation histories.
Test memory: Ask your agent "My name is Alex." Then in a follow-up message, ask "What's my name?" With memory configured, it responds "Alex." Without memory, it says "I don't know."
Step 7: Build a RAG Agent — Answer Questions From Your Documents
RAG (Retrieval-Augmented Generation) lets your agent search through your own documents and answer questions based on their content. This is the foundation for customer support bots, knowledge base Q&A, and legal document analysis.
Setup a RAG pipeline:
-
Add a Vector Store:
- In Credentials, add a "Qdrant" (free cloud tier at qdrant.io) or "Pinecone" credential
- Or use the built-in "In-Memory Vector Store" for testing (data resets on restart)
-
Create the ingestion workflow:
- Trigger: "Manual Trigger"
- Node: "Read Binary Files" → point to a folder of PDFs, markdown files, or text documents
- Node: "Default Data Loader" → splits documents into chunks
- Node: "Embeddings OpenAI" → converts text chunks into vectors
- Node: "Vector Store" (Qdrant/Pinecone/In-Memory) → stores the vectors
Run this workflow once to index your documents.
-
Create the Q&A workflow:
- Trigger: "Chat Trigger" (gives you a chat UI at
http://localhost:5678/chat) - Node: "AI Agent"
- Model: gpt-4o or claude-sonnet-4-20250514
- + Add Tool → "Vector Store Tool" → select your Qdrant/Pinecone store
- System Prompt:
You are a knowledgeable assistant. When asked a question, first search the vector store for relevant document chunks, then answer based on what you find. If the documents don't contain the answer, say so honestly. Always cite which document you found the information in.
- Node: "AI Agent" output connects back to the Chat Trigger
- Trigger: "Chat Trigger" (gives you a chat UI at
-
Test: Upload your company handbook, product docs, or research papers. Ask domain-specific questions. The agent retrieves relevant chunks and generates accurate, cited answers.
Performance tip: For production, use Qdrant or Pinecone (persistent, fast). In-Memory is fine for testing but loses data on restart.
Step 8: Deploy and Trigger Your Agent
Your agent is useless if nobody can reach it. Here are the three most common trigger methods:
1. Webhook Trigger (API endpoint): Your agent gets a unique URL. POST JSON to it from any app — your website, a Slack bot, a mobile app, or another n8n workflow. Perfect for integrating AI into existing products.
curl -X POST https://your-n8n-instance.com/webhook/abc123 \
-H "Content-Type: application/json" \
-d '{"question": "Summarize the latest n8n release notes"}'2. Schedule Trigger (cron):
Run your agent on a timer. Example: every Monday at 9am, search news APIs for your industry, summarize findings, and email the digest. Use the "Schedule Trigger" node with cron syntax: 0 9 * * 1 (9am every Monday).
3. Chat Trigger (built-in UI): The "Chat Trigger" node gives you a ready-to-use chat interface. Share the URL with teammates, embed it in an iframe, or use it for internal tools. The UI supports streaming responses (real-time token-by-token output), file uploads, and conversation history.
Production tips:
- Set
N8N_SECURE_COOKIE=truein your Docker environment for HTTPS - Use an nginx reverse proxy with SSL for public access
- Enable authentication (basic auth or OAuth) if exposing to the internet
- Monitor token usage: n8n shows per-execution token counts in the Executions tab
- Set spending limits on your LLM provider to prevent surprise bills
Troubleshooting
"AI Agent node says 'No model selected'" → Go to the AI Agent node settings, dropdown "Model," and select a model. You may need to add credentials first (Step 3).
"Tool call failed: 401 Unauthorized" → Your API key is invalid or expired. Go to Credentials, find the relevant credential, and update the key. Test by clicking "Test" in the credential settings.
"Agent is looping and not stopping" → Increase Max Iterations if the task genuinely needs more steps, but if the agent is stuck, your system prompt may be too vague. Add explicit instructions: "After finding the answer, output it directly. Do not search again."
"Memory doesn't persist after restart" → You're using Window Buffer Memory (in-memory only). Switch to Postgres Chat Memory for persistence. Make sure the Postgres volume is mounted in Docker.
"Vector store is empty after restart" → You're using In-Memory Vector Store. Switch to Qdrant (free cloud tier) or Pinecone. Re-index your documents after switching.
"Rate limit errors from OpenAI" → Free tier has strict rate limits (3 RPM for GPT-4o-mini). Upgrade to a paid tier ($5 minimum) or add retry logic. In the OpenAI node, enable "Retry on Fail" with 3 attempts and 5-second delay.
"Docker container exits immediately"
→ Check logs: docker logs n8n. Common cause: port 5678 already in use. Change the port mapping to -p 5679:5678 or stop the conflicting process.
Related Tutorials
相关推荐
How to Build a Full-Stack App with Bolt.new? Complete 2026 Tutorial
If you want to build a full-stack web app without setting up a local dev environment, Bolt.new lets you describe your app in plain English and generates a complete React/Next.js application with database, auth, and one-click deployment — all inside your browser.
Claude Code vs GitHub Copilot vs Cursor: Which AI Coding Tool Actually Works for Indie Hackers?
After six months of daily use shipping real projects with all three tools, here is what actually matters: Claude Code is the best pure coder but costs real money. Cursor gives you the smoothest in-editor experience. Copilot is the safe default — until you hit its new AI Credits billing. This comparison covers speed, codebase understanding, real pricing, and the annoying trade-offs nobody talks about.
主题中心
AI Agent 教程与工作流指南
比新闻更常青:按步骤搭建编程 Agent、内容流水线与 n8n 自动化,并链接到真实赚钱案例。
进入「AI Agent 教程与工作流指南」 →赚钱视角
这个趋势怎么赚钱?
WayToClawEarn 的差异在可验证的赚钱案例,而不只是资讯。从这些复盘开始:
浏览全部案例 →相关教程
相关资讯
- Agent Beacon: First Open-Source Telemetry Layer for AI Coding Agents Launches
- Why Did Anthropic Open a Seoul Office During the Fable 5 Export Ban? Korea Strategy Explained
- Can a Single Web Page Hack Your AI Coding Agent? Microsoft's AutoJack Exploit Explained
- Claude Code Artifacts Turns AI Coding Sessions Into Live, Shareable Web Pages