OpenAI API instellen in n8n
In deze gids verbind je OpenAI met n8n. We richten credentials in, bespreken model- en endpointkeuze, streaming, function-calling, retries en kostenbeheersing.
Benodigdheden
• OpenAI account + API key • Gekozen model (bijv. GPT-5/o4-mini) • n8n Credentials voor veilige sleutelopslag
Stap 1 – Credentials
Maak een n8n Credential voor je OpenAI key. Gebruik environment-variabelen en minimaliseer logging van secrets.
Stap 2 – Endpoint & headers
Stel de OpenAI base URL en vereiste headers in. Controleer rate limits en toegestane gebruiksscenario’s.
Stap 3 – Modelkeuze & fallback
Kies een model passend bij je use-case (kwaliteit, contextlengte, kosten). Definieer fallbacks bij timeouts/5xx.
Stap 4 – Streaming & function-calling
Activeer streaming voor snellere UX. Gebruik function/tool-calling voor gestructureerde outputs; valideer parameters.
Stap 5 – Kosten & limieten
Beperk tokens, zet caching/batching in en gebruik exponential back-off op 429/5xx om kosten en retries te beheersen.
Security
Bewaar keys in Credentials, masker secrets in logs en segmenteer toegang per workflow/gebruiker.
🚀 GPT-5 & Model Selectie Augustus 2025
Nieuwste modellen vergelijking:
⭐ GPT-5 (NIEUW!):
• Sterkste model, vervangt GPT-4o
• 272K input, 128K output tokens
• $1.25/1M input, $10/1M output
• 4 reasoning levels (minimal tot high)
• Multimodal: text + image input
📍 GPT-5-mini & nano:
• Kleinere, snellere varianten
• Zelfde 4 reasoning levels
• Ideaal voor high-volume
• Pricing: check platform voor actuele prijzen
📍 GPT-4o (Legacy):
• 130K context window
• $2.50/1M input, $10/1M output
• Wordt vervangen door GPT-5
📍 GPT-4o-mini:
• Budget-vriendelijk
• 128K context
• $0.15/1M input, $0.60/1M output
🧠 O-Series Reasoning Models (April 2025)
Geavanceerde reasoning modellen:
🎯 o4-mini (Aanbevolen!):
• Beste prijs-prestatie verhouding
• 200K input, 100K output tokens
• $0.15/1M input, $0.60/1M output
• $0.275/1M voor cached input
• Knowledge cutoff: Juni 2024
📍 o3:
• $1.10/1M input, $4.40/1M output
• Sterker dan o4-mini voor complexe taken
📍 o3-pro:
• Premium tier: $20/1M input, $80/1M output
• Voor de zwaarste reasoning taken
💡 Tip: o3-mini is vervangen door o4-mini!
🔑 API Key Setup & Organisatie
Stap-voor-stap API configuratie:
1) Ga naar platform.openai.com
2) Settings → API Keys → Create new secret key
3) Kopieer key direct (wordt niet meer getoond!)
4) Noteer Organisation ID (org-xxxxx)
N8N Credential setup:
• Name: OpenAI Production
• API Key: sk-xxxxx
• Organisation ID: org-xxxxx (optioneel)
💡 Pro tip: Maak aparte keys voor dev/staging/production!
💬 Chat Completions Workflow
Basic chat implementatie:{
"model": "gpt-5-mini",
"messages": [
{"role": "system", "content": "Je bent een Nederlandse assistent"},
{"role": "user", "content": "{{$json.userInput}}"}
],
"temperature": 0.7,
"max_tokens": 2000,
"reasoning_level": "low" // GPT-5: minimal, low, medium, high
}
Message roles:
• system: Instructies & context
• user: Gebruikers input
• assistant: Bot responses
• function: Function calling results
⚡ Streaming Responses
Real-time streaming setup:
1) Enable 'stream: true' in request
2) Use Server-Sent Events (SSE)
3) Process chunks met JavaScript
N8N implementatie:
• Webhook node voor SSE endpoint
• Split response in chunks
• Send partial updates naar frontend
• Handle connection drops gracefully
Perfect voor chatbots & real-time UX!
🔧 Function Calling & Tools
Structured output met functions:{
"functions": [{
"name": "get_weather",
"description": "Get current weather",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"},
"unit": {"enum": ["celsius", "fahrenheit"]}
}
}
}]
}
N8N workflow:
1) Define functions in request
2) Parse function_call response
3) Execute function (API call/database)
4) Return result to ChatGPT
5) Get final response
🧠 Embeddings & Vector Search
Semantic search implementatie:
1) Generate embeddings: text-embedding-3-small
2) Store in vector DB (Pinecone/Weaviate)
3) Query met cosine similarity
Use cases:
• Knowledge base Q&A
• Document similarity
• Recommendation systems
• Semantic caching
Kosten: $0.02/1M tokens (3-small)
🎨 DALL-E 3 Image Generation
Image generation workflow:{
"model": "dall-e-3",
"prompt": "{{description}}",
"size": "1024x1024",
"quality": "standard",
"n": 1
}
Opties:
• Sizes: 1024x1024, 1792x1024, 1024x1792
• Quality: standard ($0.04) / hd ($0.08)
• Style: vivid / natural
Auto-save images naar cloud storage!
🎤 Audio & Speech Models (2025)
Whisper Transcription:
• Standard Whisper: $0.006/minuut
• GPT-4o Transcribe: $2.50/1M input, $10/1M output
• GPT-4o-mini Transcribe: $1.25/1M input, $5/1M output
Text-to-Speech (TTS):
• TTS Standard: $15/1M karakters
• TTS HD: $30/1M karakters
• GPT-4o-mini TTS: $0.60/1M input + $0.015/min
Features:
• 6 preset voices
• Multi-language support
• Real-time streaming
• Custom voice cloning (coming soon)
🔍 Search & Advanced Features (2025)
GPT-4o Search Preview:
• $30/1000 searches (low context)
• $50/1000 searches (high context)
• Real-time web data access
• Fact-checking capabilities
Code Interpreter:
• $0.03 per session
• Python sandbox environment
• Data analysis & visualization
File Search & Storage:
• $0.10/GB/dag (1GB gratis)
• Vector search over documents
• RAG implementation
Web Search Tool:
• $2.50/1000 API calls
• Excludes Assistants API usage
📊 Token Management & Kosten
Token counting:
• 1 token ≈ 4 karakters (Engels)
• 1 token ≈ 2-3 karakters (Nederlands)
• Use tiktoken library voor exacte count
Kostenoptimalisatie:
• Cache frequent responses
• Gebruik system prompts efficient
• Batch similar requests
• Set max_tokens limits
• Monitor usage via dashboard
💰 Budget alert: Set usage limits in OpenAI dashboard!
🚀 Praktische Use Cases
1. Content Generation:
• Blog posts & social media
• Product descriptions
• Email templates
• SEO metadata
2. Customer Support:
• Chatbot responses
• Ticket classification
• FAQ generation
• Sentiment analysis
3. Data Processing:
• Text summarization
• Translation (40+ talen)
• Data extraction from PDFs
• Code generation & debugging
⚠️ Rate Limits & Retry Logic
Default limits (Tier 2):
• GPT-5: Check platform voor actuele limits
• GPT-4o: 5,000 RPM, 30M TPM
• o4-mini: 10,000 RPM, 200M TPM
• DALL-E 3: 5 images/min
Tier systeem:
• Tier 1: Free trial
• Tier 2: $50+ spend
• Tier 3: $100+ spend
• Tier 4: $500+ spend
• Tier 5: $1000+ spend (o3 access)
N8N retry strategy:{
"retryOnFail": true,
"maxTries": 3,
"waitBetweenTries": 2000,
"backoffStrategy": "exponential"
}
🔐 Security Best Practices
Data protection:
• Never log full API keys
• Sanitize user inputs (prompt injection)
• Use content filters
• Implement user rate limiting
• Store conversations encrypted
Compliance:
• OpenAI retains data 30 dagen
• Opt-out van training mogelijk
• GDPR: implement data deletion
• Log alle API usage voor audit
🛠️ Advanced Prompt Engineering
Technieken voor betere results:
📍 Few-shot learning:
Geef 2-3 voorbeelden in prompt
📍 Chain-of-thought:
"Denk stap voor stap..."
📍 Role playing:
"Je bent een expert in..."
📍 Output formatting:
"Respond in JSON format: {example}"
📍 Temperature tuning:
• 0.0-0.3: Factual, consistent
• 0.7-0.9: Creative, diverse
🔄 Assistants API Integration
Stateful conversations:
1) Create assistant met instructions
2) Upload files voor knowledge base
3) Create thread per conversation
4) Run assistant on messages
Tools available:
• Code Interpreter (Python sandbox)
• File Search (RAG)
• Function calling
Pricing: $0.03/session + model costs
📚 Handige Resources
Documentatie:
• OpenAI API Docs
• OpenAI Cookbook
• N8N AI Agents Guide
Tools:
• OpenAI Playground
• Tokenizer tool
• Fine-tuning UI
• Usage dashboard