How to Build an AI Agent in n8n: Memory, Tools and LangChain
Build an n8n AI agent that holds up in practice: the AI Agent node, chat models, memory, tool-calling, structured output and where agents should stop.
Executive Summary: An n8n AI agent is an AI Agent node connected to three kinds of sub-nodes: a chat model, a memory and a set of tools. The model decides which tools to call, n8n runs them and the loop continues until the agent can answer. I build a practical agent step by step, explain how memory and tool-calling really work, and show where an agent beats a fixed workflow and where it does not. The running example is my Telegram-driven editorial pipeline, grown from a single model call into an agent with tools.
My Chat-Ops Editorial Pipeline began with one model call. A Telegram message arrived, a prompt turned it into a draft outline, and the result went to the CMS. It worked, but it was rigid. Every brief followed the same path, whether it needed research, a check against existing posts or nothing at all.
The obvious next step was an agent: let the model decide whether to search, whether to look up related articles and when the draft was ready. That move taught me more about agents than any tutorial, mostly about where to give the model freedom and where to take it away.
This guide follows the same path. It is written for engineers who know what a language model is and want to build an n8n AI agent that behaves predictably. If the underlying concepts of chains and prompts are new, my LangChain 101 post covers the foundations that n8n’s AI nodes are built on.
The Anatomy of an n8n AI Agent
Structurally, an agent in n8n is a cluster: one root node with sub-nodes attached underneath. The root is the AI Agent node. The sub-nodes give it capabilities.
| Part | n8n node | Job |
|---|---|---|
| Trigger | Chat Trigger, Webhook, Telegram Trigger or any other trigger | Delivers the user’s message |
| Brain | AI Agent node with a chat model sub-node | Reads the input, decides what to do next |
| Memory | Simple Memory, Postgres Chat Memory, Redis Chat Memory and others | Keeps recent conversation turns |
| Tools | HTTP Request Tool, Call n8n Workflow Tool, app nodes used as tools | Lets the agent act and fetch information |
| Output parser (optional) | Structured Output Parser | Forces the final answer into a JSON shape |
At run time, the AI Agent node runs a loop. It sends the conversation, the system message and the tool descriptions to the model. If the model asks for a tool, n8n runs that tool and feeds the result back. The loop ends when the model produces a final answer or hits the iteration limit. The Tools Agent documentation describes each option on the node.
Step 1: Start with a Trigger and a Model
For learning and internal tools, the Chat Trigger is the fastest start. It gives you a chat window in the editor and a public or authenticated chat URL. In my pipeline, the Telegram Trigger plays the same role, passing the message text into the agent.
Attach a chat model sub-node to the AI Agent node and choose your provider: OpenAI, Anthropic, Google, Mistral, a local model through Ollama and others. Pick the model on behaviour, not hype. Tool-calling reliability varies more between models than raw writing quality does. Test your actual tools with two or three candidates before you commit.
Step 2: Write a System Message Like a Job Description
The system message is where most agents succeed or fail. Vague instructions produce vague behaviour, so write it like a job description for a careful new hire.
You are an editorial assistant for a technical blog.
Your job: turn a short brief into a structured outline.
Rules:
- Use the search_posts tool before outlining, to avoid duplicating existing articles.
- Use the fetch_reference tool only for links included in the brief.
- Never invent statistics, quotes or sources.
- If the brief is unclear, ask one clarifying question instead of guessing.
Output: a title, a one-line angle and 5 to 8 section headings.
First, notice the structure: role, goal, explicit tool rules, prohibitions and the expected output. Each tool rule tells the model when to use a tool, not just that it exists. That single habit removes a large share of pointless tool calls.
Step 3: Give the Agent Memory, Carefully
Without memory, each message is a fresh start. With memory, the n8n AI agent can handle follow-ups such as “make the third section shorter”.
Simple Memory keeps the last few exchanges in n8n itself, keyed by a session ID. The Chat Trigger provides that ID automatically; with Telegram, the chat ID is a natural session key. Simple Memory is fine for experiments, but it does not suit production in queue mode, because workers do not share it. For production, use Postgres Chat Memory or Redis Chat Memory, so any worker can load the conversation.
Also, keep the window small. A context window of a handful of turns is usually enough. Larger windows cost more tokens on every call and often make the agent worse, because old instructions compete with new ones. The memory documentation explains how the different memory nodes store and retrieve messages.
Step 4: Tools Are Where Agents Become Useful
An agent without tools is just a chat model with extra steps. Tools let it look things up and take actions. n8n offers three main ways to provide them.
- App nodes as tools. Many regular nodes, such as Google Sheets, Slack or the Data Table node, can attach as tools. The
$fromAI()function lets the model fill specific parameters, while you fix the rest. - HTTP Request Tool. Calls any API, with credentials stored safely in n8n.
- Call n8n Workflow Tool. Runs a whole sub-workflow as a tool. This is the most powerful option, because the sub-workflow can validate input, call several systems and handle errors before returning a clean result.
In my editorial pipeline, the most valuable tool is a sub-workflow that searches existing posts and returns titles and URLs. That one tool keeps the agent from proposing topics I have already covered. It also showed me a design rule: tools should return small, structured results, not raw API dumps that flood the context.
Write tool descriptions for the model
Remember that the model chooses tools based on their names and descriptions. “search_posts: Search published blog posts by keyword. Returns up to 5 titles and URLs.” beats “Tool 1”. Be specific about inputs, outputs and when the tool is appropriate.
Step 5: Constrain the Output
Free text is fine for chat. However, for anything downstream, such as writing to a CMS, you want structure. Enable the option to require a specific output format and attach a Structured Output Parser with a JSON schema.
{
"type": "object",
"properties": {
"title": { "type": "string" },
"angle": { "type": "string" },
"sections": {
"type": "array",
"items": { "type": "string" },
"minItems": 5,
"maxItems": 8
}
},
"required": ["title", "angle", "sections"]
}
After that, validate the parsed result in a normal node before you use it. Models occasionally return output that parses but does not make sense, such as an empty title. A cheap check prevents a broken draft from reaching the CMS.
Step 6: Set Limits Before You Publish
An n8n AI agent can loop, call tools repeatedly and burn tokens. Set limits early.
- Max iterations. Keep it low for simple agents. If an agent needs many iterations, the task is probably too broad.
- Timeouts on tools. Slow tools stall the whole loop.
- Read-only tools by default. Give write access only where it is required, and consider a human approval step for anything irreversible.
- Return intermediate steps during development, so you can see which tools the agent called and why.
The production checklist in my post on LLM app cost, caching, retries and safety applies directly to agents, and it is worth a read before your first launch.
Debugging an Agent That Misbehaves
Sooner or later, an n8n AI agent will do something odd: skip a tool it should use, call the same tool five times or answer confidently without checking anything. Debugging this feels different from debugging a normal workflow, but the method is similar.
- Read the trace first. Open the execution and inspect the agent node’s logs. With intermediate steps enabled, you can see every tool call, its input and its result.
- Check the tool result, not just the call. Many “wrong” answers come from a tool that returned an error message or an empty list, which the model then interpreted creatively.
- Tighten the tool description. If the agent picks the wrong tool, the descriptions probably overlap. Make each one say clearly when to use it and when not to.
- Shrink the task. If the agent loops, the goal is often too broad. Split it, or move a step out of the agent into the workflow.
- Pin the input. Pin a problematic message on the trigger, then rerun while you change the prompt. Change one thing at a time.
Keep a small set of difficult briefs as test cases. In my pipeline, these include a vague one-line brief, a brief that duplicates an existing post and a brief with a broken reference link. Rerunning them after every prompt change catches regressions early. An n8n data table works well as the home for these cases, as I described in the n8n data tables guide.
Code still has a role, too. Small Code nodes that clean tool results or validate the agent’s output keep the model’s job narrow. The Code node guide covers how to write those safely.
When an Agent Is the Wrong Choice
The honest lesson from my pipeline: most of it did not need an agent. Formatting the outline, saving the draft and sending the Telegram confirmation are fixed steps. Only two decisions benefited from the model’s judgement: whether research was needed and whether the topic duplicated an existing post.
Therefore, the final design is a workflow with a small agent inside it, not an agent that runs everything. The workflow controls the order and the side effects. The agent handles the judgement calls and returns structured output. That split keeps costs predictable and failures easy to trace.
A good test is to ask whether you could draw the process as a flowchart. If you can, build the flowchart and use a single model call where judgement is needed. Reach for an agent only when the path genuinely depends on what the model discovers along the way. I explore this further in a later article on AI enrichment workflows, which are often the better first step.
Frequently Asked Questions
Which model is best for an n8n AI agent?
The one that calls your tools reliably at an acceptable cost. Test two or three providers with your real tools and prompts, because tool-calling behaviour varies a lot between models.
Does an n8n AI agent remember previous conversations?
Only if you attach a memory sub-node and pass a consistent session ID. Use a database-backed memory, such as Postgres Chat Memory, for production and queue mode.
Can an n8n AI agent call other workflows?
Yes. The Call n8n Workflow Tool runs a sub-workflow as a tool. It is the best way to give an agent complex, validated capabilities.
Give the Model Judgement, Not Control
Building an n8n AI agent takes an afternoon. Building one you trust takes clear instructions, small and well-described tools, durable memory, structured output and firm limits. Above all, it takes restraint: let the workflow own the process and let the agent own only the decisions that truly need a model.
Last updated on 29 November 2026