Skip to main content
Automation June 10, 2026 · 12 min read

How to Build an AI Marketing Agent with n8n: Step-by-Step Guide

Build an AI marketing agent in n8n using the AI Agent node, OpenAI, and web search. Step-by-step tutorial with marketing workflows you can deploy today.

Edward Chalupa

Edward Chalupa

Founder, Whtnxt · Dallas, TX

How to Build an AI Marketing Agent with n8n: Step-by-Step Guide

Every week, marketing teams in Dallas, Fort Worth, and across Texas ask me the same question: “Can n8n actually run an AI agent, or do I need a developer for that?”

The short answer is yes, n8n can run AI agents - and you do not need a developer to build one.

I have been running n8n agents in production since early 2025 for client work. They handle competitor research, content brief generation, lead triage, and SEO keyword discovery. The AI Agent node in n8n now supports OpenAI, Anthropic, Mistral, Google Gemini, and local models via Ollama, all inside a visual workflow builder that costs nothing to self-host.

This guide walks through building a marketing research agent from scratch. You will end up with a working agent that can research competitors, analyze search results, and write structured reports - all triggered from a simple webhook or scheduled to run daily.

What This AI Marketing Agent Will Do

The agent we are building performs three marketing-specific tasks:

  • Competitor monitoring: it reads a competitor URL, extracts content, and flags changes in positioning, pricing, or offers.
  • Keyword opportunity discovery: it searches Google for a target term, reads top-ranking pages, and identifies content gaps.
  • Structured report generation: it writes findings to Google Sheets and sends a Slack or email summary.

This is not a chatbot. It is an autonomous marketing research agent that runs on a schedule, produces output your team can actually use, and costs pennies per execution.

What You Will Need

Before we start, make sure you have these:

  • n8n running - self-hosted with Docker (free) or n8n Cloud (paid). I cover the self-hosted setup in my previous n8n guide
  • An OpenAI API key - the AI Agent node uses it for reasoning. Anthropic and Mistral work too, but OpenAI gives the best tool-calling results for marketing workflows
  • A SerpAPI key - the agent needs web search access. SerpAPI costs $0.01 per search and works directly inside n8n
  • A Google Sheets connection (optional) - for storing agent output. n8n has native Google Sheets nodes

You also need basic familiarity with n8n workflows. If you are new, start with the lead routing tutorial first.

Step 1: Create the Workflow and Add a Trigger

Open n8n and create a new workflow. Name it “Marketing Research Agent.”

For this agent, add a Schedule Trigger node that fires daily at 8 AM. Marketing research is most useful when it runs on a cadence, not on demand.

Configure the trigger:

  • Trigger Times: “Every Day”
  • Hours: 8
  • Minutes: 0

If you prefer to test manually first (recommended), add a Manual Trigger node alongside the schedule. Connect both to the next step using n8n’s “Merge” node with “Combine” mode.

Step 2: Add the AI Agent Node

Search for “AI Agent” in the node palette and add it. This is the core of the system.

The AI Agent node in n8n wraps LangChain’s agent framework. It works by running a reasoning loop: the model receives a prompt, decides which tool to call, executes the tool, and decides whether the result satisfies the original goal or needs another step. If you are new to n8n’s workflow patterns, the three automations every marketing team needs post covers the foundational workflows that complement an AI agent.

Configure these settings:

  • Language Model: Select “OpenAI” and connect an existing credential or create one with your API key
  • Model: gpt-4o-mini (cheapest option for research tasks - $0.15 per million input tokens)
  • Max Iterations: 10 (the agent will stop after 10 tool calls to prevent runaway loops)
  • System Prompt: Enter the prompt template below

The system prompt is the most important part. It tells the agent what it is and how to behave:

You are a marketing research agent. Your job is to research competitors,
find keyword opportunities, and write structured reports.

When given a target company or keyword:
1. Search for the most recent information using the web search tool
2. Read at least two top-ranking pages from the results
3. Extract key findings: positioning, pricing signals, content gaps
4. Write a structured report with findings

Be specific. Include numbers, dates, and direct quotes where possible.
Do not make up information. If you cannot find data, say so.
Structure your final report with clear sections.

