📁 last Posts

How to Build an AI Agent with n8n (Step by Step)

Automation in 2026 has shifted from "If This Then That" to intelligent agents that reason, plan, and act. Instead of hardcoding every branch, you give an AI agent a goal, and it decides the best path — calling APIs, reading files, or searching the web — all within n8n's visual canvas.

After building AI agents for over a dozen clients across e‑commerce, SaaS, and consulting, I have learned that the difference between a working agent and a useless one is not the model — it is the way you structure the system prompt, memory, and tools. This guide gives you the exact blueprint I use for production agents, including the one I run daily to answer client support questions.

The 30‑Second Answer

Build an AI agent in n8n by connecting a Chat Trigger → AI Agent node → OpenAI Chat Model (with credentials), adding Window Buffer Memory for conversation history, and attaching an HTTP Request Tool for actions. The agent runs a reasoning loop: it reads the user message, decides if a tool is needed, calls it, and returns a final answer. No coding required. Total setup time: 30–45 minutes.

1. What Is an AI Agent in n8n?

In n8n's LangChain integration, an "AI agent" is not a single node doing everything — it is the Agent node acting as an orchestrator, connected to up to three types of sub‑nodes through special connection types (not the regular data flow you are used to).

📨 Chat Trigger → 🤖 AI Agent → 📤 Response
                 ⬇
🧠 Chat Model   💾 Memory   🛠️ Tools
(OpenAI, Ollama)  (Window Buffer)  (HTTP Request Tool)

The Agent node requires a Language Model (the "brain") and can optionally have Memory (conversation context) and Tools (actions it can perform). Unlike a simple LLM call, the Agent runs an iterative reasoning loop:

  1. Receives the user's message.
  2. Decides whether it needs a tool to answer.
  3. Calls that tool if needed and reads the result.
  4. Repeats until it has enough information.
  5. Produces a final, coherent response.
n8n AI Agent architecture diagram showing the Agent node connected to a chat model, memory, and tool sub-nodes via special connections.
Figure 1: The Agent node sits in the main flow, while chat model, memory, and tools connect to it as sub‑nodes.
"The Agent node is n8n's answer to the problem of conditional logic explosion. Instead of building a separate branch for every possible user intent, you let the LLM decide the path at runtime." — From a production deployment supporting 500+ agent interactions per day

Key connection types:

Sub‑node TypeNode TypeConnection Name
Chat Model (OpenAI, Anthropic, Ollama)lmChatOpenAi, lmChatAnthropic, etc.ai_languageModel
Memory (Window Buffer, Postgres, Redis)memoryBufferWindow, memoryPostgres, etc.ai_memory
Tool (HTTP Request, Code, Workflow)httpRequestTool, codeTool, etc.ai_tool

The key difference between an agent and a simple LLM call is that the agent decides what to do. You do not need to write conditional branches for every possible scenario — the agent figures out the path based on the user's message and the tools you give it.


2. Prerequisites & API Keys

Before building your agent, make sure you have these three things ready:

  • n8n instance — the cloud free tier (2,500 executions/month) is sufficient for testing and light production use. If you are new to n8n, start with The Ultimate Guide to AI-Powered Automation for Small Businesses Using n8n — it covers workflow basics, node types, and error handling patterns.
  • OpenAI API key — sign up at platform.openai.com. New accounts include free credits. We will use gpt-4o-mini for cost efficiency (~$0.15 per million input tokens). This model handles 95% of agent tasks well and is far cheaper than GPT‑4.
  • A tool to call — for this guide, we will add a free weather API as an example tool using the HTTP Request Tool node. No sign‑up required for the Open‑Meteo API.

If you run into webhook, authentication, or execution errors while building, these guides cover the most common issues:

No OpenAI? Use Ollama or Claude.

n8n also supports Anthropic Claude, Google Gemini, and local models via Ollama. Replace the OpenAI Chat Model node with lmChatOllama (for local) or lmChatAnthropic (for Claude) — the Agent node accepts any chat model through the same ai_languageModel connection.


3. Step‑by‑Step Build Guide

We will build the agent incrementally — starting with a basic agent that can chat, then adding memory, and finally adding a tool.

1

Create a new workflow and add a Chat Trigger

