How to Build OpenAI Workflows with n8n (Classify, Summarize, and Generate at Scale)
Build n8n OpenAI workflows using the LangChain node. Classify leads, summarize emails, and generate content at scale. Browse ready-made n8n templates.
n8n OpenAI workflows connect a self-hosted automation engine to capable text models, and the integration is more direct than most tutorials suggest.
The pattern goes like this: something triggers the workflow (a form submission, a webhook, a Slack message), the incoming data gets assembled into a prompt, OpenAI returns a response, and n8n routes the result somewhere useful. Classification, summarization, content generation, data extraction — all follow the same four-step spine. You're wiring it together once, then it runs on its own.
Where things break isn't usually in the OpenAI call itself. It's in prompt construction, output parsing, and occasionally credential handling. The @n8n/n8n-nodes-langchain.openAi v2.1 node returns text at $json.output[0].content[0].text. A lot of n8n builders still copy-paste from 2022–2023 tutorials referencing the deprecated n8n-nodes-base.openAi node, which has a different output path. Nothing fails loudly. It just returns empty. Hard to debug if you don't know what to look for.
This guide covers the canonical patterns so you don't have to discover that gap the hard way.
What OpenAI Can Do Inside n8n
The range of tasks that fit naturally into an n8n OpenAI pipeline:
- Lead scoring and routing (score 0–100 with a reason field, push high-scores directly to sales)
- Support ticket classification (category, priority, and a suggested first reply)
- Email thread summarization pushed to Slack in under 60 seconds
- Blog draft generation from a brief or a set of keywords
- Sentiment scoring for customer reviews or feedback at volume
- Data extraction from unstructured text (pull vendor names, amounts, due dates from PDFs or email bodies)
- A/B copy variant generation for ads, subject lines, and landing page headlines
Every task above runs the same node sequence: Trigger → Prompt Assembly → OpenAI → Parse → Route → Action. The prompt content changes; the wiring doesn't. Learn it once, and you'll recognize the shape everywhere.
Building the n8n OpenAI Pipeline
The canonical shape of an n8n OpenAI workflow:
Trigger → Code (prompt) → openAi → Code (parse) → IF/Switch → Action nodes
Classification can sometimes skip the parse step if the model returns a single word. Generation often adds an extra delivery node at the end. But the spine doesn't change. When something breaks in production, the first question is always: which segment broke? Prompt assembly, OpenAI call, output parse, or routing?
Step by Step: From Trigger to Action
1. Collect the Input
What arrives at the trigger determines the prompt. A Webhook node might carry a raw email body in $json.body.text. A Schedule trigger might pull rows from Google Sheets via an HTTP Request node. Either way, map the relevant fields before touching OpenAI.
A Code node before the prompt assembly step is useful for shaping the raw input — extracting a subject line, stripping HTML tags, or capping text at 1,000 characters when token costs matter. Token limits add up fast on high-volume workflows.
2. Build the Prompt
Don't concatenate strings directly inside the OpenAI node's message fields. Build the prompt in a Code node first, then reference $json.systemPrompt and $json.userPrompt in the LangChain node. This keeps the prompt logic versioned separately from the node configuration and makes testing individual prompts much easier.
A system message and a user message is the minimum. The system message sets behavior and constraints; the user message carries the variable data. Keep system messages under 100 tokens — longer ones eat context window and you're billed for every token.
3. Call OpenAI
The node is @n8n/n8n-nodes-langchain.openAi (v2.1). Select the credential, choose the model. gpt-4o-mini for classification and extraction (fast, cheap, reliable enough). gpt-4o for generation where output quality matters and you can absorb the cost.
Temperature: 0 for classification, 0.7 for creative generation. That's the setting most n8n OpenAI workflows get wrong. Running classification at temperature 0.7 introduces random variance into what should be a deterministic bucket — you'll get inconsistent category labels across similar inputs, and it won't be obvious why.
Set maxTokens explicitly. Leaving it unbounded on a workflow that runs 500 times a day is how bills spike overnight.
4. Parse the Output
This is where most n8n OpenAI workflows fail silently. The model returns text. The next node expects structured data.
Always add a Code node immediately after the OpenAI node:
const text = $json.output[0].content[0].text;
// If the model was asked to return JSON:
const parsed = JSON.parse(text);
return [{ json: parsed }];
If the model wasn't instructed to return JSON (a plain summary, for example), just pass the text through without parsing. But if you asked for JSON and skip this step, the downstream node will fail in a way that points at the wrong place.
One more thing: wrap the JSON.parse call in a try/catch. Models hallucinate JSON brackets roughly once in 200 runs. Not always. But it happens, and without the catch, it takes down the entire execution.
5. Route and Act
After parsing, an IF node or Switch node handles branching. A lead score above 70 routes to a Salesforce create-contact node. A ticket classified as "billing" triggers a Stripe customer lookup. A negative sentiment score fires a Slack alert to the support channel.
The parsed output is now in $json like any other n8n data. No special handling needed — it behaves the same as a webhook payload or a database row.
The old n8n-nodes-base.openAi node still shows up in tutorials from 2022 and 2023. Don't use it. The output path is different, the node ID changed after the LangChain integration, and copy-pasting from those tutorials will silently break your parse step. If you're debugging an empty output with no visible error, that's the first thing to check.
Implementation Patterns Worth Knowing
Pattern 1 — Batch Classification. When processing hundreds of items (tickets, leads, reviews), don't call OpenAI once per item in serial. n8n's SplitInBatches node with a batch size of 20–50 lets the workflow process chunks without hitting rate limits. OpenAI's standard tier allows 500 RPM on gpt-4o-mini — enough to process 50 items in roughly 6 seconds. Push that rate too hard and you'll start seeing 429 errors that require retry logic.
Pattern 2 — JSON-Mode Extraction. When structured output is non-negotiable (extracting fields from contracts, parsing invoice details), tell the model in the system message exactly what to return: "Return ONLY valid JSON with keys: amount, currency, due_date, vendor_name. No other text." Then wrap the Code parse step in a try/catch and emit a fallback item on failure. You can't trust every response to be well-formed. Costless to defend against.
Pattern 3 — Chained Calls. Some tasks need two OpenAI calls: one to classify, one to generate a response based on the classification result. Wire them as two separate openAi nodes with a Code node between each. Don't try to do both classification and generation in a single complex prompt. The outputs are less predictable, and the execution log becomes nearly unreadable when debugging.
n8n Nodes You'll Use Most
| Node | Purpose |
|---|---|
@n8n/n8n-nodes-langchain.openAi v2.1 | Chat completions, classification, summarization, generation |
n8n-nodes-base.code v2 | Prompt assembly; parse JSON from LLM output |
n8n-nodes-base.splitInBatches | Process large item sets without rate-limit hits |
n8n-nodes-base.if | Route items based on classification result or score |
n8n-nodes-base.httpRequest v4.2 | Direct API calls or fetching external context before the prompt |
n8n-nodes-base.merge | Combine AI-enriched data back with the original record |
Getting Started with n8n OpenAI Templates
- Install n8n. Self-host via Docker or use n8n Cloud. Self-hosting removes the task billing entirely — relevant if you're running high-volume classification where task counts stack fast.
- Add OpenAI credentials. Settings → Credentials → New → OpenAI API. Paste your key. The
@n8n/n8n-nodes-langchain.openAinode picks it up automatically once saved. - Start from a working template. The AI Lead Scoring and Email Routing template handles lead classification out of the box — scoring inbound messages 0–100 with a reason field, routing high-scores to a priority email sequence, and logging every contact to Google Sheets. It's worth studying before building custom logic: the prompt assembly and parse steps are wired correctly.
- Customize the prompt. Open the Code node before the OpenAI call, update the system message for your use case, and adjust the JSON schema the model returns.
- Set temperature and max tokens explicitly. Never leave
maxTokensunbounded on a workflow you're deploying. - Add the parse node. Even if it looks redundant, add the Code node that reads
$json.output[0].content[0].text. You'll thank yourself when debugging. - Test with real inputs. LLMs respond differently to placeholder text versus real-world inputs. Always test with a representative sample before deploying.
For content generation at volume, the Content Scheduler and Distributor template chains an RSS trigger through an OpenAI prompt that returns five-channel variants (YouTube, Facebook, Twitter, and more), then routes each to the right output with platform-specific formatting. It's a good example of chained prompt logic done cleanly.
For teams building evaluation loops around their AI outputs, the RAG Eval Blind A/B Tester runs both models, anonymizes outputs, and scores them with a judge model — delivering a findings report to Google Sheets. If you're iterating on prompt variants for a classification workflow, this is worth running before you ship.
The OpenAI integration in n8n doesn't require much ceremony. The node is stable, the credential setup is straightforward, and the output path is consistent once you know it. What takes time is getting the prompt assembly and parse steps right for your specific use case. For a broader look at what's possible with AI in n8n, see How to Build AI-Powered Automations with n8n. For generation-focused pipelines specifically, How to Automate Content Creation with n8n covers the distribution side in detail.
Browse All n8n AI Templates →Common questions
How do I connect OpenAI to n8n?
Which n8n node should I use for OpenAI in 2026?
How do I parse JSON from an OpenAI response in n8n?
Get the workflow templates this guide is built on
Import-ready n8n JSON, step-by-step setup, and tested end-to-end. One-time payment, own it forever.
More automation guides

How to Automate HR Workflows with n8n (Onboarding, Compliance, and Wellness Monitoring)
HR Admin Runs on Repetition. n8n Handles Repetition. Every new hire triggers the same chain of tasks. Welcome email, Notion page, Trello cards, payroll enrollment reminder, badge request. Someone copy…

How to Automate HubSpot with n8n (Contacts, Deals, and Email Sequences)
HubSpot Automation That Goes Beyond the Built-In Workflow Builder HubSpot's native workflow builder handles simple branching inside HubSpot well. The moment you need to sync a closed deal to your acco…

How to Automate Shopify with n8n (Orders, Customers, and Inventory)
Shopify Automation That Actually Runs Every Shopify store hits the same wall. You're manually exporting order CSVs to your fulfillment partner. Someone has to tag VIP customers by hand after their thi…