Skip to main content

n8n

n8n is a workflow automation tool. You draw a workflow from nodes, such as "when a ticket arrives, summarise it with a model and post the summary to the team channel", and n8n runs it on a trigger or a schedule. Its AI nodes reach models through an OpenAI credential, which can point at the gateway instead of a provider. Every model call a workflow makes then uses a Spanway virtual key, so an automation that runs all night is held to a budget and a rate limit, each run shows on the Logs page, any model the gateway serves can be used from the same nodes, and the provider keys stay on the gateway instead of in n8n.

A real-world scenario​

An operations team runs n8n for ticket triage. A workflow reads each new support ticket, asks a model to classify it and write a one line summary, and posts the result to a channel. A bad filter once sent every historical ticket through the workflow in one night. The admin now gives each workflow its own gateway key with a 50 USD monthly budget and 30 requests per minute. When the same mistake happens again, the workflow slows to the rate limit and stops at the budget, the n8n execution shows the gateway's 429 and then 422, and the admin sees on Logs exactly which workflow made the calls.

Before you start​

  • A running gateway that the n8n server can reach, for example https://gateway.example.com. n8n calls it from its server, so the address must resolve there. When n8n runs in Docker and the gateway on the same host, the address is http://host.docker.internal:4000.
  • An n8n account that may create credentials.
  • A virtual key for the workflow, made in the next section.

Make a key for the workflow​

  1. In the Admin UI open Virtual Keys (/ui/api-keys) and click + Create New Key.
  2. Under Key Ownership pick Service Account and a Team, set Service Account ID to the workflow, such as n8n-ticket-triage, and leave Key Type on AI APIs.
  3. In Models, pick the models the workflow's nodes use, including the embedding model when the workflow writes to a vector store.
  4. Open Optional Settings. Set Max Budget (USD) and Reset Budget, and Requests per minute Limit (RPM), because a workflow that loops over many items sends one call per item. Leave Tags empty unless the gateway has an Enterprise license, because key tags need one and without it the key is not created (Only premium users can add tags to keys). The key name already keeps this tool's spend apart in Usage.
  5. Click Create Key and copy the key. It is shown once.

The same key from the API:

curl -X POST https://gateway.example.com/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "n8n-ticket-triage", "key_type": "llm_api", "team_id": "<team id>", "models": ["claude-haiku-5-5", "text-embedding-3-large"], "max_budget": 50, "budget_duration": "30d", "rpm_limit": 30}'

Use one key per workflow, or per team of workflows, so a runaway workflow cannot spend another one's budget.

Steps​

  1. Check the key from the n8n server with the same address n8n will use.

    curl https://gateway.example.com/v1/models -H "Authorization: Bearer $SPANWAY_API_KEY"
  2. In n8n open Credentials, create a new credential and choose OpenAI.

  3. Set API Key to the virtual key and Base URL to https://gateway.example.com/v1, with /v1 and nothing after it. n8n adds /chat/completions and /models itself. Leave Organization ID empty.

  4. Save the credential. n8n tests it by listing the models on the gateway and answers Connection tested successfully.

  5. In a workflow, add an AI Agent or Basic LLM Chain node, attach an OpenAI Chat Model sub-node and pick the credential. Under Model, choose a gateway model from the list, or switch to By ID and type a public name such as claude-haiku-5-5.

  6. Click Execute workflow or Execute step, then open Logs (/ui/logs) in the Admin UI, click Filters, pick the key in Key Alias and click Apply Filters.

The model list in step 5 comes from the gateway's /v1/models, so it holds every name the key may call, Claude and Gemini names included, and nothing else. If the OpenAI Chat Model node lists a Base URL under its options, leave it empty, because a value there replaces the credential's address for that node only and can send it somewhere else.

The same credential serves the OpenAI app node, such as its message a model action, and the Embeddings OpenAI sub-node for vector stores, with a gateway embedding model such as text-embedding-3-large.

Any route with the HTTP Request node​

For a gateway route the AI nodes do not cover, such as /v1/messages or /v1/images/generations, use the HTTP Request node.

  1. Set Method to POST and URL to the full route, for example https://gateway.example.com/v1/chat/completions.

  2. Set Authentication to Generic Credential Type, then Header Auth, and create a credential with Name Authorization and Value Bearer <virtual key>.

  3. Turn on Send Body, pick JSON, and paste the body.

    {"model": "claude-haiku-5-5", "messages": [{"role": "user", "content": "Classify this ticket: the invoice total is wrong."}]}
  4. Execute the node. The output is the gateway's JSON answer.

A workflow exported from n8n carries the credential by id and name only, never the key itself, so it is safe to share.

Expected result​