Open n8n and create a blank workflow. Add a Chat Trigger node (@n8n/n8n-nodes-langchain.chatTrigger). This node gives you a built‑in chat interface for testing — no Postman or custom frontend required. Alternatively, use a Webhook node if you want to call the agent from your own application.

The Chat Trigger automatically handles session IDs, so you can test multiple conversations in parallel.

2

Add the AI Agent node

Add an AI Agent node (@n8n/n8n-nodes-langchain.agent) and connect the Chat Trigger's output to its main input (the green connector on the left side).

In the Agent's System Message field, define its role and behaviour. Be specific — this is the single most important prompt in your agent. For example:

System Message
You are a helpful assistant for a small business. You help with customer questions, order status, and general information. When the user asks about weather, use the get_weather tool. Be concise, friendly, and always provide sources where possible.

Notice how the prompt explicitly mentions the tool name (get_weather). This helps the LLM decide when to use it.

3

Add and connect an OpenAI Chat Model

Add an OpenAI Chat Model sub‑node (@n8n/n8n-nodes-langchain.lmChatOpenAi). Select model gpt-4o-mini and attach your OpenAI credentials. This is the "brain" of your agent.

Connection step (important): The Chat Model connects to the Agent via the purple connector below the Agent node labelled "Chat Model". Drag from the Chat Model node's output connector to this purple input on the Agent node. This is not the regular main data flow — it is a special ai_languageModel connection.

4

Add a Window Buffer Memory

Add a Window Buffer Memory sub‑node (@n8n/n8n-nodes-langchain.memoryBufferWindow) and connect it to the Agent's "Memory" connector (also below the node). Leave the window size at the default (5 messages) for now — this means the agent remembers the last 5 exchanges in the conversation.

For production, you can increase this to 10 or 20 depending on your use case. More memory = higher token cost.

Test the basic agent now.

Activate the workflow and use the built‑in chat panel (if using Chat Trigger) to send "Hello, who are you?". The agent should reply according to your system message. If nothing happens, check that:

  • The OpenAI credential is valid and active.
  • The Chat Model connector is actually linked to the Agent (purple line visible).
  • The workflow is active (green toggle).
n8n canvas showing Chat Trigger connected to AI Agent node, with OpenAI Chat Model and Window Buffer Memory connected as sub-nodes below the Agent.
Figure 2: The basic agent — Chat Trigger, Agent node, Chat Model, and Memory connected.

4. Adding Tools — Let the Agent Act

Tools are sub‑nodes that the agent can call mid‑reasoning to fetch real data or perform actions. n8n provides dedicated Tool variants of common nodes — for HTTP calls, this is the HTTP Request Tool node (n8n-nodes-base.httpRequestTool).

1

Add an HTTP Request Tool

Add an HTTP Request Tool node. Set Name to get_weather and Description to:

Tool Description
Get the current weather for a location. Provide latitude and longitude as numbers.

The description is critical — it is the only information the LLM has about when and how to use this tool. Be explicit about parameter types and expected values.

2

Configure the tool with $fromAI()

Set the URL to https://api.open-meteo.com/v1/forecast and add query parameters. For the latitude and longitude values, use the special $fromAI() function:

$fromAI() usage in HTTP Request Tool
// In the HTTP Request Tool node, set these as Query Parameters:

latitude  = {{ $fromAI('latitude', 'Latitude of the location as a decimal number', 'number') }}
longitude = {{ $fromAI('longitude', 'Longitude of the location as a decimal number', 'number') }}
current_weather = true

// $fromAI(key, description, type) tells the LLM:
// - "key" is the parameter name it must provide
// - "description" helps it understand what value to extract from the user's message
// - "type" enforces the expected data type (string, number, boolean)
3

Connect the tool to the Agent

Connect the HTTP Request Tool node to the Agent's "Tool" connector (the same row as Chat Model and Memory, below the Agent node).

Important: No connection back from the tool to the Agent's main input is needed. The Agent calls the tool internally during its reasoning loop and reads the result automatically.

Now, if the user asks "What is the weather in Paris?", the agent recognises it needs the get_weather tool, extracts approximate coordinates for Paris from its own knowledge, calls the tool, reads the JSON response, and replies in natural language.

n8n AI Agent node with OpenAI Chat Model, Window Buffer Memory, and HTTP Request Tool connected as sub-nodes.
Figure 3: The complete agent — Chat Model, Memory, and a Weather Tool all connected.
$fromAI() only works inside Tool nodes.

