WayToClawEarn
入门阅读约 45 分钟2026年6月20日

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:

yaml
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:

terminal
docker compose up -d

Open 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:

ComponentWhat It DoesExample
Chat Model (Brain)The LLM that reasons and decides what to doOpenAI GPT-4o, Claude Sonnet 4, Ollama Llama 4
Memory (Context)Stores conversation history so the agent remembers previous turnsPostgres Chat Memory, Window Buffer Memory
Tools (Hands)External actions the agent can call — APIs, databases, scriptsHTTP Request, Code node, Postgres node
Output ParserFormats the final responseStructured 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

  1. In n8n, click Add Workflow.
  2. Add a Webhook node as the trigger. Set HTTP Method to POST and Response Mode to Last Node.
  3. 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

  1. Drag in the AI Agent node (found under Advanced AI).
  2. Set Agent Type to Tools Agent.
  3. Drag in an OpenAI Chat Model node (or Anthropic Claude / Ollama).
  4. Connect your API key in the OpenAI node credentials.
  5. Connect the Chat Model to the AI Agent's "Chat Model" input.

3.3 Create the GitHub Tool

  1. Add an HTTP Request node. Set Method to GET and URL to:
https://api.github.com/repos/{{ $json.body.repo }}/pulls?state=open&per_page=10
  1. Add these headers:
code
Accept: application/vnd.github+json
User-Agent: n8n-ai-agent-tutorial
  1. 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

  1. Add a Slack node (Message). Authenticate with your Slack workspace.
  2. Set Channel to your target channel (e.g., #dev-updates).
  3. In the Text field, write:
code
📊 *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') }}_
  1. Connect the AI Agent output to the Slack node.

3.5 Test the Workflow

  1. Click Listen for Test Event on the Webhook node.
  2. Send a test request:
terminal
curl -X POST http://localhost:5678/webhook-test/your-webhook-path \
  -H "Content-Type: application/json" \
  -d '{"repo": "n8n-io/n8n"}'
  1. 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)

  1. Drag in a Window Buffer Memory node.
  2. Set Session Key to {{ $json.sessionId }} (or a custom identifier).
  3. Set Context Window Length to 10 (last 10 messages).
  4. 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:

  1. Drag in a Postgres Chat Memory node.
  2. Connect to a Postgres database (or use the n8n built-in SQLite).
  3. Set the Table to chat_history.
  4. 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:

caddyfile
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:

  1. Add an error workflow that sends you a Slack DM when any workflow fails.
  2. 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:

  1. Create a GitHub Personal Access Token.
  2. Add it as a Header credential in n8n.
  3. 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 CaseAdditional Tools NeededComplexity
Customer support triageGmail node + Pinecone vector storeIntermediate
Daily news digestRSS Feed Read + HTTP Request (NewsAPI) + Slack/EmailBeginner
Database query assistantPostgres/MySQL node + AI AgentIntermediate
Code review botGitHub node + Code node (run linters)Advanced
Content calendar plannerGoogle Sheets node + AI AgentBeginner

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

免责声明:本站案例均为知识分享内容,仅供灵感与参考,不构成收益承诺;由此进行的外部执行与结果请自行判断并承担相应责任。

相关推荐