Skip to content
Wasevo
BlogAI & Automation 15 min read

n8n AI agent: build one that handles real exceptions

How to build an n8n AI agent that holds up: what the AI Agent node can do reliably, how it fails, the guardrails to add, and when a fixed workflow is better.

Haseeb RazaHaseeb RazaWeb & AI Systems Lead
Updated
n8n AI agent: build one that handles real exceptions

Summarize with:

Share:

An n8n AI agent is an AI Agent node with a chat model, at least one tool and optional memory, where the model chooses which tool to call. It stays reliable when its actions are narrow, its output is validated, risky tools wait for a person and every failure has a route (n8n docs, checked 13 November 2026).

To build a first agent, add a Chat Trigger, an AI Agent node, a chat model and one tool, then run it in the chat panel. n8n's AI examples show complete builds. The rest of this guide covers what to add before the agent touches real data.

Key takeaways

  • The AI Agent node needs a chat model and at least one tool. The model chooses which tool to call, so the path can change from run to run.
  • Cap the loop with Max Iterations, give the agent few tools, and validate its output before anything downstream uses it.
  • Gate any tool that sends, writes or deletes behind the Human review step. A denied call cancels the action and tells the agent.
  • Use an error workflow (an Error Trigger workflow) so a failed run alerts someone instead of failing silently.
  • If the steps are known in advance, a fixed workflow with a Text Classifier or Information Extractor node follows the same path on every run, which makes it easier to reason about than an agent that chooses its own tools.

What an n8n AI agent is made of

An n8n AI agent is one AI Agent node plus sub-nodes connected to it. The AI Agent node documentation says you connect a chat model and one or more tools, and the agent decides which tools to call. The node works as a Tools Agent. The pieces are:

Piecen8n node or settingWhat it doesDoc page
Chat modelOpenAI, Anthropic, Groq, Mistral Cloud or Microsoft Foundry Chat ModelReads the prompt and decides the next stepTools Agent
PromptPrompt: Take from previous node automatically (called Connected Chat Trigger Node on the Common issues page), or Define belowSupplies the user messageTools Agent
InstructionsSystem Message optionGuides the agent's decisions before the conversation startsTools Agent
ToolsCall n8n Workflow, Code, HTTP Request, app nodes and othersLet the agent read data or actHow tools work
MemorySimple Memory, Postgres Chat Memory, Redis Chat Memory and othersKeeps chat history so a conversation can continueHow memory works
Output formatRequire Specific Output Format with an output parserForces a structure on the replyTools Agent
Loop limitMax Iterations option, default 10Caps how many times the model runsTools Agent

The Tools Agent page lists OpenAI, Groq, Mistral Cloud, Anthropic and Microsoft Foundry as the supported chat models. Check that page for the current list before you plan around a different provider. The agent type setting on older nodes is deprecated, and the docs say the old version of the node (v1) will be removed in n8n 3.0, so update copied templates to the current node.

What an n8n AI agent can and cannot do reliably

n8n's evaluation docs say AI models are different from code: code is deterministic and you can reason about it, while LLM output has to be measured by running data through it (Understand why to test). Treat an agent as proven only for the narrow job you have measured.

Jobs that fit an agent:

  • Reading a free-text message and deciding which of a few read-only lookups to run.
  • Drafting a reply that a person approves.
  • Asking a follow-up question when a required value, such as an email address, is missing. The $fromAI() docs say that in chat workflows the model may ask the user for a value it cannot find.

Jobs that do not fit without a person or a fixed check in front of them:

  • Anything irreversible, such as refunds, deletions or external messages. n8n's docs list irreversible actions as a case for human review.
  • Anything where a wrong value is expensive, such as an amount, an account number or a date used in a contract.
  • Anything that has to give the same answer every time. The same input can produce different tool choices on different runs.

Agent or fixed workflow, and how to decide

Use an agent only when the next step depends on what the model finds. n8n separates chains, which follow a predetermined sequence of calls, from agents, which use a language model to determine which actions to take (What agents do).

QuestionIf yesIf no
Are the steps the same every run?Fixed workflowConsider an agent
Is the model only classifying or extracting?Text Classifier or Information Extractor nodeAgent or chain
Does the task need the model to choose between several tools?AgentFixed workflow
Does it need chat memory?Agent (chain nodes cannot use memory in n8n)Chain or fixed workflow
Can a wrong action not be undone?Human review on that tool, or keep it out of the agentAgent with validation

One layout combines the two. The Text Classifier node has a When No Clear Match option with an Output on Extra, 'Other' Branch setting, so the clear cases follow fixed branches and only the leftovers go to an agent or a person. If you are unsure whether your process is ready for either, scoping a workflow automation project covers how to list the steps first.

How an n8n AI agent fails, and what to do about it

Each failure below has a setting or node in n8n that limits it.

FailureWhat happensControl in n8n
Wrong tool callThe model picks a tool that does not fit, or calls one it should notFewer tools, clear tool names and descriptions, System Message, human review on risky tools
Hallucinated parameterThe model fills a tool field with a value it invented. The $fromAI() arguments are hints the model uses to populate data, not references to real valuesValidate before the tool runs, give each $fromAI() field a description and a type, show the reviewer the parameters, lower Sampling Temperature (the docs say a higher temperature raises the risk of hallucinations)
LoopThe agent keeps calling tools without finishingMax Iterations (default 10), lower it to the smallest number the job needs
Malformed outputThe reply is not the structure your next node expectsRequire Specific Output Format, Structured Output Parser, Auto-fixing Output Parser, then a validation step
Null promptA 400 error, "expected a string, got null", when an expression in Prompt resolves to nothing (Common issues)Make sure expressions resolve, remove null values from chatInput
Rate limitThe provider returns HTTP 429Retry On Fail, the Max Retries option on the OpenAI Chat Model node, an error workflow
Lost contextThe conversation starts freshAttach a memory node and set a Session Key. The Tools Agent page says memory does not persist between sessions
Runaway cost or run timeOne execution makes many model callsMax Iterations, Timeout Workflow, a separate model choice for simple steps

The second column describes general language-model behaviour. The third column lists the n8n settings that limit each failure.

Rate limits deserve one extra note. A 429 can mean a short rate limit or an exhausted quota, and retrying only fixes the first. Anthropic's documentation shows both: a 429 rate_limit_error can carry a retry-after header to wait on, while the 429 returned at a tier's monthly spend cap has no retry-after header and keeps failing until access resumes (checked 13 November 2026, Anthropic errors and rate limits). Alert after repeated 429s instead of retrying forever, and check your own provider's documentation for the same distinction.

Guardrails to build in, in order

Work through these in order. Steps 5 and 6 go together.

  1. Shrink the tool list. Connect only the tools the task needs. Prefer read-only tools. Wrap a write in a Call n8n Workflow Tool so a fixed sub-workflow does the writing and checks its own inputs. In production the sub-workflow must be published, or the tool call fails with "Workflow is not active and cannot be executed" (Call n8n Workflow Tool docs).
  2. Set Max Iterations. The default is 10. Lower it to what the job needs.
  3. Require a specific output format. Turn on Require Specific Output Format and connect a Structured Output Parser. With Generate from JSON Example, n8n treats every field as mandatory. With Define using JSON Schema, $ref is not supported. Still validate the result in the next node, for example with an IF node that checks the category is one you expect.
  4. Add the Guardrails node on the way in and out. The Guardrails node checks text before it reaches the model or after it comes back. Check Text for Violations sends any violating item to the Fail branch. Sanitize Text replaces detected URLs, secret keys and personal data such as phone and card numbers with placeholders. LLM-based checks such as Jailbreak need a chat model connected to the node.
  5. Put a person in front of risky tools. In the Tools Panel, find the Human review section, pick a channel (Chat, Slack, Discord, Telegram, Microsoft Teams, Gmail, WhatsApp Business Cloud, Google Chat or Outlook) and connect the gated tools. The workflow pauses and asks. n8n's pricing page lists human approval for tool calls as included on Starter, Pro and Enterprise (checked 13 November 2026, n8n pricing). Approve runs the tool, deny cancels it (Human-in-the-loop for tools).
  6. Tell the agent about the gate. The same page says to describe the human review setup in the system prompt, including which tools need approval and what to do after a denial.
  7. Route every failure. Create a workflow that starts with the Error Trigger, then choose it under Workflow Settings, Error workflow. The Handle errors gracefully page says the error workflow runs when an execution fails (Handle errors gracefully). The Error Trigger page says you cannot test error workflows by running a workflow manually, so test one with an automatic run. Use the Stop And Error node to fail on purpose when validation fails, so the error workflow fires.
  8. Choose what a failed node does. The node's On Error setting offers Stop Workflow, Continue, or Continue (using error output). Retry On Fail reruns a failed node (node settings). Use the error output to send a failed item to a human.
  9. Keep a record. Turn on Return Intermediate Steps to see the steps the agent took. The workflow settings include Save failed production executions and Save successful production executions, and Redact production execution data hides node input and output when the data is sensitive. n8n's pricing page lists log streaming under Enterprise, which n8n pricing explained covers.
  10. Test against real cases. n8n evaluations run a dataset of test cases through the workflow. The docs suggest light evaluation with a handful of examples before deployment, then a bigger dataset from production runs, adding any input that caused a bug.

