Node-RED AI Integration
What This Article Covers
- Integrating Ollama and other AI models into Node-RED.
- Working with Function nodes and dedicated AI nodes.
- Building event-driven AI flows (sensor β AI β action).
- Practical examples for text processing, classification, and analysis.
- Best practices for performance, error handling, and security.
Introduction: AI in Node-RED Explained
Node-RED is a visual flow editor. AI integration works like this: a node receives data (from a sensor, email, or HTTP request), a Function node or Ollama node processes it with AI, and another node executes an action. The result is event-driven AI automation without needing a code framework.
This article is for users who want to add AI capabilities to their Node-RED flows. For background, see Node-RED installation and Ollama.
Why Use AI in Node-RED?
Imagine a sensor detects unusual temperature readings. A basic flow sends an alert. With AI, the flow analyzes the data, understands the context (βtemperature spike after maintenance, probably fineβ), and intelligently decides whether an alert is needed.
How AI Works in Node-RED
You connect an input node (trigger) to a Function node that calls Ollama, then to an output node (action). Alternatively, use dedicated Ollama nodes from the palette. The flow reacts to events and processes them with AI.
The core pattern is simple: Event β AI Processing β Action.
Who Should Read This?
- Node-RED users building AI features into their flows.
- IoT developers analyzing sensor data with AI.
- Smart home enthusiasts wanting intelligent automation.
- Self-hosters running AI flows locally.
Basic familiarity with Node-RED and Ollama is helpful.
Key Concepts
- Node-RED - Visual flow editor. Use when: building the platform.
- Ollama - Local model server. Use when: you need an AI backend.
- Function Node - JavaScript node. Use when: calling AI models.
- HTTP Request Node - HTTP client node. Use when: querying Ollama API.
- node-red-contrib-ollama - Ollama nodes. Use when: you want simpler integration.
- Function Calling - Tool use. Use when: you need structured AI outputs.
- MQTT - IoT protocol. Use when: triggering on sensor data.
Method 1: Function Node with fetch()
// Function Node: Call Ollama
const response = await fetch("http://ollama:11434/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "llama3.1",
messages: [
{ role: "system", content: "You are an analysis assistant." },
{ role: "user", content: msg.payload }
],
stream: false
})
});
const data = await response.json();
msg.payload = data.message.content;
msg.ki_response = data;
return msg;
Method 2: HTTP Request Node
[Inject/Trigger] β [HTTP Request: Ollama] β [Debug/Action]
HTTP Request Node:
Method: POST
URL: http://ollama:11434/api/chat
Headers: Content-Type: application/json
Body:
{
"model": "llama3.1",
"messages": [{"role": "user", "content": "{{msg.payload}}"}],
"stream": false
}
Method 3: Dedicated Ollama Node
# Install
cd /data
npm install node-red-contrib-ollama
# Or via Palette Manager:
# Menu β Manage palette β Install β "ollama"
The node provides ready-made configurations for chat, embeddings, and completion.
Practical Example 1: Analyzing Sensor Data
Flow: MQTT Sensor β AI Analysis β Alert on Anomaly
[MQTT In: sensor/temperature]
β
βΌ
[Function: Build context]
msg.payload = `Temperature: ${msg.payload}Β°C, Time: ${new Date()},
Sensor: Living Room, Threshold: 30Β°C`
β
βΌ
[HTTP Request: Ollama]
"Is this temperature critical? Reply: yes/no + explanation"
β
βΌ
[Switch: critical?]
β
ββ yes β [Alert: Telegram/Email]
ββ no β [Debug: OK]
Practical Example 2: Email Classification
Flow: Email arrives β AI classifies β Sort to folder
[Email In]
β
βΌ
[Function: Extract email content]
β
βΌ
[HTTP Request: Ollama]
"Classify: invoice, support, newsletter, spam, other"
β
βΌ
[Switch: Category]
β
ββ invoice β [Move to: Invoices]
ββ support β [Move to: Support]
ββ spam β [Delete]
ββ other β [Move to: General]
Practical Example 3: Log Monitoring with AI
Flow: Log file β AI analyzes β Report
[Watch: /var/log/app.log]
β
βΌ
[Function: Collect new lines]
β
βΌ
[HTTP Request: Ollama]
"Analyze these log entries for errors and patterns"
β
βΌ
[Function: Check for critical errors]
β
βΌ
[Alert: Slack/Email]
Practical Example 4: Voice Command β AI β Action
Flow: Process voice command
[HTTP In: /api/command] β from Rhasspy/Home Assistant
β
βΌ
[HTTP Request: Ollama]
"Interpret: '{{msg.payload.command}}'
Available actions: licht_an, licht_aus, temperatur_abfragen,
musik_starten, musik_stoppen
Reply as JSON: {action: '...', params: {...}}"
β
βΌ
[Switch: action]
β
ββ licht_an β [call service: light.turn_on]
ββ temperatur_abfragen β [MQTT: read sensor] β [TTS: Respond]
ββ musik_starten β [call service: media_player.play]
Embeddings in Node-RED
// Function Node: Create embedding
const response = await fetch("http://ollama:11434/api/embeddings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "nomic-embed-text",
prompt: msg.payload
})
});
const data = await response.json();
msg.embedding = data.embedding;
return msg;
Error Handling
// Function Node with error handling
try {
const response = await fetch("http://ollama:11434/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "llama3.1",
messages: [{ role: "user", content: msg.payload }],
stream: false
}),
signal: AbortSignal.timeout(30000) // 30s timeout
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
msg.payload = data.message.content;
msg.success = true;
} catch (error) {
msg.payload = "AI unavailable: " + error.message;
msg.success = false;
node.error("Ollama error: " + error.message, msg);
}
return msg;
Performance Optimization
// Debounce: Don't call Ollama on every event
// Use context for caching
let cache = context.get("cache") || {};
const key = msg.payload;
if (cache[key] && (Date.now() - cache[key].time) < 60000) {
// Cache: less than 1 minute old
msg.payload = cache[key].result;
return msg;
}
// ... Ollama call ...
cache[key] = { result: msg.payload, time: Date.now() };
context.set("cache", cache);
return msg;
Security Considerations
- Validate inputs: Sensor data and emails can contain prompt injection attacks. See Prompt Injection.
- Network isolation: Do not expose Ollama. See Network Isolation.
- Validate outputs: Check AI responses before executing actions.
- Critical actions: Require human approval for critical operations like alarms or deletions. See Human Approval.
Common Pitfalls
- Docker networking:
localhostinside the flow refers to the Node-RED container itself. Usehttp://ollama:11434instead. - Timeout too short: Large models need time to process. Set timeout to 60-120 seconds.
- Missing error handling: If Ollama goes down, your flow will crash without proper try/catch blocks.
- Too many AI calls: High event frequency can overwhelm Ollama. Cache or filter events upstream.
- Non-persistent context: Flow context is lost on restart. Use persistentContext to retain state across restarts.
Further Reading
- Node-RED Guide - Node-RED in depth.
- Node-RED Installation - Setup instructions.
- Node-RED with Home Assistant - Home Assistant integration.
- Ollama REST API - API reference.
- Function Calling - Tool calling basics.
- Workflow Automation - Fundamentals.
- Prompt Injection - Security.
Key Takeaways:
- AI in Node-RED: Use a Function Node with fetch(), the HTTP Request Node, or dedicated Ollama nodes.
- Event-driven AI: Sensor β Analysis β Action.
- Local Ollama: No API costs, data stays on your hardware.
- Error handling and timeouts are essential.
- Cache responses when event frequency is high.
FAQ
How do I connect Node-RED to Ollama?
Should I use a Function Node or an Ollama Node?
What can I use AI in Node-RED for?
How fast is this?
Can I generate embeddings in Node-RED?
What should I do if Ollama fails?
Node-RED or n8n for AI?
Is this secure?
Sources and Further Reading
- Node-RED - Official website.
- node-red-contrib-ollama - Ollama node.
- Ollama API - API reference.
- Node-RED Cookbook - Flow recipes.


