n8n ai nodes official
Use when building or editing AI inside an n8n workflow: the AI Agent node, Text Classifier, Information Extractor, Sentiment Analysis, Summarization Chain, Basic LLM Chain, embeddings, vector stores, single one-shot LLM calls, or AI media generation (image / audio / video) via the native LangChain provider nodes. Also when a first-class n8n Agent can''t do the job: trigger data mapped exactly into tool parameters, or memory shared across workflows. Triggers on any `@n8n/n8n-nodes-langchain.*` node, "AI Agent node", "LLM with tools", "tool calling", "fromAi", "system prompt", "memory window", "structured output", "outputParser", "RAG", "vector store", "embeddings", "classify with AI", "extract fields with LLM", "sentiment analysis", "summarize with LLM", "single LLM call", chat triggers with files, Slack / Discord / Teams / Telegram bot workflows, AI image / video / audio generation, or any multi-turn or one-shot LLM step in a workflow.
By- name:
- n8n-ai-nodes-official
- description:
- Use when building or editing AI inside an n8n workflow: the AI Agent node, Text Classifier, Information Extractor, Sentiment Analysis, Summarization Chain, Basic LLM Chain, embeddings, vector stores, single one-shot LLM calls, or AI media generation (image / audio / video) via the native LangChain provider nodes. Also when a first-class n8n Agent can''t do the job: trigger data mapped exactly into tool parameters, or memory shared across workflows. Triggers on any `@n8n/n8n-nodes-langchain.*` node, "AI Agent node", "LLM with tools", "tool calling", "fromAi", "system prompt", "memory window", "structured output", "outputParser", "RAG", "vector store", "embeddings", "classify with AI", "extract fields with LLM", "sentiment analysis", "summarize with LLM", "single LLM call", chat triggers with files, Slack / Discord / Teams / Telegram bot workflows, AI image / video / audio generation, or any multi-turn or one-shot LLM step in a workflow.
n8n AI nodes
The AI Agent node (@n8n/n8n-nodes-langchain.agent) is a multi-turn LLM driver with sub-nodes for the model, memory, tools, and optional output parser. It lives inside a workflow, which owns its trigger, control flow, and lifecycle.
AI Agent node or first-class n8n Agent?
"Build me an agent" means a first-class n8n Agent (n8n-agents-official) by default. Use the node when the workflow owns the control flow and AI is one bounded step, or when the first-class Agent hits a limit:
| Need | Why the node wins today |
|---|---|
| Trigger or upstream data mapped exactly into a tool parameter | Agent tool expressions only see the model's own arguments. Node tools can use $('Webhook').item.json... |
| One conversation shared between a chat channel and other workflows | Agent channel sessions and workflow sessions never meet |
create_agent isn't in the MCP tool list |
Agents aren't enabled on this instance |
When to use the Agent node vs raw chat completion
Decision:
- Need tool calls, multi-turn reasoning, or memory? Agent. Also a fine default when you don't want to think about it: standardizing on Agent across the workflow is reasonable and makes the path to upgrade simpler.
- Want the lightest possible single-shot text-out call? Basic LLM Chain (
@n8n/n8n-nodes-langchain.chainLlm) with a chat-model sub-node (OpenRouter Chat Model,OpenAI Chat Model,Anthropic Chat Model, etc.). No agent loop, no tool/memory/parser slots, easier to debug. Note: chat-model nodes are sub-nodes, and they don't run standalone. They wire into a chain or agent. Agent works here too if you'd rather standardize. - Routing to one of N output branches based on natural-language input (the AI's job is to pick the branch)? Use the Text Classifier node (
@n8n/n8n-nodes-langchain.textClassifier). N output handles, one per category, and downstream paths wire directly into each. Every category needs both a name AND a description (the description is what the model picks against, names alone aren't enough). Setoptions.enableAutoFixing: truefor robustness on edge inputs. Pair with a chat-model sub-node (OpenRouter Chat Model,OpenAI Chat Model, etc.). Don't reach for Agent + Switch for this. Text Classifier is one node and purpose-built. - Structured output but no tools? Agent is the easier default with future expansion in mind. Basic LLM Chain also accepts an
outputParserStructuredsub-node and works fine where you want the lighter node. - Image / audio / video generation? The native single-call node for that provider when calling them directly (OpenAI Image, Gemini Image, ElevenLabs, etc.). HTTP Request when routing through an aggregator (OpenRouter, Together, etc.), because no native aggregator node exists and the native nodes hardcode their provider's base URL on the media operation. Don't wrap media generation in an Agent, see "Binary and the agent boundary" below.
There are other LangChain "chain" / utility nodes for narrow tasks: Information Extractor (pull structured fields from text), Sentiment Analysis (3-way branch), Summarization Chain, Basic LLM Chain.
Agent is a reasonable default for most LLM steps. Reach for Basic LLM Chain when you specifically want the leaner node for a one-shot text call with no tools, memory, or iteration. Reach for Information Extractor / Sentiment Analysis / Summarization Chain / Text Classifier when one of those purpose-built nodes matches the task exactly.
Non-negotiables
- Tool names and descriptions are part of the prompt. The model picks tools by name and description. Vague tool node names like (
doStuff) or weak descriptions ("does things with the data") cause silent failure: the model skips your tool, mis-selects it, or hallucinates parameters. Treat both like API design. Seereferences/TOOLS.md. - Structured output: parse AND autoFix.
outputParserStructuredwithautoFix: trueand a coding-capable fixer model (e.g., Claude Sonnet 4.6) is the production pattern.
Strong defaults
- Tool descriptions are modular prompt fragments. Anything specific to how to call this tool belongs in the tool's description, not the system prompt. Keeps the system prompt focused, and tools become reusable across agents. See
references/SYSTEM_PROMPT.md. - Sub-workflow tools (
toolWorkflow) for anything multi-step. Any workflow becomes a tool with typedfromAi()inputs, and composes with branching, error handling, sub-workflows. Seereferences/SUBWORKFLOW_AS_TOOL.md. - Wrap tools with user-visible side effects in human review. Sends, payments, refunds, account changes. Gate them behind a Slack / Chat / Discord / Telegram approval node so a human signs off before the tool runs. See
references/HUMAN_REVIEW.md.
The sub-node pattern
The Agent node has a main input (the prompt or user message) and sub-node inputs:
const aiAgent = node({
type: '@n8n/n8n-nodes-langchain.agent',
config: {
name: 'Customer Support Agent',
parameters: {
promptType: 'define',
text: '={{ $json.userMessage }}',
options: {
systemMessage: '...',
passthroughBinaryImages: true, // for vision / multimodal
},
},
subnodes: {
model: openRouterModel,
memory: simpleMemory,
tools: [generateImage, editImage, searchKnowledgeBase],
outputParser: structuredParser, // optional
},
},
})
The four sub-node slots:
model(required): the language model. OpenAI, Anthropic, OpenRouter, etc. Use chat-model variants, not completion variants.memory(optional): conversation memory. Without it, every call is stateless. Seereferences/MEMORY.md.tools(optional, but the point of using an agent): tools the agent can call. Seereferences/TOOLS.md.outputParser(optional): forces structured JSON output. Seereferences/STRUCTURED_OUTPUT.md.
Triggers
Different triggers shape the input differently:
- Chat Trigger (
@n8n/n8n-nodes-langchain.chatTrigger) withavailableInChat: true: powers the canvas chat tester so you can poke at an agent while building it. Input is{ chatInput, sessionId, files[] }.sessionIdis what memory keys on, so pass it through wherever conversation continuity is needed. Files come in viafiles[], see binary section below. Not a production surface, use Slack / Discord / Teams / Telegram / webhook for that. - Webhook: arbitrary input shape, no session by default. Manage continuity by passing a session/conversation ID through the request body and forwarding it to the memory node.
- External chat surface (Slack, Discord, Teams, Telegram): every chat-triggered workflow that posts replies MUST filter out the bot's own user ID, or it loops forever potentially crashing n8n. Prefer trigger-level filtering when the surface supports it (Slack's
options.userIdsis an exclusion list); otherwise filter in the first node after the trigger. Semantics differ per surface, seereferences/CHAT_SURFACE_PATTERNS.md. A first-class n8n Agent can connect to Slack, Telegram, Discord, and Linear natively with no workflow, seen8n-agents-official. Beyond the anti-loop filter, a simple bot (trigger → agent → reply) is fine in one workflow. Split into a "shell" workflow + agent-core sub-workflow once you need loading UX, sub-agents, reuse across surfaces, or robust error handling. - Manual / Schedule: ad-hoc invocations. Memory rarely useful unless explicitly continuing a previous run.
- Execute Workflow Trigger (sub-workflow): when an agent is itself a tool of another agent. Treat the trigger's declared inputs as the contract.
Binary and the agent boundary
The model can see uploaded files (vision) via passthroughBinaryImages: true. But tools cannot receive binary, and fromAi() parameters are JSON only. Base64 is also not accepted by tools, even through non-AI bindings.
Workaround: pre-stage uploads to storage before the agent runs, inject the storage keys into the system prompt, tools accept the key as a string parameter and re-fetch internally. Full pattern in n8n-binary-and-data-official references/AGENT_TOOL_BINARY.md.
On the output side: the Agent's output formatter is text-shaped (or structured-text when an outputParser is wired). When a model returns binary (image bytes, audio bytes, video), the Agent doesn't surface it at all. There's nothing to dig out downstream, and trying to recover it via a Code or Set node after the Agent does not work. For one-shot media generation, use the provider's native single-call node directly such as @n8n/n8n-nodes-langchain.googleGemini or @n8n/n8n-nodes-langchain.openAi.
The exception: when a media step genuinely belongs in an agent (one tool among several, picked based on conversation context, or editing a previously-generated image), the workaround is a tool sub-workflow that uploads the result to storage and returns a key or URL. Pattern in n8n-binary-and-data-official references/AGENT_TOOL_BINARY.md. Don't reach for this by default. The upload + key + re-fetch path adds nodes and a storage dependency you don't otherwise need. Only when the orchestration actually requires an agent's tool selection.
What goes in the system prompt vs the tool description
| Belongs in system prompt | Belongs in the tool's description |
|---|---|
| Persona, role, voice | What this specific tool does |
| Output format rules ("respond in markdown") | When to use this tool vs others |
| Refusal/safety behavior | What each parameter means and its expected shape |
Display protocols ("show images via ![]() markdown") |
Examples of good vs bad invocations |
| Universal context (current date, user role) | Tool-specific gotchas (rate limits, edge cases) |
| Inter-tool flow ("after generating, always show via display protocol") | Tool-specific input transformations |
Benefit: tools become reusable. A well-described tool works in any agent that drops it in. The system prompt stays focused on role and shared behavior.
For deeper guidance and worked examples, see references/SYSTEM_PROMPT.md and references/TOOLS.md.
Tool selection: the four types
Pick the lightest option that covers the job:
- Native n8n tool node exists? (e.g.,
slackTool,gmailTool,calculatorTool) Use it. Lowest config overhead.- Native node is missing an operation or needs custom params (e.g., a Notion endpoint the node doesn't expose, a non-standard header, a different pagination shape)? HTTP Request Tool with the service's "Predefined Credential Type". Reuses the existing OAuth / API-key credential, gives full API access, no custom auth code.
- Multi-step logic, or reusing a sub-workflow already in the project? Sub-workflow as tool (
toolWorkflow). Anything you can build as a workflow becomes a tool with typedfromAi()inputs. The most powerful option in n8n, so default here when in doubt. Seereferences/SUBWORKFLOW_AS_TOOL.md. - Calling an external HTTP API the agent should orchestrate directly? HTTP Request Tool. Also good for slow async work via long-poll callback.
- Tool already exists as a published, MCP-accessible workflow? MCP tool. Useful for cross-workflow agent capabilities. See
n8n-extending-mcp-official.
See references/TOOLS.md for deeper guidance on each option and how to wire fromAi() parameters.
Human review
Before adding or skipping human review on a tool, check with the user. Whether sign-off is needed is a product / policy call (blast radius, audit requirements, how much they trust the model) that the user is better positioned to make than you. Surface the question, recommend based on the criteria below, and let them decide.
When a tool's effects need human approval before execution (sends, payments, refunds, account changes, customer-facing actions), wrap it with a review tool node: slackHitlTool, discordHitlTool, telegramHitlTool, gmailHitlTool, etc. (n8n's node names use Hitl for the human-in-the-loop pattern, and "human review" is what it's called in the UI.) The review node sits between the wrapped tool and the agent on the ai_tool connection: the wrapped tool's ai_tool output wires into the review node, and the review node's ai_tool output wires into the Agent. The agent calls through, the review node pauses for approval, on approve, the wrapped tool runs.
Default to / recommend human review when:
- The tool sends, pays, refunds, or otherwise mutates user-visible state.
- The approver is different from the chatter (manager-approves-customer-action, support team approves a customer-triggered refund).
- The trigger is non-interactive (order, form, schedule) but the tool's effect needs human sign-off.
Approval messages should display the actual parameters the wrapped tool will receive, not text the model paraphrases. Use $tool.parameters.<name> directly, or iterate over $tool.parameters to list every param. Don't fill the approval text via fromAi(). You'd be approving a paraphrase, not the literal call. Customize button labels with the actual values, e.g. Approve {{ $tool.parameters.amount }} refund.
Full config patterns, per-platform setup, and the multi-channel approver pattern in references/HUMAN_REVIEW.md.
Output parsing: when and how
Add an outputParser sub-node when downstream needs structured data, not free-form text.
const parser = outputParser({
type: '@n8n/n8n-nodes-langchain.outputParserStructured',
config: {
parameters: {
schemaType: 'manual',
inputSchema: JSON.stringify({
type: 'object',
properties: {
score: { type: 'integer', minimum: 1, maximum: 5 },
category: { type: 'string', enum: ['bug', 'feature', 'question'] },
reason: { type: 'string' },
tags: { type: 'array', items: { type: 'string' } },
},
required: ['score', 'category', 'reason'],
}),
autoFix: true,
customizeRetryPrompt: true,
prompt: '...retry instructions...', // generally leave as default
},
subnodes: {
languageModel: fixerModel, // coding-capable model, e.g. Claude Sonnet 4.6
},
},
})
- Use
schemaType: 'manual'with a real JSON schema, notjsonSchemaExample. An example can't express optional fields, enums, value ranges, or array constraints, so you outgrow it the first time the shape gets non-trivial. A schema lets you mark fields required vs optional, define enums, constrain numbers and string formats, and gives the model clearer rules to follow. Reach forschemaType: 'fromJson'with an example only for one-off shapes you're certain will never grow constraints. autoFix: trueadds retry on parse failure. Wire a coding-capable model as the fixer sub-node (e.g., Claude Sonnet 4.6 or similar). Fixing malformed JSON against a schema is a structured-output / coding task, and a weak or generic model often produces another malformed retry, defeating the point.
For the full pattern including custom retry prompts, see references/STRUCTURED_OUTPUT.md.
Memory: brief mental model
- No memory: stateless. Right for one-shot tasks (classify, summarize).
memoryBufferWindow: keeps the last N messages per memory key and persists across executions via n8n's internal store. The key is whatever expression you bind tosessionKey. Chat triggers fillsessionIdautomatically, but you can key on anything (Slackthread_ts, a webhook conversation ID, a multi-tenant composite). The default for chat memory. The "window" is the sliding cap on how many messages stay in context, not a scope on persistence.memoryPostgres/memoryRedis/ similar: reach for these when you need to query or read memory outside the agent: displaying conversation history in your own UI, analytics on past chats, or sharing memory with another system. OtherwisememoryBufferWindowis enough.
Plumb a stable key from the trigger to memory consistently, or conversations get crossed. See references/MEMORY.md.
RAG (retrieval augmented generation)
n8n has the LangChain RAG primitives: document loaders, text splitters, embeddings, vector stores, retrievers, rerankers. The pieces work, but opinionated end-to-end recipes ("which vector store, which chunking, when to rerank") depend heavily on data shape and scale.
This skill keeps RAG opinions thin on purpose. See references/RAG.md for more details on RAG.
Reference files
| File | Read when |
|---|---|
references/TOOLS.md |
Adding tools to an agent, choosing between the four tool types, writing tool names and descriptions |
references/SUBWORKFLOW_AS_TOOL.md |
Wiring a sub-workflow as an agent tool via toolWorkflow, mapping fromAi overrides |
references/SYSTEM_PROMPT.md |
Writing or refactoring a system prompt, deciding what goes in the system prompt vs tool descriptions |
references/STRUCTURED_OUTPUT.md |
Forcing JSON output, configuring autoFix retries, validating downstream |
references/MEMORY.md |
Choosing a memory type, persistence and sessionId handling |
references/RAG.md |
Building retrieval-augmented agents, intentionally a stub |
references/HUMAN_REVIEW.md |
Adding human approval to a tool, configuring approval messages, multi-channel approver patterns |
references/CHAT_SURFACE_PATTERNS.md |
Building a chat bot workflow on Slack, Discord, Teams, Telegram, or any custom chat surface: shell + core + sub-agents, including a first-class Agent as the core via Message an Agent |
Anti-patterns
| Anti-pattern | What goes wrong | Fix |
|---|---|---|
Generic tool names (doStuff, runQuery) |
Model can't tell which tool to pick, skips them or hallucinates parameters | Verb-first specific names: Search customer database, Generate image with Veo |
| Empty or one-line tool descriptions | Model has no clue when to invoke, bad selection | Write a real description: what it does, when to use, parameter meanings |
| Cramming everything into the system prompt | Bloated prompt, reuse impossible, per-tool guidance buried | Move tool-specific instructions to tool descriptions, keep system prompt to persona + global rules |
| Code-node tool where a sub-workflow would work | Not reusable, can't be tested independently, can't compose with branching | Use toolWorkflow with a proper sub-workflow |
| Passing binary directly to a tool | Doesn't work, binary can't cross the tool boundary | Pre-stage to storage, pass keys via fromAi, tool fetches internally. See n8n-binary-and-data-official |
outputParserStructured without autoFix |
One bad model output and the workflow fails | Set autoFix: true with a cheap fixer model |
Hardcoded sessionId or no sessionId |
Conversations cross or memory never matches | Pass sessionId from trigger consistently to memory and tools |
| Two near-identical tools instead of one with branching | Model gets confused, selection is non-deterministic | One tool with internal branching driven by parameters |
| Hardcoding a system prompt that's reused across workflows or iterated often | Editing requires republishing, can't share across workflows, tuning churn lives in node JSON | Store in a Data Table, load at runtime |
| Wrapping image / audio / video generation in an Agent | Binary doesn't flow through tools or out of the output formatter, Agent adds nodes for no gain | Use the provider's native single-call node directly (OpenAI Image, Gemini Image, ElevenLabs), HTTP Request only when going through an aggregator |
| Reaching for Agent + Switch to route on natural-language input | Two nodes plus prompt boilerplate where Text Classifier is one node with N built-in output branches | Use Text Classifier (@n8n/n8n-nodes-langchain.textClassifier), each category gets its own output handle, wire downstream paths directly |
| Tool that mutates user-visible state (send, pay, refund) without human review | Agent fires irreversible action on a wrong inference | Wrap with the review tool node that fits the channel (Slack/Chat/Discord/Telegram), show actual params via $tool.parameters |
Filling the review approval message via fromAi() |
The model paraphrases, you approve text not values | Use $tool.parameters.<name> directly so the literal call is visible |
| Chat-triggered agent workflow that posts replies without filtering out the bot's own user ID | Bot's own messages re-trigger the workflow, infinite loop that burns runs and tokens until rate limits or n8n concurrency stops it | Prefer trigger-level filtering when available (Slack Trigger's options.userIds is an exclusion list, put the bot ID there). Otherwise filter on $json.user !== '<BOT_USER_ID>' (or the surface equivalent) as the first node after the trigger. Required for ANY chat-triggered workflow that sends a reply (Slack, Discord, Teams, Telegram), regardless of complexity. See references/CHAT_SURFACE_PATTERNS.md for per-surface semantics |
Passing the bare blocks array to the Slack node's blocksUi when the agent returns Block Kit |
The Slack node accepts the input silently and posts the message with no rich content; no error, no warning | Wrap as { "blocks": [...] } with the value as a real array, not a stringified one. Expression: ={{ { "blocks": $('Agent').item.json.output.blocks } }}. See n8n-node-configuration-official references/COMMS_NODES.md "Block Kit messages" |
Open this reference as its own page
Chat surface patterns: shell + core + sub-agents
For external chat surfaces: Slack, Discord, Microsoft Teams, Telegram, embedded webhook chats. The pieces (memory, tools, sub-workflow as tool, structured output) are covered in their own refs. This file covers the multi-workflow composition that production chat agents grow into, plus chat-surface-specific gotchas the other refs don't.
The shell is the same whether the core is an AI Agent node sub-workflow or a first-class n8n Agent called with Message an Agent. For the second, see "Core as Message an Agent" below. If the first-class Agent's own channel (Slack, Telegram, Discord, Linear) covers the need, no shell is needed at all: see n8n-agents-official references/CHANNELS.md.
Anti-loop filtering is required regardless of complexity. Any chat-triggered workflow that posts a reply MUST filter out the bot's own user ID right after the trigger, or it triggers itself forever. That's the minimum bar for every bot, not a reason to split. Some triggers may have built in parameters for this.
Beyond that, a simple bot (one trigger → one agent → one reply, with the bot-user filter) lives fine in a single workflow. The shell + core + sub-agents split is for production robustness, not the default. It earns its keep once any of these is true:
- The bot needs loading-state UX (typing indicator, reaction, placeholder message) and graceful error handling beyond a single message.
- The bot is invoked from more than one surface (Slack AND Discord, Teams AND Telegram).
- There are specialist domains the agent shouldn't carry inline (Notion DB schema, CRM custom fields, Linear labels).
- The agent or its tools will be reused across other workflows.
If none of those apply, keep it in one workflow (with the bot-user filter still in place).
The shape:
[chat-surface workflow] ──► [agent core workflow] ──► [sub-agent workflows]
("the shell") ("the brain") ("specialists")
- Trigger from the surface - Stateless - One narrow domain each
- Anti-loop filter - chatInput + threadId - chatInput only
- Routing / event types - Memory keyed on threadId - Their own tools + model
- Loading + error UX - Tools, sub-agents
- Render the reply
Examples in examples/slack-router.json, examples/agent-core.json, examples/notion-ideas-subagent.json.
The shell
Receives chat events, decides whether to respond, manages UX, calls the core, renders the reply. No reasoning, no LLM.
Anti-loop filter (load-bearing)
The bot's own messages re-trigger the workflow. Slack, Discord, Teams all emit events for posts the bot itself made. Without filtering, every reply triggers another run, then another, until rate limits or n8n concurrency stops it.
Prefer trigger-level filtering when the trigger supports it. Some triggers expose user-ID filtering in their options so the loop breaks before any downstream node fires. Semantics differ per surface, verify against the version you're on:
- Slack (
n8n-nodes-base.slackTrigger):options.userIdsis an exclusion list. Listed users are dropped before the workflow runs. Put the bot's user ID here for anti-loop. Verified in the trigger source: the handler returns earlyif (userIds.includes(event.user)). - Telegram (
n8n-nodes-base.telegramTrigger):additionalFields.userIdsis an inclusion / allowlist (only listed users fire the trigger). Not a bot-exclusion filter, but useful for restricting a private bot to specific human users; bot loops are usually a non-issue on Telegram since bots don't see their own messages by default. Pair withadditionalFields.chatIdsfor scope. - Discord, Teams: no native user-level trigger filter. The downstream filter node below is the only option.
Slack trigger-level example:
const slackTrigger = trigger({
type: 'n8n-nodes-base.slackTrigger',
config: {
parameters: {
trigger: ['message'],
channelId: { __rl: true, mode: 'list', value: '<CHANNEL_ID>' },
options: {
userIds: '={{ ["<BOT_USER_ID>"] }}',
},
},
},
})
channelId (getChannels) and the exclusion options.userIds (getUsers) are lookup values: resolve real IDs via explore_node_resources instead of hardcoding the placeholders. RLC values in this skill's examples/*.json are instance-specific, re-resolve before reuse.
When the trigger filters at its own boundary, you don't need a separate filter node.
When the trigger doesn't expose a usable exclusion filter (currently Teams, plus Discord via community nodes that vary), the first node after the trigger must filter the bot's own user ID out:
const filterBot = node({
type: 'n8n-nodes-base.filter',
config: {
parameters: {
conditions: {
conditions: [
{
leftValue: '={{ $json.user }}',
rightValue: '<BOT_USER_ID>',
operator: { type: 'string', operation: 'notEquals' },
},
],
},
},
},
})
The bot user ID is the API ID from your bot's auth (Slack bot_user_id, Discord application ID, Teams botId).
Switch on event type and identity
The same trigger fires for messages, reactions, threads, mentions, slash commands, button clicks. One Switch right after the bot-loop filter routes each event to the right handler. The shell stays thin: it classifies the event and dispatches, and the actual work happens in dedicated sub-workflows per case.
Example for a Slack assistant (your shape will vary by what you support):
Switch case Goes to
──────────────────────────────────────────────────────────────────────────
"owner message" ──► Execute Workflow: agent-core
"owner reaction" ──► no-op (or Execute Workflow: reaction-handler)
"unknown user" ──► Send canned reply (or 4xx-shaped equivalent)
"slash command: /summary" ──► Execute Workflow: summary-command
"slash command: /search" ──► Execute Workflow: search-command
"button click" ──► Execute Workflow: interaction-handler
Each case has its own sub-workflow because the routing decision (what kind of event is this) and the work (run an agent, run a one-off tool, post a follow-up) are different concerns and often need different models, timeouts, or memory shapes. Adding a new slash command or button means adding one Switch output and one sub-workflow, not a new top-level workflow with its own trigger.
Slack-specific routing notes (payload shapes evolve on both Slack's side and n8n's, so verify field paths against a live event before relying on the exact shape):
- Reactions and mentions typically flow through the Slack Trigger as Events API events (
reaction_added,app_mention). - Slash commands and Block Kit button clicks generally don't come through the Slack Trigger, since Slack delivers those to separate Request URLs (Slash Command Request URL and Interactivity Request URL) outside the Events API. Two ways to bring them into the shell:
- Add a Webhook node as a second trigger in the same shell, configured as Slack's Request URL for that case. The shell then has Slack Trigger + Webhook(s) feeding the same Switch.
- Use a community Socket Mode node (e.g.,
@mbakgun/n8n-nodes-slack-socket-mode) that consolidates messages, slash commands, and interactivity into a single trigger.
- For matching, slash commands generally expose a
commandfield, and Block Kit interactions arrive withtype === 'block_actions'and anactionsarray (commonly routed byactions[0].action_id). These are reasonable starting points, but check the captured payload in your version before hardcoding.
Loading-state UX
Users assume nothing is happening if they don't see acknowledgement. Pattern: add a loading indicator before the agent call, remove it on every exit path, including error.
[Trigger] → [Filter bot] → [Switch]
→ (owner message)
→ [Add loading reaction] # :chatgpt:, :spinner:, etc.
→ [Execute Workflow: Agent core]
onError: 'continueErrorOutput'
├── (success) → [Remove reaction] → [Send reply]
└── (error) → [Remove reaction] → [Send error message with link]
The error path is the easy one to forget. Without it, the loading indicator sits forever and the user thinks the bot is still working. onError: 'continueErrorOutput' on the Execute Workflow node enables the second branch (see n8n-error-handling-official references/NODE_ERROR_OUTPUTS.md).
For Slack: slack node with resource: 'reaction', operation: 'add' and 'remove'. For Discord/Telegram, typing indicators are time-bounded, so for long agents, you could, for instance, send a placeholder message and edit it instead.
Threading as session continuity
Use the surface's thread primitive as the memory sessionKey:
workflowInputs: {
value: {
chatInput: '={{ $("Filter bot").item.json.text }}',
threadId: '={{ $("Filter bot").item.json.thread_ts || $("Filter bot").item.json.ts }}',
},
}
thread_ts || ts is the canonical Slack idiom: replies in a thread carry thread_ts referencing the parent, and the parent itself only has ts. Falling back to ts means the parent message becomes the session key for the thread it starts. Each thread is a fresh conversation, and memory doesn't leak across unrelated threads.
User ID, channel ID, and workspace ID alone are wrong: they cross conversations.
When sending the reply, target the same thread by setting otherOptions.thread_ts.replyValues.thread_ts to the same thread_ts || ts. Without it, replies go to the channel root and the thread context is lost.
Error UX: surface, don't hang
The error branch sends a short message with a link to the failed execution:
There was a workflow error. https://<n8n-host>/workflow/<id>/executions/{{ $execution.id }}
$execution.id is the live execution ID at the time the error fires. Parameterize the host if you ship across environments.
The agent core
A sub-workflow with two declared inputs: chatInput (the user's message) and threadId (the surface's thread/session ID). Returns the agent's final output: string, structured object, or surface-specific envelope (Block Kit, adaptive card).
The only chat-specific wiring not covered in MEMORY.md is plumbing threadId straight to sessionKey:
sessionIdType: 'customKey',
sessionKey: '={{ $json.threadId }}',
threadId flows trigger → (any pass-through nodes) → memory. Don't put it behind fromAi (covered in SUBWORKFLOW_AS_TOOL.md).
Per-execution context (user identity, attached files) goes in a Set node before the agent and gets templated into the system prompt, pattern in SYSTEM_PROMPT.md "File handling injection" and "Template + variables." Don't add a Set node speculatively for context that isn't varying yet. Inline in systemMessage is fine until reuse is real.
For Slack Block Kit, Discord embeds, or Teams adaptive cards, pair the agent with outputParserStructured (see STRUCTURED_OUTPUT.md). The general guidance to default to schemaType: 'manual' with a real JSON Schema applies even more strongly here: Block Kit and adaptive cards lean heavily on oneOf union types across block kinds, plus enums for fields like style and per-block constraints, none of which jsonSchemaExample can express. Examples will produce confidently-wrong block trees that the surface rejects.
Core as Message an Agent
When the brain is a first-class n8n Agent, the core sub-workflow collapses into one Message an Agent node (n8n-nodes-base.messageAnAgent) in the shell. The shell, anti-loop filter, loading UX, and error UX above stay exactly the same.
const askAgent = node({
type: 'n8n-nodes-base.messageAnAgent',
version: 3.1,
config: {
name: 'Ask support agent',
onError: 'continueErrorOutput',
parameters: {
agentId: { __rl: true, mode: 'id', value: '<AGENT_ID>' },
message: '={{ $("Filter bot").item.json.text }}',
advanced: {
session: { session: {
sessionIdType: 'customKey',
sessionKey: '={{ "support-slack-" + ($("Filter bot").item.json.thread_ts || $("Filter bot").item.json.ts) }}',
} },
},
},
},
})
What changes versus an AI Agent node core:
- The reply is
$json.text, plusstructuredOutput,toolCalls,usage,finishReason, andsession.{agentId, projectId, sessionId, threadId}. - Session keys are project-wide, not per agent. A key belongs to the first agent that uses it. The same agent with the same key from any workflow continues the session; a different agent with that key fails with "Failed to create the agent execution record". Prefix every key with the agent's purpose (
support-slack-<thread_ts>), even if only one agent uses it today. Max 74 characters.<!-- TEMPORARY: sessions can't be shared between native channel conversations (Slack, Telegram, Discord, Linear, n8n Chat) and Message an Agent calls from workflows. Revisit if n8n adds a way to key into a native session from a workflow, or vice versa. --> - A shell session never meets a native-channel session. If the same agent also has its own Slack channel, those threads and the shell's keys are separate conversations with separate memory.
- No approvals. A tool with approval required fails the node with "Suspend/resume is not supported in workflow execution context". Put human review in the shell instead: have the agent return a structured decision, then gate the action with a send-and-wait node.
- Draft vs published. Manual and chat-mode executions run the Agent's draft; production executions run the published version.
Full node reference: n8n-agents-official references/MESSAGE_AN_AGENT.md.
Sub-agents (agent as a tool)
A sub-agent is its own workflow with its own Agent node, called from the router agent via toolWorkflow. Use it when:
- The domain has a schema or enum set the router shouldn't carry (Notion DB properties, Linear labels, CRM fields).
- The domain has 5+ tools that would clutter the router's tool list.
- The capability is reused across more than one router agent.
- The domain warrants a different (cheaper, faster) model than the router.
The contract is stateless. The router sends the full request in chatInput, with no shared memory and no implicit context. Reinforce in both the tool description (router-side) AND the sub-agent's system prompt (callee-side):
IMPORTANT: This tool is stateless. Send all relevant context in a single message. If you need to create an entry, include ALL required fields upfront.
Without that, the router assumes implicit context and the sub-agent guesses.
For everything else about wiring sub-workflows as tools (the toolWorkflow node, fromAi mapping, plumbed-vs-agent-filled values, return shapes), see SUBWORKFLOW_AS_TOOL.md.
Fresh schema injection
When the domain schema can change at runtime (Notion DB property options evolve, Linear teams add labels), refetch on every sub-agent call instead of hardcoding it in the system prompt:
[Execute Workflow Trigger]
↓
[Notion: Get Database] # fetches the schema
↓
[Agent] # system prompt template includes:
## Database Schema
{{ $('Get a database').first().json.properties.toJsonString() }}
One extra API call per invocation, and in exchange the sub-agent never returns "that property doesn't exist" because the prompt is stale. Worth it for low-call-volume chat assistants. For high-volume hot paths, cache the schema in a Data Table with a TTL.
Worked example: a personal Slack assistant
Three workflows demonstrating the full pattern:
| Workflow | Role |
|---|---|
| Slack router | The shell. Bot-loop filter, event-type switch, loading reaction, error UX with execution link. |
| Agent core | Stateless agent. Memory keyed on threadId. Native tools (web search, deep research, calculator) plus two sub-agents. Block Kit output. |
| Notion ideas sub-agent | Specialist for a Notion ideas DB. Fetches schema fresh per call. Cheaper model (Claude Haiku 4.6). |
Cross-references
TOOLS.md: tool naming, descriptions,fromAi().SUBWORKFLOW_AS_TOOL.md: thetoolWorkflowshape and parameter mapping.SYSTEM_PROMPT.md: per-execution context, file injection, prompt storage.STRUCTURED_OUTPUT.md: parser config, autoFix, fixer model selection.MEMORY.md: memory types,sessionKeypersistence options.n8n-error-handling-officialreferences/NODE_ERROR_OUTPUTS.md:onError: 'continueErrorOutput'.n8n-node-configuration-officialreferences/COMMS_NODES.md: Slack node parameter shapes.n8n-binary-and-data-officialreferences/AGENT_TOOL_BINARY.md: receiving uploaded files and returning generated files. Read the "Surface-specific seams" section: every platform's file events and image rendering differ.
Anti-patterns
| Anti-pattern | What goes wrong | Fix |
|---|---|---|
| No bot-user-ID filter at the top of the shell | Bot's own messages re-trigger the workflow, infinite loop | Prefer trigger-level filtering when available (Slack: options.userIds is an exclusion list, put the bot ID there). Otherwise filter on $json.user !== '<BOT_USER_ID>' as the first node after the trigger |
Putting the bot's user ID in Telegram's userIds expecting exclusion semantics |
Telegram's userIds is an allowlist, not an exclusion list. Only the bot would fire the trigger, which means no human messages get through. Workflow looks "fixed" until you realize it's been silent for hours |
Telegram bots don't see their own messages by default, so anti-loop usually isn't needed. If you need to restrict who can talk to the bot, use userIds as the allowlist of permitted humans, not as a place for the bot's ID |
| Loading indicator added but only removed on the success path | User sees the bot stuck "thinking" forever after any error | onError: 'continueErrorOutput' on the agent call, remove the indicator on both branches |
| Using user ID, channel ID, or workspace ID as the session key | Conversations cross threads inside the same channel | Use the surface's thread primitive (Slack `thread_ts |
| Stuffing trigger + UX + agent + sub-agent tools into one workflow when the agent already has multi-surface, sub-agent, or reuse needs | Can't reuse across surfaces, UX leaks into reasoning, harder to test in isolation | Split into shell + core + sub-agents (but only once one of those needs is real, simple bots stay in one workflow) |
| Sub-agent that reads or writes shared memory | Caller can't reason about behavior, not safely retryable | Sub-agents are stateless, full context goes in chatInput |
| Hardcoding domain schema (Notion properties, Linear labels) in a sub-agent's system prompt | Schema rots, sub-agent picks invalid options weeks later | Re-fetch the schema at the start of the sub-agent and template it into the system prompt at runtime |
| Set-before-agent context injection for static text "in case I want to reuse it" | Extra node, no actual reuse, more places to update | Inline in systemMessage until reuse is real, use Set only for per-execution variability |
| Calling the agent core synchronously without an error UX | Worker fails, user sees nothing, debug requires opening n8n | Error branch surfaces a short message with a link to the failed execution |
Open this reference as its own page
Human review for agent tools
Human review gates a tool behind explicit human approval. Without approval, the wrapped tool does not run, regardless of how confident the agent is. The default safety pattern for any agent tool with user-visible side effects.
n8n docs and node names use HITL, human-in-the-loop, and Human Review for the same concept, and the review tool nodes are named accordingly (slackHitlTool, discordHitlTool, etc.).
Topology
The review node sits between the wrapped tool and the agent on the ai_tool connection:
[wrapped tool] --ai_tool--> [review node] --ai_tool--> [Agent]
- The agent doesn't know the review node is there. It sees the wrapped tool by the wrapped tool's name, description, and parameter schema. The review node is a transparent intercept on the execution path.
- When the agent calls the wrapped tool, the review node intercepts: it collects the parameters the agent built, pauses, sends an approval prompt to a human via the configured platform, and only on approval does the wrapped tool actually run with those parameters.
SDK syntax
Wire the wrapped tool into the review tool's subnodes.tools array. The agent registers the review tool in its own subnodes.tools. The SDK auto-resolves both ai_tool connections in the saved workflow JSON.
const refundTool = tool({
type: 'n8n-nodes-base.stripeTool',
config: {
name: 'Refund customer',
parameters: { resource: 'charge', operation: 'update', /* ... */ },
credentials: { stripeApi: newCredential('Stripe') },
},
});
const slackReview = tool({
type: 'n8n-nodes-base.slackHitlTool',
version: 2.4,
config: {
name: 'Slack approval',
parameters: { message: '...', user: { __rl: true, mode: 'list', value: '...' }, approvalOptions, options }, // resolve user/channel IDs via explore_node_resources (getUsers/getChannels)
credentials: { slackApi: newCredential('Slack') },
subnodes: { tools: [refundTool] }, // wrapped tools go here
},
});
const agent = node({
type: '@n8n/n8n-nodes-langchain.agent',
config: { /* ... */ },
subnodes: { model, tools: [slackReview] },
});
Don't use .to() to wire the wrapped tool into the review tool: .to() creates a main connection, and validate_workflow flags the wrapped tool as DISCONNECTED_NODE. The wrapped-tool-into-review wiring happens through subnodes.tools only.
Tell the agent the review is there
Because the agent doesn't see the review node, it doesn't know its tool is gated. Models with safety priors hedge on destructive-looking tools (send, delete, refund, charge) by default: they refuse, ask the user for confirmation first, or pick a less-direct option. With human review wrapping the tool, that caution is doubled up: the model self-censors AND a human reviews. Sometimes the model never even gets to the review step because it talked itself out of trying.
If you see the agent over-hedging on the wrapped tool (refusing to use it, asking the user for permission first, picking less-direct options), add a note to the wrapped tool's description that the review exists. Per the modular-prompt principle (see SYSTEM_PROMPT.md), tool-specific behavior belongs with the tool so it travels across agents and stays out of an already-busy system prompt.
Example addition to the tool description:
"This tool is gated by a human review step. Use it freely when relevant. A human will see the exact parameters and approve before anything is sent. Don't ask the user for confirmation first."
Don't pre-emptively add this to every wrapped tool. Many agents already use the tool freely without it. Deploy when the symptom (hedging, refusing, talking itself out of trying) actually shows up. Concrete payoff when it does apply: faster turn-taking (one approval click vs back-and-forth confirmation messages), better tool selection (the model isn't artificially de-prioritizing the gated tool), and the reviewer sees the model's actual decisions rather than its hedging.
When to default to human review
- Sends, pays, refunds, account changes. Anything user-visible and hard to roll back.
- The approver is different from the chatter. Customer triggers a workflow that asks support staff to approve the refund. Customer doesn't see the approval, support does.
- Non-chat triggers. Order received, form submitted, schedule fired. The action is taken on someone's behalf, and a person approves before it runs.
- Production-bound agent tools where the cost of a wrong call (money, customer trust, reputation) outweighs the cost of a one-step delay.
Skip review when the tool is read-only, idempotent and cheap to undo, or when the deployment is internal and exploratory with mocked services.
Available review tool nodes
| Node | When to use |
|---|---|
n8n-nodes-base.slackHitlTool |
Approver is on Slack (multi-channel pattern: chatter elsewhere, support staff approves in Slack) |
n8n-nodes-base.discordHitlTool |
Approver is on Discord |
n8n-nodes-base.telegramHitlTool |
Approver is on Telegram |
n8n-nodes-base.gmailHitlTool |
Approval via Gmail |
n8n-nodes-base.emailSendHitlTool |
Approval via generic SMTP email |
n8n-nodes-base.googleChatHitlTool |
Approval in Google Chat |
n8n-nodes-base.microsoftOutlookHitlTool |
Approval via Outlook email |
More platforms are added over time. Verify what's available on the target instance with search_nodes({ queries: ['hitl'] }).
Response types
responseType chooses the response shape the human sees:
approval: button-based approve / disapprove. Sub-configured viaapprovalOptions.values.approvalType:'single'(the default): one button (Approve only). Use when disapproval isn't a meaningful choice. The approver either acts or ignores.'double': two buttons (Approve / Disapprove). For actions where Disapprove needs to be a loud, recordable choice.
freeText(Slack / Discord / Telegram / Gmail / etc.): the human types a free-form response. Useful when the agent is genuinely asking a question and any answer is valid.customForm(every variant): a multi-field form supporting text, dropdown, radio, checkbox, and file inputs. The human fills in the form before the wrapped tool runs with those values. This is the practical answer to "editable parameters": define a form whose fields match the wrapped tool's parameters and the human can override what the agent picked.
A two-button "semantic choice" (e.g., "Schedule for today" / "Schedule for tomorrow") is NOT a separate response type. Use responseType: 'approval' with approvalType: 'double' and customize approveLabel / disapproveLabel.
Wait timeout
options.limitWaitTime (in seconds) bounds how long the workflow pauses for approval before erroring out. Default is 45 minutes. Set it explicitly on production workflows. Without setting it, paused executions can sit indefinitely if approvers don't act, and the queue piles up.
Approval message content
Show the actual parameters the wrapped tool will receive. The model picked them, and the human is approving the literal call.
Reference parameters via $tool.parameters.<name>
The agent wants to refund {{ $tool.parameters.amount }} to {{ $tool.parameters.customerId }}.
Reason: {{ $tool.parameters.reason }}.
$tool.name is the wrapped tool's display name. $tool.parameters is the full object the agent built.
Iterate over all parameters
So that adding a parameter to the wrapped tool doesn't silently leave it out of the approval message:
The agent wants to call {{ $tool.name }}:
{{
$tool.parameters.keys()
.map(param => `${param}: ${$tool.parameters[param]}\n`)
.join('')
}}
Drop this into the message field and any future parameter on the wrapped tool shows up automatically.
Don't fill the approval message via fromAi()
fromAi() asks the model to produce a value, including, if you let it, the approval text itself. That means the human approves a model-paraphrased description rather than the literal parameters about to be sent. Defeats the point of human review.
// WRONG
parameters: {
message: expr("{{ $fromAI('approvalText', 'describe the action for approval') }}"),
}
// RIGHT
parameters: {
message: expr("Refund {{ $tool.parameters.amount }} to {{ $tool.parameters.customerId }}?"),
}
Customize button labels with the actual values
Embed values in button text so the click is as clear as possible:
approvalOptions: {
values: {
approvalType: 'double',
approveLabel: expr("Approve ${{ $tool.parameters.amount }} refund"),
disapproveLabel: 'Cancel',
}
}
A button that says "Approve $50 refund" is unambiguous. A button that says "Approve" alone is not. Default disapprove label is "Decline" if you don't override it.
slackHitlTool also exposes buttonApprovalStyle and buttonDisapprovalStyle ('primary' | 'secondary') for visual emphasis on Slack's button styling.
Multi-channel pattern: approver isn't the chatter
A common production pattern: customer chats with an agent on a website (or via email, order trigger, form submission), and support staff approves sensitive actions in Slack.
[customer chat / order trigger]
-> [Agent]
-> [Slack review tool] -> [refund / cancel / escalate tool]
The customer never sees the Slack channel. The Slack review message routes via slackHitlTool.parameters.user, a resource locator with a select parent ('channel' | 'user'). The user branch uses mode: 'list' | 'id' | 'username' plus a value, and the channel branch uses channelId. On approval, the wrapped tool fires, and the agent's response goes back to the customer via the original chat path.
This pattern also works without any chat at all: trigger could be a webhook, schedule, form, or queue. The review tool is the only human-facing surface.
UI quirk: test data autofill
When building a review tool, click "Approve" once on the test execution in the canvas editor. n8n autofills the test data so subsequent runs work without manual input. Easy to miss, and new builders often think the tool is broken because the $tool.parameters.<name> is highlighted red since there is no test data.
Editable parameters: use customForm
For "I want to approve, but at $40 instead of $50" workflows, use responseType: 'customForm' (see Response types above). The human fills in a multi-field form whose values feed the wrapped tool, so they can override what the agent picked. Available on every Hitl variant.
Don't try to build editable approvals on top of the approval response type. The form mode is the supported path.
Note: the form mode is not an ideal UX and is reported feeling like a work around. Keep that in mind. Sometimes it may be better to have the user respond with a chat to decline with changes.
Anti-patterns
| Anti-pattern | What goes wrong | Fix |
|---|---|---|
| Tool that mutates user-visible state without human review | Agent fires irreversible action on a wrong inference | Wrap with the right review tool node |
Approval message via fromAi() |
You approve a paraphrase, not the literal call | Use $tool.parameters.<name> |
| "Approve" button with no context in the label | Approver clicks without seeing what they're approving | Embed actual values: Approve {{ $tool.parameters.amount }} |
| Review on a channel the approver doesn't actively monitor | Tool sits indefinitely, executions pile up | Pick a channel approvers watch, consider TTL / fallback patterns |
Open this reference as its own page
Agent memory
Memory is wired as a sub-node on the Agent. Without it, every invocation is stateless. With it, the agent holds a conversation across turns (and across executions, depending on type) keyed by a sessionId.
n8n memory node availability shifts between versions, so check what's installed on the target instance with search_nodes({ queries: ['memory'] }).
The non-negotiables
- Plumb a stable key through. Memory buckets by whatever expression you bind to
sessionKey. The chat trigger fillssessionIdautomatically. For other triggers, derive a stable identifier (Slackthread_ts, a webhook conversation ID, a generated UUID, a multi-tenant composite) and forward it to memory and any session-keyed tools. Without consistency across the same conversation, memory never matches. - Default to
memoryBufferWindow. It persists across executions via n8n's internal store, keyed on whatever you bind tosessionKey, and is the right choice for nearly every chat agent. Reach formemoryPostgres/memoryRedisonly when memory needs to be queried or read outside the agent (your own UI displaying chat history, analytics, sharing memory across systems).
The memory types
memoryBufferWindow
In-execution memory of the last N turns. The default for "remember the last few exchanges in this conversation."
const bufferMemory = memory({
type: '@n8n/n8n-nodes-langchain.memoryBufferWindow',
config: {
parameters: {
contextWindowLength: 50,
},
},
})
contextWindowLength is the number of exchanges retained. The default is 5, which is very low for modern chat expectations, where users typically assume a conversation feels close to endless. 50 is a reasonable starting point for most chat agents. Higher = more context, more tokens.
Messages past the window are removed from memory entirely. Once the buffer fills, the oldest exchanges are dropped and the agent can't recall, search, or know they ever existed. If a user said something 60 turns ago and the window is 50, that information is gone from the agent's perspective. For recall beyond the window, raise contextWindowLength, or persist key facts in a Data Table that's read and injected into the system prompt.
Persistence: keeps the last N messages per memory key and persists across executions via n8n's internal store. With sessionIdType: 'customKey', you bind the key to any expression: {{ $json.sessionId }} from a chat trigger, a Slack thread_ts, a multi-tenant composite, etc. Multiple users / threads / contexts each get their own memory bucket. The "window" is the sliding cap on how many messages stay in context, not a scope on persistence.
Right for: the default for chat memory. Nearly every user-facing chat agent.
Postgres / Redis stores (when memory needs to be readable outside the agent)
Reach for these when memory needs to be queried or read outside the agent: displaying conversation history in your own UI, analytics on past chats, sharing memory across systems, or migrating to a different n8n instance cleanly. Not necessary just to make chat survive across executions, since memoryBufferWindow already does that.
const postgresMemory = memory({
type: '@n8n/n8n-nodes-langchain.memoryPostgresChat',
config: {
parameters: {
sessionIdType: 'customKey',
sessionKey: '={{ $json.sessionId }}',
},
// ...connection config via credentials
},
})
Right for: chat history exposed to non-agent code (your own UI, analytics, multi-system queries).
Wrong for: the default chat agent case. memoryBufferWindow is the cleaner pick.
Custom memory patterns (Memory Manager)
Most agents don't need this. The default memoryBufferWindow with a sensible contextWindowLength covers the vast majority of chat use cases. But when a fixed window isn't enough, the Chat Memory Manager node (@n8n/n8n-nodes-langchain.memoryManager) is a powerful lever for building custom patterns on top of any memory backend.
The node operates against any wired memory sub-node (BufferWindow, Postgres, Redis, etc.) and exposes three modes:
load(default): read the current memory contents into the workflow. Useful for inspection, branching on size, or feeding contents into a summarization step.insert: append a message to memory. An optionalhideFromUIflag covers messages that should affect the agent but not show in the chat UI.delete: remove some or all messages from memory.
Pattern: rolling summarization
When a conversation runs long and you want the agent to retain the gist of older turns instead of dropping them entirely past the window:
- After each turn,
loadthe buffer contents. - If the buffer is approaching the cap, route to a summarizer branch (otherwise no-op).
- Run the older turns through an LLM that produces a concise summary.
deleteeverything in the buffer.insertthe summary back as a single message, plus optionally the most recent few turns to keep continuity.
The agent now sees [summary of turns 1-40] + [most recent 5 turns] instead of [turns 1-50], paying for far fewer input tokens while still having access to long-history context.
Other patterns built the same way
- Prune by relevance.
load, filter messages,delete, theninsertonly the ones worth keeping. - Inject runtime system facts.
insertwithhideFromUI: truefor facts the agent should know but the user shouldn't see in the transcript. - Reset on command.
deleteeverything when a "/clear" command (or equivalent) fires.
These are plausible patterns, but the Memory Manager node is more recent than the rest of n8n's memory tooling. Verify the modes you intend to use against your installed version before relying on them in production.
Session ID handling
Where the session ID comes from depends on the trigger:
Chat Trigger
Sets sessionId automatically. Wire it:
- Memory node:
sessionKey: '={{ $('Chat Trigger').first().json.sessionId }}' - Tools:
sessionId: '={{ $('Chat Trigger').first().json.sessionId }}'(NOT throughfromAi) - Storage keying: derive bucket keys / file names from sessionId for trivial per-session cleanup
Webhook trigger
You manage it:
- Caller passes a header or body field (
body.sessionId), and you forward it. - Or issue a session ID on first call, return it, expect callers to pass it back.
Either way, the session ID must be consistent across the whole conversation, including across reconnections.
Manual / scheduled
Usually no session. Use a stable identifier per "conversation" if one exists (Slack thread ID, ticket ID), otherwise memory adds nothing and should be omitted.
Memory and tools
When a tool is invoked, the tool's sub-workflow does NOT see conversation memory. Memory is the agent's context, not the tool's input. Pass needed context through fromAi parameters explicitly.
For tools that need session-keyed state, pass sessionId and have the tool look up state from a Data Table or storage keyed by session.
Memory and binary
Memory stores text turns. Binary uploaded mid-conversation is NOT in memory. It's in the chat trigger's files[] for that turn's input.
If the agent should remember "the user uploaded a file last turn":
- The text-side memory captures that "the user mentioned uploading a file."
- To actually USE the file in a later tool call, it must still be in storage (per
n8n-binary-and-data-officialAGENT_TOOL_BINARY.md) and the storage key must be in THAT turn's system prompt.
In practice, inject the session's file inventory into the system prompt every turn (loaded by sessionId).
Common mistakes
- Hardcoding
sessionId: 'default'. All conversations share one session. Memory contents become meaningless. - Different sessionId on memory vs tools. Memory keys on one, tools on another. Memory looks right but tools can't find related state.
- Using
memoryBuffer(unbounded) for chat. Token cost grows until timeout. Use BufferWindow with a sane limit. - Adding memory when there's no session. A "summarize this article" workflow doesn't need memory.
- Expecting tools to see memory. Tools see only their
fromAiparameters and plumbed-in context. - Drift between the chat surface and memory. If anything posts to the conversation outside the agent (a scheduled workflow replies in the Slack thread, a human writes directly, another workflow injects a message), the surface and the agent's memory diverge. The agent then operates on an incomplete view and will contradict or ignore messages it can't see. Whatever shows up in the user-facing surface must also be
inserted into memory via Memory Manager (or the equivalent path for your backend), so the workflow logic stays in sync with what the user can see.
Operational notes
- Memory size affects token cost. A 15-turn buffer of 200-token messages is 3000 tokens of input every turn before the user's input. Plan for it.
- Rate limits. A model that's hit a rate limit fails mid-conversation, and memory holds everything until then. After resolving, the next turn picks up (assuming session-id continuity).
- Concurrent sessions. Persistent backends key on sessionId, so concurrent conversations don't interfere. Verify with two simultaneous tests.
Cross-references
- For where the agent fits in the bigger picture: parent
SKILL.md. - For passing session-keyed state into tools:
SUBWORKFLOW_AS_TOOL.md. - For session-keyed file storage:
n8n-binary-and-data-officialreferences/AGENT_TOOL_BINARY.md.
Open this reference as its own page
RAG (retrieval augmented generation)
RAG in n8n is built on the LangChain primitives: document loaders, embeddings, vector stores, retrievers, and (eventually) rerankers. They wire onto agents and chains the same way models and memory do.
Before you go vector
Not every retrieval problem needs a vector store. Three cheaper alternatives to rule out first:
- Database or Data Table for exact lookups. "Look up customer X's record", "fetch issue #1234", "get rows where status = 'open'" are not RAG problems. Use a database query or
n8n-data-tables-officialdirectly. - Live search for freshness. If you need information that isn't in anything you've indexed (current news, live API state, anything time-sensitive), a search tool (Tavily, etc.) beats RAG.
- Grep-style / file-browse tools for small or structured sets of documents. When the set of documents is small enough to list out (a repo, a docs site, a few hundred markdown files), giving the agent list / fetch / search tools and letting it navigate is often simpler than ingesting. As an abstract example, an agent browsing a GitHub repo can be wired with
n8n-nodes-base.githubTool(list files at a path) plus an HTTP Request Tool againstapi.github.com/repos/{owner}/{repo}/contents/{path}withAccept: application/vnd.github.raw+jsonto fetch raw text. No ingest, no embeddings, full source paths in citations.
Reach for vector RAG when there are too many documents to list out, queries are semantic rather than navigational, and you need similarity-based retrieval at low latency.
Quickest start: in-memory vector store
The fastest path to a working RAG flow uses the in-memory vector store (@n8n/n8n-nodes-langchain.vectorStoreInMemory). It needs no external service, no provisioning, and no extra credentials beyond whichever embedding / chat-model provider you already use. Just drop it into the workflow. Data is lost on workflow restart, so this is right for prototypes, learning, and tests, not production.
Setup at a glance:
- Ingest workflow: any trigger that produces documents → Default Data Loader → Vector Store In-Memory (mode:
insert) with an Embeddings node wired intoai_embedding. For manual testing, the Form Trigger with a file-upload field is a quick way to drop in PDFs / CSVs without scripting. - Query workflow: Chat Trigger → Agent → Vector Store In-Memory (mode:
retrieve-as-tool), with the SAMEmemoryKeyvalue as ingest and the SAME embedding model.
When the data needs to survive restarts or scale beyond a single instance, swap the in-memory node for a persistent vector store (vectorStoreQdrant, vectorStoreSupabase, etc.). The rest of the wiring stays the same.
n8n ships a starter template that demonstrates the in-memory pattern end-to-end. See n8n's RAG docs.
Vector RAG: the pieces
n8n exposes the LangChain primitives as sub-nodes:
- Document loaders (
@n8n/n8n-nodes-langchain.documentDefaultDataLoader): pull from sources, optionally with metadata. Wires into a vector store node'sai_documentinput. - Text splitters (
textSplitter*): chunk into retrievable pieces. Default loader can do this inline for simple cases. - Embeddings (
embeddingsOpenAi,embeddingsCohere, etc.): turn chunks into vectors. Wires intoai_embeddingon both ingest and query sides. - Vector stores: store and query vectors. Start with
vectorStoreInMemory(no external service, no extra credential). For persistence across restarts, the built-in alternatives arevectorStoreQdrant,vectorStoreSupabase(Postgres pgvector), andvectorStorePinecone. Each has multiple modes:insertfor ingest,retrieve-as-toolfor the agent'sai_toolslot, and others for direct querying inside a workflow. - Vector-store tools (third-party):
n8n-nodes-qdrant.qdrantToolexposes raw Qdrant operations (list collections, scroll, etc.) to the agent. Distinct from the LangChain vector-store node'sretrieve-as-toolmode, which only does similarity retrieval. Useful when the agent needs to discover what's in the store, not just search it.
Vector RAG: two workflows
Vector RAG splits cleanly into two workflows, one per direction.
Ingest workflow
Triggered manually, by schedule, by webhook, or as a sub-workflow tool the agent calls when it wants to add to the store. Shape:
[Trigger]
-> [Vector Store, mode: 'insert']
ai_document <- [Default Data Loader (with metadata)]
ai_embedding <- [Embeddings (OpenAI / Cohere / etc.)]
Ingest does not have to be a tool. Most often it's a separate scheduled workflow that pre-populates the vector store on a cadence (e.g. nightly), or a webhook-triggered workflow invoked by the system that produces the documents. Wire it as an agent tool only when the documents change dynamically based on conversation (the agent learns something it should remember). For static or system-managed document sets, a standalone workflow is simpler and easier to reason about.
The Default Data Loader's metadata field is load-bearing: anything you want to filter or display alongside retrieval results (source URL, document type, tenant ID) goes there. Without it, retrieval results are just chunks with no provenance.
Query workflow
[Chat / webhook trigger]
-> [Agent]
ai_tool <- [Vector Store, mode: 'retrieve-as-tool']
ai_embedding <- [Embeddings (same model as ingest)]
ai_languageModel <- [Chat Model]
ai_memory <- [Memory]
Wired as ai_tool, the vector store becomes a tool the agent calls when it judges retrieval relevant. Wire retrieval directly into the main flow (pre-agent) instead only when every turn requires retrieval, which is rare in practice.
Embedding model must match. Whatever model embedded the documents on ingest must also embed the query. Mismatched models produce garbage retrieval. If you change embedding models, re-ingest the documents.
What's still open
Specific defaults depend too much on context to encode here. Verify against current n8n docs and your team's choices.
Vector store selection
- In-memory (
vectorStoreInMemory): zero ops, lost on restart. Right for prototypes and tests. - Qdrant (
vectorStoreQdrant): open-source, self-hostable, fast, mature in n8n. The built-in node covers insert and retrieve. The third-partyqdrantTooladds raw Qdrant operations as agent tools when similarity search alone isn't enough. - Postgres pgvector / Supabase (
vectorStoreSupabase): Postgres-based, ideal if you're already running Postgres or on Supabase. SQL-side queries (filter by metadata, join with relational data) compose nicely. - Pinecone (
vectorStorePinecone): fully managed, per-request pricing.
Embedding model
OpenAI's text-embedding-3-large, Cohere's embed-v3, and various open-source models are common. Cost, dimension count, and quality differ, choose carefully upfront to avoid the need to reembed.
Retrieval-as-tool vs retrieval-before-agent
- Retrieval-as-tool: agent decides when retrieval is relevant AND can phrase the query itself (reformulate, decompose, expand the user's wording into something the vector search will actually match). Extra round trip per retrieval, fewer wasted retrievals overall, and a better hit rate per query.
- Retrieval-before-agent: simpler, predictable. Pays the retrieval cost every turn AND uses the user's raw input as the query, so the agent can't optimize the search. Vague or conversational user phrasing ("can you remind me how that thing works again?") goes straight into the vector store.
Either works. Tool-based composes better in multi-capability agents (retrieval is one tool among several). Always-retrieve is fine for narrow Q&A bots where every question is a knowledge-base question.
Cross-references
- For agent fundamentals: parent
SKILL.md. - For wiring sub-workflows as tools, including agentic retrieval tool patterns:
SUBWORKFLOW_AS_TOOL.md. - For tool naming and descriptions on retrieval tools:
TOOLS.md. - For Data Tables (sometimes a viable alternative to a vector store for small structured data):
n8n-data-tables-officialSKILL.
Open this reference as its own page
Structured output
Non-negotiable: parse and retry on failure
The pattern
const structuredParser = outputParser({
type: '@n8n/n8n-nodes-langchain.outputParserStructured',
config: {
parameters: {
schemaType: 'manual',
inputSchema: JSON.stringify({
type: 'object',
properties: {
score: { type: 'integer', minimum: 1, maximum: 5 },
reason: { type: 'string' },
},
required: ['score', 'reason'],
}),
autoFix: true,
customizeRetryPrompt: true,
prompt: '...retry instructions...',
},
subnodes: {
languageModel: fixerModel,
},
},
})
const aiAgent = node({
type: '@n8n/n8n-nodes-langchain.agent',
config: {
parameters: {
options: {
systemMessage: '...you must respond in JSON matching {"score":...,"reason":...}...',
},
},
subnodes: {
model: mainModel,
outputParser: structuredParser,
},
},
})
Why a schema, not an example
schemaType: 'manual' with a real JSON Schema is the default. jsonSchemaExample looks easier, but an example can't express:
- Required vs optional fields. An example is one snapshot, the parser can't tell which keys are mandatory.
- Enums.
"category": "compliance"doesn't constrain the model tocompliance | history | risk. It'll invent new categories. - Numeric ranges.
"score": 3doesn't say1-5. The model will return7or0.85and pass the parser. - Array constraints. Min items, max items, item type uniformity.
- String formats. Email, UUID, ISO date, regex patterns.
A schema gives the model clearer rules and gives the parser real validation:
inputSchema: JSON.stringify({
type: 'object',
properties: {
decision: { type: 'string', enum: ['approve', 'reject', 'escalate'] },
confidence: { type: 'number', minimum: 0, maximum: 1 },
reasons: {
type: 'array',
items: {
type: 'object',
properties: {
category: { type: 'string', enum: ['compliance', 'history', 'risk'] },
weight: { type: 'number', minimum: 0, maximum: 1 },
note: { type: 'string' },
},
required: ['category', 'weight'],
},
},
follow_up_required: { type: 'boolean' },
},
required: ['decision', 'confidence', 'reasons', 'follow_up_required'],
})
Reach for schemaType: 'fromJson' with jsonSchemaExample only for one-off shapes you're certain will never grow constraints. Once a field needs to be optional, enum-ed, or range-bounded, you're rewriting the parser anyway, so start with the schema.
autoFix: true and the fixer model
The model can produce almost-but-not-quite-valid JSON: trailing comma, missing field, wrong type. Without autoFix, the workflow halts. With it, the parser sends the bad output to a model with a "fix this" prompt, retries, and continues.
{
autoFix: true,
customizeRetryPrompt: true,
prompt: `Instructions:
--------------
{instructions}
--------------
Completion:
--------------
{completion}
--------------
Above, the Completion did not satisfy the constraints given in the Instructions.
Error:
--------------
{error}
--------------
Please try again. Please only respond with an answer that satisfies the constraints laid out in the Instructions.
This is a structured output parser tool in n8n. Ensure the output format is correct to pass the parsing.
DO NOT wrap the output in a markdown code block.`,
}
Placeholders {instructions}, {completion}, {error} are filled at retry time.
The fixer is wired as a sub-node. Use a coding-capable model (e.g., Claude Sonnet 4.6 or similar). Reconciling broken JSON against a schema with enums, ranges, and required fields is a structured-output / coding task, not a mechanical transform. Weak or generic models routinely produce another malformed retry, which defeats the point and burns tokens.
"DO NOT wrap the output in a markdown code block"
This line is load-bearing. Models default to wrapping JSON in json ... , which breaks the parser. If you see parse failures on output that's clearly valid JSON inside a code block, this instruction is the fix.
You may also need it in your main system prompt if the main model wraps aggressively:
"When responding with structured output, return raw JSON only. DO NOT wrap in markdown code blocks. DO NOT include any prose before or after the JSON."
System prompt + parser: belt and suspenders
The parser tells the model the schema. The system prompt should ALSO tell it what shape to produce:
## Output Format
Respond with a JSON object matching this exact shape:
{ "score": 1-3 integer, "reason": "brief explanation" }
ONLY output the JSON. No prose, no markdown wrapping.
Repetition with the parser, but the model takes the system prompt seriously and reinforcement helps. The parser catches what slips through.
Common parse failures and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| "Failed to parse output" but the text looks like JSON | Wrapped in markdown code block | Add "DO NOT wrap in markdown" to retry prompt and system prompt |
| Empty fields where the schema expects values | Model thinks it can omit when it doesn't know | Add "Use empty string '' or null for unknown fields, never omit" to the system prompt |
| Wrong types (number as string) | Schema example wasn't typed clearly | Use a real number in the example, not a string |
| Truncated JSON (unclosed brace) | Hit max_tokens mid-response | Increase max tokens, tighten the prompt to produce shorter output |
| Field names paraphrased ("Score" instead of "score") | Schema didn't fix the name | Be explicit in system prompt: "field names are exactly as shown" |
autoFix retries forever |
Fixer model is too weak for the schema | Swap in a coding-capable model (Sonnet-class), tighten the retry prompt |
When NOT to use a parser
- Free-form responses to the user. Conversational chat replies don't need parsing.
- Tool calls only, no final structured output. If the user-visible output is text, no parser needed.
- Simple key-value extraction. A
Setnode withJSON.parse($json.output)handles trivial cases.
The parser is for when downstream nodes need to consume strict JSON.
Cross-references
- For why and where to use agents at all: parent
SKILL.md. - For the system prompt half of the structured-output story:
SYSTEM_PROMPT.md. - For tools that themselves return structured output (vs the agent's final response):
TOOLS.md.
Open this reference as its own page
Sub-workflow as agent tool
The default agent-tool shape for anything beyond one node is the Tool Workflow node (@n8n/n8n-nodes-langchain.toolWorkflow). Any sub-workflow becomes a tool the agent can call, with typed inputs filled by fromAi(). Composes with everything good about n8n: branching, error handling, sub-workflow reuse, native nodes, custom logic.
If you're tempted to write a Code-node tool: a sub-workflow is usually cleaner, but not always. See "When NOT to use sub-workflow as tool" below for the exception.
Why this is the default in n8n
In raw LangChain, a tool is a function in code. In n8n, a tool can be a whole workflow, meaning it can:
- Branch on input (IF/Switch nodes).
- Call multiple APIs and aggregate.
- Have its own error handling, retries, fallbacks.
- Call OTHER sub-workflows.
- Read/write Data Tables.
- Be tested independently with
test_workflowand pinned data. - Be reused across agents AND non-agent workflows.
A function-as-tool can't do most of this without growing into a workflow anyway. n8n gives you the workflow primitive directly.
The shape
Two things you need:
- A sub-workflow with an
Execute Workflow Triggerthat declares typed inputs. - A
Tool Workflownode in the agent's workflow that points at the sub-workflow and binds its parameters viafromAi().
The sub-workflow side
const subTrigger = trigger({
type: 'n8n-nodes-base.executeWorkflowTrigger',
config: {
parameters: {
workflowInputs: {
values: [
{ name: 'imagePrompt', type: 'string' },
{ name: 'imageName', type: 'string' },
{ name: 'sessionId', type: 'string' },
],
},
},
},
})
Each declared input becomes a parameter the caller can fill. Type enforcement happens on the agent side via the type argument of $fromAI(key, description, type, defaultValue?), not at the trigger itself. Allowed types: string, number, boolean, json. A wrong-typed value fails the call, so match the type in the trigger and in $fromAI.
The trigger MUST be in "Define Below" mode (typed fields), not passthrough. Passthrough has no schema, so the agent has nothing to fill via fromAi. Two exceptions: (a) the sub-workflow needs binary, in which case it can't be wired as an agent tool directly (pre-stage binary to storage and pass storage keys as typed string fields instead), or (b) the sub-workflow takes no inputs at all, in which case passthrough is the only option since Define Below requires at least one field, and the tool's only decision is whether to invoke (see TOOLS.md "zero fromAi parameters"). See n8n-binary-and-data-official AGENT_TOOL_BINARY.md and n8n-subworkflows-official SKILL.md "Sub-workflow inputs and outputs".
The Tool Workflow side
const generateImageTool = tool({
type: '@n8n/n8n-nodes-langchain.toolWorkflow',
config: {
parameters: {
workflowId: { __rl: true, value: '<sub-workflow-id>', mode: 'id' }, // no @searchListMethod on this RLC: get the real ID from search_workflows
workflowInputs: {
mappingMode: 'defineBelow',
value: {
imagePrompt: '={{ $fromAI("imagePrompt", "Detailed prompt describing the desired image", "string") }}',
imageName: '={{ $fromAI("imageName", "Storage key of an existing image to edit, or empty for new generation. Format: \\"abc123.png\\"", "string") }}',
sessionId: '={{ $("Chat Trigger").first().json.sessionId }}',
},
schema: [
{ id: 'imagePrompt', displayName: 'imagePrompt', type: 'string', display: true },
{ id: 'imageName', displayName: 'imageName', type: 'string', display: true },
{ id: 'sessionId', displayName: 'sessionId', type: 'string', display: true },
],
},
},
},
})
The mapping is per-input:
- Agent-filled:
={{ $fromAI('paramName', 'description', 'string') }}. Agent decides the value. - Workflow-filled:
={{ $('SourceNode').first().json.field }}. Your workflow plumbs it in.
The sessionId example is critical: it's NOT an agent decision. Plumbed from the chat trigger so memory and downstream session-keyed work stays consistent. Don't put sessionId behind fromAi or the agent will fabricate one.
What the agent sees
The agent sees the tool's name (the Tool Workflow node's name) and description (a parameter on the node). Both follow the rules from TOOLS.md: specific, written like API docs, treated as prompt.
The agent does NOT see:
- Sub-workflow internals.
- The sub-workflow's name (only the Tool Workflow node's name).
- Plumbed-in values like
sessionId. OnlyfromAiparameters appear in the tool schema.
Encapsulation: the sub-workflow can be refactored heavily without changing what the agent sees.
Wiring example: image-edit tool
Goal: an agent that can generate or edit images. Both share most logic (prompt → Gemini → upload → return URL), but they differ in whether they download an existing image first.
Sub-workflow Generate or edit image (tags subworkflow, tool):
[Execute Workflow Trigger: { imagePrompt, imageName, sessionId }]
↓
[Crypto: hash for new filename]
↓
[IF: imageName empty?]
├── empty (generate from scratch) ──► [Gemini: image generation] ──┐
└── not empty (edit existing): │
[S3: Download by imageName] │
↓ │
[Gemini: image edit with downloaded binary] ───────────────────┤
↓
[S3: Upload result]
↓
[Set: { imageUrl, imageKey }]
Agent side, one Tool Workflow node. Let the agent decide mode via the imageName parameter:
const generateOrEditImage = tool({
type: '@n8n/n8n-nodes-langchain.toolWorkflow',
config: {
name: 'Generate or Edit Image',
parameters: {
description: 'Use to create a new image from a prompt OR edit an existing image. Pass imageName as the storage key (e.g. "abc123.png") to edit; leave empty to generate from scratch.',
workflowId: { value: '<id>', ... }, // real ID from search_workflows (no @searchListMethod)
workflowInputs: {
mappingMode: 'defineBelow',
value: {
imagePrompt: '={{ $fromAI("imagePrompt", "Detailed image description") }}',
imageName: '={{ $fromAI("imageName", "Storage key of existing image to edit, or empty for new generation") }}',
sessionId: '={{ $("Chat Trigger").first().json.sessionId }}',
},
},
},
},
})
One tool, and the agent picks the mode by what it puts in imageName. Two near-identical tools would have made selection harder. (In a real workflow you might still split for clearer descriptions, but the principle holds: collapse near-identical tools.)
Patterns inside the sub-workflow
Return a stable shape
The caller (agent or deterministic workflow) receives whatever the sub-workflow's last node outputs. Pick a shape and keep it across modes:
{ "imageUrl": "https://...", "imageKey": "abc123.png" }
Don't sometimes return { url, key } and other times { result: { url, key } }. Sub-workflow tools are reusable across agents AND deterministic workflows, and the output shape is a contract every caller depends on: agents read it as part of the prompt, deterministic callers wire downstream nodes to specific paths. Drift breaks callers silently.
For calls that can fail "expectedly" (e.g., search with no results), return:
{ "ok": false, "error": "no_results", "message": "No matches found for query" }
Either kind of caller can branch on ok without per-tool error wiring.
When to throw instead: Stop and Error
For unexpected-but-handled errors (auth failure, upstream down, malformed input the sub-workflow can't recover from), use a Stop and Error node with a detailed message:
node({
type: 'n8n-nodes-base.stopAndError',
config: {
parameters: {
message: 'Auth failed for {{ $json.provider }}: {{ $json.error.code }}',
},
},
})
This propagates as a thrown error. Agents see a tool error and can retry, switch tools, or report. Deterministic callers catch it via onError: 'continueErrorOutput' on the Execute Workflow node. Pick this over { ok: false, ... } when the outcome is a true error, not a normal branch the caller should evaluate.
For the broader error story (4xx/5xx mapping, retries, error workflows, deciding throw vs. continue), see the n8n-error-handling-official skill.
Keep tool sub-workflows discoverable
Tag them with tool (plus a domain tag like customer where it applies) so search_workflows({ tags: ['tool'] }) finds them. Attach tags with update_workflow addTags after creating, since create_workflow_from_code can't set tags. Give them a plain descriptive name; the Tool Workflow node references them by ID (stable), and tags carry the category.
Wire onError: 'continueErrorOutput' on fallible nodes
Inside the sub-workflow, fallible nodes (HTTP, S3, DB) should set onError: 'continueErrorOutput' and route to a clean error response. Both agent and deterministic callers receive a structured error rather than the sub-workflow halting silently.
Don't put sessionId behind fromAi
The agent doesn't know your session ID, and behind fromAi it'll hallucinate a UUID. Plumb it from the trigger:
sessionId: '={{ $("Chat Trigger").first().json.sessionId }}'
Treat the input contract as an API
The Execute Workflow Trigger's declared inputs are this tool's API. Document them in the sub-workflow's description:
description: |
Generates or edits an image.
Inputs:
imagePrompt (string, required): detailed image description.
imageName (string, optional): storage key of existing image to edit. Empty for new generation.
sessionId (string, required): chat session ID, used for storage keying.
Returns:
{ imageUrl, imageKey }
This makes the sub-workflow understandable on its own.
Testing the sub-workflow independently
A sub-workflow tool can be tested without the agent:
prepare_workflow_pin_dataon the Execute Workflow Trigger generates representative input.test_workflowruns the sub-workflow with that pinned data.- Verify the output shape matches what the agent will receive.
When NOT to use sub-workflow as tool
- Simple one-node wrappers. "Call this HTTP endpoint and return" is shorter as an HTTP Request Tool.
- One-off code-only logic specific to this agent. A few lines of JS/Python that exist nowhere else and won't be reused work fine as a Code-node tool. Decision rule: reusable business logic → sub-workflow, one-off agent-specific transform → Code-node tool. Either way, the Code rules in
n8n-code-nodes-officialstill apply (Code is a last resort, expressions and Edit Fields first, no comments unless WHY is non-obvious). - Capabilities that already exist as native tool nodes. Don't wrap
slackToolin a sub-workflow.
For everything else, sub-workflow as tool is the default.
Cross-references
- For the four tool types overview:
TOOLS.md. - For how
fromAiparameter descriptions affect agent behavior:TOOLS.md's "fromAi" section. - For sub-workflow patterns generally (stateless, naming, search-before-build):
n8n-subworkflows-official. - For the Execute Workflow Trigger config details:
n8n-node-configuration-officialreferences/TRIGGER_NODES.md. - For the Code-node-tool exception and the rules Code follows wherever it's used:
n8n-code-nodes-official.
Open this reference as its own page
System prompts
The system prompt is the load-bearing config of an agent. Most "agent isn't doing what I want" problems trace back to a system prompt that's too long, too vague, or mixing concerns.
This file is opinionated: keep system prompts focused on persona and global behavior, push tool-specific instructions into tool descriptions, and iterate the prompt.
What the system prompt is for
- Persona / role. Who, scope, tone.
- Global output rules. Format conventions, display protocols (e.g. "show images via
![]()markdown"), language. - Refusal and safety behavior. What the agent should NOT do. Prefer specific bounds over generic boilerplate.
- Universal context. Current date, user's name/role, company or product context.
- Inter-tool flow rules. "After generating, always show via display protocol", "Confirm before destructive operations". These touch multiple tools.
- File handling injection. When chat includes uploaded files, inject storage keys so the agent can reference them in tool calls. See
n8n-binary-and-data-officialAGENT_TOOL_BINARY.md.
What it's NOT for: per-tool usage instructions. Those go in the tool's description.
Always include the current date
Current date: {{ $now }}
The modular split
Here's the mental model:
System prompt → Persona, global behavior, format rules, file handling
Tool description → How to use THIS specific tool, its parameters, when to choose it over others
fromAi description → What value to put in this specific parameter
Why this split:
- Reuse. A well-described tool works in any agent. System prompt stays specific to the role.
- Token efficiency. The model only "loads" tool details when considering that tool. Per-tool instructions in the system prompt burn tokens every turn.
- Maintainability. Update one tool description, not a paragraph buried in a 5000-token prompt.
What to move where: examples
| Was in the system prompt | Better location |
|---|---|
"When using the Generate Image tool, prefer realistic photography aesthetics over 8k cinematic keywords" |
Generate Image tool description |
| "When the user uploads an image and asks for background changes, do not generate a new image, edit the existing one" | Edit Image tool description (and possibly Generate Image description as a "do not use" boundary) |
| "Always preserve focus depth when editing backgrounds, match the original's blur level" | Edit Image tool description |
| "Use 9:16 aspect ratio for video tools" | Generate Video tool description |
"Respond with markdown image embeds: " |
System prompt (it's a global display rule) |
| "Refuse to generate images of real people without consent" | System prompt (global safety) |
| "Today is 2026-04-25" | System prompt (universal context) |
The first four moved out, and the last three stay in.
Storing the prompt
Inline (the system prompt typed directly into the node parameter) is fine for a first agent or any prompt that lives in one place. A 1500-token inline system prompt is a normal shape, and reaching for Data Tables, git-versioned files, or template engines on day one can be overkill. Don't push first-time agent builders toward externalization.
The real reason to externalize is piecing, not prompt length. Reusable chunks of context, things like COMPANY_DESCRIPTION, MARKET_FIT, BRAND_VOICE, COMPETITIVE_ANALYSIS, CURRENT_PROMOTION, each get one canonical home, and every prompt that needs them references that home instead of copying. Suggest this pattern when you see one of:
- Multiple agents share the same context (same product description, same compliance language).
- Pieces drift on their own cadence:
COMPANY_DESCRIPTIONchanges once a quarter,CURRENT_PROMOTIONchanges weekly. - A non-engineer owns part of the prompt (marketing owns brand voice, legal owns disclosures, product owns the feature list).
- You want to A/B test one chunk without touching the rest.
If none apply, stay inline. Mid-prompt restructures cost more than they save when there's no second consumer to pay them back.
How piecing works
The "template" is the system prompt expression itself. Load each chunk at workflow start (one node per chunk: a Data Table Get Row, an HTTP fetch, a Set node, whatever fits the source), then reference them inline in the agent's systemMessage where they should appear:
=You are the assistant for {{ $('Company Description').first().json.value }}.
## Market positioning
{{ $('Market Fit').first().json.value }}
## Brand voice
{{ $('Brand Voice').first().json.value }}
Current date: {{ $now }}
User: {{ $('Lookup').first().json.name }}
Mix where chunks come from:
- Data Table: default for chunks shared across agents. Editable in UI, queryable, can be version-stamped.
- n8n Variables (
$vars.X, paid plans only): instance or project wide key/value strings referenced inline without a node call. Right when the chunk is a short shared value (brand name, default tone, support email) and Variables are available on the paid plans. - Computed at run time:
$now, current user, available files. Just an expression, no storage needed.
File handling injection
See n8n-binary-and-data-official AGENT_TOOL_BINARY.md for how to handle binary in agents
Common patterns to include or exclude
Include
- Display protocols for output that needs specific formatting (markdown image syntax, link format, code block conventions).
- Conversational style cues for user-facing agents: "ask one clarifying question before destructive actions", "confirm before sending external messages".
- Boundaries unique to this agent: "only answer questions about [domain X], otherwise redirect".
- Universal context that changes per execution (date, user identity, files).
Exclude
- Per-tool usage docs. Move to tool descriptions.
- Generic safety language. Built in. Reinforcing adds tokens without changing behavior. Reserve for specific risks.
- "You are a helpful assistant" preamble. Replace with a specific role.
- Lengthy examples that aren't carrying their weight. One sharp example beats five mediocre ones.
Iteration loop
Treat the system prompt like code:
- Run the agent on representative inputs.
- Note where it does the wrong thing.
- Decide: system-prompt fix, tool-description fix, or downstream-validation fix?
- Make the smallest change that addresses it.
- Re-test on the same inputs PLUS one or two new ones.
- Watch for regressions on previously-working inputs.
Most "the agent doesn't follow my instructions" issues are conflicts between system prompt, tool descriptions, and model defaults. Resolve those conflicts first.
Anti-patterns
| Anti-pattern | Symptom | Fix |
|---|---|---|
| "You are a helpful assistant" + no specifics | Generic responses, agent has no identity | Replace with a specific role and scope |
| 5000-token prompt with sections per tool | Token cost, slow responses, hard to edit | Move tool sections to tool descriptions |
| Hardcoded date / "current year" | Stale immediately | Inject $now.toFormat(...) at runtime |
Stack of DON'T rules |
Model gets defensive, refuses too eagerly | Frame as positive instructions where possible |
| Multiple "examples" pasted in | Cargo-cult, rarely earns its tokens | One sharp example or none |
| Per-execution context buried in the system prompt | Hard to update | Build the prompt from a template + variables |
Open this reference as its own page
Agent tools
The agent picks tools by reading their name and description. Both are part of the prompt. Treat tool design like API design: what it does, when to use it, what each parameter means, and proper error handling.
The four tool types
1. Native tool nodes
Pre-built tool nodes from n8n: slackTool, gmailTool, googleSheetsTool, calculatorTool, httpRequestTool, etc. Same as their non-tool counterparts, except parameters can be filled by the agent via fromAi().
Pros: minimal config, well-tested integrations, consistent and native feel. Cons: one node = one operation. Multi-step logic doesn't fit.
Use when: the capability maps cleanly to one existing n8n node and one operation.
2. Sub-workflow as tool (toolWorkflow)
The default for any tool that does more than one thing. Any n8n workflow becomes a tool, with typed inputs via Execute Workflow Trigger filled by fromAi().
Pros: full power of n8n inside the tool: branching, error handling, sub-sub-workflow calls, native nodes, custom logic. Reusable across agents. Independently testable. Cons: one extra workflow boundary, (very) slight latency.
Use when: the capability is more than one node, the logic might be reused, or you want testability.
The canonical n8n way to build agent capabilities. Covered in depth in SUBWORKFLOW_AS_TOOL.md.
3. HTTP Request Tool
A wrapper around the HTTP Request node that exposes its parameters to the agent.
Pros: any HTTP API is a tool with one node. Cons: only HTTP. Auth/retry/error handling is yours to wire.
Use when: calling a single external API the agent should orchestrate. One thing to know: HTTP Request has its own HTTP-level timeout (default 5 minutes). For slow endpoints, bump options.timeout. Agent tools themselves have no timeout, the agent will wait as long as the tool takes.
Also useful when you want to give the agent more agency over the call shape. A native Notion tool node exposes one operation with fixed parameters. Point an HTTP Request Tool at the Notion API with the Notion predefined credential, and the agent can compose the path, method, and full JSON body itself, covering operations the native node doesn't expose. Trade-off: the agent is now writing API requests, which is more error-prone than deterministic tools and needs a capable model (Sonnet-tier or better) and clear endpoint guidance in the description. The user should understand they are widening the blast radius in exchange for flexibility.
4. MCP tool
The MCP Client Tool node connects the agent to any MCP server. Two flavors:
- External MCP servers: any third-party or self-hosted MCP (Linear, GitHub, Notion, Sentry, custom internal tools, etc.). The agent gets every tool that server exposes in one node.
- n8n-hosted MCP: a workflow on the same n8n instance published with MCP access enabled (per
n8n-extending-mcp-official). Same client node, just pointed at an n8n MCP trigger URL.
Pros: one node exposes many tools, vendor-maintained integrations stay current without you wiring each operation, and n8n-hosted MCP lets one workflow serve many agents and external clients. Cons: tool descriptions and shapes come from the MCP server, so quality varies and you can't easily tune them. Auth and network reachability are yours to manage.
Use when: a maintained MCP server already covers the capability, or you want to expose your own n8n logic to many agents (internal and external) through one published interface.
Decision: which tool type?
Capability the agent needs?
├── One existing native node + one operation does it
│ └── Use that as a tool node
│
├── More than one node, or logic that might be reused
│ └── Sub-workflow as tool (toolWorkflow). Default to this.
│
├── A single external HTTP API call (or long-running async via webhook callback)
│ └── HTTP Request Tool
│
└── A maintained MCP server covers it, or you want one published n8n workflow to serve many agents
└── MCP Client Tool (external MCP, or n8n-hosted MCP)
fromAi(): how the agent fills tool parameters
Tool parameters that the agent should determine are wrapped in fromAi():
{
sendTo: fromAi('recipient', 'Email address of the recipient'),
subject: fromAi('subject', 'Email subject line, concise and informative'),
body: fromAi('body', 'Email body in plain text, professional tone'),
}
The shape:
fromAi(<paramName>, <description>, <type?>, <defaultValue?>)
paramName: the name the model uses internally. snake_case or camelCase fine, but be consistent.description: tells the model what to fill in. Part of the prompt. Be specific: format, range, example.type(optional):'string'(default),'number','boolean','json'. Enforced: a wrong-typed value from the model fails the tool call.defaultValue(optional): used when the model omits the parameter.
A good description for a string parameter:
fromAi(
'imageName',
'Storage reference for an existing image to edit, or leave empty for a new generation. Format depends on the backend: an object-storage key like "abc123.png", a Dropbox file ID, a Google Drive file ID. Use the exact key/ID shown in the system prompt; do not reconstruct.',
'string'
)
A bad description:
fromAi('imageName', 'image name') // useless to the model
Treat fromAi descriptions like JSDoc for an API: the model reads them to figure out what to pass.
Workflow-filled parameters: hide what the agent shouldn't decide
Tool parameters don't all have to be fromAi. Any parameter can be filled deterministically from workflow context, and workflow-filled values are invisible to the agent: not in the tool schema, not in any turn, not influence-able by anything the model produces.
workflowInputs: {
value: {
reason: '={{ $fromAI("reason", "Why the user is requesting a refund") }}', // agent-filled
customerId: '={{ $("Chat Trigger").first().json.user.id }}', // hidden from agent
maxRefundAmount: '={{ $("Get user tier").first().json.refundLimit }}', // hidden from agent
idempotencyKey: '={{ $("Chat Trigger").first().json.sessionId }}', // hidden from agent
},
}
Use for anything the agent shouldn't be able to get wrong or read:
- Identity:
userId,customerId, authenticated actor, tenant scope. - Authority limits: refund caps, tier flags, allowed regions, role-based permissions.
- Correlation IDs:
sessionId, idempotency keys, trace IDs. - Anything the agent doesn't need to see to do its job.
The strongest version: a sensitive tool with zero fromAi parameters. The agent's only decision is whether to call the tool. A "Refund order" tool can take orderId from the chat trigger payload, amount from the order record fetched in an earlier node, and actor from the authenticated session, all plumbed in deterministically. The agent literally cannot refund the wrong order or the wrong amount, it can only choose whether to fire the call.
Capability-style tool design: give the agent a button to push, not a steering wheel. Pair with the patterns in HUMAN_REVIEW.md for actions that need deterministic params AND human sign-off.
Tool name and description as prompt
Selection process:
- Model gets the system prompt, conversation, and list of available tools.
- For each tool, it sees name + description + parameter schema (with
fromAidescriptions). - It picks the tool whose description best matches what it needs to do.
Bad names and descriptions cause bad selection. The failure mode isn't always loud: sometimes the model just doesn't call your tool, or it calls a different one with garbage parameters.
Tool name patterns
Use verb-first specific names:
| Good | Bad | Why |
|---|---|---|
Search customer database |
query |
"query" is generic, "search customer database" is specific |
Generate image with Veo |
imageGen |
Specific tool, specific model, "imageGen" doesn't say which |
Edit existing image |
edit |
"edit" doesn't say what's being edited |
Send Slack message to channel |
slack |
The name should hint at the action, not just the surface |
Lookup user by email |
getUser |
"getUser" doesn't say how |
Tool description patterns
A well-written tool description has three parts:
- What the tool does (one sentence).
- When to use it (one or two sentences with examples or boundaries).
- Parameter format notes (only if not covered in
fromAidescriptions).
Example:
Edit Image: Modifies an existing image based on a prompt. Use when the user has uploaded an image and asks for changes (color, style, composition, or content edits). Do not use for generating new images from scratch; use Generate Image for that. The `imageName` parameter must be the storage key of the existing image as listed in your available files; do not pass the original filename or a URL.
This description does work that would otherwise sit in the system prompt. That's the point. See "Tool descriptions as modular prompts" below.
Tool descriptions as modular prompts
Anything specific to how to call this tool belongs in the tool's description, not the system prompt. Three reasons:
- Reusability. A well-described tool works in any agent. The system prompt doesn't teach each new agent how to use it.
- Token efficiency. The model only "loads" tool descriptions when deciding to use a tool. Per-tool guidance in the system prompt is loaded every turn, even when irrelevant.
- Maintainability. When tool behavior changes, update the tool description, not a paragraph buried in a 5000-token system prompt.
Examples of what to move:
| In the system prompt | Better in the tool description |
|---|---|
| "When generating images, always preserve focus depth" | Edit Image: "When editing background only, match the original's depth of field..." |
| "If you call the search tool with no results, summarize that politely" | Search: "Returns up to 10 results, and if empty, report 'no matches found' rather than retrying with broader terms" |
| "Use 9:16 aspect ratio for video tools" | Generate Video: "Defaults to 9:16 for vertical/mobile, pass aspectRatio: '16:9' for landscape" |
Long system prompts often have multiple "when calling X, do Y" sections that can move into X's tool description.
Granularity: one tool with branching, not two near-identical tools
The model gets confused choosing between near-identical tools. If two tools are ~80% the same internally, consider:
- One tool with a parameter that branches. Branch in the sub-workflow based on a parameter value.
- Two tools only when the use cases are genuinely distinct AND descriptions can clearly differentiate.
Example: Send DM vs Send Channel Message are distinct, and the model needs to decide from the user's request. Generate Image vs Edit Image look distinct but share most logic, so collapse to one with an imageName parameter (empty = generate, populated = edit).
Operational notes
- Max iterations. Agents have a configurable tool-call iteration cap. When stuck in a loop, it caps out, surfacing as "max iterations reached" or empty output. Build a fallback, and don't trust graceful recovery.
- Tool call cost. Each tool call is at minimum one extra model round-trip. Frequently-called tools should return concise results, since bloated returns burn tokens fast.
- Tool failure handling. Wire
onError: 'continueErrorOutput'on tool sub-workflows where you want the agent to receive an error string rather than halting. The agent can retry, switch tools, or report to the user.
Cross-references
- For the sub-workflow tool pattern in detail:
SUBWORKFLOW_AS_TOOL.md. - For passing binary into tools:
n8n-binary-and-data-officialreferences/AGENT_TOOL_BINARY.md. - For wrapping APIs as MCP tools accessible to agents:
n8n-extending-mcp-official. - For tool naming alignment with the rest of the workflow conventions:
n8n-workflow-lifecycle-officialreferences/NAMING_CONVENTIONS.md.
More in this playbook
Safe to turn on
Use this skill when an agent or person is about to create, change or enable an automation inside someone else's account or a shared environment: "create this workflow", "build it in the customer's account", "turn it on", "go live", "deploy this automation". Produces a proposal the human approves, an automation created in the off state, and a short list of what only the human can finish.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.


