How to Integrate OpenAI API with n8n for Advanced Automation
Integrating the OpenAI API with n8n is the fastest way for a small or medium-sized business to put a language model to work inside real processes: sorting emails, enriching CRM records, drafting replies, extracting data from documents. No SaaS lock-in, no custom app to build. This guide walks you through the full setup, from generating your API key to configuring the OpenAI node in n8n, and closes with the cost-control practices we apply after 40+ production deployments for SMEs.
Why connect the OpenAI API to n8n?
n8n is the orchestrator: it watches your inbox, your CRM, your forms, your files. The OpenAI API is the brain you plug into that orchestration. Separately they are useful; together they automate work that used to require human judgment. Two use cases we deploy most often for SMEs:
Use case 1: AI-powered email triage
A shared inbox receiving 50 to 200 emails a day (support, sales, invoices, spam) is a classic SME bottleneck. With an n8n workflow, every incoming email is sent to an OpenAI model that classifies it (support, sales, invoice, urgent, other), assigns a priority, and drafts a suggested reply for the categories that allow it. The team starts the day with a sorted inbox and pre-written drafts, instead of an undifferentiated pile. Typical gain observed: 5 to 10 hours per week for the whole team.
Use case 2: CRM enrichment and lead qualification
A new lead fills your contact form. Before anyone even opens the notification, n8n has already: fetched the company's website, asked the OpenAI model to summarize what the company does, estimated the fit with your offer against your qualification criteria, scored the lead, and written a two-line briefing in the CRM record. Your sales rep opens a qualified lead with context, not a bare email address. The same pattern works to keep existing records clean: deduplication, normalization of job titles, industry tagging.
Step-by-step: integrating OpenAI into n8n
Prerequisite: a running n8n instance. Self-hosted on a VPS (around 5-10€/month) or n8n Cloud (from 20€/month). If you are not set up yet, see our n8n self-hosting guide (in French).
Generate your OpenAI API key
Create an account on platform.openai.com (this is separate from ChatGPT Plus: API usage is billed per token, not by subscription). In the dashboard, go to Settings → API keys → Create new secret key. Name the key after its purpose (e.g. n8n-production), copy it immediately (it is shown only once) and store it in a password manager. Then, and this step is not optional, open Settings → Limits and set a monthly usage cap plus an email alert threshold. This single setting is what turns a bad prompt loop into a 20€ incident instead of a 2,000€ one.
Create the OpenAI credential in n8n
In n8n, open Credentials → Add credential → OpenAI, paste your secret key, save, and hit Test to confirm the connection. The key is stored encrypted in your n8n database. Good practice: one credential per environment (test / production) so you can rotate or revoke one without breaking the other, and so costs are traceable per key in the OpenAI dashboard.
Add and configure the OpenAI node
In your workflow, add the OpenAI node (or the AI Agent node if you need tools and memory). For a classification or extraction task, choose the Message a Model operation, select your credential, then pick the model: start with the mini tier for classification and extraction, and switch to the flagship model only where output quality visibly matters. Map your input data (the email body, the lead's website text) into the prompt using n8n expressions like {{ $json.body }}.
Structure your prompts for automation
A prompt inside a workflow is not a chat message: it must return a machine-readable output every single time. Three rules. First, use the system prompt to fix the role and the output contract. Second, enumerate the allowed values (a classifier that can invent categories will invent them). Third, request JSON and enable the structured output option so the node parses the response for you. A triage prompt looks like this:
Keep prompts short and factual. Every token you send is billed, and long "personality" preambles add cost without adding accuracy on classification tasks.
Test, then wire the output to your tools
Run the node on 10-20 real examples (real emails, real leads) and check the edge cases: empty body, wrong language, attachments only. Then branch on the model's output with a Switch node: urgent → Slack alert, invoice → accounting folder, sales → CRM record creation. The LLM decides, n8n executes.
💡 GDPR note for EU businesses: API data is not used for model training by default, and OpenAI provides a Data Processing Addendum. Still, send only the fields the task needs, never a full customer record. For strict data sovereignty requirements, we deploy the same n8n patterns with EU-hosted models instead.
Best practices to keep your OpenAI token budget under control
The OpenAI API is cheap per call and expensive per bad habit. These are the rules we apply on every SME deployment:
- Right-size the model. Classification, routing, extraction and short summaries belong on the mini tier, which costs a fraction of the flagship price. In our deployments, 80% of workflow calls never need the flagship model. Mixing models within one workflow is normal, not an optimization trick.
- Set hard limits at the source. A monthly usage cap and alert thresholds in the OpenAI dashboard (step 1), plus a
max_tokensceiling on every node. An output limit protects you from the model rambling; the account cap protects you from your own workflow bugs. - Trim the input. Do not send a full email thread when the last message is enough. Do not send raw HTML when text will do (strip it with a Code node first). Input tokens are usually 80-90% of the bill on triage workflows.
- Filter before the LLM, not after. A free IF node can discard newsletters and out-of-office replies before they ever reach the OpenAI node. Every email you filter with a rule is a call you do not pay for.
- Batch where latency allows. For non-urgent jobs (nightly CRM cleanup, weekly reports), group records and process them in scheduled batches rather than one call per event.
- Log usage per workflow. The OpenAI response includes token counts. Write them to a Google Sheet or database with the workflow name attached. When the monthly bill moves, you will know which workflow moved it in 30 seconds.
- Watch for retry loops. The classic budget killer: an error-handling branch that re-sends the same failed request forever. Cap retries at 2-3 with backoff, and alert on repeated failures instead of retrying silently.
Applied together, these practices keep a typical SME running 3-5 production workflows in the range of 10 to 50€ of API costs per month. Prices per token evolve regularly, so check OpenAI's pricing page when sizing a new project rather than relying on figures from an article, including this one.
Where to go from here
Once your first OpenAI workflow runs in production, the pattern repeats everywhere: quote drafting, support FAQ answers, document data extraction, meeting summaries. The orchestration skeleton (trigger → prompt → structured output → action) stays the same; only the prompt and the connected tools change. And if you later need to switch providers (Claude, Mistral, an EU-hosted model), n8n makes it a one-node swap, not a rebuild.
Want this running in your business?
Book a free 30-minute call. We audit your processes and send you a precise quote within 48 hours, in English or in French.
Book my free audit →