Step 3: Connect a Web Search Tool

The AI Agent node needs tools to accomplish its tasks. Without tools, it can only respond based on its training data - which for a marketing agent means outdated or hallucinated information.

Add an HTTP Request node as a sub-node of the AI Agent. This will call the SerpAPI Google Search endpoint.

Configure the HTTP Request:

  • Method: GET
  • URL: https://serpapi.com/search
  • Query Parameters:
    • q: {{ $json.query }} (the agent will pass a search query)
    • api_key: your SerpAPI key
    • engine: google
    • num: 5
  • Response Format: JSON Auto-Parse

The key insight here is that the AI Agent automatically converts this HTTP Request node into a tool it can call. When the agent decides it needs to search, it outputs a JSON object with a “query” field, which the HTTP Request node receives and executes.

Connect a second HTTP Request node for page content extraction. This tool lets the agent read actual articles:

  • Method: GET
  • URL: {{ $json.url }}
  • Response Format: String (the agent will parse it for relevant information)

Name this node “Read Web Page” so the agent understands its purpose.

You can add more tools - a Slack node for sending notifications, a Google Sheets node for storing results, or a Notion node for updating a database. Each becomes a new capability the agent can use autonomously.

For a honest comparison of n8n’s AI capabilities against other platforms, see my MCP servers for marketers guide.

Step 4: Add Agent Memory

A marketing agent that starts fresh every run is fine for batch research, but if you want the agent to remember past findings, you need memory.

Add a Window Buffer Memory sub-node to the AI Agent node:

  • Context Window Length: 20 (messages)
  • Session Key: marketing-research-session

With memory, the agent can reference its previous research, avoid duplicating work, and build on earlier findings. For example, asking “what did we find about Goat Home Services last week?” would work because the conversation history includes the prior research report.

For production deployments handling multiple clients, use Postgres Memory instead. It stores session state in a database table keyed by session ID, so each client’s research stays isolated. This is how I run it for client work at Whtnxt - one agent workflow, many session keys, zero data leakage.

Step 5: Build a Structured Output Formatter

Raw AI agent output is useful but messy. The final step routes the agent’s response through a formatter before storing it.

Add a Code node after the AI Agent node. This transforms the agent’s markdown report into a structured object:

// Parse agent response into structured fields
const response = $input.first().json;

const text = response.output || response.text || '';

