How to Build an AI Agent with n8n and OpenAI: Step-by-Step Guide
How to build an AI agent with n8n and OpenAI is one of the most practical skills a business owner or operator can pick up in 2026. An AI agent built on this stack does not just answer questions. It takes actions. It reads incoming data, reasons about what to do next, calls external tools, writes results to your CRM, sends messages, books appointments, and loops back to check its own output, all without a human in the loop.
This guide walks through the full build from a blank n8n canvas to a working AI agent connected to OpenAI, equipped with memory, and wired into your business tools. If you want to understand how this fits into a broader automation strategy before getting into the technical steps, read about how AI automation works for service businesses first.
What an AI Agent Actually Does Versus a Simple Chatbot
Most business owners have seen a chatbot. You type a question, it returns an answer, the conversation ends. A chatbot is reactive and stateless. It does not remember the previous message unless the developer explicitly passes conversation history into each request, and it does not take any action beyond generating text.
An AI agent is different in three ways. First, it has tools it can call during a conversation, meaning it can look up live data, write to a database, send an email, or trigger another workflow based on what the user says. Second, it has memory that persists across turns, so it knows what was said earlier in the conversation and can reference it later. Third, it can reason about multi-step tasks and decide on its own which tool to use next based on the current context.
Building this on n8n and OpenAI gives you full control over every layer. You decide which tools the agent can access, what it remembers, how it handles errors, and where it sends its output. Nothing is locked inside a proprietary platform you cannot inspect or modify.
What You Need Before You Start
Before opening n8n, have three things ready.
An n8n instance either on n8n cloud or self-hosted. The cloud version at app.n8n.cloud works for building and testing. For production use, a self-hosted instance on a VPS with at least 2GB RAM gives you better performance and no execution limits.
An OpenAI API key from platform.openai.com. You will use this to connect n8n to GPT-4o or GPT-4o-mini. GPT-4o-mini is significantly cheaper for high-volume workflows while still capable enough for most business agent tasks. Keep your API key handy because you will paste it into n8n's credential manager in the first setup step.
A clear definition of what your agent will do. The most common mistake in AI agent builds is starting with the technical setup before defining the agent's job. Write one paragraph describing what the agent does, what inputs it receives, what decisions it makes, and what outputs it produces. That paragraph becomes the foundation of your system prompt.
Step 1: Set Up Your OpenAI Credentials in n8n
Open your n8n instance and go to Settings, then Credentials. Click Add Credential and search for OpenAI. Paste your API key into the API Key field and save. n8n will verify the connection automatically.
Name the credential something clear like "OpenAI Production" so you can identify it quickly when building multiple workflows. If you manage client accounts or have separate OpenAI keys for different projects, create a separate credential for each one rather than sharing a single key across all workflows.
Step 2: Create a New Workflow and Add a Trigger
Click New Workflow in the n8n dashboard. Every workflow starts with a trigger node that defines what causes the agent to run.
For a conversational AI agent that responds to messages, use the Chat Trigger node. This creates a built-in chat interface inside n8n that you can test with immediately. It also generates a webhook URL you can connect to an external frontend, a WhatsApp integration, a website chat widget, or any other input source later.
For an agent that processes incoming emails, use the Gmail Trigger or Email Trigger node. For an agent that runs on a schedule to process a batch of records, use the Schedule Trigger. The trigger type depends entirely on your agent's job. For this guide we will use the Chat Trigger since it is the fastest way to test agent behavior in real time.
Add the Chat Trigger node to your canvas by clicking the plus icon and searching for "Chat Trigger." Click it once to open settings. Leave the default settings for now and close the panel. You will see a green chat bubble icon on your canvas. This is your agent's entry point.
Step 3: Add the AI Agent Node
Click the plus icon below your Chat Trigger and search for "AI Agent." Select the AI Agent node. This is n8n's core agent orchestration node. It handles the reasoning loop, tool selection, memory retrieval, and response generation in a single node rather than requiring you to wire all of that manually.
Inside the AI Agent node settings you will see four key sections: Chat Model, Memory, Tools, and System Prompt.
Leave the node open and work through each section in order.
Step 4: Connect OpenAI as the Chat Model
Inside the AI Agent node, find the Chat Model section and click the model selector. Choose OpenAI Chat Model from the dropdown. A sub-node will appear on your canvas connected to the AI Agent node. Click it to open its settings.
Select the OpenAI credential you created in Step 1. For the model field, choose gpt-4o for maximum capability or gpt-4o-mini for cost efficiency on high-volume workflows. Set Max Tokens to 1000 for most business agent tasks. This controls the maximum length of each response and directly affects your API cost per call.
Temperature controls how creative versus how predictable the model's responses are. For a business agent handling factual tasks like lead qualification, appointment booking, or FAQ answering, set temperature to 0.3. For a more conversational agent where some variation in phrasing is acceptable, 0.7 works well.
Step 5: Add Memory So the Agent Remembers the Conversation
Without memory, your AI agent forgets everything the user said the moment a new message arrives. Every turn starts from scratch. This is acceptable for single-turn tasks but makes multi-turn conversations completely non-functional.
Inside the AI Agent node, find the Memory section and click Add Memory. Select Window Buffer Memory from the options. This is the simplest memory type and works well for most business agents. It stores the last N turns of the conversation in n8n's internal memory and passes them into each new OpenAI request automatically.
Set the Window Size to 10. This means the agent remembers the last 10 messages, which covers most business conversations without bloating the context window and increasing API costs unnecessarily.
For agents that need to remember information across separate sessions, such as a returning customer's preferences or a client's project history, you need a persistent memory solution like Supabase or Pinecone. That is a more advanced setup covered in a follow-up guide.
Step 6: Write the System Prompt
The system prompt tells the AI agent who it is, what it does, what it knows, and how it behaves. This is the most important configuration step in the entire build. A vague system prompt produces an agent that drifts off topic, hallucinates, and fails to take the right actions. A precise system prompt produces an agent that behaves consistently and professionally across every conversation.
Inside the AI Agent node, find the System Prompt field. Write your prompt using this structure:
Start with identity. You are [name], an AI assistant for [business name]. Your job is to [specific function].
Follow with behavioral rules. You speak in a [tone] tone. You never discuss [off-limits topics]. You always [specific required behaviors like confirming contact details before ending a conversation].
Add a knowledge block. List the business's services, hours, service area, pricing guidelines, and any FAQs the agent should answer from memory rather than deferring to a human.
End with escalation instructions. If a user asks something outside your knowledge, tell them [specific response]. If a user expresses urgency or frustration, [specific behavior].
A well-written system prompt for a business agent is typically 400 to 700 words. Do not try to compress it. Every sentence of a good system prompt prevents a category of bad agent behavior.
Step 7: Add Tools So the Agent Can Take Actions
Tools are what separate an AI agent from a chatbot. Without tools, the agent can only generate text. With tools, it can look up data, create records, send messages, and trigger other workflows.
Inside the AI Agent node, find the Tools section and click Add Tool. n8n shows you available tool types. The most commonly used tools for business agents are HTTP Request Tool for calling external APIs, n8n Workflow Tool for triggering other n8n workflows as sub-agents, and native integration tools for specific apps like Google Calendar, HubSpot, or GoHighLevel.
For a lead qualification agent, add a tool called "create_crm_contact" with a description that says: "Use this tool when you have collected the caller's name, email, phone number, and service interest. Create a new contact record in the CRM." Connect it to your CRM via the relevant n8n node or HTTP Request.
For an appointment booking agent, add a tool called "book_appointment" with a description that tells the agent when to call it. Connect it to a Calendly webhook or a GoHighLevel calendar API call.
The tool description is critical. The AI agent reads the description to decide when to use each tool. Write the description as a clear instruction, not a technical label.
Step 8: Test the Agent End to End
Save your workflow and click the chat bubble icon on the Chat Trigger node to open the built-in test chat. Type a message that represents a real user interaction your agent will handle.
Watch the execution panel on the right side of the canvas. n8n shows you every node that fires, the data that passed through it, and whether each step succeeded. If the agent responds incorrectly, check the AI Agent node's output to see what the model returned and trace back to which system prompt instruction it violated or which tool description was ambiguous.
Run at least ten test conversations covering normal cases, edge cases, and frustration scenarios before connecting the agent to a live input source. The execution log makes debugging fast because you see exactly what the model received and what it decided to do at every step.
Once the agent performs correctly across all test scenarios, connect your Chat Trigger to a live input source. This could be a website chat widget via webhook, a WhatsApp Business API integration, a Slack bot, or a custom frontend. The Chat Trigger's webhook URL is the connection point for all of these.
Connecting Your AI Agent to GoHighLevel
For service businesses using GoHighLevel as their CRM, connecting your n8n AI agent to GHL closes the loop between conversation and pipeline management automatically.
Add an HTTP Request node as a tool inside your AI Agent. Configure it to call the GoHighLevel API endpoint for creating contacts. Pass the name, email, phone, and any service interest data the agent collected during the conversation as the request body. When the agent determines it has enough information to create a contact, it fires the tool, GHL creates the record, and the lead appears in your pipeline without any manual entry.
You can extend this further by adding a second GHL API call that creates a task or opportunity record linked to the new contact, assigns it to a team member, and sends an internal SMS notification. The entire sequence fires automatically within seconds of the agent collecting the lead's information. To see how this fits inside a complete front-office automation system, the AI automation services for local businesses page covers what a full client deployment looks like.
What to Build After Your First AI Agent
Once your first agent is live and handling real conversations, the natural next steps are a second agent that specializes in a different task and a supervisor workflow that routes incoming requests to the right specialist agent based on intent.
Common second agents for service businesses include a follow-up agent that re-engages leads who did not convert after the first contact, a review request agent that messages completed job customers asking for a Google review, and a reactivation agent that reaches out to past customers who have not booked in over six months.
Each of these runs on the same n8n and OpenAI stack you built in this guide. The system prompt changes, the tools change, and the trigger changes, but the architecture is identical. For businesses that want this entire agent network built and deployed without handling the technical build themselves, book a free audit with Octacs Systems and we will scope the full system based on your current operations.
Frequently Asked Questions
Do I need coding experience to build an AI agent with n8n and OpenAI?
The core agent setup in n8n requires no coding. The Chat Trigger, AI Agent node, OpenAI Chat Model, and Window Buffer Memory all configure through point-and-click interfaces with no code required. Where basic technical knowledge helps is in writing tool definitions and connecting the agent to external APIs via the HTTP Request node, which involves reading API documentation and mapping fields. Most business owners with some comfort around SaaS tools can complete this setup in a day. If you want a production-ready agent without the learning investment, an n8n specialist can build it for you in a few hours.
How much does it cost to run an AI agent on n8n and OpenAI?
The cost has two components. n8n self-hosted on a basic VPS costs $10 to $20 per month with no execution limits. OpenAI API costs depend on the model and usage volume. GPT-4o-mini costs approximately $0.15 per million input tokens and $0.60 per million output tokens as of mid-2026. A business agent handling 500 conversations per month at an average of 500 tokens per turn spends roughly $2 to $5 in OpenAI API costs. Total monthly cost for a self-hosted n8n agent handling moderate business volume sits between $12 and $25, far below the cost of any commercial AI agent platform.
What is the difference between an AI agent and an n8n automation workflow?
A standard n8n automation workflow follows a fixed path. Every execution follows the same steps in the same order. An AI agent workflow uses a reasoning loop where the model decides which step to take next based on the current context. This means the agent can handle inputs it has never seen before and choose the right tool for each situation dynamically. A standard automation is better for predictable, repeatable tasks with consistent inputs. An AI agent is better for tasks that require interpretation, judgment, or handling a wide variety of possible inputs.
Can the AI agent remember information from previous conversations?
Window Buffer Memory in n8n retains conversation history within a single session only. When the session ends, the memory clears. For agents that need to remember information across separate conversations, such as a returning customer's previous service history or preferences, you need to connect the agent to a persistent database. Supabase works well for this. You store conversation summaries or key facts in a Supabase table after each session ends and retrieve them at the start of the next session using a tool the agent can call when it recognizes a returning user.
Which OpenAI model should I use for a business AI agent?
GPT-4o-mini is the right starting point for most business agent tasks including lead qualification, FAQ answering, appointment booking, and basic customer support. It is fast, cheap, and capable enough for structured business conversations. GPT-4o is worth the higher cost when the agent needs to handle complex reasoning, nuanced customer situations, or tasks that require following multi-step instructions accurately across long conversations. Start with GPT-4o-mini, test it against your real use cases, and upgrade to GPT-4o only for the specific tasks where the quality difference is noticeable.
How do I connect my n8n AI agent to a website chat widget?
The Chat Trigger node in n8n generates a webhook URL when you activate the workflow. Any chat widget that supports custom webhook endpoints can connect to this URL and send messages directly to your agent. For a more polished integration, you can build a simple frontend using a JavaScript chat widget library that posts messages to the webhook URL and displays responses. If your website runs on WordPress or a similar CMS, plugins exist that let you point a chat widget at a custom webhook without writing code. For a fully branded chat experience embedded in your business website, a developer can build a lightweight frontend in an afternoon.
Share this post

Written by
Octacs Systems
Octacs Systems is a hybrid AI automation and digital solutions agency helping service businesses across the United States grow smarter. We build AI agents, workflow automation systems, and professional websites that generate real leads for plumbers, electricians, contractors, and local service businesses.
Related Articles

How to Build a WhatsApp Chatbot with n8n: Complete Setup Guide
How to build a WhatsApp chatbot with n8n in 2026. Full setup covering WhatsApp Business API, triggers, message handling, and CRM connection.

How to Build an AI Voice Receptionist with VAPI
VAPI lets you build an AI voice receptionist that answers calls, qualifies leads, and books appointments 24/7. Full setup guide inside.

GoHighLevel for Contractors: How to Automate Your Leads, Follow-Up, and Bookings in 2026
GoHighLevel for contractors handles your leads, bookings, and reviews automatically. Here is exactly how to set it up and what it does for your business