Example: a support agent with an approval step

This layout is built from the documentation, not run. It shows where each control sits and has not been tested.

  1. Chat Trigger receives the message.
  2. Guardrails (Check Text for Violations) with Jailbreak and Secret Keys, and a chat model connected to its Model input, which the Jailbreak check needs. The Fail branch replies with a fixed message.
  3. Text Classifier with categories order_status and refund_request, and When No Clear Match set to the Other branch, which goes to a person.
  4. AI Agent with Require Specific Output Format turned on with the Structured Output Parser below, a chat model, Simple Memory (Session Key set to the conversation id), Max Iterations set to 4, and two tools: a read-only order lookup and a refund tool behind Human review in Slack.
  5. IF node checks the parsed output against the allowed values. Anything else goes to a fixed reply that tells the customer a colleague will follow up, and then to Stop And Error so the error workflow alerts the team. The error workflow does not run in the editor's chat test, so check it with a production run. n8n's Set a human fallback for AI workflows shows a related pattern.

The System Message tells the agent about the gate:

text
You answer order questions using the order_lookup tool.
The issue_refund tool needs human approval. If approval is denied,
tell the customer a colleague will follow up and do not retry.
Never state an order id, amount or date that did not come from a tool.

The reviewer message uses the $tool variable, which exposes the tool name and the parameters the model chose:

text
The AI wants to use {{ $tool.name }} with:
{{ JSON.stringify($tool.parameters, null, 2) }}

The Structured Output Parser uses a JSON schema so the next node can check the result:

json
{
  "type": "object",
  "properties": {
    "category": { "type": "string", "enum": ["order_status", "refund_request"] },
    "order_id": { "type": "string" },
    "reply": { "type": "string" },
    "needs_human": { "type": "boolean" }
  },
  "required": ["category", "reply", "needs_human"]
}

n8n's docs do not state that the parser enforces enum, so the IF node still checks category and needs_human itself. A parser reduces malformed output, and a separate check catches what gets through.

What an n8n AI agent costs and how long it runs

Two meters run at once. n8n bills workflow executions on its plans, and model calls are billed separately, through your own provider keys or n8n's prepaid Gateway credits. The plan side, including how executions are counted, is in n8n pricing explained, and the licence side is in Is n8n free. For a quick refresher on the tool itself, see what n8n is.

The agent runs several times inside one execution. The n8n docs say that when you execute a workflow containing an agent, the agent runs multiple times, for example a setup run, a run to call a tool and a run to evaluate the result. Each model run is a request your provider bills. That makes Max Iterations a cost control as well as a loop control. With a worst case of 10 model runs per execution at the default and 4 after you lower it, the ceiling falls by a factor of 2.5, whatever the per-run price is.

For an estimate of the agent node's cost, use this method with your provider's current price page. Use the largest token counts you see in the execution data, and add the model calls made by Guardrails, Text Classifier and the Auto-fixing Output Parser separately:

text
estimated upper cost of the agent node per execution =
  Max Iterations x (input tokens x input price + output tokens x output price)

Set a timeout too. Timeout Workflow cancels an execution after the time you set. n8n's timeouts page says that in the main process the timeout is soft and takes effect after the current node finishes, so it does not stop a long agent node mid-run. Max Iterations is the limit inside the node. On self-hosted n8n, the EXECUTIONS_TIMEOUT variable defaults to -1, which means no timeout. On n8n Cloud, each plan has its own maximum run time, listed in n8n pricing explained.

Next step

List the tools your agent would need and mark each one read-only, reversible or irreversible. Put the irreversible ones behind Human review and write the failure route before you write the prompt. To scope an n8n agent build, see n8n automation services or AI automation.

Frequently asked questions

The AI Agent node lets you build an AI agent in n8n. You connect a chat model and at least one tool, and the agent decides which tools to call to finish a task. Memory and an output parser are optional. n8n's docs say all current AI Agent nodes work as a Tools Agent.

Haseeb Raza

Written by

Haseeb Raza

Web & AI Systems Lead at Wasevo. Writes about AI agents, chatbots, WhatsApp automation and n8n workflows.

Related articles

Get new guides by email

One short email when we publish something useful. No spam; unsubscribe at any time.

n8n · AI agents · Integrations

Automate the work your team repeats.

Book a free call

15 minutes, no sales pitch