n8n + AI Agents: How to Build Your First Automated Workflow (Step-by-Step)
On this page (13)
- Prerequisites
- What Makes a Workflow “Agentic” vs Fixed-Sequence Automation
- Step 1: Set Up Your Trigger
- Step 2: Add an AI Agent Node with Tool Calling
- Step 3: Define Your Agent’s Tools
- Tool 1: Look Up Company Information
- Tool 2: Score the Lead
- Tool 3: Post to Slack
- Step 4: Handle Memory and Context
- Step 5: Test, Error Handling, and Guardrails
- The Lead Qualification Example — Walking Through It
- Common Pitfalls to Avoid
- Getting Started
If you’ve built workflows in n8n before, you know the pattern: trigger fires, then a hardcoded sequence of steps executes—look up a contact, send an email, log the result. Fixed. Deterministic. Predictable.
Agentic workflows are different. Instead of you choreographing every step, you give the AI agent a set of available tools, describe what you want it to achieve, and the agent decides which tools to call, in what order, how many times, and when to stop. It’s the difference between playing chess with predetermined moves and playing chess where the system figures out the best move for each position. That flexibility is powerful—and worth the added complexity if you’re solving problems where the path isn’t known in advance.
This is a step-by-step guide to building your first agentic workflow in n8n, using a concrete example: an inbound lead qualification agent that looks up a company, scores the lead based on company size and industry, and posts the result to Slack. By the end, you’ll know how to wire up an AI agent node, give it tools, handle errors, and deploy something that actually works.
Prerequisites
Before you start, you’ll need:
- An n8n instance. Either self-hosted (via Docker, a VPS, or Coolify) or n8n Cloud (which has a free tier). I’ll assume you can SSH into your instance or access n8n Cloud’s editor.
- An LLM API key. OpenAI (GPT-4 or 4o-mini), Anthropic Claude, or another provider that supports tool calling. Costs are usually a few cents per workflow run.
- Read access to a data source. In our example, we’ll use an HTTP request to a public company database (or mock one). In production, this is usually your CRM API (HubSpot, Pipedrive, Salesforce).
- Write access to Slack (or wherever you want to log results). You’ll need a Slack bot token with the
chat:writepermission.
What Makes a Workflow “Agentic” vs Fixed-Sequence Automation
A fixed-sequence workflow looks like this:
- Trigger fires (new form submission).
- Step 1: Look up the person in HubSpot.
- Step 2: If not found, create a contact.
- Step 3: Send a welcome email.
- Step 4: Log to database.
Every path is predefined. You, as the builder, control the logic.
An agentic workflow looks like this:
- Trigger fires (new form submission).
- AI Agent receives: the form data + a list of available tools (look up company, score lead, send email, log result).
- Agent decides: “I should look up the company first, score them, then decide whether to send an email or a Slack alert based on the score.”
- Agent executes tool calls in whatever order and frequency it decides.
- Workflow returns the agent’s final reasoning and results.
The key difference: the agent chooses which tools to call and in what order. You provide guidance via system prompts and tool definitions, but the agent has agency. This is incredibly useful when the workflow depends on what you discover along the way—e.g., “if the company is a startup, handle it differently than if it’s enterprise.”
In n8n, agentic workflows are built with the AI Agent node (also called the “n8n AI Agent” or in some versions, the “Langchain Agent” node), paired with any LLM that supports function calling.
Step 1: Set Up Your Trigger
Start with the simplest trigger: a webhook. This simulates a form submission or an inbound event.
- Create a new workflow in n8n.
- Add a Webhook node (in n8n, this is under Core Nodes → Webhook).
- Set the HTTP method to POST and give it a path like
/lead-intake. - Save the node. n8n will give you a webhook URL to test with.
For this example, imagine the webhook receives JSON like:
{
"name": "Alice Chen",
"email": "alice@example.com",
"company": "Acme Corp",
"message": "Interested in your automation service"
}
Step 2: Add an AI Agent Node with Tool Calling
Now add the AI Agent node:
- In the n8n editor, add a new node → search for “AI Agent” (the exact name depends on your n8n version; look for “Langchain Agent” or “AI Agent”).
- Connect it to the Webhook node.
- Select your LLM model and add your API key (OpenAI, Anthropic, etc.). Make sure the model supports function calling (GPT-4 Turbo, Claude 3 Haiku/Sonnet/Opus, etc.).
- In the Agent Configuration, write a system prompt. This is crucial—it tells the agent what its job is:
You are a lead qualification agent. Your job is to:
1. Look up the company information using the available tools.
2. Score the lead based on company size, industry, and the inbound message.
3. Post a summary to Slack with the score and recommendation.
Be methodical. Look up the company first, then score, then notify. Do not skip steps.
- Leave the “Max Iterations” at 10-15. This is the max number of tool calls the agent will make before stopping (a safety limit).
Step 3: Define Your Agent’s Tools
This is where you specify what the agent can actually do. In n8n, you’ll use the “Tools” section of the AI Agent node to list each tool. Each tool is either:
- A built-in n8n node (HTTP Request, CRM Query, Slack Message, etc.), or
- A custom tool defined via JSON.
For our lead qualification agent, define three tools:
Tool 1: Look Up Company Information
Use an HTTP Request node (or a native CRM node if you’re using HubSpot).
Tool name: lookup_company
Description: "Fetch company details including size, industry, and location. Takes a company name as input and returns company_size (small/medium/large), industry, and headquarters location."
Input: company_name (string)
Output: { company_size, industry, location, founded_year }
In n8n, reference this by wiring an HTTP Request node to the AI Agent node’s “Tools” array, or by creating a sub-workflow the agent can call.
Tool 2: Score the Lead
Create a Code node (or use a function call to Claude) that scores based on criteria:
Tool name: score_lead
Description: "Score the lead on a scale of 1-10 based on company size, industry, and message sentiment. Returns a score, reasoning, and a recommendation (cold, warm, hot)."
Input: company_size, industry, message
Output: { score, reasoning, recommendation }
Tool 3: Post to Slack
Use an HTTP Request or Slack node:
Tool name: post_to_slack
Description: "Post a message to the sales-leads Slack channel with the lead summary and score."
Input: lead_name, company, score, recommendation
Output: { status, timestamp }
In n8n’s AI Agent node, you’ll reference these tools. The exact syntax depends on your n8n version, but it looks something like:
[
{
"name": "lookup_company",
"description": "Fetch company details by name.",
"inputSchema": {
"type": "object",
"properties": {
"company_name": { "type": "string" }
},
"required": ["company_name"]
}
},
{
"name": "score_lead",
"description": "Score the lead 1-10 based on company and message.",
"inputSchema": {
"type": "object",
"properties": {
"company_size": { "type": "string" },
"industry": { "type": "string" },
"message": { "type": "string" }
}
}
},
{
"name": "post_to_slack",
"description": "Post the lead summary to Slack.",
"inputSchema": {
"type": "object",
"properties": {
"lead_name": { "type": "string" },
"company": { "type": "string" },
"score": { "type": "number" },
"recommendation": { "type": "string" }
}
}
}
]
Step 4: Handle Memory and Context
One of the trickiest parts of agentic workflows is state management: making sure the agent remembers what it discovered in earlier steps and can refer to it.
n8n handles this via the message history in the AI Agent node. Each tool call and response is logged, so the agent sees:
Agent: "I'll look up Acme Corp."
Tool response: { company_size: "large", industry: "SaaS", founded_year: 2015 }
Agent: "Acme is large and SaaS. With the positive message, the lead score is 8/10."
The LLM’s context window includes all of this. If you’re running multi-step workflows that take a while, you can explicitly pass state between nodes:
- After the AI Agent completes, add a Merge or Code node to extract and log the agent’s final output:
{ "lead": webhook.data.name, "company": webhook.data.company, "agent_score": agent.output.score, "agent_reasoning": agent.output.reasoning, "actions_taken": agent.output.tool_calls } - Store this in a database (PostgreSQL, MongoDB, Airtable) for auditing and re-running workflows if needed.
Step 5: Test, Error Handling, and Guardrails
Before you deploy, test locally:
- Use n8n’s Test button to send a sample JSON to your webhook.
- Watch the Agent node execute. You’ll see each tool call and the agent’s reasoning in the debug panel.
- Check Slack—did the message post?
Now add error handling:
Timeout handling: If the LLM doesn’t respond in 30 seconds, the workflow should fail gracefully. In n8n, use a Try-Catch block around the AI Agent node:
Try:
- Run AI Agent
Catch:
- Log error to database
- Post error message to Slack (e.g., "Lead qualification failed. Manual review required.")
Limit tool calls: Set maxIterations on the AI Agent node to something reasonable (10-15). If the agent gets stuck in a loop calling the same tool repeatedly, it’ll stop after N iterations.
Hallucination guard: Some LLMs occasionally invent tool names that don’t exist. Mitigate this by:
- Using a smaller, cost-efficient model like Claude Haiku, which tends to be more conservative in tool calling than larger models.
- Keeping tool descriptions concise and unambiguous.
- Testing with your actual LLM before deploying.
Cost limits: If you’re calling an expensive LLM, add a conditional node that checks the query length or cost estimate before calling the AI Agent. For the lead qualification example, you’re probably fine (small queries, few tool calls). For high-volume workflows, watch your token spend.
The Lead Qualification Example — Walking Through It
Here’s a concrete walkthrough of what happens when Alice’s form submission arrives:
-
Webhook fires. n8n receives:
{ name: "Alice Chen", email: "alice@example.com", company: "Acme Corp", message: "Interested in your automation service" } -
AI Agent starts. The LLM (Claude, GPT-4) receives the form data and the system prompt:
“You are a lead qualification agent. Look up Acme Corp, score Alice based on company info and her message, then post to Slack.”
-
Agent calls
lookup_companywith input"Acme Corp". The HTTP Request node runs, and returns:{ company_size: "large", industry: "SaaS", location: "San Francisco", founded_year: 2015 } -
Agent calls
score_leadwith:{ company_size: "large", industry: "SaaS", message: "Interested in your automation service" }The Code node returns:
{ score: 8, reasoning: "Large SaaS company, established (2015), message indicates genuine interest. High-intent lead.", recommendation: "hot" } -
Agent calls
post_to_slack:{ lead_name: "Alice Chen", company: "Acme Corp", score: 8, recommendation: "hot" }Slack receives and posts the message to #sales-leads.
-
Workflow completes. n8n returns the full execution log: agent reasoning, all tool calls, final results.
The whole thing takes 5-10 seconds (depending on LLM latency). Next time an inbound lead arrives, the agent repeats the exact same process, without you coding it.
Common Pitfalls to Avoid
1. Unrestricted tool access. Don’t give the agent tools it doesn’t need. If it can call delete_all_leads and send_unlimited_emails, and it hallucinates a tool call, you’ll regret it. Be specific: “the agent can look up companies and post to Slack—nothing else.”
2. No cost or rate limits. If your lookup_company tool queries a paid API, and the agent calls it 20 times on one lead, you’ll get a bill. Add:
- Rate limiting: “This tool can be called max 3 times per workflow.”
- Cost estimates: Before calling an expensive LLM, estimate the token cost and reject if it exceeds your threshold.
3. No fallback when the LLM call fails. Network hiccups, API outages, rate limits—it happens. Always wrap the AI Agent node in error handling. A fallback might be: “Log to database, send alert to ops team, don’t try to call Slack.”
4. No human-in-the-loop for high-stakes actions. If the agent is scoring leads and the score drives next actions (auto-send email, auto-add to HubSpot, auto-book a call), you probably want a human to review high-stakes decisions. Add a review step:
If score >= 8, create a task in Linear for the sales team to review before auto-emailing.
If score < 5, auto-decline silently.
If 5 <= score < 8, add to a "manual review" queue.
5. Vague system prompts. “Be helpful” or “analyze the lead” won’t cut it. Be explicit:
“Score leads 1-10 based only on: company_size (1 point if small, 3 if medium, 5 if large), industry match (0-2 points if matches our target list), and message sentiment (1-3 points). Do not score based on personal name, email domain, or other factors.”
Getting Started
To ship your first agentic workflow:
- Create a simple trigger (webhook, scheduled, or manual).
- Add an AI Agent node with a single tool (e.g., an HTTP lookup).
- Test locally via n8n’s Test button.
- Add error handling (Try-Catch, fallback messages).
- Deploy and monitor for a week to catch edge cases.
Agentic workflows are not a silver bullet. They’re best for workflows where the path isn’t predetermined—classification, research, decision-making, multi-step discovery. For simple automations (send email when form submitted), stick with fixed sequences; they’re faster and more predictable.
But when you need flexibility, when the next step depends on what you discover, agents are game-changers. Start small, test thoroughly, and iterate.
Ready to build? If you need help scaling automation or designing complex workflows, check out our AI Automation service. And if you want to go deeper into agentic design patterns, system prompts, and production practices, the AI Product Builder course covers all of it hands-on.