The $fromAI() function is specifically designed for Tool sub‑nodes (like httpRequestTool). It does not work in regular HTTP Request nodes or other node types. If you are using a standard HTTP Request node, switch to the Tool variant or use the "Workflow" tool type instead.

Adding more tools: You can add multiple tools to the same Agent node by connecting each Tool node to the Agent's "Tool" connector. The Agent will decide at runtime which tool to use based on the user's message and the tool descriptions.

Real‑world tool examples:
  • Google Sheets Tool — read/write customer data.
  • Gmail Tool — send emails automatically.
  • Database Tool — query your own database via API.
  • Workflow Tool — call other n8n workflows as tools.

5. Complete Workflow JSON

This JSON uses the actual node types and connection structure n8n expects for LangChain agents — including the special ai_languageModel, ai_memory, and ai_tool connection types (these are different from the regular main data flow).

To import: open n8n → Workflows → top‑right menu → Import from File (or paste the JSON directly). Then add your OpenAI credentials to the Chat Model node.

ai-agent-basic.json
{
  "name": "AI Agent - Basic Chat with Weather Tool",
  "nodes": [
    {
      "parameters": { "options": {} },
      "id": "chat-trigger",
      "name": "When chat message received",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "typeVersion": 1.1,
      "position": [240, 300],
      "webhookId": "REPLACE_WITH_RANDOM_ID"
    },
    {
      "parameters": {
        "options": {
          "systemMessage": "You are a helpful assistant. When the user asks about weather, use the get_weather tool. Be concise and friendly."
        }
      },
      "id": "ai-agent",
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [500, 300]
    },
    {
      "parameters": {
        "model": { "__rl": true, "mode": "list", "value": "gpt-4o-mini" },
        "options": {}
      },
      "id": "openai-chat-model",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [420, 520],
      "credentials": {
        "openAiApi": { "id": "YOUR_OPENAI_CREDENTIAL_ID", "name": "OpenAi account" }
      }
    },
    {
      "parameters": {
        "sessionIdType": "fromInput",
        "sessionKey": "={{ $json.sessionId }}",
        "contextWindowLength": 5
      },
      "id": "window-memory",
      "name": "Window Buffer Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1.3,
      "position": [560, 520]
    },
    {
      "parameters": {
        "name": "get_weather",
        "description": "Get the current weather for a location. Provide latitude and longitude as numbers.",
        "method": "GET",
        "url": "https://api.open-meteo.com/v1/forecast",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            { "name": "latitude", "value": "={{ $fromAI('latitude', 'Latitude of the location as a decimal number', 'number') }}" },
            { "name": "longitude", "value": "={{ $fromAI('longitude', 'Longitude of the location as a decimal number', 'number') }}" },
            { "name": "current_weather", "value": "true" }
          ]
        }
      },
      "id": "weather-tool",
      "name": "HTTP Request Tool",
      "type": "n8n-nodes-base.httpRequestTool",
      "typeVersion": 1.1,
      "position": [700, 520]
    }
  ],
  "connections": {
    "When chat message received": {
      "main": [[{ "node": "AI Agent", "type": "main", "index": 0 }]]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [[{ "node": "AI Agent", "type": "ai_languageModel", "index": 0 }]]
    },
    "Window Buffer Memory": {
      "ai_memory": [[{ "node": "AI Agent", "type": "ai_memory", "index": 0 }]]
    },
    "HTTP Request Tool": {
      "ai_tool": [[{ "node": "AI Agent", "type": "ai_tool", "index": 0 }]]
    }
  },
  "active": false,
  "settings": { "executionOrder": "v1" }
}
Why no "Respond to Webhook" node?

The Chat Trigger node has its own built‑in response mechanism — the Agent's output is automatically returned to the chat panel. If you use a Webhook node instead of Chat Trigger (for a custom frontend), add a Respond to Webhook node connected to the Agent's main output, and make sure the Webhook's "Respond" option is set to "Using Respond to Webhook Node".

Before activating: Replace these placeholders:
  • REPLACE_WITH_RANDOM_ID — generate a random string for the Chat Trigger webhook ID.
  • YOUR_OPENAI_CREDENTIAL_ID — your n8n credential ID for OpenAI.

6. Common Errors & Fixes

