The agent blueprint

The five layers under every agent we ship

A website chatbot, an inbound email agent, and a phone agent. Three channels, one skeleton. Four of the five layers are close to literal copy-paste between them.

Maksym BondarenkoSystems & Automation Engineering, Azuro AILast updated
Source: our own production workflowsBuilt in n8n3 live agents

People price an AI agent like a bespoke build. Ours aren't, and the diff between our three is short enough to say in one line: the trigger node, and the list of tools. Everything else is the same five layers in the same order, often the same JSON with two strings changed.

That is less of a design boast than it sounds. The real payoff is that the failure modes repeat too, and a repeating failure mode is one you can build a checklist against. Below is the actual skeleton, the node types we use at each layer, and the layer almost everyone leaves out until something goes wrong in public.

[1 TRIGGER] --> [2 NORMALIZE] --> [3 AGENT CORE] --> [4 RESPOND] --> [5 LOG]
                                      |
                      +---------------+---------------+---------------+
                      |               |               |               |
                   model          memory         knowledge          tools
               (gpt-4o-mini)   (Postgres)    (vector search)   (HTTP nodes)

Layers 1 and 4 are channel plumbing. Layer 3 is the agent. Layer 5 is the one that decides whether you can prove any of it worked.


Layer 1. Trigger

THE ONLY LAYER THAT IS GENUINELY DIFFERENT PER AGENT

One node. It is the whole reason the three agents look like different products from outside.

  • Website chatbot: a chat trigger in webhook mode, with responseMode: responseNode so a later node sends the reply, and loadPreviousSession: memory so a returning visitor sees their own history.
  • Email agent: an inbound webhook from the mail provider, fired on every received message.
  • Phone agent: a webhook from the voice platform, fired when the assistant calls a tool or the call ends.

Swap this node and nothing downstream needs to know which channel it is serving. That property is the entire point of layer 2.

Layer 2. Normalize

ONE CODE NODE, IMMEDIATELY AFTER THE TRIGGER

A single Code node that reads the raw webhook payload and returns flat, renamed, top-level fields. A session id, the user's message, a phone number, whatever the tool call carried. Every node after it reads from this node. Nothing downstream is allowed to reach back into the raw webhook body.

It looks like pointless indirection on day one. It is the cheapest node in the workflow and it has saved us more rework than any other.

What it cost us to learn that

On a voice-agent build for a client, every node read the incoming tool call's payload directly through .arguments. n8n's expression editor runs in a restricted sandbox that refuses any property access through arguments and throws "Cannot access 'arguments' due to security concerns". Bracket notation does not help. Different quoting does not help. It is a sandbox restriction, not a syntax error.

A plain Code node is ordinary Node.js and has no such restriction, so a Code node was the only place that payload could ever be read. Inserting one took ten minutes. Repointing the roughly 27 downstream nodes that had already been wired against the raw payload did not.

Layer 3. The agent core

ONE AGENT NODE WITH FOUR THINGS PLUGGED INTO ITS SIDE

This is where people expect the complexity to live, and where there is least of it. One agent node. Four sub-nodes attached to its side ports, which in n8n are separate connection types rather than normal flow wires.

Model

gpt-4o-mini, temperature 0.7, max tokens 1000. Identical in the chatbot and the email agent, down to the number. The token cap is doing real work: it keeps replies to a few sentences, which is what you want on a widget and in an inbox.

Memory

Postgres chat memory, keyed on a custom session key that comes from layer 2, with a context window of 10 messages.

sessionIdType:        customKey
sessionKey:           {{ $('Email Parser').item.json.sessionId }}
tableName:            conversation
contextWindowLength:  10

The session key is the decision that matters. On the chatbot it is the widget's session id. On the email agent it is derived from the mail thread. Pick it wrong and two customers share one memory, which is the single worst bug this kind of system can have.

Knowledge

A Supabase vector store node in retrieve-as-tool mode, pointed at a documents table, topK 10, with an embeddings node attached to it. The chatbot and the email agent use the same node against the same table, with the same tool description text, verbatim.

That tool description is prompt engineering, not documentation. Ours ends with an instruction to always search before claiming not to know something, because without it the model would confidently answer pricing questions from thin air.

Tools

This is the part that surprises people. The tools are not code. They are ordinary HTTP Request nodes, and the parameter values are $fromAI() calls that let the model fill in each field.

one real tool: check calendar availability
GET https://api.cal.com/v2/slots