// Extract sections using simple markers
const sections = {
  fullReport: text,
  competitorSummary: text.match(/(?<=## Competitor Summary\s*\n)[\s\S]*?(?=\n##|$)/)?.[0]?.trim() || '',
  keywordFindings: text.match(/(?<=## Keyword Findings\s*\n)[\s\S]*?(?=\n##|$)/)?.[0]?.trim() || '',
  recommendations: text.match(/(?<=## Recommendations\s*\n)[\s\S]*?(?=\n##|$)/)?.[0]?.trim() || '',
  wordCount: text.split(/\s+/).length,
  timestamp: new Date().toISOString()
};

// Add a confidence score based on how many sections were filled
const filledSections = [sections.competitorSummary, sections.keywordFindings, sections.recommendations]
  .filter(s => s.length > 20).length;
sections.completenessScore = Math.round((filledSections / 3) * 100);

return sections;

This code checks that the agent actually produced useful output. If completenessScore is under 30%, the agent probably failed to find useful data - a downstream workflow could skip sending that report.

Step 6: Route the Output

Connect the Code node to two outputs:

  1. Google Sheets - store every report in a research log. This gives you a running history you can review, search, and analyze for trends over weeks or months.

  2. Slack or Email - send a summary notification. Use n8n’s Slack node or SMTP node to deliver the report title, key finding, and a link to the full results.

Configure the Google Sheets node:

  • Operation: Append
  • Sheet ID: your spreadsheet ID
  • Range: Sheet1 (or a named range)
  • Columns Mapping: Map the Code node output fields to columns

The Google Sheets approach is particularly valuable for agencies and consultancies in DFW managing multiple clients. Each client gets their own sheet tab, and the agent writes to the correct location based on the trigger parameter.

Step 7: Deploy and Schedule

Activate the workflow. The Schedule Trigger will fire at 8 AM daily.

Test it now by clicking “Execute Workflow” on the manual trigger. The agent will:

  1. Receive a default research target (you can hard-code one in the trigger for initial testing)
  2. Search the web
  3. Read competitor pages
  4. Write a structured report
  5. Append to Google Sheets
  6. Send a Slack notification

The first run takes 30-60 seconds because the agent makes multiple tool calls. Subsequent runs with cached data are faster.

Real-World Usage: DFW Marketing Research Agent

Here is how I run this exact agent for my agency:

Every morning at 7:30 AM, the agent researches three DFW home service competitors - companies that target the same keywords as my client in Dallas, Plano, Frisco, and McKinney. It checks their Google Ads copy, reads their latest blog posts, and flags any new offers or pricing pages. The report lands in a Google Sheet by 8 AM.

Over three months, this agent has logged 180 research reports. It flagged a competitor’s seasonal discount campaign six days before the client noticed it organically. It identified five content keywords the competitors were ranking for that my client did not have pages for, which became the basis for a two-week content sprint.

The total cost: about $2.40 per month in SerpAPI calls and $0.60 in OpenAI API usage.

When an AI Agent Makes Sense vs When It Does Not

I see people build AI agents for tasks that a simpler n8n workflow handles better. Here is my rule of thumb:

Use an AI Agent when:

  • The input changes unpredictably (different competitors, different questions each run)
  • You need the system to reason and make decisions (what to research, what to prioritize)
  • The output needs to adapt to the findings (longer report for rich data, shorter for sparse data)

Use a plain n8n workflow when:

  • The task is predictable (always scrape the same URL, always format the same way)
  • You need absolute consistency (AI agents are probabilistic - same input, different output)
  • The data volume is high (AI agents cost per call; workflows cost nothing to run)

For most marketing teams, the sweet spot is 2-3 AI agent workflows for research and triage, plus 10-15 standard n8n workflows for everything else. This is the architecture I describe in my marketing automation engine guide.

Production Tips

After running AI agents in n8n for six months, here is what I have learned:

Set error handling on every tool node. AI agents will call tools with bad parameters. Add “Continue on Fail” and “Retry on Fail” on the HTTP Request nodes so the agent recovers gracefully and logs the failure instead of crashing the entire workflow.

Pin test outputs to bypass the agent during testing. When testing downstream formatting, pin the Code node input so you do not pay for AI calls on every test run. Right-click any node in the n8n editor and select “Pin Data.”

Use gpt-4o-mini, not gpt-4o. For research and summarization, the mini model costs 95% less and produces nearly identical results. Reserve gpt-4o for tasks requiring deep reasoning, like analyzing legal documents or complex pricing spreadsheets.

Add a human-in-the-loop for high-stakes actions. If the agent is writing social media posts or sending emails, insert an n8n Approval node. The agent drafts the content, the human approves or edits it, and only then does it send. This catches the hallucinations before they reach customers.

Monitor execution costs weekly. n8n’s execution log shows the duration of each workflow run. Multiply by your model’s per-token cost to track spending. A well-configured research agent should cost $3-5 per month. If you are spending more, reduce the max iterations or switch to a cheaper model. For broader context on how these costs compare to other automation approaches, the self-hosting NocoDB vs Airtable guide covers the economics of running your own stack.

Next Steps

You now have a working AI marketing agent in n8n. From here, you can:

  • Add more tools: connect a Google Analytics node so the agent checks traffic data before making SEO recommendations
  • Build a multi-agent system: one agent for research, another for content brief generation, a third for distribution - each calling the others via n8n sub-workflows
  • Hook it to a client dashboard: use n8n’s webhook trigger so clients can request custom research on demand. The client onboarding automation pipeline shows how to connect agent outputs to a full client-facing workflow.

The AI Agent node in n8n turns your marketing automation stack from a set of rigid if-this-then-that rules into a system that can actually think, research, and make decisions. It is not magic - it is LangChain running under a visual interface - but for marketing teams, that distinction does not matter. What matters is that your competitor research happens automatically at 8 AM every day, and you get a usable report in your inbox, without writing a line of Python.

n8nAI agentmarketing automationworkflow automationOpenAIAI automationno-code automation
Share: