Build an AI Agent with Gemma 4 and n8n: A No-Per-Token Workflow

By the end of this tutorial you will have an n8n workflow that receives a support message on a webhook, lets Gemma4-26B-A4B Uncensored look up the customer's order through a tool call, classifies the message, drafts a reply and sends it. The model runs on your own pod with no per-token billing. Allow about half an hour.
The method is the same for any OpenAI-compatible endpoint: give n8n a custom base URL and a key. The details that trip people up are small (one toggle, one path), and each is called out below.
Why Gemma 4 suits n8n automation
An agent is not one model call. It asks the model what to do, runs a tool, sends the result back, and asks again. Three properties of this model fit that pattern.
- Speed. On our RTX 5090 pod it generates 175 tokens per second. A 300-token step takes under two seconds, so an agent run with three or four model calls still finishes while the customer is on the page.
- Native function calling. Google built function calling into Gemma 4, and tool calls are switched on in our build. n8n's agent relies on exactly that: it passes your tools in the request and expects a structured tool call back.
- Pod time, not tokens. You rent the pod in time packs. A workflow that loops five times, retries on failure or resends a long thread costs the same as one that runs once.
Two more help in a support setting. The context window is 256K tokens, so a long email thread plus your policy document fits in one request. And prompts stay on your pod with no provider content filter in front, which matters when incoming messages contain abuse, fraud attempts or medical detail that a filtered service may decline to process. The Gemma4-26B-A4B Uncensored guide has the full specification.
What you will build
Webhook (POST /support-inbox)
|
AI Agent
|-- Chat Model: OpenAI Chat Model -> https://YOUR-POD-ENDPOINT/v1
|-- Tool: lookup_order (HTTP Request Tool)
|-- Output Parser: category, urgency, needs_human, reply
|
IF needs_human
|-- true -> Slack: alert the team, include the draft
|-- false -> Send Email: reply to the customer
Prerequisites
- A running pod. Deploy Gemma4-26B-A4B Uncensored, then open your console.
- n8n, Cloud or self-hosted, recent enough to include the AI Agent node. On an older install, the HTTP Request node in Step 2 works with any version.
- Somewhere to send results: an SMTP account for the Send Email node, a Slack credential, or both.
- An order lookup URL of your own that returns JSON for an order number. If you have none, Step 6 lists substitutes.
Step 1: Copy three values from the console
| Value | Placeholder in this guide | Where it goes in n8n |
|---|---|---|
Base URL, ending in /v1 | https://YOUR-POD-ENDPOINT/v1 | OpenAI credential, Base URL field |
| API key | YOUR_API_KEY | OpenAI credential, API Key field |
| Model id | YOUR_MODEL_ID | OpenAI Chat Model node, Model field |
Always use the https:// form of the URL. Copy the model id from your console exactly; a guessed name returns a "model not found" error.
Step 2: Prove the connection with an HTTP Request node
Before building the agent, confirm that n8n can reach the pod. This uses only the generic HTTP Request node, so it works on every n8n version, and it is also the simplest way to add a one-shot model step (summarise, classify, rewrite) to any workflow.
Add an HTTP Request node and set these fields on its Parameters tab:
| Field | Value |
|---|---|
| Method | POST |
| URL | https://YOUR-POD-ENDPOINT/v1/chat/completions |
| Authentication | None |
| Send Headers | On, with Specify Headers set to Using Fields Below |
| Header name | Authorization |
| Header value | Bearer YOUR_API_KEY (the word Bearer, one space, the key, no quotes) |
| Send Body | On |
| Body Content Type | JSON |
| Specify Body | Using JSON |
Paste this body:
{
"model": "YOUR_MODEL_ID",
"messages": [
{ "role": "user", "content": "Reply with the single word: ready" }
],
"temperature": 0.6,
"top_p": 0.9,
"top_k": 64
}
Click Execute step. A working connection returns HTTP 200 and OpenAI-format JSON:
{
"object": "chat.completion",
"model": "YOUR_MODEL_ID",
"choices": [
{
"index": 0,
"message": { "role": "assistant", "content": "ready" },
"finish_reason": "stop"
}
],
"usage": { "prompt_tokens": 17, "completion_tokens": 2, "total_tokens": 19 }
}
The reply text is at choices[0].message.content. In a later node, read it with:
{{ $json.choices[0].message.content }}
If the expression comes back empty, drag the content field from the node's output panel into the next node and let n8n write the path for you.
Note the URL here is the full path to /v1/chat/completions. The credential in the next step takes only the part ending in /v1. Mixing the two up is the most common cause of a 404. The site's n8n integration guide walks through this same node field by field.
Step 3: Create an OpenAI credential with a custom base URL
n8n's OpenAI credential accepts a custom base URL, which is how its OpenAI nodes can talk to any OpenAI-compatible server.
- Open Credentials and create a new credential of type OpenAI.
- API Key:
YOUR_API_KEY. - Base URL:
https://YOUR-POD-ENDPOINT/v1. It must end in/v1, with nothing after it. - Leave the organisation field empty and save. Name it something recognisable, such as "Gemma pod".
Moving the key into a credential also keeps it out of workflow exports, unlike the header field used in Step 2.
Step 4: Add the Webhook trigger
Start a new workflow and add a Webhook node.
- HTTP Method:
POST - Path:
support-inbox - Respond: Immediately
The workflow will expect a body like this from your contact form or mail parser:
{
"from": "sam@example.com",
"subject": "Where is my order?",
"message": "Hi, I ordered a standing desk two weeks ago, order number 58213, and it still has not arrived. Can you check?"
}
n8n places a webhook's JSON under body, so the message is at {{ $json.body.message }}.
Step 5: Add the AI Agent and point it at your pod
Add an AI Agent node after the webhook.
- Source for Prompt: Define below
- Prompt (User Message):
From: {{ $json.body.from }}
Subject: {{ $json.body.subject }}
{{ $json.body.message }}
- System Message (under Options):
You triage customer support email for an online furniture shop.
If the message mentions an order number, call lookup_order before answering.
Classify the message as one of: shipping, billing, returns, product, other.
Set urgency to low, medium or high.
Set needs_human to true for legal threats, chargebacks, injuries or anything you cannot resolve from the order data.
Write a reply of under 120 words in a calm, direct tone. Never invent order details.
Now connect the model. Click the Chat Model connector under the agent and choose OpenAI Chat Model.
- Credential: the one from Step 3.
- Model: switch the selector from the list to ID and paste
YOUR_MODEL_ID. If the list loads your model, picking it there is equivalent. - Use Responses API: turn it off. With it on, the node calls a different endpoint than Chat Completions, and the pod serves Chat Completions. This toggle is the usual reason an agent fails although Step 2 worked.
- Options: set Sampling Temperature to 0.6 and Top P to 0.9. These follow the build author's suggested settings and keep tool calls and structured output steady. Google's default for Gemma 4 is temperature 1.0 and top_p 0.95, better suited to creative writing than to triage.
Step 6: Give the agent a tool
Click the Tool connector under the agent and add an HTTP Request Tool. Rename the node lookup_order.
- Description:
Look up one order by its order number. Returns status, carrier and expected delivery date. Use it whenever the customer mentions an order number. - Method:
GET - URL:
https://YOUR-ORDER-API/orders/{{ $fromAI('order_number', 'The order number mentioned in the customer message', 'string') }}
YOUR-ORDER-API is your own shop or ERP system, not the pod. The $fromAI() expression tells n8n that the model fills in this value.
What happens at run time: n8n sends the tool's name, description and parameters to the model in the request's tools field. Gemma answers with a tool call asking for lookup_order with order number 58213. n8n performs the GET, returns the JSON to the model, and the model writes its reply using the real status. The description is what the model reads when deciding whether to call the tool, so write it as an instruction, not a label.
No order API to hand? Any tool node works the same way. Swap in a spreadsheet lookup, a database query, or the tool that calls another n8n workflow.
Step 7: Make the output structured
Downstream nodes need fields, not a paragraph. On the AI Agent node, switch on Require Specific Output Format. An Output Parser connector appears; attach a Structured Output Parser and give it this JSON example:
{
"category": "shipping",
"urgency": "medium",
"needs_human": false,
"reply": "Hi Sam, thanks for getting in touch. ..."
}
The agent's result now arrives as $json.output.category, $json.output.urgency, $json.output.needs_human and $json.output.reply.
Step 8: Route and send
Add an IF node with the condition {{ $json.output.needs_human }} is true.
True branch: Slack. Post to your support channel:
Needs a human ({{ $json.output.category }}, {{ $json.output.urgency }})
From: {{ $('Webhook').item.json.body.from }}
Draft reply: {{ $json.output.reply }}
False branch: Send Email.
- To:
{{ $('Webhook').item.json.body.from }} - Subject:
Re: {{ $('Webhook').item.json.body.subject }} - Text:
{{ $json.output.reply }}
For the first week, consider sending every draft to Slack and none to customers. Read what the agent writes on real mail before you let it send unattended.
Test it
Click Execute workflow so the webhook listens for a test event, then post a sample message to the test URL shown on the Webhook node:
curl -X POST https://YOUR-N8N-HOST/webhook-test/support-inbox \
-H "Content-Type: application/json" \
-d '{
"from": "sam@example.com",
"subject": "Where is my order?",
"message": "Hi, I ordered a standing desk two weeks ago, order number 58213, and it still has not arrived. Can you check?"
}'
Check three things in the execution view:
- The AI Agent's log shows a call to
lookup_orderwith58213, followed by a second model call. - The agent's output has all four fields, with
categoryset toshipping. - The email or Slack message arrives with the drafted reply.
Then send a message with a chargeback threat and no order number. It should skip the tool and take the Slack branch. When both cases pass, activate the workflow and switch your form to the production URL, which uses /webhook/ in place of /webhook-test/.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| 401 Unauthorized | Missing Bearer prefix, or a wrong or rotated key | Re-copy the key from the console; in the HTTP Request node the value is Bearer YOUR_API_KEY |
| 404 Not Found from the agent | Credential Base URL does not end in /v1, or has /chat/completions appended | Set Base URL to https://YOUR-POD-ENDPOINT/v1 exactly |
| 404 Not Found from the HTTP Request node | URL stops at /v1 | Use the full https://YOUR-POD-ENDPOINT/v1/chat/completions |
| Step 2 works but the agent errors on its first call | Use Responses API is on | Turn it off in the OpenAI Chat Model node |
| "Model not found" | Model id typed from memory | Copy the model id from your console and paste it with the selector set to ID |
| Model list is empty | n8n could not load the list from the endpoint | Set the selector to ID and paste the id |
| Agent answers without calling the tool | Tool description too vague | Say when to use it in the description and repeat the rule in the System Message |
| Output parser error | The model wrapped the JSON in extra text | Keep temperature at 0.6, keep the schema small, add "Return only the JSON object" to the System Message |
| Connection refused or timeout | http:// used, or the pod has stopped because its time pack ended | Use https://; check the pod's status in the console |
| Works in test, silent in production | Workflow not activated, or the form still posts to the test URL | Activate the workflow and use the /webhook/ URL |
Running it day to day
Plan around pack length. Packs run for 11 hours, 24 hours, 1 week or 1 month, and the pod stops when the pack's time ends. A workflow that fires after that fails at the model step. Add an error workflow that alerts you, and choose a pack that covers the hours the automation must be live.
Turn on retries. In the settings of the AI Agent node, enable Retry On Fail so a dropped connection does not lose a customer message.
Share the pod. One credential serves every workflow in your n8n instance, so the same pod can triage mail, summarise calls and tag CRM records. They share one GPU; throughput under parallel load is not yet measured, so test with your real volume.
Send images when it helps. The model reads images as well as text, so a customer's photo of a damaged item can go in the same request through the HTTP Request node.
For the cost side of this, with a worked example of what a pack buys, see Gemma 4 26B API vs self-hosted. For a broader design, read the open-source customer support agent blueprint.
FAQ
Can n8n use a self-hosted or local LLM for the AI Agent?
Yes. Any server that speaks the OpenAI Chat Completions format works: create an OpenAI credential with your server's base URL and key, then attach an OpenAI Chat Model node to the AI Agent.
How do I set a custom OpenAI base URL in n8n?
Open the OpenAI credential and fill in the Base URL field with your endpoint ending in /v1, plus your API key. Every OpenAI node that uses that credential then calls your endpoint.
Why does the n8n AI Agent fail with my OpenAI-compatible endpoint?
The most common cause is the Use Responses API option on the OpenAI Chat Model node. Turn it off so the node uses Chat Completions, and check that the base URL ends in /v1.
Does Gemma 4 support tool calling in n8n?
Yes. Function calling is native to Gemma 4 and tool calls are enabled on our pods, so the AI Agent node can attach tools and the model will call them.
Do I pay per token or per workflow run with this setup?
Neither on the model side. You pay for the pod's time in packs, with no per-token billing, so loops and retries do not change the model cost. n8n's own plan is billed separately by n8n.
Should I use the OpenAI Chat Model node or the HTTP Request node?
Use the OpenAI Chat Model node with the AI Agent when you need tools and multi-step reasoning. Use the HTTP Request node for single calls, for extra parameters such as top_k, or on n8n versions without the agent nodes.


