All posts

Mithilesh Gaurihar

How to Build Better AI Agents with n8n

By Mithilesh Gaurihar. Last verified: November 2026.

A signed contract comes back from Northwind as a phone scan, and your n8n workflow picks it up from the shared inbox like any other PDF. Extract from File reads it and passes the AI Agent node two blank lines. On the text version of the same contract, that node returned 4,062 characters. The scan has no text to read, so the agent has no contract value to return.

To build better AI agents with n8n, you need five things: fewer tools with clear jobs, named fields instead of prose, memory keyed on something that lasts, a person in front of anything you can't undo, and a test set you run before every change. n8n's AI Agent node has a part for each. Scans need one more step first, because Extract from File reads a PDF's text layer and a scan doesn't have one.

When contracts arrive as scans, a RocketRide agent called from n8n's HTTP Request node runs OCR and extraction in one call and sends the terms back as fields, and the tutorial at the end builds it.

Five choices that make an n8n agent better

The AI Agent node already holds the whole agent. You connect a chat model, the tools it may use and a memory sub-node, and the agent decides which tool to call at each step. Because it sits inside the workflow, the trigger that starts it and the apps it writes to are one connection away.

Give the agent fewer tools, described in plain words

Each extra tool is another choice the model can get wrong, and agents with overlapping tools tend to loop until they hit the iteration limit (Tools Agent docs). "Look up a customer by email in the CRM" tells the model far more than "CRM tool".

On n8n Cloud the Code node can't import Python libraries, so code that needs them belongs on a self-hosted instance.

If one agent can't cover the work, a front agent can hand it to a specialist through the AI Agent Tool node or the Call n8n Workflow tool. Split only when the jobs need different tools, models or reviewers, since each hand-off is one more model call to pay for and test.

Ask for named fields, then branch on a number

A routing check needs a number, and a regex over the agent's prose breaks as soon as a contract spells its value out in words. Ask the agent for a set format and attach a Structured Output Parser, so an IF node checks a number. Tell it what to do when a term is missing: the contract prompt asks for "not stated" instead of a guess. While you debug, turn on Return Intermediate Steps to see which tools it called.

A hand-drawn flow on a cream background titled

Key memory on something that lasts

Simple Memory forgets everything between sessions. To remember a customer across days, an agent needs a database such as Postgres Chat Memory, Redis or MongoDB.

Pick the session key on purpose: the contract workflow keys memory on the Gmail thread, so replies share context and a new thread starts clean. Retrieval has the same trap: the Simple Vector Store loses its data when n8n restarts.

Put a person in front of anything you can't undo

n8n can pause an agent before a chosen tool runs and wait for approval in Slack, n8n chat or another channel (human-in-the-loop guide). Use it for anything that leaves the company, like the CRM update in the contract case. The Guardrails node can also swap phone and card numbers for placeholders before a model sees them.

Test on contracts you already know the answers to

n8n has evaluations built in. Start with ten real contracts, names removed, and the fields you expect from each, and run them on every prompt or model change. Put a scan or two in the set, since scans are what comes back empty. Add metric-based scoring once the agent is live.

Then keep a way back. n8n keeps a short workflow history on every plan, and Git-based source control comes with Business and Enterprise; on other plans, export the workflow JSON after each change that matters. Self-hosted n8n deletes executions after 14 days by default.

Where n8n gets awkward, and when to stay in n8n

Four jobs take more work in n8n than they should:

  • Scanned documents. Extract from File reads only a PDF's text layer, and on my scan it returned two blank lines. n8n does have an OCR option: the Mistral AI node has an Extract Text operation for documents and images. It needs a Mistral La Plateforme account with payments activated, it sends the file to Mistral's cloud, and it returns text, so fields still need another step. I read its docs but didn't run it.
  • Heavy extraction on the n8n instance. n8n doesn't limit how much data a node processes, and large files, Code nodes and other workflows running at the same time all draw on the same memory (n8n's memory guide). Its advice is more memory or splitting the work into sub-workflows.
  • Versioning and testing the agent on its own. The prompt, model and tools live inside one workflow and change with it. Testing the same agent from a script or another tool still means going through that workflow.
  • One document flow that several teams share. A Webhook trigger, or the MCP Server Trigger, which makes n8n workflows available to MCP clients, can share it. When legal, finance and procurement each want their own version of the same contract reader, each team ends up with a copy of the workflow or depends on someone else's.

I'd keep an agent in n8n when the process is internal, the agent has a few tools, the documents have a text layer, and nobody needs the AI step versioned and tested on its own. n8n already gives you human approval, evaluations, workflow history and a RAG path for a small knowledge base. A second system is one more thing to run, secure and pay for. On licensing, RocketRide is MIT licensed; n8n uses its Sustainable Use License, which it calls fair-code.

