Skip to content
BotServBotServ
n8nAI AgentsAI Agent NodeToolsAgentic Workflows

Building AI Agents in n8n

Build AI agents in n8n with AI Agent Node, tool integration, multi-step workflows, Ollama backend and practical examples.

S

schutzgeist

7 min read
Building AI Agents in n8n

Building AI Agents in n8n

What this article covers

  • How to build agents using the AI Agent Node in n8n.
  • Connecting tools to your agent (search, databases, APIs).
  • Using Ollama as a backend for your agent.
  • How multi-step agents and memory work.
  • Practical examples for different agent types.

Introduction: AI agents in n8n explained

n8n has included a dedicated AI Agent Node since version 1.x. This node is not a simple text generator, but a true agent: it can invoke tools, make decisions, and execute multiple steps to solve a task. Combined with Ollama, everything runs locally.

This article is for users who want to build real agents in n8n, not just simple prompts. You’ll find foundational concepts in AI Agents and n8n-Ollama Integration.

Why use AI agents in n8n?

A simple workflow calls the model once: β€œsummarize this text.” An agent workflow works differently: the agent receives a goal (β€œresearch this topic and create a report”), decides which tools it needs (web search, document reader, calculator), and executes multiple steps until the goal is reached.

AI agents in n8n, simplified

The AI Agent Node in n8n connects a language model (Ollama, OpenAI, Claude) with tools (HTTP requests, code, databases, search). The agent plans its own steps, invokes tools, and iterates until the task is complete.

The core idea: Model + Tools + Loop = Agent.

Who is this article for?

  • n8n users who want to move beyond simple prompts.
  • Automation builders creating agentic workflows.
  • Self-hosters running agents locally with Ollama.
  • Developers using n8n as an agent platform.

Familiarity with n8n and AI agents is helpful.

Key terms

  • AI Agent Node - n8n’s agent node. Use case: the core component.
  • Tool - An instrument the agent can use. Use case: what the agent can invoke.
  • Ollama - Local model server. Use case: as an agent backend.
  • Function Calling - Tool-use mechanism. Use case: how the agent invokes tools.
  • Memory - Conversation history. Use case: for multi-turn agents.
  • Window Buffer Memory - Simple memory buffer. Use case: for conversations.
  • ReAct - Reasoning plus acting. Use case: the agent pattern.

The AI Agent Node in detail

Basic structure

The AI Agent Node has several connections:

                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
Trigger ──────────► β”‚   AI Agent Node  β”‚ ──► Output
                    β”‚                  β”‚
   Model ─────────► β”‚  β—‹ Chat Model    β”‚
   Memory ────────► β”‚  β—‹ Memory        β”‚
   Tool 1 ────────► β”‚  β—‹ Tool          β”‚
   Tool 2 ────────► β”‚  β—‹ Tool          β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  • Chat Model: The language model (Ollama, OpenAI, etc.)
  • Memory: Optional, for conversation context
  • Tool: One or more tools the agent can invoke

Agent types

n8n offers several agent types:

TypeDescriptionWhen to use
Tools AgentReAct pattern with toolsStandard, flexible
Conversational AgentChat with memoryChatbots
Plan-and-ExecutePlan first, then executeComplex tasks
ReAct AgentReasoning plus actingTransparent decision-making
SQL AgentFor database queriesDatabase workflows

Setup: Ollama as your agent model

1. Configure the chat model

Add an Ollama Chat Model node and connect it to the chat model input of the AI Agent Node:

Ollama Chat Model:
  Model: llama3.1
  Base URL: http://ollama:11434
  Temperature: 0.3

Important: For tool calling, you need a model that supports it. See Function Calling.

2. Suitable models for tool calling

ModelTool CallingVRAM
llama3.1:8bYes~5 GB
qwen2.5:14bYes~9 GB
mistral-nemoYes~8 GB
llama3.1:70bYes (excellent)~40 GB

Connecting tools

// Custom Tool Node: Web search via SearXNG
{
  "name": "web_search",
  "description": "Searches the web for current information. Input: search query as string.",
  "schema": {
    "type": "object",
    "properties": {
      "query": { "type": "string" }
    }
  }
}

// In the Tool Node: HTTP Request to SearXNG
// POST http://searxng:8080/search?q={{query}}&format=json

Tool 2: Code (calculations)

// Code tool for calculations
// The agent can execute JavaScript code

const input = $json.input;
// Example: percentage calculation
const result = eval(input);
return { result };

Tool 3: Database (Postgres)

// Postgres tool: The agent can query the database
{
  "name": "query_database",
  "description": "Executes a SQL query on the customer database.",
  "schema": {
    "type": "object",
    "properties": {
      "sql": { "type": "string" }
    }
  }
}

Tool 4: Workflow as tool

A powerful pattern: another n8n workflow becomes a tool:

AI Agent
  └─ Tool: "Process document"
       └─ Sub-workflow:
            β”œβ”€ Download PDF
            β”œβ”€ Extract text
            └─ Summarize

Practical example 1: Research agent

Workflow: Research Agent

1. Webhook Trigger: Topic comes in
2. AI Agent Node:
   - Model: Ollama llama3.1
   - Tools:
     * web_search (SearXNG)
     * fetch_page (HTTP Request)
     * save_note (Code)