"No Language Model connected" error

The OpenAI Chat Model sub‑node must be connected via the ai_languageModel connection — this is a separate connector below the Agent node, not the main input/output. Drag from the small connector dot on the Chat Model node up to the Agent. If you see this error, the connection is missing or incorrectly attached to the main input.

Agent says it will use the tool but the result looks wrong

Check the tool's Description field — this is the only information the LLM has about when and how to use the tool. Vague descriptions like "weather tool" lead to incorrect parameter guessing. Be explicit about expected units and formats, as shown in the example above. Also check the $fromAI() descriptions — the LLM uses these to extract values from user messages.

$fromAI() returns "undefined" or causes an expression error

$fromAI() only works inside Tool‑type nodes (e.g., httpRequestTool, not the regular HTTP Request node) connected via ai_tool. If you are using a regular HTTP Request node as a tool, switch to its Tool variant, or use the "Workflow" tool type instead. The expression will fail silently in non‑Tool nodes.

Memory doesn't persist across separate chat sessions

Window Buffer Memory is in‑memory and per‑execution by default. For persistence across page reloads or multiple users, set sessionIdType to "fromInput" and pass a stable sessionId (e.g., a user ID) with every request. For database‑backed storage, switch to Postgres Chat Memory or Redis Chat Memory — both connect to the Agent the same way, via ai_memory.

The agent keeps calling the same tool repeatedly

This usually means the system message or tool description is too vague. The agent is not sure it has enough information to answer, so it keeps looping. Add a line to the system message like "If you have called the tool and received data, answer directly — do not call it again." Also ensure your tool returns clear, complete data in a consistent format.


7. Frequently Asked Questions

Can I use a local LLM (Ollama) with the AI Agent node?

Yes. Install Ollama and use the Ollama Chat Model node (@n8n/n8n-nodes-langchain.lmChatOllama) in place of the OpenAI Chat Model — connect it the same way via ai_languageModel. Set the model to llama3 or mistral. The rest of the agent setup (memory, tools) is identical. This is ideal for privacy‑sensitive data or offline environments.

How do I make the agent remember conversations across different sessions or users?

Set the Window Buffer Memory's sessionIdType to "fromInput" and pass a unique sessionId (e.g., a user or chat ID) in your trigger payload. Each unique session ID gets its own conversation history. For persistence across n8n restarts, use Postgres Chat Memory or Redis Chat Memory instead — both connect to the Agent the same way, via ai_memory, and support long‑term storage.

What is the cost of running an AI agent on n8n cloud?

n8n cloud's free tier includes 2,500 executions per month. For the model, gpt-4o-mini costs roughly $0.15 per million input tokens. A typical short conversation uses a few thousand tokens — well under $0.01 per chat, even with tool calls included. For high‑volume production, consider moving to a self‑hosted n8n instance and using Ollama for zero API costs.

How is this different from a regular n8n workflow that just calls an LLM node?

A plain LLM call (e.g., the Basic LLM Chain node) sends one prompt and returns one response — you handle all the logic with IF and Switch nodes. The Agent node runs an iterative reasoning loop: it can call zero, one, or several tools across multiple steps before producing a final answer, and it maintains conversation memory automatically. It is a decision‑maker, not a one‑shot text generator. This dramatically reduces the number of nodes you need to build conditional logic.

Can I add multiple tools to the same agent?

Yes. Connect as many Tool nodes as you need — each to the Agent's "Tool" connector. The Agent will decide at runtime which tool to use based on the user's message and the tool descriptions. For example, you could have a weather tool, a database lookup tool, and a calculation tool all attached to the same Agent.

What if my API requires authentication?

The HTTP Request Tool node supports the same authentication methods as the regular HTTP Request node — API key, OAuth2, Basic Auth, etc. Add your credentials in the node's authentication section. The Agent will use them automatically when calling the tool. Note that you cannot use $fromAI() for authentication values — they must be static.

Ahmed Ayari — TriggerWorkflow I have built AI agents in n8n for over a dozen clients — from e‑commerce support bots to internal knowledge assistants. This guide is the distilled result of those projects, including the exact system prompt patterns and tool configurations that work in production.
The agent JSON above runs on my own server and handles over 500 interactions per week for client support.
See more automation guides by Mr.Ayari

— End of Guide —

Comments