Skip to content
BotServBotServ
Node-REDAI IntegrationOllamaLLMFlows

Node-RED AI Integration

Integrate AI in Node-RED. Ollama nodes, Function nodes for LLM calls, AI flows and practical examples.

S

schutzgeist

6 min read
Node-RED AI Integration

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: localhost inside the flow refers to the Node-RED container itself. Use http://ollama:11434 instead.
  • 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

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?

Use a Function Node with fetch(), an HTTP Request Node, or the dedicated node-red-contrib-ollama package. The URL is http://ollama:11434 when both run in the same Docker network.

Should I use a Function Node or an Ollama Node?

Use a Function Node for maximum control. Use an Ollama Node for simpler configuration. The HTTP Request Node offers a middle ground without additional installation.

What can I use AI in Node-RED for?

Analyze sensor data, classify emails, parse logs, interpret voice commands, detect anomalies, or summarize text.

How fast is this?

Each Ollama call takes 2-10 seconds depending on the model. For real-time use cases, cache or filter events. For batch processing, performance is not a concern.

Can I generate embeddings in Node-RED?

Yes, via the Ollama Embeddings API (nomic-embed-text). Store embeddings in a vector database for semantic search.

What should I do if Ollama fails?

Implement error handling in your Function Node: use try/catch blocks, set timeouts, and provide fallback logic. Your flow should gracefully degrade instead of crashing.

Node-RED or n8n for AI?

Choose Node-RED for IoT and event-driven AI. Choose n8n for business workflows and complex agents. Both can use Ollama. See Classic Workflows vs. AI Agents.

Is this secure?

Yes, when run locally. All data stays on your server. However, validate inputs for prompt injection and verify AI responses before triggering critical actions.

Sources and Further Reading

Back to Blog
Share:

Related Posts