eventTypeId  <your event type id>
start        {{ $fromAI('start', 'Start of the range to check.
             Beginning of the requested date in UTC ISO format', 'string') }}
end          {{ $fromAI('end', 'End of the range to check,
             in UTC ISO format', 'string') }}
timeZone     {{ $fromAI('timeZone', 'The customer timezone, e.g.
             America/New_York. You must have collected this
             from the customer before calling this tool.', 'string') }}

header  cal-api-version: 2024-09-04

The second argument of $fromAI() is a description the model reads. It is the only thing standing between you and a well-formed API call containing a guessed timezone. Ours spells out the prerequisite in the description itself, because stating it in the system prompt alone was not enough.

Our calendar tool set is six of these nodes: get availability, create, find, get, reschedule, cancel. Both the chatbot and the email agent carry the same six. The chatbot adds one more HTTP node that upserts the booked customer into the CRM by email, so a booking and a contact record happen in the same turn rather than in a nightly sync.

A tool is a URL, a method, and a set of $fromAI() slots. If you can call it with curl, it can be a tool, and you do not need a framework to make it one.

Layer 4. Respond

ANSWER ON THE CHANNEL THE TRIGGER OPENED

The chatbot responds through a webhook response node. The email agent posts the reply to the mail provider's send API with an HTTP node, which is why there is a disabled built-in email node sitting in that workflow that we never removed. The phone agent responds through a webhook response node per tool call, and this one is load-bearing: a voice tool call with no response does not fail, it hangs, and the caller sits in silence until the platform times out.

Layer 5. Log

THE THREE NODES ALMOST EVERYONE SKIPS

Three nodes, in this order, in every agent we run: Company Config (a Set node), then Calculate Metrics (a Code node), then Send Logs (a database insert). They write one row per interaction to a single automation_logs table.

Company Config

A Set node in raw mode holding every constant the rest of the chain needs, so none of them are buried inside code.

{
  "customerId":       "<redacted - your tenant id>",
  "companyName":      "Azuro AI",
  "workflowName":     "AI Email Agent",
  "actionType":       "email",
  "hourlyRate":       100,
  "baseTimeSaved":     5,
  "bookingBonusTime": 10,
  "leadBonusTime":     5
}

One gotcha that cost a client workflow a day of debugging: in n8n's Set node, that value has to be a JSON string, not a native object. The node calls .startsWith() on it before parsing, so an object literal throws "jsonOutput?.startsWith is not a function" at runtime while looking completely correct in the file.

Calculate Metrics

A Code node that turns one interaction into a row of numbers. Real code from the email agent, lightly trimmed:

const out = $('AI Agent').first().json.output || '';
const booked = /booked|appointment.{0,20}confirm/i.test(out) ? 1 : 0;
const timeSaved = 2;
const hourlyRate = $('Company Config').first().json.hourlyRate || 100;

const metrics = {
  emails_delivered: 1,
  time_saved: timeSaved,
  cost_savings: Math.round(timeSaved * (hourlyRate / 60))
};
if (booked) metrics.appointments_booked = 1;

return { json: { metrics } };

At a $100/hour baseline that works out to $1.67 a minute, which is the whole cost-savings model. No attribution modelling, no blended multiplier. Minutes the agent handled, times a rate the client agreed to in writing before launch.

And a confession about that booked line, since you can read it as clearly as we can: it is a regex against the agent's own reply. If the model phrases a confirmation in a way our pattern misses, the booking happened and the metric did not. We know. It is on the list. We would rather show you the crude version than a diagram of one we have not built.

Send Logs

One insert, same eight columns for every agent, which is what makes a single dashboard possible across all of them.

customer_id     uuid     which tenant
company_name    text
workflow_id     text     {{ $workflow.id }}, the runtime value
workflow_name   text     "AI Email Agent"
action_type     text     "email" | "chat" | "call" | "booking"
status          text     "success" | "failed"
metrics         jsonb    the object built above
created_at      timestamptz

Because metrics is a JSON column, a new agent can log keys no other agent has without a migration, and every agent still answers the one question a client actually asks at renewal: what did this thing do for me last month.


The same five layers, three agents

Read SAME as copy-paste and NEW as the real work of a new build.

LayerWebsite chatbotEmail agentPhone agent
1 TriggerNEW chat triggerNEW mail webhookNEW voice webhook
2 NormalizeSAME Code nodeSAME Code nodeSAME Code node
3 ModelSAME 4o-mini / 0.7 / 1000SAME identicalSAME platform side
3 MemorySAME Postgres, window 10SAME Postgres, window 10NEW platform turn state
3 KnowledgeSAME vectors, topK 10SAME same tableSAME same table
3 ToolsNEW 6 calendar + CRMNEW 6 calendar + activityNEW calendar + CRM + SMS
4 RespondSAME webhook responseNEW POST to send APISAME webhook response
5 LogSAME Config, Metrics, insertSAME identicalSAME identical

Two columns of real work. That is the honest size of "building another agent" once the skeleton exists, and it is why the second one takes days rather than weeks.

The failure half of layer 5 is where builds get hurt

Layer 5 is also where our worst bugs have lived, and they were never the model's fault.

On a client voice-agent system we audited in July, we found four failure-logging nodes wired backwards. The error branch pointed at the logger, and the logger pointed at the metrics node, so in the graph the loggers were sources rather than sinks and nothing ever triggered them. The same pass turned up fifteen more nodes whose error branch led nowhere at all: every calendar call, both document lookups, every confirmation text. A genuine calendar API failure meant the webhook never responded, so the caller's tool call simply hung.

The nastiest one in that pass was an ordering mistake rather than a missing wire. A success metric had been chained behind a notification text. Booking succeeds, confirmation text fails for an unrelated reason like a bad staff phone number, execution aborts, and the successful booking never gets logged at all. The customer has an appointment. The dashboard says the agent did nothing that day.

The rule we build to now

Every node that can error gets an explicit error output, and that output has to land on a failure logger. Trace it through the connections end to end rather than trusting the canvas, because a wire that goes to the wrong place looks identical to a wire that goes to the right one. And never let a business metric sit downstream of a side effect: fire the metric in parallel with the confirmation, not after it.

None of those failures showed up on an error dashboard. Every one of them returned a 200. That is the thing worth internalising before you build your first agent, more than any model choice: a system that does not error is not the same as a system that works.

Companion Claude Skill

Take the skeleton with you

Everything above, as a Claude Skill. Drop it in your skills directory and your assistant will wire the five layers in order, in your own n8n instance, including the pitfalls that cost us the most time.

n8n-agent-skeleton/SKILL.md
---
name: n8n-agent-skeleton
description: Wire a new AI agent in n8n on the five-layer skeleton (trigger, normalize, agent core, respond, log) without re-deriving the structure each time.
version: 1.0.0
license: MIT
---

# Build an AI agent on the five-layer skeleton

Use this when you are standing up a new AI agent in n8n (chat widget, inbound
email, phone/voice tool calls) and want the same structure every time, so the
second agent takes days instead of weeks.

## When to use

- "Build me a chatbot / email agent / voice booking agent in n8n."
- "Add a tool to the existing agent."
- "Why does my agent work in the editor and fail on real traffic?"

Not for: choosing a model (that decision is nearly always irrelevant, see
pitfalls), or writing the system prompt itself.

## The skeleton

Build in this order. Do not skip layer 2 or layer 5, they are the two that
get skipped and the two that cause the expensive failures.

```
[1 TRIGGER] -> [2 NORMALIZE] -> [3 AGENT CORE] -> [4 RESPOND] -> [5 LOG]
                                      |
                   model / memory / knowledge / tools
```

### Layer 1. Trigger (the only per-channel part)

- Chat widget: chat trigger, webhook mode, `responseMode: responseNode`,
  `loadPreviousSession: memory`.
- Inbound email: the mail provider's inbound webhook.
- Voice/phone: the voice platform's webhook.

Gate voice and chat platform webhooks on the event type FIRST. Platforms
commonly post ten or more event types (conversation updates, speech updates,
status changes, hangs, end-of-call reports) to the same URL, and only one of
them carries a tool call. Add a Switch on the message/event type with one
branch per type you handle and a fallback branch that returns a clean 200.

### Layer 2. Normalize (one Code node, always)

A single Code node right after the trigger that returns flat, renamed,
top-level fields. Every downstream node reads from THIS node, never from the
raw webhook body.

Name it something explicit like `Extract Tool Arguments`. Non-negotiable
reason: n8n's expression sandbox throws
`Cannot access 'arguments' due to security concerns` on any property access
through `arguments`, in any notation. A Code node is real Node.js and is not
subject to that restriction, so it is the only place a tool-call payload can
be read. Retrofitting this later means repointing every downstream node.

(Reading `function.name` for routing is fine directly. Only `.arguments`
needs the Code node.)

### Layer 3. Agent core (one agent node, four side ports)

- **Model**: start at a small, cheap model. Cap max tokens deliberately
  (~1000 forces short replies, which is what chat widgets and inboxes want).
  Temperature around 0.7.
- **Memory**: Postgres chat memory, `sessionIdType: customKey`, session key
  sourced from layer 2, context window ~10 messages.
  **The session key is the highest-risk decision in the build.** Get it wrong
  and two users share one conversation history.
- **Knowledge**: vector store node in retrieve-as-tool mode over a documents
  table, topK ~10, embeddings node attached. Write the tool description as
  prompt text, including an explicit instruction to search before claiming
  not to know something, or the model will answer pricing from thin air.
- **Tools**: plain HTTP Request Tool nodes. Parameter values are
  `$fromAI('name', 'description', 'string')` calls. The description is read
  by the model every time, so put hard prerequisites in it, e.g.
  "You must have collected the customer timezone before calling this tool."
  Stating the rule only in the system prompt is not enough.

### Layer 4. Respond

Answer on the channel the trigger opened: a webhook response node for chat
and for each voice tool call, an HTTP POST to the provider's send API for
email. A voice tool call with no response does not error, it hangs, and the
caller sits in silence until timeout.

### Layer 5. Log (three nodes, in this order)

`Config` (Set node, raw mode) -> `Calculate Metrics` (Code) ->
`Send Logs` (DB insert). One row per interaction, same columns for every
agent, metrics as a JSON column so a new agent can log new keys without a
migration.

Suggested row shape:

```
customer_id, company_name, workflow_id, workflow_name,
action_type, status, metrics (json), created_at
```

A simple, defensible savings model: minutes handled x (hourly rate / 60),
with the rate agreed in writing before launch.

## Procedure

1. Create the trigger. If it is a platform webhook, add the event-type gate.
2. Add the normalize Code node. Flatten every field any downstream node needs.
3. Add the agent node. Attach model, memory, knowledge, tools in that order.
4. For each tool: write the URL, method, and `$fromAI()` slots with
   prerequisite-carrying descriptions.
5. Add the respond node for every terminal path, including failure paths.
6. Add the three logging nodes for every success AND failure path.
7. Walk the connections end to end and verify every error output lands on a
   failure logger. Do this by reading the connection list, not by looking at
   the canvas.

## Pitfalls

- **A Set node's raw JSON must be a string, not an object.** n8n calls
  `.startsWith()` on it before parsing, so an object literal throws
  `jsonOutput?.startsWith is not a function` at runtime while looking
  correct in the file.
- **Error branches that dead-end.** A node with an error output wired
  nowhere swallows failures silently. In one audit we found four failure
  loggers wired backwards (logger -> metrics instead of metrics -> logger,
  so they were sources, not sinks) plus fifteen nodes whose error branch led
  nowhere at all.
- **Never chain a business metric behind a side effect.** If the success
  metric sits downstream of a confirmation SMS, a Twilio failure aborts the
  execution and a real booking never gets logged. Fire metrics in parallel
  with notifications.
- **Timestamps:** one ISO 8601 string with an explicit offset or Z, plus a
  separate timezone field. Never split date and time into two fields, and
  never concatenate them into an API request. Unmarked timestamps get read
  as UTC and bookings land hours off with no error.
- **Check the API version scheme.** A credential type that appends
  `?apiKey=` is a v1 scheme; v2 endpoints usually want a bearer token.
  Wrong auth mechanism, not just an old one.
- Do not debug a model you have not instrumented. If layer 5 is missing you
  cannot tell a broken agent from a working one.

## Verification

- [ ] Every downstream node reads the normalize node, not the raw webhook.
- [ ] Platform webhooks gate on event type with a fallback 200.
- [ ] Session key is unique per end user, and you can say why.
- [ ] Every tool's `$fromAI()` descriptions name required prerequisites.
- [ ] Every terminal path has a response node, including failures.
- [ ] Every error output traces to a failure logger in the connection list.
- [ ] No business metric is downstream of a notification send.

Save it as n8n-agent-skeleton/SKILL.md in your skills directory. Works in Claude Code, Claude Desktop, or any agent that reads SKILL.md files.

Questions about any of this?

Happy to talk through how these layers map onto whatever you're running now — no pitch, just answers.

Azuro AI · Built from our own production n8n workflows and engineering notes. Client names, tenant identifiers, credential IDs and endpoints have been removed. Every incident described is real and dated in our internal records.