3. Agent prompt:
   "Research the topic [TOPIC].
    Use web_search for sources,
    fetch_page for details,
    save_note for intermediate results.
    Create a final report with sources."
4. Email Node: Send report

Practical example 2: Ticket agent

Workflow: Support Ticket Agent

1. Webhook: New ticket
2. AI Agent Node:
   - Model: Ollama qwen2.5
   - Memory: Window Buffer (for follow-ups)
   - Tools:
     * knowledge_base (RAG via Qdrant)
     * ticket_status (Database)
     * create_response (Code)
3. Agent prompt:
   "Answer the support ticket.
    First search the knowledge base.
    Check ticket status.
    If you find no answer, escalate."
4. IF Node: Escalated? β†’ Send to human / Send response

Practical example 3: Database agent

Workflow: SQL Agent

1. Schedule Trigger: Daily at 8 AM
2. AI Agent Node (SQL Agent):
   - Model: Ollama llama3.1
   - Tools: Postgres (automatically as SQL tool)
3. Prompt:
   "Analyze sales figures from last week.
    Create a report with top products and trends."
4. Slack/Email: Send report

Configuring memory

Window Buffer Memory

// Simple memory: last N messages
{
  "type": "windowBuffer",
  "windowSize": 10  // Last 10 messages
}

Persistent Memory (Redis/Postgres)

For long-running conversations:

// Redis Memory
{
  "type": "redis",
  "host": "redis",
  "port": 6379,
  "sessionKey": "{{$json.session_id}}"
}

Error Handling in Agents

// Retry logic in Agent Node
{
  "maxIterations": 10,      // Max 10 tool calls
  "returnIntermediateSteps": true  // Debugging
}

// After the agent: check for success
const output = $json.output;
if (!output || output.includes("I don't know")) {
  // Fallback or escalation
  return { status: "failed", needs_human: true };
}

Guardrails for Agents

// Guardrail Node before the agent
function validateInput(input) {
  // Filter prompt injection
  const dangerous = ["ignore previous", "system:", "forget all"];
  for (const pattern of dangerous) {
    if (input.toLowerCase().includes(pattern)) {
      throw new Error("Potential prompt injection");
    }
  }
  return input;
}

See Configuring Guardrails and Prompt Injection.

Security Considerations

  • Restrict tool permissions: The agent should only read what it needs. See Tool Permissions.
  • Max Iterations: Limit the number of tool calls to prevent infinite loops.
  • Validate output: Critical actions (sending emails, deleting data) should require human approval. See Human Approval.
  • Logging: Log all agent decisions. See Logging.
  • Sandboxing: Execute generated code in isolation. See Sandboxing.

Common Pitfalls

  • Model without tool-calling: Not every model can call tools. Use llama3.1 or qwen2.5.
  • Too many tools: More than 5-7 tools overwhelms the model. Less is more.
  • Poor tool descriptions: The model chooses which tool to use based on the description. Be precise.
  • No iteration limit: Agents can get stuck in loops. Always set maxIterations.
  • Context overload: Long tool outputs strain the context window. Truncate them.
  • No fallback: When the agent fails, a fallback should kick in.

Further Reading

Key Takeaways:

  • The AI Agent Node connects a model, tools, and memory into a true agent.
  • Ollama with llama3.1 or qwen2.5 as your local backend.
  • Tools: HTTP requests, code execution, databases, even sub-workflows.
  • Set max iterations and write precise tool descriptions.
  • Security: restrict tool permissions, validate output, log everything.

FAQ

What is the AI Agent Node in n8n?

A node that connects a language model with tools. The agent plans on its own, calls tools, and iterates until the task is complete, not just a single prompt.

Which Ollama models can call tools?

llama3.1, qwen2.5, mistral-nemo, and other recent models. The model must support Function Calling. llama3.1:8b is a good starting point.

Which tools can I connect?

HTTP requests (APIs, web search), code nodes (calculations), databases (Postgres, MySQL), vector databases (RAG), and even other n8n workflows as tools.

How does memory work?

Memory stores the conversation history. Window Buffer keeps the last N messages, while Redis/Postgres enable persistent conversations across sessions.

What is maxIterations?

The maximum number of tool calls the agent is allowed to make. Prevents infinite loops. 10 is a good starting value.

Are agents in n8n secure?

With the right measures: restrict tool permissions, set maxIterations, validate critical outputs, filter prompt injection, and log everything.

Which agent type should I choose?

Tools Agent for most cases. Conversational Agent for chat. Plan-and-Execute for complex multi-step tasks. SQL Agent for database queries.

How fast are local agents?

Each tool call takes 2-10 seconds depending on your model and hardware. An agent with 5 steps takes roughly 30-60 seconds. Larger models are slower but better.

How do I debug agents?

Enable returnIntermediateSteps to see every tool call and decision. n8n displays all steps in the Executions log.

Local or cloud model for agents?

Local (Ollama) for privacy and no API costs. Cloud (OpenAI, Claude) for better tool-calling quality on complex agents. Hybrid is possible.

Sources and Further Reading

Back to Blog
Share:

Related Posts