How to Build an AI Agent in n8n: Complete Beginner Guide 2026
If you want to build an AI agent in n8n that fetches GitHub pull requests and sends Slack summaries — this tutorial gives you the complete step-by-step guide, from Docker self-hosting to a deployed agent with memory, tools, error handling, and production security in about 45 minutes.
入门 · 45 分钟 · 2026年6月20日
TL;DR
If you are searching for "how to build an AI agent in n8n," here is the direct answer: you connect an AI Agent node to a chat model (OpenAI, Claude, or local Ollama), attach tools (HTTP Request, Code node, database queries) that the agent can call autonomously, and add optional memory with a database node so the agent remembers conversation context. This tutorial walks you through the entire flow — from Docker self-hosting to a deployed AI agent that sends Slack summaries of GitHub pull requests — in about 45 minutes.
Prerequisites
- A computer with Docker installed (works on macOS, Windows, or Linux)
- An OpenAI API key (or Anthropic Claude / Ollama for local models)
- Basic familiarity with web APIs and JSON (helpful but not required)
- No coding experience needed — n8n's visual editor handles logic
Step 1: Self-Host n8n with Docker (5 Minutes)
Self-hosting n8n gives you unlimited workflow executions for free, full data privacy, and access to community nodes. The cloud version limits you to 5 active workflows on the free tier.
Create a docker-compose.yml file:
version: '3.8'
services:
n8n:
image: n8nio/n8n:latest
container_name: n8n
ports:
- "5678:5678"
environment:
- N8N_SECURE_COOKIE=false
- N8N_HOST=localhost
- N8N_PORT=5678
- N8N_PROTOCOL=http
- NODE_ENV=production
- DB_TYPE=sqlite
volumes:
- n8n_data:/home/node/.n8n
restart: unless-stopped
volumes:
n8n_data:Run it:
docker compose up -dOpen http://localhost:5678, create your admin account, and you are in.
Production tip: For real deployments, switch DB_TYPE to postgresdb and add N8N_ENCRYPTION_KEY (a random 32-character string) to encrypt stored credentials. Without this, API keys are stored in plain text.
Step 2: Understand the AI Agent Node Architecture
The AI Agent node in n8n has four core components that work together like a real assistant:
| Component | What It Does | Example |
|---|---|---|
| Chat Model (Brain) | The LLM that reasons and decides what to do | OpenAI GPT-4o, Claude Sonnet 4, Ollama Llama 4 |
| Memory (Context) | Stores conversation history so the agent remembers previous turns | Postgres Chat Memory, Window Buffer Memory |
| Tools (Hands) | External actions the agent can call — APIs, databases, scripts | HTTP Request, Code node, Postgres node |
| Output Parser | Formats the final response | Structured Output Parser (JSON schema) |
The agent works through a reasoning loop: it receives input → the chat model decides which tool to call → the tool executes → the result goes back to the model → the model decides the next step or returns a final answer. This loop continues until the model determines the task is complete.
Critical insight: The quality of your agent depends more on tool design than model choice. A well-designed tool with clear descriptions and proper error handling will outperform a vague prompt to a top-tier model every time.
Step 3: Build Your First AI Agent — GitHub PR Summarizer
We will build an agent that, given a GitHub repository name, fetches open pull requests and sends a summary to Slack. This teaches you the three essential patterns: external API calls, data transformation, and output delivery.
3.1 Create the Workflow Trigger
- In n8n, click Add Workflow.
- Add a Webhook node as the trigger. Set HTTP Method to
POSTand Response Mode toLast Node. - The webhook gives you a test URL. We will send a JSON payload like
{"repo": "n8n-io/n8n"}.
3.2 Add the AI Agent and Chat Model
- Drag in the AI Agent node (found under Advanced AI).
- Set Agent Type to
Tools Agent. - Drag in an OpenAI Chat Model node (or Anthropic Claude / Ollama).
- Connect your API key in the OpenAI node credentials.
- Connect the Chat Model to the AI Agent's "Chat Model" input.
3.3 Create the GitHub Tool
- Add an HTTP Request node. Set Method to
GETand URL to:
https://api.github.com/repos/{{ $json.body.repo }}/pulls?state=open&per_page=10
- Add these headers:
Accept: application/vnd.github+json
User-Agent: n8n-ai-agent-tutorial- Connect this HTTP Request node to the AI Agent's "Tools" input. The agent can now call the GitHub API.
Important: Name your HTTP Request node descriptively (e.g., "Fetch GitHub Pull Requests"). n8n uses the node name as the tool description for the LLM. A clear name helps the model decide when to use the tool.
3.4 Add the Slack Output
- Add a Slack node (Message). Authenticate with your Slack workspace.
- Set Channel to your target channel (e.g.,
#dev-updates). - In the Text field, write:
📊 *PR Summary for {{ $json.body.repo }}*
{{ $fromAI('Summarize these pull requests in 3 bullet points. Include title, author, and status.', $json.body) }}
_Generated by n8n AI Agent at {{ $now.format('YYYY-MM-DD HH:mm') }}_- Connect the AI Agent output to the Slack node.
3.5 Test the Workflow
- Click Listen for Test Event on the Webhook node.
- Send a test request:
curl -X POST http://localhost:5678/webhook-test/your-webhook-path \
-H "Content-Type: application/json" \
-d '{"repo": "n8n-io/n8n"}'- Check your Slack channel — you should see a formatted summary of open PRs.
Step 4: Add Memory and Multi-Turn Conversations
The agent above is stateless — every call starts fresh. For real assistants, add memory:
4.1 Window Buffer Memory (Simple)
- Drag in a Window Buffer Memory node.
- Set Session Key to
{{ $json.sessionId }}(or a custom identifier). - Set Context Window Length to
10(last 10 messages). - Connect it to the AI Agent's "Memory" input.
This keeps the last 10 messages in context. Good for short sessions, but resets when the workflow restarts.
4.2 Postgres Chat Memory (Persistent)
For persistent memory across sessions:
- Drag in a Postgres Chat Memory node.
- Connect to a Postgres database (or use the n8n built-in SQLite).
- Set the Table to
chat_history. - When the agent responds, the entire conversation is saved.
With memory, you can ask follow-up questions like "Show me only PRs from last week" and the agent remembers the repository from the previous turn.
Step 5: Deploy to Production — Security and Reliability
5.1 Set Up HTTPS
For production, put n8n behind a reverse proxy with HTTPS. Using Caddy:
n8n.yourdomain.com {
reverse_proxy localhost:5678
}Update N8N_HOST to your domain and N8N_PROTOCOL to https.
5.2 Secure API Keys
Always use n8n Credentials — never hard-code API keys in nodes. Go to Settings → Credentials and create entries for OpenAI, Slack, GitHub, and any other services. Reference them by name in your nodes.
5.3 Error Handling
Add an Error Trigger node to catch failures:
- Add an error workflow that sends you a Slack DM when any workflow fails.
- In the main workflow's settings, set "Error Workflow" to this alert workflow.
5.4 Rate Limiting
The GitHub API allows 60 unauthenticated requests per hour. For production:
- Create a GitHub Personal Access Token.
- Add it as a Header credential in n8n.
- Use it in the GitHub HTTP Request node's Auth settings.
5.5 Activate the Workflow
Toggle the Active switch in the top-right corner. n8n starts the webhook listener and keeps it running. Your AI agent is now live.
Real-World Extensions
Once you have the basic agent working, you can extend it with these patterns:
| Use Case | Additional Tools Needed | Complexity |
|---|---|---|
| Customer support triage | Gmail node + Pinecone vector store | Intermediate |
| Daily news digest | RSS Feed Read + HTTP Request (NewsAPI) + Slack/Email | Beginner |
| Database query assistant | Postgres/MySQL node + AI Agent | Intermediate |
| Code review bot | GitHub node + Code node (run linters) | Advanced |
| Content calendar planner | Google Sheets node + AI Agent | Beginner |
Troubleshooting
AI Agent did not call any tools
Cause: The model cannot match the user request to any available tool. Fix: (1) Rename your tool nodes to be more descriptive — "Fetch GitHub Pull Requests" is better than "HTTP Request". (2) Add descriptions in the tool node's "Description" field. (3) Check that the model supports function calling (GPT-4o and Claude Sonnet do; older models may not).
Memory is not persisting between calls
Cause: The session key is changing between requests. Fix: Use a consistent sessionId in your webhook payload, or use a fixed key for single-user agents. For Postgres Chat Memory, verify the database connection works by running a test query.
Workflow times out on large responses
Cause: The model is generating very long responses or the API is slow. Fix: (1) Set a lower max_tokens in the chat model node (1024–2048 is usually enough). (2) Add a timeout setting in the HTTP Request node. (3) For large GitHub repos with 50+ PRs, reduce per_page to 5.
Docker container keeps restarting
Cause: Port conflict or permission issue. Fix: (1) Check if port 5678 is already in use: lsof -i :5678. (2) Ensure the n8n_data volume has write permissions. (3) Run docker compose logs n8n to see the error message.
401 Unauthorized on OpenAI API
Cause: Invalid or expired API key. Fix: (1) Regenerate your key at platform.openai.com/api-keys. (2) Check your usage limits and billing status. (3) Verify the key in n8n Credentials has no extra whitespace.
Slack message shows raw JSON instead of formatted text
Cause: The $fromAI() function output is not being parsed correctly. Fix: Wrap it in a Code node that extracts $json.output or use {{ $fromAI('...').output }} if your n8n version supports property access on expressions.
Related Tutorials
相关推荐
How to Automate PR Code Reviews with Claude Code CLI + GitHub Actions
If you want Claude Code to automatically review every pull request before a human sees it — catching bugs, security issues, and performance problems — this tutorial gives you a complete CI pipeline in 35 minutes: prompt template, GitHub Actions workflow, and a Python script that posts line-level comments back to your PR.
How to Automate Daily AI Research with n8n and DeepSeek: Zero-Code Guide
If you want an automated daily AI research digest without writing code, this tutorial walks you through a complete n8n workflow in 30 minutes. Use the Schedule Trigger to fetch headlines from NewsAPI, pipe them through DeepSeek for intelligent summarization, and deliver the finished digest to Slack, email, or Notion — all drag-and-drop.
主题中心
AI Agent 教程与工作流指南
比新闻更常青:按步骤搭建编程 Agent、内容流水线与 n8n 自动化,并链接到真实赚钱案例。
进入「AI Agent 教程与工作流指南」 →赚钱视角
这个趋势怎么赚钱?
WayToClawEarn 的差异在可验证的赚钱案例,而不只是资讯。从这些复盘开始:
浏览全部案例 →相关教程
相关资讯
- Claude Code Artifacts Turns AI Coding Sessions Into Live, Shareable Web Pages
- How Do You Track Codex CLI Token Usage? Codex v0.140 Adds /usage, Claude Code Import, and Session Deletion
- Can Claude Design Replace Your Design Tool? Anthropic Adds Code Round-Trips, Figma Imports, and 2x Tokens
- Will Claude Require ID Verification? Anthropic's New Privacy Policy Explained