The node's output panel shows the model's answer, for example the output field of the AI Agent node or choices[0].message.content from the HTTP Request node. On the gateway side:

  • Logs has one row per model call, filtered by Key Alias, with the model, tokens, cost and route /v1/chat/completions. An AI Agent node that calls a tool makes two or more calls for one item, and a node that runs once per item makes one row per item.
  • Virtual Keys, the key's Overview tab, shows the workflow's spend against its budget, and Usage groups it by the tag.
  • Each answer carries x-spanway-call-id, the id to search for on Logs, x-spanway-response-cost, and x-spanway-model-group, x-spanway-model-id and x-spanway-routing-reason for the deployment that served it, see routing headers. The HTTP Request node shows them when you turn on Include Response Headers and Status under Options, Response.

What works through the gateway​

FeatureHow it behavesKnown limits
Tool callingThe AI Agent node's tools work on every model behind the name that supports tool calling, whatever the provider.A model without tool support fails the agent step with a provider 400.
Structured outputThe Structured Output Parser and JSON output formats work, and the gateway can repair an answer that does not match the schema.Strict schema mode depends on the provider.
ImagesImage inputs reach vision models from every provider.A model without vision answers with a provider 400.
Responses APITurning on Use Responses API on the OpenAI Chat Model node uses the gateway's /v1/responses, which serves every model.None known.
StreamingNot needed in workflows. Each node waits for the full answer.Long answers can hit a proxy's idle timeout, see the errors below.
RetriesThe node's Max Retries option and the node setting Retry On Fail both retry, and so does the gateway.Retries add up, so one failing item can cost several provider calls. Keep one layer of retries, ideally the gateway's retries and fallbacks.

Errors​

n8n shows a failed node in red with a short message, and the full gateway answer under the error details of the execution. The client error reference lists every gateway error.

CaseWhat n8n showsCauseFix
Credential test failsCouldn't connect with these settingsThe Base URL is wrong, unreachable from the n8n server, or the key is rejected.Run the curl from step 1 on the n8n server, and correct the URL or the key.
401Authorization failed - please check your credentials, with Authentication Error, Invalid proxy server token passed in the detailsThe key is wrong, blocked or deleted.Paste the key into the credential again, or create a new one.
403 model not allowedForbidden - perhaps check your credentials?, with The requested model '<model>' is not available for this API key, or the model name is invalid.The node asks for a model the key may not use, often an embedding model.Add the model to the key in Virtual Keys, or pick a model from the node's list.
400 unknown modelBad request - please check your parameters, with Invalid model name passed in model=<name>A name typed with By ID does not exist on the gateway.Pick the model from the list, or copy the exact name from GET /v1/models.
422 budgetBudget has been exceeded! with the current cost and maximum in the detailsThe workflow's key spent its budget.Find why the workflow ran so often, then raise Max Budget (USD) or wait for the reset.
429 rate limitThe service is receiving too many requests from you, with Rate limit exceeded for <scope>: <value>.The workflow is over the key's RPM or TPM limit, usually a loop over many items.Add a Wait node or batch the items, or ask for a higher Requests per minute Limit (RPM).
404 wrong path or doubled /v1The resource you are requesting could not be found, with Not FoundThe Base URL is the full route, such as /v1/chat/completions, or carries /v1 twice, or a node level Base URL option points elsewhere.Set the credential's Base URL to https://gateway.example.com/v1 and clear the node option.
Connection refusedThe service refused the connection - perhaps it is offline, or ECONNREFUSEDn8n runs in Docker and the URL says localhost, or the gateway is down.Use host.docker.internal or the gateway's service name, and check curl https://gateway.example.com/health/liveliness.
TLS or CA errorunable to get local issuer certificate or self-signed certificate in certificate chainThe gateway's certificate comes from a company authority n8n does not trust.Mount the company root certificate into the n8n container and set NODE_EXTRA_CA_CERTS to its path.
Timeout on long answerstimeout or The connection was aborted after about a minuteA proxy or load balancer in front of the gateway closed the idle connection.Raise the idle timeout on that hop, or the node's Timeout option.

Troubleshooting​

  1. Open the failed execution in n8n's Executions list and read the node's error details, which hold the gateway's full JSON answer.
  2. Open Logs in the Admin UI, filter by Key Alias and the time of the execution. No row means the request never reached the gateway, so the address, network or TLS is wrong on the n8n side. A row shows the status, the error text and the deployment the router picked.
  3. Run the same request with curl -i and the same key to see the x-spanway response headers.
  4. Start n8n with N8N_LOG_LEVEL=debug to see each outgoing request in its log, and compare the URL with the steps above.
  5. When the request reaches the gateway but the reason is unclear, run a test gateway with --detailed_debug, see troubleshooting.

Rotate or remove the key​

Open the key in Virtual Keys and click Regenerate Key with a Grace Period such as 24h, which needs an Enterprise license. Without one, create a new key and delete the old one after the switch. Then open the credential in n8n, paste the new key into API Key and save. Every workflow that uses the credential picks it up on its next run, with no change to the workflows.

To stop a workflow's model calls at once, click Block Key in the key's actions menu, and Unblock Key to undo it. To remove the key, click Delete Key and type the alias, and delete or update the n8n credential too.