The typical n8n pattern chains "trigger, process, output" into an automated flow: summarize incoming email, classify leads after a form submission, or generate copy when a new row appears in a spreadsheet. Adding OpenAI gives these flows a natural-language step, but it also raises new questions: how to manage keys, what to put in the Base URL, and why costs jump when you run batches.

This article follows the order of an actual build: choose an integration path, configure credentials, run the first workflow, then handle errors and cost. Node names and fields refer to the n8n version you are using.

Note: n8n and OpenAI are trademarks of their respective owners, and this article is not affiliated with those vendors. Model names and prices are subject to the in-site model pricing.

1. Choose between two integration paths

There are two common ways to connect OpenAI in n8n:

Path Best for Advantages Limitations
OpenAI node Standard operations such as chat, summaries, classification, images, and transcription Visual parameters and centralized credential management Limited to the operations the node implements
HTTP Request node Custom parameters, batch requests, or special fields Flexible; can call /v1/chat/completions directly You write the request body, authentication, and error handling yourself

Start with the OpenAI node and switch to HTTP Request only when needed. Do not hand-write requests from the beginning unless you truly need parameters the node does not expose.

2. Configure credentials and Base URL

In n8n's credential manager, create an OpenAI credential and enter the API key. If you need to route through a custom gateway, enter the Base URL in the same credential, usually ending at /v1. Field names and whether a Base URL input exists depend on your version.

A few practical rules:

  1. Keep the key in credentials only; never write it into a Code node or the workflow JSON.
  2. Use different keys for production and testing so you can set separate limits and disable them independently.
  3. When self-hosting, protect N8N_ENCRYPTION_KEY; after you change it, existing credentials can no longer be decrypted.
  4. Do not include /chat/completions in the Base URL; the node appends the path itself.
  5. On a shared team instance, split credentials by project or use virtual keys from the gateway.

After configuration, validate with a minimal request:

curl https://your-gateway.example.com/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"your-model-name","messages":[{"role":"user","content":"Reply with OK only"}]}'

3. Run your first workflow

Take "generate a reply draft after form submission" as an example:

  1. Add a Form Trigger or Webhook node to receive the form content.
  2. Add an OpenAI node and choose the Message a Model operation.
  3. Select the credential and model, then pass form fields into the prompt with expressions such as {{ $json.message }}.
  4. Add a Set node to clean up the fields returned by the model and keep only what later steps need.
  5. Add a Gmail, Slack, or spreadsheet node to write the result to its destination.
  6. Execute once manually, inspect the input and output of each node, then activate the workflow.

If you use an HTTP Request node, the request body can look like this:

{
  "model": "your-model-name",
  "messages": [
    {"role": "system", "content": "You are a customer service assistant. Answer only from the information provided."},
    {"role": "user", "content": "{{ $json.message }}"}
  ],
  "temperature": 0.3,
  "max_tokens": 500
}

Two things to watch: the field names in expressions must match the actual output of the previous step, and the request header should use Authorization: Bearer <key>; do not pass the key in the JSON body.

4. Four task types worth automating

Not every task deserves a model call. These categories tend to pay off directly:

  • Text processing: Email summaries, comment classification, ticket tagging, and multilingual translation.
  • Structured extraction: Pull names, amounts, and dates from inquiries, resumes, or invoice text and output JSON.
  • Content generation: Generate titles, selling points, or reply drafts from spreadsheet rows, then send them for human review.
  • Judgment and routing: Route items to different owners based on urgency.

For structured extraction, define the output format explicitly and add a validation node afterward. Models occasionally add explanatory text, which breaks JSON parsing. Use a prompt that says "output JSON only, no Markdown code fences," and prepare one retry.

5. Error handling: the most overlooked part of automation

For unattended workflows, failure is normal. Configure each item in the node settings:

  1. Retry On Fail: Retry 429, 5xx, and network timeouts, with 2–3 attempts.
  2. Retry interval: Use exponential backoff so you do not add pressure during rate limiting.
  3. On Error: Distinguish "stop the workflow" from "continue and log" so one bad record does not take down the whole batch.
  4. Timeouts: Set a reasonable timeout for HTTP requests. Long text generation can be more generous, but should never wait indefinitely.
  5. Error workflow: Send failures to Slack or email with the execution ID and an input summary.
  6. Idempotency: Before retrying, check whether the target system already has the record, to avoid duplicate messages or double bookkeeping.

Common errors can be checked in this order:

Symptom Likely cause Fix
401 Wrong key or credential not selected Reselect the credential and check for extra spaces
404 Wrong Base URL path Confirm it ends at /v1, without the full endpoint path
429 Concurrency too high or quota exceeded Reduce concurrency and enable backoff retries
400 Upstream does not support a parameter Remove incompatible fields and verify the model name
Empty response Output truncated or content filtering triggered Raise the output limit and review the prompt and filter policy
JSON parsing failure Model added extra text Require JSON only; retry once on failure

6. Cost control: do not let loops multiply the bill

n8n batch processing can easily turn one call into hundreds. Control cost through workflow structure:

Measure How to do it Effect
Model tiering Small models for classification and cleanup; strong models for generation Lowers average cost per call
Output limits Set a maximum output token count and ask for brevity in the prompt Prevents long answers from inflating cost
Request batching Combine text that can be processed together into one request Reduces request count and repeated context
Deduplication Use a database or cache to skip records already processed Avoids duplicate calls
Context truncation Send only necessary fields; summarize or split long text first Reduces input tokens
Usage logging Store the usage field from responses and report by workflow Reveals abnormal consumption

Two more details: every call inside a loop node is billed separately, so merge calls when possible; and do not run debugging against the full dataset. Validate with one sample first. For actual rates, see model pricing.

7. Data and permissions

Automation workflows often touch customer information. Before connecting a model, define:

  • Which fields may be sent to the model and which must be masked or processed locally.
  • Whether the model service retains request data and whether it uses data for training.
  • Workflow execution history stores inputs and outputs, so set a retention period.
  • Tighten export permissions for credentials and workflow JSON.
  • Add a human review node to flows involving contracts or identity information.

Self-hosted n8n gives you more control over the data path, but that does not automatically make the setup compliant; you still need to confirm the upstream model's data terms separately.

FAQ

Does the n8n OpenAI node support a custom Base URL?

Most versions provide a Base URL field in the OpenAI credential for proxies or self-built gateways. If your version lacks that field, use an HTTP Request node to call /v1/chat/completions directly.

Why does a workflow run in the editor but fail on a schedule?

Common causes are different credential scopes, environment variables, or network egress. Check the execution record for the exact node and error code, then confirm that the instance running the schedule can reach the target address.

What should I watch when processing hundreds of records in a batch?

Control concurrency and retry counts, give each record a unique identifier, and log the original input on failure. Prefer smaller batches with intervals between them to avoid rate limits.

How do I estimate the cost of one workflow?

Record input and output tokens from the response's usage field, multiply by the model's rate, and add retries and failed requests. Run 20–50 real samples and average them; that is more reliable than guessing.

How do I make model-generated JSON more stable?

Constrain fields and types in the prompt and forbid extra explanation. Add a downstream JSON validation node, retry once on parse failure, and if it still fails, route to a person or an exception queue.

Next steps

The key to n8n plus OpenAI is not how pretty the node graph looks, but credential security, error handling, and cost boundaries. Validate with a small volume on one real business process before opening it up. If you need a unified OpenAI-compatible entry point and usage management, register for the ZSQH AI Gateway; models and prices are listed at model pricing.

Related reading: