n8n AI Agent 完整入门教程:从零构建智能工作流
如果你想用AI自动化任务但又不想写后端代码,n8n的AI Agent节点让你能通过拖拽画布构建智能工作流。本分步指南涵盖从Docker安装到构建一个能搜索网页、阅读文章、总结内容并保存到Google Sheets的完整智能体——全程不到30分钟。
入门 · 30 分钟 · 2026年6月30日
TL;DR
If you want to automate tasks with AI without writing a backend service, n8n's AI Agent node lets you build intelligent workflows that reason, call APIs, search the web, and send emails — all from a drag-and-drop canvas. In this tutorial, you'll build a fully functional AI agent in under 30 minutes that can search the web, summarize articles, and save results to Google Sheets. No coding required beyond basic workflow logic.
Prerequisites
Before you start, make sure you have:
- n8n installed: Self-hosted via Docker, npm, or n8n Cloud (free tier works). This tutorial uses the self-hosted Docker setup.
- An OpenAI API key (or Anthropic, Google Gemini, Ollama, DeepSeek — any LLM provider n8n supports). We use OpenAI for this guide, but the setup is identical for other providers.
- A Google account (for Google Sheets integration in the final step).
- Basic familiarity with the n8n editor canvas — you should know how to drag nodes and connect them.
Step 1: Install and Launch n8n
The fastest way to get n8n running locally is with Docker:
docker run -d \
--name n8n \
-p 5678:5678 \
-v n8n_data:/home/node/.n8n \
-e N8N_SECURE_COOKIE=false \
docker.n8n.io/n8nio/n8nOnce the container starts, open http://localhost:5678 in your browser. You'll see the n8n editor — a blank canvas with a node panel on the left.
Alternative install methods:
- npm:
npm install -g n8n && n8n start - n8n Cloud: Sign up at n8n.io — the free tier gives you 50 workflow executions per month, which is enough for testing.
First-time setup: Create an owner account when prompted. This account manages your workflows and credentials. After logging in, you'll land on the main dashboard.
Step 2: Create Your First Workflow
Click "Create Workflow" to open a blank canvas. You'll build an AI agent that:
- Receives a topic (via Webhook or Manual trigger)
- Uses an AI Agent to decide what to do
- Searches the web for information
- Summarizes the results
- Saves everything to Google Sheets
Add a trigger: Click the "+" button or press Tab to open the node panel. Search for "Manual Trigger" and add it to the canvas. This lets you test the workflow by clicking "Execute" — perfect for development.
Rename the trigger by double-clicking its title. Call it "Start Agent".
Add input fields: Click the Manual Trigger node, then under "Parameters", add an input field called topic with type "String" and a default value like "latest AI news". This is what your agent will research.
Step 3: Add the AI Agent Node
This is the core of your workflow. The AI Agent node is n8n's reasoning engine — it takes a prompt, decides which tools to use, calls them, evaluates results, and loops until it has a satisfactory answer.
Search for "AI Agent" in the node panel and drag it onto the canvas. Connect it after the Manual Trigger.
Configure the agent:
-
Prompt: This is the system instruction. Write a clear, specific prompt:
codeYou are a research assistant. When given a topic: 1. Search the web for the latest information about it. 2. Read the top 3 most relevant articles. 3. Write a concise summary of key findings. 4. Format the output as bullet points. Always cite your sources. -
Chat Messages: Connect this to the trigger output. Click the "Chat Messages" field, then drag the
topicfield from the Manual Trigger node's output. The agent will receive this as the user message. -
Require Specific Output: Toggle this ON and set the output type to "Text". This ensures the agent returns clean text instead of raw JSON.
How the AI Agent node works under the hood: It implements a ReAct (Reasoning + Acting) loop. The agent receives your prompt, thinks about what tool to call, executes the tool, examines the result, and decides whether to call another tool or produce a final answer. This loop continues until the agent is satisfied or hits the maximum iteration limit (default: 25).
Step 4: Connect an LLM Provider
The AI Agent needs a language model to power its reasoning. You connect this through a sub-node called the LLM Chat Model.
Click the "+" inside the AI Agent node (or drag a new node onto the "LLM" connector). Search for "OpenAI Chat Model" and add it.
Set up credentials:
- Click the OpenAI Chat Model node.
- Under "Credential for OpenAI API", click "Create New".
- Enter your OpenAI API key. Give the credential a name like "My OpenAI Key".
- Click "Save".
Model selection: Choose gpt-4o for the best quality, or gpt-4o-mini for speed and lower cost. If you're testing, gpt-4o-mini costs about $0.15 per million input tokens — a typical agent interaction costs well under $0.01.
Using other LLM providers: The setup is the same for any provider. Swap "OpenAI Chat Model" for:
- Anthropic Chat Model — Claude Sonnet 4 or Claude Opus 4
- Google Gemini Chat Model — Gemini 2.5 Pro or Flash
- Ollama Chat Model — any local model (free, private)
- DeepSeek Chat Model — budget-friendly alternative
Step 5: Give Your Agent Tools
Tools are what make the AI Agent useful. Without tools, it's just a chatbot. With tools, it can search the web, read websites, query databases, send emails, and more.
For our research agent, add these tools:
Tool 1: Web Search (SerpAPI)
Search for "SerpAPI" in the node panel and add it as a tool to the AI Agent. Connect it to the agent's "Tools" connector.
Configure SerpAPI:
- Get a free API key from serpapi.com (100 searches/month free).
- Create a credential in n8n with your SerpAPI key.
- Under "Parameters", map the
topicfrom the AI Agent's chat input to theq(query) field.
The agent will use this tool to search Google when asked to find information.
Tool 2: Read Webpage (HTTP Request)
Add an "HTTP Request" node as a tool. This lets the agent fetch and read article content.
- Method: GET
- URL: The agent will dynamically fill this based on search results. Leave it as
={{ $fromAI("url") }}— this placeholder tells the agent to pass the URL as a parameter.
Tool 3: Google Sheets (Save Results)
Add a "Google Sheets" node as the final tool. This saves the agent's research output to a spreadsheet.
- Operation: Append
- Spreadsheet ID: Create a new Google Sheet and copy its ID from the URL.
- Sheet Name: "Research Results"
- Fields to append: Map the agent's final output text.
Credential setup: You'll need to authenticate with Google. n8n supports OAuth2 — click "Connect" and follow the Google authorization flow. This one-time setup takes about 2 minutes.
How the Agent Uses Tools
When you execute the workflow, here's what happens:
- The agent receives the topic from the Manual Trigger.
- It reasons: "I need to search the web for this topic."
- It acts: Calls the SerpAPI tool with the search query.
- It observes: Reads the search results.
- It reasons again: "These 3 articles look relevant. I should read them."
- It acts: Calls the HTTP Request tool for each URL.
- It observes: Reads the article content.
- It reasons: "I have enough information. Let me summarize."
- It acts: Calls Google Sheets to save the summary.
- It returns the final result to you.
This ReAct loop is the foundation of all AI agent workflows — the agent iteratively thinks, acts, and observes until the task is complete.
Step 6: Add Memory for Context
By default, the AI Agent has no memory — each tool call is independent. For complex tasks, you want the agent to remember previous steps.
n8n offers three memory types:
- Window Buffer Memory: Remembers the last N interactions. Simple and fast. Set "Context Window Length" to 10 for most use cases.
- Postgres Memory: Persistent storage for long-running conversations. Requires a Postgres database.
- MongoDB Memory: Persistent storage using MongoDB.
For our research agent, Window Buffer Memory is perfect:
- Click the AI Agent node.
- Find the "Memory" section.
- Select "Window Buffer Memory".
- Set Context Window Length to
5.
This means the agent remembers the last 5 steps in the conversation. When it reads the third article, it still knows what the first two were about — leading to better summaries.
When to use persistent memory: If you're building a chatbot that maintains context across days (like a customer support agent), use Postgres or MongoDB memory. For single-session workflows like ours, window buffer is sufficient.
Step 7: Test and Deploy
Test the workflow: Click the "Execute Workflow" button at the bottom of the canvas. The Manual Trigger will fire, and you'll see each node light up green as it executes. The execution log on the right shows exactly what the agent is thinking and doing.
What to expect: A typical execution takes 30-90 seconds depending on how many articles the agent reads. You'll see:
- ✅ Manual Trigger fires
- ✅ AI Agent begins reasoning
- ✅ SerpAPI returns search results
- ✅ HTTP Request fetches article content
- ✅ Google Sheets appends the summary
Open your Google Sheet — you should see a new row with your topic and a bulleted summary.
Deploy to production: Once tested, switch the Manual Trigger to a Webhook trigger for API access, or a Schedule trigger to run automatically:
- Webhook: Replace Manual Trigger with "Webhook" node. n8n generates a unique URL. Send POST requests with
{"topic": "your query"}to trigger the agent. - Schedule: Replace with "Schedule Trigger" and set a cron expression like
0 9 * * *to run daily at 9 AM. - Email Trigger: Use the "Email Trigger (IMAP)" node to fire the agent when you send an email with a specific subject line.
Cost management tip: Set a max token limit in the LLM Chat Model node (e.g., 4096 output tokens). This prevents runaway costs if the agent loops unexpectedly. For a typical research query with gpt-4o-mini, expect to spend $0.005-$0.02 per execution.
Troubleshooting
AI Agent timed out
Increase the "Max Iterations" setting in the AI Agent node from 25 to 50. If the agent is reading many articles, it needs more iterations. Also check that your tools are returning results — a broken tool causes the agent to retry indefinitely.
429 Too Many Requests" from OpenAI
You've hit a rate limit. Add a Wait node between the AI Agent and your LLM Chat Model (set to 2 seconds). For production workloads, upgrade your OpenAI tier or use multiple API keys with round-robin.
Google Sheets authentication failed
Re-authenticate: go to Settings → Credentials, find your Google Sheets OAuth2 credential, and click "Reconnect". Google tokens expire after 7 days if not used.
Agent returns irrelevant results
Refine your system prompt. Be more specific about what you want. Instead of "search the web," write "search for the most recent news articles about X from the past week." Instead of "write a summary," write "write a 3-bullet summary focusing on key facts and dates."
SerpAPI returned no results
Your search query might be too specific. Add a Code node before the SerpAPI tool that appends "site:reputable-domain.com" or broadens the query. Alternatively, switch to the Google Custom Search node (requires a Google API key but has higher rate limits on the free tier).
Related Tutorials
相关推荐
AI Coding Agents Complete Guide: Setup, Security, Workflow & Case Studies
If you are researching AI coding agents and want to know which one to use, how to set it up safely, and what real developers are building with them — this hub organizes every tutorial, case study, and comparison we have published. Start with the decision guide below to find the right path for your skill level and goals.
AI微SaaS FAQ:25个常见问题完整解答(2026)
关于构建和盈利AI微SaaS产品你需要知道的一切。本FAQ涵盖创意生成、技术栈选择、定价策略、零预算营销、法律考虑,以及从$100到$10K MRR的扩展路径。基于使用Claude Code、Cursor等AI编码工具的成功独立构建者的真实案例研究和数据。
主题中心
AI Agent 教程与工作流指南
比新闻更常青:按步骤搭建编程 Agent、内容流水线与 n8n 自动化,并链接到真实赚钱案例。
进入「AI Agent 教程与工作流指南」 →赚钱视角
这个趋势怎么赚钱?
WayToClawEarn 的差异在可验证的赚钱案例,而不只是资讯。从这些复盘开始:
浏览全部案例 →