How to Build Your First AI Agent with n8n: A Step-by-Step Guide
If you want to build an AI agent without writing code, n8n is the fastest path. This guide walks you through installing n8n, configuring the AI Agent node with an LLM, adding memory for conversation context, connecting tools like web search and email, and deploying to production. You will build two complete agents — an email summarizer and a web research assistant — in under 30 minutes, with zero coding required.
入门 · 30 分钟 · 2026年7月2日
TL;DR
If you are searching for "how to build an AI agent with n8n," the short answer is: install n8n (Docker or npm), add an AI Agent node, connect it to an LLM (OpenAI, Claude, or a local model via Ollama), attach tools like web search or email, and optionally add a Memory node for conversation context. Your agent will be running in under 30 minutes — no coding required.
What You'll Learn
By the end of this tutorial, you will:
- Understand what an AI agent is and how n8n's agent architecture works
- Install n8n locally or on a server using Docker
- Configure the AI Agent node with an LLM provider
- Add Memory so your agent remembers conversation context
- Connect Tools (web search, HTTP requests, email) to give your agent real-world capabilities
- Build two complete AI agents: an email summarizer and a web research assistant
- Troubleshoot the five most common errors (API key issues, memory loss, infinite loops)
Prerequisites
- A computer running macOS, Windows, or Linux
- An API key from at least one LLM provider (OpenAI, Anthropic, or Google AI Studio)
- Docker Desktop installed (recommended) — or Node.js 18+ for npm install
- Basic familiarity with the JSON data format (you will inspect node outputs)
- No coding experience required — n8n is fully visual
Cost note: Running this tutorial with OpenAI's GPT-4o-mini will cost under $0.05. Claude Haiku and Gemini Flash are similarly inexpensive.
Step 1: Install and Start n8n
n8n can be installed several ways. Docker is the fastest path to a working instance.
Option A: Docker (Recommended)
docker run -d \
--name n8n \
-p 5678:5678 \
-v n8n_data:/home/node/.n8n \
-e N8N_SECURE_COOKIE=false \
docker.n8n.io/n8nio/n8nWait 10 seconds, then open http://localhost:5678 in your browser. Create an owner account with your email and a password.
Option B: npm (if you already have Node.js)
npm install -g n8n
n8n startOption C: n8n Cloud
If you prefer not to self-host, sign up at n8n.cloud for a free trial. The visual editor is identical — all steps in this tutorial work the same way.
Once the editor loads, you will see the workflow canvas. On the left is the Nodes panel; the center is your blank canvas. Every automation starts with a trigger node.
Step 2: Understand the AI Agent Architecture
Before connecting nodes, let us clarify what happens under the hood. An n8n AI agent is a workflow that follows this pattern:
## Trigger] → [AI Agent] → [LLM Model] → [Memory (optional)] → [Output
↕
## Tools: Web Search, HTTP, Email, Database, etc.The AI Agent node is the brain. It receives a user query (from the trigger), sends it to the LLM, and decides whether to use a tool. If the LLM says "I need to search the web," the agent calls the web search tool, feeds the result back to the LLM, and repeats until the LLM produces a final answer. The Memory node stores conversation history so the agent can reference earlier exchanges.
Three agent types are available in n8n:
| Agent Type | Best For | Reasoning |
|---|---|---|
| Tools Agent | Most use cases | Calls tools iteratively, handles multi-step tasks |
| ReAct Agent | Complex reasoning | Thought-Action-Observation loop, better for multi-hop questions |
| OpenAI Functions Agent | OpenAI models only | Uses native function calling, fastest for simple tool use |
| SQL Agent | Database queries | Specialized for generating and executing SQL |
For this tutorial, use the Tools Agent — it works with any LLM provider and handles the widest range of tasks.
Step 3: Build Your First Agent — Email Summarizer
Let us build a simple agent that takes an email body as input and returns a concise summary with action items.
3.1 Add a Manual Trigger
Click the + button on the canvas or press Tab. Search for "Manual" and select the Manual Trigger node. This lets you execute the workflow by clicking "Test workflow" — perfect for development.
3.2 Add the AI Agent Node
Click the + below the Manual Trigger. Search for "AI Agent" and add it.
In the AI Agent configuration panel:
- Agent Type: Select Tools Agent
- Prompt: Leave the system message as default for now
3.3 Connect an LLM
The AI Agent node needs a "brain." Click the + inside the agent's LLM Model field.
- For OpenAI: Select "OpenAI Chat Model," create new credentials by pasting your API key, and choose the model (
gpt-4o-miniis fast and cheap) - For Claude: Select "Anthropic Chat Model," add your API key, and pick
claude-3-haiku - For Google: Select "Google Gemini Chat Model," add your API key, and pick
gemini-1.5-flash
3.4 Add Memory (Optional but Recommended)
Without memory, the agent treats every message as a fresh conversation. Add a Window Buffer Memory node:
- Click + on the AI Agent's Memory connector
- Search for "Window Buffer Memory" and add it
- Set Session Key to
email_session(this groups messages by user) - Set Context Window Length to
10(keeps the last 10 exchanges)
3.5 Wire the Input
Create a way to pass email text into the agent:
- Add a Set node between the Manual Trigger and the AI Agent
- In the Set node, create a field called
email_bodywith a sample value:
Hey team, just a reminder that the Q3 review meeting is scheduled for Friday at 2pm in Conference Room B. Please bring your department summaries and be prepared to discuss budget allocations for the next quarter. Also, the office will be closed on Monday for the holiday. Thanks, Sarah
- In the AI Agent Prompt field, replace the default with:
You are an email summarizer. Given the email body below, return:
1. A one-sentence summary
2. Key action items as bullet points
3. Any dates or deadlines mentioned
Email body: {{ $json.email_body }}3.6 Test the Agent
Click the Test workflow button at the bottom of the screen. n8n will execute the workflow and show each node's output. Click on the AI Agent node to see the LLM's response — you should get a clean summary with action items.
What just happened: The agent received your email text, passed it to the LLM with the summarization prompt, and returned structured output. With memory enabled, if you run it again with a follow-up email, the agent will reference context from the first run.
Step 4: Build a Web Research Agent with Tools
Now let us build a more capable agent that can search the web, browse pages, and compile research — all autonomously.
4.1 Create a New Workflow
Click the n8n logo to return to the dashboard, then New Workflow.
4.2 Set Up the Trigger and Agent
- Add a Manual Trigger node
- Add an AI Agent node (Tools Agent type)
- Attach an LLM (same as before)
- Add Window Buffer Memory (Session Key:
research_session)
4.3 Add Tools — Web Search and HTTP Request
The agent needs hands. Add two tools:
Tool 1: SerpAPI (Google Search)
- Click + on the AI Agent's Tools connector
- Search for "SerpAPI" and add it
- Create credentials: sign up at serpapi.com (free tier: 100 searches/month), paste your API key
- This tool lets the agent search Google and retrieve results
Tool 2: HTTP Request (Web Scraping)
- Click + on the AI Agent's Tools connector again
- Search for "HTTP Request" and add it
- Set Method to
GET - Leave URL empty — the agent will fill it in dynamically
- Set Response Format to
String(the agent reads raw HTML)
4.4 Configure the Agent Prompt
In the AI Agent's Prompt field:
You are a research assistant. When given a topic, you should:
1. Search the web for recent, credible sources
2. Read the most relevant pages
3. Compile a structured research brief with:
- Key findings (3-5 bullet points)
- Source URLs
- Any conflicting viewpoints
- A "confidence level" assessment (high/medium/low)
Always cite your sources with URLs. If you cannot find information, say so honestly.
Research topic: {{ $json.query }}4.5 Add Input and Test
- Add a Set node before the AI Agent
- Create a field
querywith a test topic:"AI agent frameworks comparison 2026" - Click Test workflow
The agent will:
- Call SerpAPI to search for "AI agent frameworks comparison 2026"
- Pick relevant results from the search output
- Use the HTTP Request tool to fetch page content
- Process the content through the LLM
- Return a structured research brief
This may take 30-60 seconds depending on how many pages the agent decides to visit. You can watch each tool call in the execution log.
Step 5: Deploy to Production
Once your agent works locally, here is how to make it production-ready:
5.1 Switch the Trigger
Replace the Manual Trigger with a real one:
- Webhook: Accept HTTP POST requests — ideal for integrating with other apps
- Schedule: Run on a cron schedule (hourly, daily)
- Email Trigger (IMAP): Watch an inbox and process new emails automatically
- Form Trigger: Accept submissions from an n8n form
For the email summarizer, use the Email Trigger (IMAP) node. For the research agent, use a Webhook node — then you can POST research queries from Slack, a dashboard, or any HTTP client.
5.2 Add Error Handling
Production agents break in predictable ways. Add an Error Trigger workflow:
- Create a new workflow with an Error Trigger node
- Connect it to an Email node (or Slack/Discord) to notify you when any workflow fails
- In the original workflow's settings, set Error Workflow to this new workflow
5.3 Set Resource Limits
In the AI Agent node settings under Options:
- Max Iterations: Set to
8(prevents infinite loops — the agent retries tool calls if results are unclear) - Timeout: Set to
300seconds (5 minutes max per execution)
5.4 Use Environment Variables
Never hardcode API keys in production workflows. In your Docker command or .env file:
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
SERPAPI_API_KEY=...In n8n, reference them as {{ $env.OPENAI_API_KEY }} in credential fields.
Step 6: Advanced Patterns
Once you are comfortable with basic agents, try these patterns:
Multi-Agent Orchestration
Chain multiple AI Agent nodes together. For example:
## Web Research Agent] → [Summarizer Agent] → [Fact-Checker Agent] → [Report Writer AgentEach agent specializes in one task and passes structured output to the next. Add Split In Batches and Merge nodes for parallel processing.
Human-in-the-Loop
Add a Wait node that pauses execution and sends a message to Slack or Discord for human approval before the agent takes action — critical for email sending agents or database write operations.
Custom Tools via Code Node
The Code node (JavaScript/Python) lets you build custom tools the AI agent can call:
// A custom tool that returns the current weather for a city
const city = $input.first().json.city;
const response = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41¤t_weather=true`);
return await response.json();Wire this code node as a tool on the AI Agent, describe its purpose in the tool's Description field, and the LLM will decide when to call it.
Troubleshooting
No model specified" Error
Symptom: The AI Agent node shows a red error badge with "No model specified."
Fix: Click the AI Agent node, find the LLM Model field, and make sure you have selected a chat model node (not left empty). The sub-node must be a Chat Model type — Basic LLM and other node types will not work here.
Agent Calls the Wrong Tool
Symptom: The agent uses the HTTP Request tool when you wanted it to use SerpAPI.
Fix: Each tool node has a Description field. Write a clear one-sentence description of what the tool does and when to use it. The LLM reads these descriptions to decide which tool to call. Example: "Use this tool to search Google for current information. Use it when the user asks about recent events, news, or facts you do not already know."
Agent Gets Stuck in a Loop
Symptom: The workflow runs for minutes, repeatedly calling the same tool without producing output.
Fix:
- Set Max Iterations to 5-8 in the agent node options (prevents runaway loops)
- Check the tool's output format — if the LLM cannot parse the JSON, it will keep retrying. Add a Code node after the tool to clean up the output before it goes back to the agent
- In the AI Agent prompt, add: "If a tool returns no useful information after 2 attempts, stop and report what you have found so far."
Memory Not Persisting Between Runs
Symptom: The agent does not remember previous conversations when you test again.
Fix:
- Make sure the Session Key in the Memory node matches across runs
- In Manual Trigger mode, each "Test workflow" click creates a new session by default. Add a Chat Trigger node instead for persistent conversation testing
- For production, use Postgres as the memory backend instead of the default in-memory buffer (configure in n8n's
DB_SQLITE_*orDB_POSTGRESDB_*environment variables)
Rate Limiting / "429 Too Many Requests
Symptom: The agent fails with an HTTP 429 error from the LLM provider.
Fix:
- Reduce Max Iterations so the agent makes fewer API calls per run
- Add a Wait node between the AI Agent and LLM with a 2-second delay
- For OpenAI, check your usage tier at platform.openai.com — free tier accounts have low rate limits (3 RPM for some models)
- Switch to a model with higher rate limits (GPT-4o-mini has higher limits than GPT-4o)
Related Tutorials
相关推荐
Build an AI Agent in n8n: Complete Step-by-Step Tutorial
If you want to automate tasks with AI without writing backend code, n8n's AI Agent node lets you build intelligent workflows from a drag-and-drop canvas. This step-by-step guide covers everything from Docker installation to a working agent that searches the web, reads articles, summarizes content, and saves results to Google Sheets — all in under 30 minutes.
How to Use Bolt.new? Build Full-Stack Apps From Your Browser
Bolt.new turns natural language descriptions into working full-stack web applications in under 60 seconds, all inside your browser tab. No local setup, no terminal, no IDE required. This 2026 guide covers everything from writing your first effective prompt to deploying production-ready apps, managing tokens, connecting external databases, and knowing when Bolt.new is (and is not) the right tool for your project.
主题中心
AI Agent 教程与工作流指南
比新闻更常青:按步骤搭建编程 Agent、内容流水线与 n8n 自动化,并链接到真实赚钱案例。
进入「AI Agent 教程与工作流指南」 →赚钱视角
这个趋势怎么赚钱?
WayToClawEarn 的差异在可验证的赚钱案例,而不只是资讯。从这些复盘开始:
浏览全部案例 →相关教程
相关资讯
- Claude Fable 5 Is Back: Export Controls Lifted After 18 Days, Lasting Impact on AI Coding
- Claude Code Hid User Fingerprints in System Prompts: What the Steganography Code Actually Does
- Claude Sonnet 5 Is Now Default in Claude Code: 85.2% SWE-bench at $2/$10
- X Launches Hosted MCP Servers: What First-Party MCP Means for AI Coding Agents