Tutorial: send a scanned contract from n8n to a RocketRide agent

Acme's legal ops team gets signed contracts back in a shared Gmail inbox, many of them phone scans, and the terms have to reach Slack. I built an agent that takes the PDF over a webhook, runs OCR and returns twelve fields to n8n, which posts them to Slack. To keep it short, a file-reading node stands in for the Gmail Trigger, Slack gets the message in a test channel, and there's no approval step.

RocketRide is an AI meta-harness with an enterprise-grade runtime built on C++, for companies and pro-builders building durable AI at production scale. Here it gives n8n one HTTP Request node that turns a scan into fields.

A hand-drawn flow on a cream background titled

1. Set the keys in one place

The agent reads its model key from the RocketRide workspace's .env, and n8n reads the Slack webhook from its own environment. These are all the variables the tutorial uses:

# RocketRide workspace .env
ROCKETRIDE_URI=          # your RocketRide server (RocketRide Cloud in my run)
ROCKETRIDE_APIKEY=       # your RocketRide API key
ROCKETRIDE_GEMINI_KEY=   # a Gemini API key; the agent file reads it as ${ROCKETRIDE_GEMINI_KEY}

# n8n environment
SLACK_WEBHOOK_URL=                   # a Slack incoming webhook for a test channel
N8N_BLOCK_ENV_ACCESS_IN_NODE=false   # lets the Slack node read SLACK_WEBHOOK_URL

RocketRide fills in only variables whose names start with ROCKETRIDE_. The agent's public key comes later, once it's running.

2. Write the agent file

The webhook takes the PDF, the parser splits it into text and page images, OCR reads the images, and the extractor asks Gemini for twelve typed fields. I saved this as contract-scan.pipe:

{
  "project_id": "6f3173d6-63e8-4073-a763-d87e5c412ddd",
  "components": [
    { "id": "webhook_1", "provider": "webhook", "config": { "type": "webhook", "mode": "Source" } },
    { "id": "parse_1", "provider": "parse", "config": { "type": "parse" },
      "input": [{ "lane": "tags", "from": "webhook_1" }] },
    { "id": "ocr_1", "provider": "ocr", "config": { "type": "ocr" },
      "input": [{ "lane": "image", "from": "parse_1" }] },
    { "id": "extract_data_1", "provider": "extract_data",
      "config": {
        "type": "extract_data", "profile": "default",
        "default": { "fields": [
          { "column": "party_a", "type": "text" },
          { "column": "party_b", "type": "text" },
          { "column": "agreement_type", "type": "text" },
          { "column": "effective_date", "type": "date" },
          { "column": "term_months", "type": "int" },
          { "column": "total_value_usd", "type": "decimal" },
          { "column": "payment_terms", "type": "text" },
          { "column": "notice_period_days", "type": "int" },
          { "column": "auto_renew", "type": "text" },
          { "column": "governing_law", "type": "text" },
          { "column": "liability_cap", "type": "text" },
          { "column": "signatories", "type": "text" }
        ] }
      },
      "input": [{ "lane": "text", "from": "parse_1" }, { "lane": "text", "from": "ocr_1" }] },
    { "id": "llm_gemini_1", "provider": "llm_gemini",
      "config": { "profile": "gemini-3_1-flash-lite-preview",
                  "gemini-3_1-flash-lite-preview": { "apikey": "${ROCKETRIDE_GEMINI_KEY}" } },
      "control": [{ "classType": "llm", "from": "extract_data_1" }] },
    { "id": "response_answers_1", "provider": "response_answers",
      "config": { "type": "response_answers", "laneName": "contract" },
      "input": [{ "lane": "answers", "from": "extract_data_1" }] }
  ]
}

Then I checked it against the server, and it came back valid:

rocketride validate contract-scan.pipe

3. Start the agent and copy its public key

Starting the agent creates its webhook and a public authorization key, which starts with pk_ and can only submit data to this one run. That's the key n8n gets.

export TOKEN=$(rocketride start --pipeline contract-scan.pipe --json | python3 -c 'import sys,json;print(json.load(sys.stdin)["token"])')
python3 - <<'EOF'
import asyncio, os
from rocketride import RocketRideClient
async def main():
    async with RocketRideClient() as c:
        st = await c.get_task_status(os.environ["TOKEN"])
        print([n["auth-key"] for n in st["notes"] if "auth-key" in n][0])
asyncio.run(main())
EOF

TOKEN is the run's private token: keep it for rocketride stop and never give it to n8n. If you start the agent from the IDE instead, the Project Log shows the same public key. The webhook address is https://api.rocketride.ai/webhook/ followed by the project_id from the agent file and the source id, webhook_1.

4. Add the HTTP Request node in n8n

In n8n I created a Bearer Auth credential holding the pk_ key, then added an HTTP Request node after the node that reads the PDF. These are its parameters from the workflow I ran:

"parameters": {
          "method": "POST",
          "url": "https://api.rocketride.ai/webhook/6f3173d6-63e8-4073-a763-d87e5c412ddd/webhook_1",
          "authentication": "genericCredentialType",
          "genericAuthType": "httpBearerAuth",
          "sendBody": true,
          "contentType": "multipart-form-data",
          "bodyParameters": {
            "parameters": [
              {
                "parameterType": "formBinaryData",
                "name": "file",
                "inputDataFieldName": "data"
              }
            ]
          },
          "options": {
            "timeout": 300000,
            "response": {
              "response": {
                "responseFormat": "json"
              }
            }
          }
        }

The form field is named file and takes the binary the previous node wrote to data. The pk_ key travels in the Authorization header, and the five-minute timeout leaves room for OCR.

5. Run it and read the fields

I ran the workflow on the scan. The HTTP Request node got an OK back in under half a minute, with the fields under contract, the lane name set in the Return Answers node:

{
  "agreement_type": "Master Services Agreement",
  "auto_renew": "Yes, successive 12-month periods",
  "effective_date": "2026-03-14",
  "governing_law": "State of Delaware",
  "liability_cap": "Total fees paid or payable in the 12 months preceding the claim (excluding confidentiality, indemnification, gross negligence, or wilful misconduct)",
  "notice_period_days": 60,
  "party_a": "Acme Corporation",
  "party_b": "Northwind Analytics, Inc",
  "payment_terms": "Net 45 days",
  "signatories": "Dana Whitfield (VP, Procurement, Acme Corporation); Marcus Ellery (Chief Executive Officer, Northwind Analytics, Inc)",
  "term_months": 24,
  "total_value_usd": 486000
}

The contract value, term, notice period and effective date all match the answers I had for the text version. Free-text fields such as the liability cap come back in the model's own words, so branch on the typed fields.

6. Post the terms to Slack

A second HTTP Request node posts to the Slack incoming webhook at SLACK_WEBHOOK_URL. Its body builds the message from the fields:

          "bodyParameters": {
            "parameters": [
              {
                "name": "text",
                "value": "={{ (() => { const c = $('RocketRide - Extract Contract').item.json.data.objects.file.contract.flat()[0]; return '*New contract processed (scanned PDF)*\\n\\n*Parties*  ' + c.party_a + ' and ' + c.party_b + '\\n*Type*  ' + c.agreement_type + '\\n*Value*  $' + c.total_value_usd.toLocaleString('en-US') + ' over ' + c.term_months + ' months\\n*Effective*  ' + c.effective_date + '\\n*Notice*  ' + c.notice_period_days + ' days\\n*Governing law*  ' + c.governing_law; })() }}"
              }
            ]
          }

Slack answered ok and posted this in the test channel:

*New contract processed (scanned PDF)*

*Parties*  Acme Corporation and Northwind Analytics, Inc
*Type*  Master Services Agreement
*Value*  $486,000 over 24 months
*Effective*  2026-03-14
*Notice*  60 days
*Governing law*  State of Delaware

You know it worked when the scan comes back with all twelve fields and the Slack post shows the contract value as a dollar figure over a term in months.

n8n carried the file, one HTTP Request node with a pk_ key, and the Slack post. RocketRide carried parsing, OCR, extraction and the Gemini key, and sent back typed fields for a PDF n8n couldn't read. In production the Gmail Trigger replaces the two test nodes, as in the recorded contract demo. Keep the agent running: its webhook exists only while it's up, and a stopped agent answers "Your pipeline is not running" (n8n connection guide).

I ran this on Nov 30, 2026 with n8n 2.49.5 in Docker against RocketRide Cloud. The contract is made up: a two-page agreement between Acme and Northwind, printed to images and degraded to look like a phone scan.

If you'd rather call it as a tool from the AI Agent node, attach n8n's MCP Client Tool to the agent and point it at RocketRide's hosted MCP server, which runs an agent through its run_pipeline tool (tools reference). I tested that route on Nov 24 with the text version of the contract. Tell the agent in its system message to return only the fields RocketRide sends back.

Get contract terms out of scans before they reach Slack

Start with one scanned contract you already know the answers to and run it through Extract from File. If it comes back empty, put the agent above behind an HTTP Request node and compare its fields with your answers. Keep the Gmail trigger, the approval step and Slack in n8n. Each run executes in its own process and a crashed run is re-run rather than resumed, so turn on Retry On Fail for the HTTP Request node. Then add the scan to the contracts you test on every change. RocketRide's n8n guide covers the webhook and MCP routes.