node-red-contrib-knx-ultimate 6.4.1 → 7.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +129 -121
  2. package/README.md +4 -0
  3. package/nodes/knxUltimate-config.js +38 -38
  4. package/nodes/knxUltimate.js +1 -1
  5. package/nodes/knxUltimateAI.html +9 -5
  6. package/nodes/knxUltimateAI.js +143 -143
  7. package/nodes/knxUltimateAIHomeAssistant.html +7 -5
  8. package/nodes/knxUltimateAIHomeAssistant.js +1 -1
  9. package/nodes/knxUltimateHueController.html +1 -1
  10. package/nodes/knxUltimateMatterBridge.html +2 -2
  11. package/nodes/knxUltimateMatterControllerDevice.html +12 -12
  12. package/nodes/locales/de/knxUltimateAI.html +4 -199
  13. package/nodes/locales/de/knxUltimateAI.json +6 -6
  14. package/nodes/locales/de/knxUltimateViewer.html +1 -1
  15. package/nodes/locales/en/knxUltimateAI.html +4 -211
  16. package/nodes/locales/en/knxUltimateAI.json +6 -6
  17. package/nodes/locales/en/knxUltimateViewer.html +1 -1
  18. package/nodes/locales/es/knxUltimateAI.html +4 -199
  19. package/nodes/locales/es/knxUltimateAI.json +6 -6
  20. package/nodes/locales/es/knxUltimateViewer.html +1 -1
  21. package/nodes/locales/fr/knxUltimateAI.html +4 -199
  22. package/nodes/locales/fr/knxUltimateAI.json +6 -6
  23. package/nodes/locales/fr/knxUltimateViewer.html +1 -1
  24. package/nodes/locales/it/knxUltimateAI.html +4 -211
  25. package/nodes/locales/it/knxUltimateAI.json +6 -6
  26. package/nodes/locales/it/knxUltimateViewer.html +1 -1
  27. package/nodes/locales/zh-CN/knxUltimateAI.html +4 -199
  28. package/nodes/locales/zh-CN/knxUltimateAI.json +6 -6
  29. package/nodes/locales/zh-CN/knxUltimateViewer.html +1 -1
  30. package/nodes/plugins/knxUltimateAI-vue/assets/app.css +1 -1
  31. package/nodes/plugins/knxUltimateAI-vue/assets/app.js +10 -10
  32. package/nodes/plugins/knxUltimateAI-vue/index.html +1 -1
  33. package/nodes/plugins/knxUltimateViewer-vue/assets/app.js +2 -2
  34. package/nodes/utils/knxAiChatContext.js +4 -4
  35. package/nodes/utils/knxAiHomeMemory.js +2 -2
  36. package/nodes/utils/knxAiScheduler.js +2 -2
  37. package/package.json +1 -1
  38. package/resources/KNXAIChatAdapterMappings.js +4 -4
  39. package/examples/KNX AI - Conversational Control with Confirmation.json +0 -395
  40. package/examples/KNX AI - Summary Anomalies and Ask.json +0 -226
  41. package/examples/KNX AI - Telegrambot Direct Chat.json +0 -198
@@ -1,212 +1,5 @@
1
- <script type="text/markdown" data-help-name="knxUltimateAI">
2
- This node listens to **all KNX telegrams** from the selected KNX Ultimate gateway, builds traffic statistics, detects anomalies, and can optionally query an LLM.
3
-
4
- The editor uses two horizontal tabs: **AI assistant** contains setup, knowledge/context and provider limits; **Cerebrum (BETA)** contains chat input/output pins, proactive home and bounded memory.
5
-
6
- ## Outputs
7
- 1. **Summary/Stats** (`msg.payload` JSON)
8
- 2. **Anomalies** (`msg.payload` JSON)
9
- 3. **AI Assistant** (`msg.payload` text, with `msg.summary`)
10
- 4. **KNX operations** (one Universal Mode message per validated read or write)
11
- 5. **TTS Ultimate** (one announcement message per model-selected spoken message)
12
-
13
- Every message emitted by outputs 3 and 4 also contains a clone of the original input message in `msg.inputMessage`. This preserves the original payload, topic, chat metadata, and any other input properties for downstream nodes. Cloning and output errors are contained and reported instead of escaping into the Node-RED runtime.
14
-
15
- At node startup, output 3 emits a short Cerebrum supervision notice with `msg.boot = true`. When AI is enabled, the notice is generated by the selected model as a live inference test; `msg.knxAi.llmTest` is `passed`, while provider and model identify what answered. If AI is disabled or the call fails, the startup message is still emitted with an honest localized fallback and `llmTest` set to `disabled` or `failed`. This check never reads or writes KNX.
16
-
17
- ### Setup Doctor and safe first run
18
- The automatic **Setup Doctor** checks the selected gateway and ETS import, AI enablement, provider, model and API key, provider reachability, flow wiring, detected cameras and the optional TTS Ultimate connection. Its no-cost provider preflight calls only the provider's model-list endpoint: it never sends a chat request or consumes inference tokens. Cameras and TTS are optional, so leaving them unused does not reduce core readiness.
19
-
20
- The inventory reports the exact number of unique KNX group-address signals, the ETS areas/groups and an approximate number of logical functions. It deliberately does not claim a physical-device count, because that cannot be derived reliably from the ETS CSV. Setup Doctor reads the last deployed flow, so deploy provider, model, preset, gateway or wiring changes before clicking **Refresh** to repeat the checks.
21
-
22
- Send `/start` or `/help` from a chat to receive a deterministic, localized welcome on the chat output (output 3), with personalized installation statistics and up to three safe suggestions. This onboarding does not call the LLM, read or write KNX, or generate TTS. With the Telegram preset, suggestions appear as reply-keyboard buttons and run only after the user explicitly selects or sends one. After that explicit selection, a starter suggestion may perform exact KNX reads when needed; KNX writes and routines, camera actions, TTS, persistent-memory changes and GA-role learning remain suppressed.
23
-
24
- ### Web Intelligence
25
- Web access is disabled by default. When **Allow the AI to use the Web** is enabled, the conversational model decides from each current request whether fresh public information is needed and may choose the structured Web tool without keywords, topic-specific logic or intent classifiers. Each user turn or user-created scheduled task run can execute at most three Web operations in total. All real outbound Web operations share the configured rolling hourly budget.
26
-
27
- KNX AI does not start a fixed background Web polling cycle. If an essential detail would materially change the answer or query—such as the subject, scope, place, time window or desired outcome—the model asks one concise clarification and performs no Web operation until the user answers. Future or recurring checks are created only from an explicit natural-language request through the scheduler.
28
-
29
- Every Web-backed answer contains runtime-validated citations with a sanitized source URL and retrieval time, plus publication time when available. External content is untrusted data, never instructions, and cannot override the assistant rules or permissions. Only bounded public HTTPS resources are accepted; private, local, link-local and cloud-metadata targets, unsafe redirects, authenticated browsing and cookies are blocked. If no source can be verified, KNX AI reports that limitation instead of generating an unsourced answer.
30
-
31
- After verified Web results are available, the model may compose other enabled tools when authorized by the current chat or AI Education. Web access never expands permissions: camera, TTS and memory availability, as well as KNX reads and writes, local ETS/DPT validation and the configured KNX write confirmation, remain unchanged. Web requests expose the query and this server's public IP to external sites or the search service; KNX/ETS data, camera content, chat identifiers, learned memory and credentials are never added automatically.
32
-
33
- ### Natural-language plans and reminders
34
- In normal chat language, the user can ask KNX AI to create, list or cancel a one-time or recurring reminder, monitor or future home command. The model chooses the structured `scheduleActions` planning tool semantically from the complete request and stores the complete goal and conditions as a human-language instruction. There are no schedule keywords, trigger-phrase lists or rigid intent classifiers, so wording and language do not restrict the feature.
35
-
36
- Schedules belong to the chat session and persist per KNX AI node across Node-RED restarts. Their authoritative runtime state is `<userDir>/knxai/schedules/knxai-schedules-<node-id>.json`; KNX AI also generates `<userDir>/knxai/schedules/knxai-schedules-<node-id>.md` as a readable view. A plan can run once, repeat at intervals of at least five minutes and optionally expire. The model can list or cancel only the active schedules owned by the current chat unless the user explicitly asks to cancel all of that chat's schedules.
37
-
38
- When a task is due, KNX AI starts a separate model pass with the stored human-language instruction as trusted user authority. A monitor stays silent when its condition is not satisfied. Existing permissions still apply at execution time: a weather monitor needs **Allow the AI to use the Web** and uses the same Web budget, a spoken result leaves output 5 and therefore needs a wired TTS Ultimate node, and camera tools remain limited to detected adapters. A scheduled KNX write still uses the exact ETS/DPT checks and, when enabled, produces a preview for the same chat session and waits for confirmation before output 4 emits anything.
39
-
40
- For example, the user can write: “For the next five days, check the forecast for Cortemaggiore every 30 minutes and use TTS Ultimate only if thunderstorms are forecast.” KNX AI can preserve this complete condition and duration as one recurring monitor; the Web and TTS requirements above remain in force.
41
-
42
- ## Commands (input)
43
- Send `msg.topic`:
44
- - `summary` (or empty): emit summary immediately
45
- - `reset`: clear internal history, counters, learned home memory, every persisted chat context, and every schedule for this node; the AI Education configured on the node remains unchanged
46
- - `ask`: send a question to the configured LLM
47
- - `confirm` / `cancel`: confirm or cancel pending KNX commands without calling the LLM
48
- - `clear_chat`: clear recent turns, persistent instructions and pending commands for the current session, and cancel that session's active schedules; other sessions and AI Education remain unchanged
49
-
50
- For `ask`, provide the question in `msg.prompt` (preferred), `msg.payload` (string), or the common Telegram fields `msg.payload.content` / `msg.payload.text`.
51
-
52
- If processing takes longer than 1.2 seconds, output 3 emits the localized intermediate message “I’m thinking…” with `msg.knxAi.type = "thinking"` and `msg.knxAi.transient = true`. The chat adapter sends it immediately to the same user, while the final answer follows normally. This progress message is never stored in conversation context or learned memory.
53
-
54
- Every LLM chat request uses a provider-independent minimum timeout of 30 minutes. There is no timeout field to maintain in the editor. This is a maximum wait, not an artificial delay: faster models still finish as soon as their response is ready. If even this limit is reached, KNX AI reports that the model did not finish and suggests retrying or reducing the prompt context.
55
-
56
- KNX AI no longer exposes an application context-size selector. The complete selected ETS catalog stays inside the node and the model queries it through bounded local retrieval actions; only the retrieved objects enter the prompt. Search covers exact addresses, ETS names, aliases, hierarchy, areas, semantics, DPTs and value labels, with accent-insensitive and typo-tolerant ranking, plus exact lookup, area browsing and related command/status discovery. Without an explicit time range, KNX and adapter events cover the last 20 minutes. Packaged help, README, wiki, examples and changelog content are never embedded; the model may use the Web tool to consult public GitHub documentation when needed. Retrieved ETS data, the current request and archive rows each appear once, while only derived bus aggregates remain in the analysis block. Complete Function source is added only for an explicit Function-code review. KNX AI does not retry an oversized request by compacting the prompt.
57
-
58
- Before each request to a local model, KNX AI reserves answer space from the active 8K/16K window. It automatically bounds the newest conversation turns, exact archive rows, learned home memory, Web results, schedules, requested Function source, retrieved ETS objects and camera metadata. This is proactive prompt construction, not an oversized-request retry, and the complete selected ETS catalog remains available locally through retrieval.
59
-
60
- ### ETS object access
61
- The **ETS object access** section reproduces the group-address selector used by IoT Bridge's MQTT profile. Filter the imported list, select all or none, and mark the currently shown addresses read-only in bulk or one row at a time. Only selected addresses are available to the model. Every selected address is active and readable; read-only addresses remain visible but local validation rejects every `GroupValue_Write` to them. There is no migration or legacy fallback: after upgrading, open each existing KNX AI node, save its explicit selection and Deploy; until then its AI catalog is empty.
62
-
63
- The node's canvas status is deliberately reserved for the latest incoming request and the localized “I’m thinking…” state while the LLM is running. KNX telegrams, gateway updates, traffic rates, ready messages and technical results never overwrite it; they remain available through the node outputs, logs and Assistant data.
64
-
65
- Every Ask/chat session keeps its last 8 turns and up to 20 model-selected long-term instructions, separated by `msg.knxAi.sessionId`, `msg.sessionId`, or a detected Telegram chat ID. The model decides semantically when the meaning of a conversation should be remembered or forgotten through the structured memory tool; no language keyword or intent list is used. All KNX AI nodes using the same storage share this live context and reload it after Node-RED restarts from `knxultimatestorage/knxai/memory/knxai-chat-context.knxctx`. The atomically written file is bounded to 50 sessions and 512 KB. When KNX control is enabled, wire output 3 back to the chat sender and output 4 to a KNX Ultimate node configured in **Universal mode**. With confirmation enabled, the first reply previews every write GA, DPT, and payload without emitting writes; the same session must then reply `CONFIRM`/`CANCEL` (localized equivalents are accepted) within 5 minutes. A new request replaces any older pending plan. Each confirmed command has `msg.destination`, `msg.dpt`, `msg.payload`, and `msg.event = "GroupValue_Write"`.
66
- Recent session memory is placed immediately beside the current request so local models retain user-supplied facts such as a preferred name or language even inside a large KNX prompt. The model may persist durable facts, preferences and instructions through `memoryActions`; this remains a semantic tool choice without phrase classifiers or intent routing. Credentials, security codes and API keys must never be learned.
67
-
68
- For DPT 1.xxx writes, safe AI equivalents `true`/`false`, `1`/`0`, and `on`/`off` are normalized to a real boolean before local validation and output.
69
-
70
- ### Fresh KNX reads
71
- When the user explicitly asks for a fresh/current state, the AI may query exact objects from the imported ETS catalog, including status and other read-only objects. Output 4 emits `msg.destination`, `msg.dpt`, `msg.event = "GroupValue_Read"`, and `msg.readstatus = true`. The node waits up to 6 seconds for each `GroupValue_Response` or fresh write, then returns the decoded values on output 3 and exposes details in `msg.knxAi.readResults`. Reads never require confirmation and never become writes. If a small local model omits the operation discriminator and payload, exact ETS items are safely normalized as reads; an item containing a payload remains a validated write.
72
-
73
- ### Conversational multi-step routines
74
- Requests such as “I’m leaving”, “Good night”, or “Cinema mode” can coordinate a state-aware routine without a new editor option. In the first LLM pass, only exact ETS reads are accepted (up to 20); KNX AI sends them and supplies the fresh GA/DPT/value results to a second isolated planning pass. That pass may prepare up to 12 validated writes, but cannot request another read cycle. With confirmation enabled, the complete plan has one localized confirmation and no write or requested TTS announcement is emitted beforehand. After confirmation every write is revalidated, forwarded in order, and observed for up to 4 seconds for matching immediate bus feedback. The final reply distinguishes observed feedback from operations without immediate feedback—absence of feedback is not reported as device failure. Routine details are exposed in `msg.knxAi.routine`, `readResults`, `verifiedCount`, and `unverifiedCount`.
75
-
76
- ### Confirmation request for chat buttons
77
- While a plan is pending, output 3 contains `msg.knxAi.confirmationRequest`. The object includes `required`, `status`, `sessionId`, `expiresAt`, `commandCount`, and two entries in `actions`. Use `action.label` as the Telegram button text, `action.callbackData` as its callback, and send `action.message` back to KNX AI to confirm or cancel without typed text.
78
-
79
- ### Input/output message adapters
80
- The **Chat input and output pins** section loads its selectable mappings from `resources/KNXAIChatAdapterMappings.js`. Selecting an adapter installs two predefined synchronous JavaScript mappings internally: one before KNX AI processes an input and one before output 3 is emitted. The mappings remain hidden in the editor. Syntax and execution failures are caught and reported without stopping Node-RED.
81
-
82
- The included **windkh/node-red-contrib-telegrambot** preset follows the package's receiver/sender contract. Connect a `telegram receiver` directly to KNX AI and output 3 directly to a `telegram sender`. Confirmation uses a one-time Telegram reply keyboard: clicking **Confirm** or **Cancel** returns a normal localized message through the same receiver, so no `telegram event` or callback wiring is required. Legacy `callback_query` messages remain accepted. The input mapping extracts `msg.payload.content`, `msg.payload.chatId`, and the Telegram language. The output mapping creates the required `msg.payload.chatId`, `type`, and `content`, adding `options.reply_markup` from `msg.knxAi.confirmationRequest` when writes await confirmation. The Telegram package remains a separate optional dependency.
83
-
84
- With this preset, a Telegram voice message (`msg.payload.type = "voice"`) is handled automatically only when **Provider** is set to **OpenAI-compatible**. KNX AI verifies the provider before downloading anything, reuses its configured **Endpoint URL** and **API key**, and derives `/audio/transcriptions` and `/audio/speech` from that same connection. The token-bearing `msg.payload.weblink` is used only for the bounded download and is removed before the message reaches outputs or the LLM. OGG/Opus input is transcribed with the built-in `gpt-4o-mini-transcribe` default; a successful request receives a native Telegram OGG/Opus reply generated with `gpt-4o-mini-tts` and `alloy`, while the text caption and any confirmation keyboard are preserved. If another provider is selected, the user receives a localized instruction to select OpenAI-compatible or send text. If synthesis is unavailable, fails, or exceeds the speech limit, the complete answer is sent as text. The downloaded audio and generated reply text are sent to the same selected provider. Text messages, photos, and older saved Telegram mappings remain compatible.
85
-
86
- Every native voice caption begins with a localized **AI-generated voice** disclosure for the Telegram recipient.
87
-
88
- The included **RedBot / node-red-contrib-chatbot (Telegram)** preset follows RedBot's common message contract. Connect `chatbot-telegram-receive` directly to KNX AI and output 3 directly to `chatbot-telegram-send`; no separate callback node is needed because RedBot converts inline-button postbacks into normal inbound messages. Text and postbacks use RedBot's `message` payload. A native Telegram voice arrives as `type = "audio"` with an OGG/Opus `Buffer` already downloaded by RedBot; KNX AI applies its size and duration limits without downloading it again, transcribes it with the same OpenAI-compatible provider described above, and returns a native RedBot `audio` reply with the localized AI-generated-voice disclosure and text caption. When a KNX write needs confirmation, the reply deliberately remains a text `inline-buttons` payload because RedBot cannot attach those buttons to the same voice message. The output mapping preserves RedBot's `originalMessage`, `chat`, `api`, and `client` tracking data, and older saved RedBot mappings are upgraded at runtime. RedBot remains a separate optional dependency.
89
-
90
- ### Automatically detected camera adapters
91
- Installed camera packages can publish a camera adapter to KNX AI at runtime. There is no selector and no camera node to wire to KNX AI: available adapters, controllers and cameras are detected automatically and included in the chat context. `node-red-contrib-unifi-ultimate` is the first supported provider; other packages, such as `hikvision-ultimate`, can register through the same vendor-neutral contract.
92
-
93
- The user can ask for a current snapshot or ask the vision model what is visible. Telegram and RedBot presets emit the returned image as a native photo with a caption. The user can also create persistent notifications for motion, a smart line crossing or entry into an intrusion/loiter zone, optionally limited to detected people and to an exact named line or zone. These rules are stored in the same `knxai-chat-context.knxctx` file and are restored after Node-RED restarts. UniFi event subscriptions and snapshot requests are made directly through the detected provider; KNX AI output 4 is not involved and no intermediate flow wiring is required.
94
-
95
- Every event published by an automatically detected adapter is normalized and appended directly in KNX AI's compact native row format to a daily `YYYY-MM-DD.knxctx` file under `knxultimatestorage/knxai/adapter-history/<node-id>/`. The KNX telegram archive uses the same compact format, without intermediate JSON serialization. The archive keeps 10 days, guarantees more than 24 hours of history and stores event metadata rather than snapshot images. Existing JSONL archives are neither read nor migrated. The prompt uses the newest exact rows in the supplied interval, automatically bounded for the active local-model window.
96
-
97
- ### TTS Ultimate announcements
98
- Wire output 5 to one or more `ttsultimate` nodes from the optional `node-red-contrib-tts-ultimate` package. Normal Node-RED wiring controls the destination and fan-out; use Link Out/Link In when the TTS node is on another flow tab. The previous TTS-node selector and internal injection have been removed. Existing output positions 1–4 are unchanged, but upgraded flows must physically connect output 5 before spoken announcements can reach TTS Ultimate.
99
-
100
- The model decides whether to prepare an announcement by reasoning over the current request, persistent chat instructions and user-managed AI Education; there is no announcement intent or trigger-phrase list. KNX values, adapter events, camera content and archives remain data rather than instructions, but trusted user guidance may tell the model how to act on them. Output 5 emits the exact spoken text in `msg.payload`, sets `msg.topic = "knx_ai_announcement"`, and adds `msg.knxAi.type = "tts_announcement"` together with `msg.knxAi.sourceNodeId`, `msg.knxAi.sessionId`, and `msg.knxAi.reason`. TTS Ultimate then handles the configured player, voice, volume, hailing and queue.
101
-
102
- ### Chat context overview
103
- The node editor shows a compact card summarizing the sources available to the chat: 20-minute or explicitly ranged KNX and adapter events, the complete locally searchable ETS catalog with only retrieved objects added to each prompt, on-demand Function source, session and home memory, AI Education, active plans and detected cameras. It also shows the model-reported maximum operational context and the actual UTF-8 size of the last chat prompt; exact provider input tokens are used when reported, otherwise the token count is marked as estimated. The card lists the absolute paths of the authoritative JSON/readable Markdown schedule files, plus the KNX telegram and adapter-event archive directories and the `YYYY-MM-DD.knxctx` daily-file pattern. A temporary `knxai-last-chat-prompt-<node-id>.txt` local debug file contains the latest exact system/user prompt text—including retrieval results and the retrieved ETS subset—is overwritten before every chat call and never contains API keys or HTTP headers. AI Education is stored in the node configuration and therefore has no separate runtime file.
104
-
105
- The model receives local ETS catalog retrieval, KNX read/write operations, camera adapters, TTS announcements, persistent memory, Web access and plans/reminders as structured tools. It can select and combine them semantically from the current request and trusted learned guidance, without linguistic intent routing. Catalog retrieval is deterministic and local; the runtime validates tool arguments, camera-adapter availability and safety boundaries, while KNX writes still use complete local ETS/DPT validation and the configured confirmation step.
106
-
107
- ### Editing and backing up CHAT learning
108
- The **Cerebrum (BETA)** tab in the Node-RED KNX AI configuration includes an **Open AI Chat Learning** button that opens the Vue Web UI directly on this editor for the current node.
109
-
110
- In the Vue web UI, open **Cerebrum → AI Chat Learning** to inspect the exact shared `knxai-chat-context.knxctx`. **Native file** exposes the authoritative editable records; **Simplified text** explains the same conversations, learned instructions and camera watches in a localized read-only view. Copy follows the selected view, while download and restore always use the complete native backup. **Reinitialize Memory**, protected by an explicit confirmation, replaces it with a new empty context and clears saved sessions, instructions, camera watches and pending chat confirmations across every KNX AI node using the same storage. Saving validates and bounds the native V3 records, atomically rewrites the file and updates every live KNX AI node sharing that storage. A revision check protects newer learning.
111
-
112
- Only the native V3 format is supported. Previous Markdown/JSON V2 and Base64 V1 files are deliberately not read, imported or migrated; the old `.md` file is left untouched and KNX AI starts a new `.knxctx` context. The 50-session and 512 KB limits still apply.
113
-
114
- Open **Cerebrum → Cerebrum Memory** to inspect the shared `knxai-home-memory.md`. The **JSON** view contains the authoritative editable data, while **Simplified text** presents the same habits, occupant decisions, states, observations, notifications and known home objects as a localized read-only explanation. The browser remembers the selected view. Saving validates JSON; copy follows the current view, while download and restore remain complete backups. **Settings** contains only the strict KNX AI and Cerebrum backup import/export; it includes configuration, chat learning, home memory and schedule files.
115
-
116
- ### ETS object access
117
- ETS object access is the only operational authority. Every address selected in **ETS object access** is active and readable; a selected address is writable unless it is marked **Read only**. No inferred role classification is sent to the chat model or used to authorize a write.
118
-
119
- ## Education-driven proactive home intelligence and bounded memory
120
- From ETS hierarchy, names, roles and DPTs, the node builds a deterministic semantic model for covers, windows, doors, lights, temperature, climate, occupancy and alarms using Italian, English, German, French, Spanish and Chinese terms. Its proactive detector watches only reliably recognized non-command cover/window/door states.
121
-
122
- There is no separate switch or advanced proactive configuration. A candidate is evaluated only when the LLM is enabled and **AI Education** explicitly requests that notification. Education is the sole policy for conditions, open duration, quiet hours and repetition. The AI receives the current duration, local date/time and recent notification history; it decides whether to notify and when to reconsider the same open condition. Without an explicit Education rule, or when the LLM cannot evaluate it, no notification is sent.
123
-
124
- Cerebrum also learns bounded weekday/weekend time patterns from KNX writes and HUE, Matter or Home Assistant state changes. A pattern becomes eligible only after at least eight consistent observations spread across six distinct dates and a minimum 14-day span, with confidence of at least 0.70. Repeated telegrams on the same day cannot accelerate confirmation. If **AI Education** explicitly asks Cerebrum to anticipate learned habits, it may send one suggestion up to 30 minutes before the usual time. The suggestion is never an execution: KNX and Home Assistant actions still require the normal authorization and confirmation path, and the global limit of three proactive messages per hour still applies.
125
-
126
- Cerebrum passively observes bounded, sanitized outputs from useful Node-RED logic, HUE, Matter and Home Assistant event nodes through a runtime hook; no extra monitoring wires are required. Credentials, authorization headers, opaque media and binary payloads are discarded. For live Home Assistant state, add **Cerebrum Home Assistant** and wire `Cerebrum Home Assistant → API (ha-api) → Cerebrum Home Assistant`. Setup Doctor detects the Home Assistant add-on and reports the next missing step.
127
-
128
- The most recent chat session is remembered as the owner and receives spontaneous messages. Output 3 emits a localized message with `msg.knxAi.type = "proactive_notification"`; a synthetic `msg.inputMessage` preserves the session for the chat adapter. A hard safety limit of three proactive messages per hour prevents flooding. The node never emits output 4 or changes KNX autonomously; a subsequent user request still uses the normal validation and confirmation workflow.
129
-
130
- The shared learned reference is loaded at startup from `<userDir>/knxai/memory/knxai-home-memory.md`, rewritten atomically every 15 minutes and always hard-capped at 5 MB. It stores at most 120 significant observations, 80 aggregate habits, 80 notifications and 300 semantic ETS objects—never a raw unlimited telegram stream. Older low-priority entries are removed first.
131
-
132
- **AI Education** is limited to 16,000 characters and is a fixed property saved with the node in the Node-RED flow. Only the user changes it in the editor and applies it with Deploy. The model reads it as authoritative guidance but can never write or overwrite it. Facts and preferences requested in chat belong to learned chat memory, while one-time or recurring plans, reminders, monitoring and future commands belong to the semantic scheduler. The learned-memory file intentionally does not contain the Education text.
133
-
134
- ## Practical configuration example
135
- Put the complete notification policy in **AI Education** (`aiEducation`):
136
-
137
- ```text
138
- Call me Alex and answer in the same language I use.
139
- Keep replies short unless I ask for technical details.
140
- Notify my most recent chat when a cover, window, or door remains open for at least 120 minutes.
141
- Do not notify me between 23:00 and 07:00 and do not repeat the same alert within six hours.
142
- The office cover may remain open during the day: do not notify me about it.
143
- When "living-room light" is ambiguous, ask which light I mean.
144
- Never say that an actuator changed until a KNX status object confirms it.
145
- ```
146
-
147
- With this Education:
148
-
149
- 1. If the living-room cover status remains open for 120 minutes outside the stated quiet hours, output 3 can emit a localized `proactive_notification` to the most recent chat session.
150
- 2. If the office cover remains open, the LLM reads Education and suppresses that candidate notification.
151
- 3. If Alex later asks to close the living-room cover, KNX AI prepares the exact ETS command and still follows normal validation and confirmation before output 4.
152
-
153
- Use descriptive ETS hierarchy/object names and correct status/command roles. Education can personalize decisions and wording, but it cannot authorize an invented group address, change a DPT, or bypass KNX validation.
154
-
155
- ## Quick workflow: KNX control
156
- 1. Import the ETS CSV into the gateway and configure the LLM provider, model, and credentials.
157
- 2. Enable **LLM assistant** and **KNX state reads and actuator control**; leave confirmation enabled.
158
- 3. Connect the chat input to KNX AI while preserving a stable session/chat ID.
159
- 4. Connect output 3 to the chat reply and output 4 to KNX Ultimate in **Universal mode**.
160
- 5. The user sends a request; fresh state requests are read immediately, while writes first show the proposed GA, DPT, and value without writing to the bus.
161
- 6. Within 5 minutes, the same chat replies exactly `CONFIRM` or `CANCEL`.
162
- 7. Only `CONFIRM` revalidates and emits commands on output 4; verify execution through a KNX status GA.
163
-
164
- ## Configuration fields
165
- All fields exposed in the KNX AI editor are listed below.
166
-
167
- ### General
168
- - **Gateway**: KNX Ultimate gateway/config node used as telegram source.
169
- - **Name**: Node label and dashboard header name.
170
- - **Topic**: Base topic used in node outputs.
171
- - **Open KNX AI Web** button: Opens the full KNX AI web dashboard (`/knxUltimateAI/sidebar/page`).
172
-
173
- ### AI Assistant
174
- - **Enable LLM assistant**: Enable Ask/chat assistant features.
175
- - **Provider**: Select the LLM backend (OpenAI-compatible, Anthropic, Ollama or Bionic LM Studio).
176
- - **Endpoint URL**: Chat/completions endpoint URL.
177
- - **API key**: API key (not required for local Ollama; optional for Bionic LM Studio unless server authentication is enabled).
178
- - **Model**: Model ID/name.
179
- - **Reasoning effort**: Provider-agnostic preference for models that expose reasoning-effort control. **Automatic** sends no preference and preserves the model/provider default. Explicit choices are `none`, `minimal`, `low`, `medium`, `high`, `xhigh` and `max`; support depends on the request protocol and model, and KNX AI retries without the preference if it is rejected.
180
- - **Allow the AI to use the Web**: Off by default. Lets the model choose the general Web tool semantically and return verified, cited sources.
181
- - **Maximum Web calls per hour**: Rolling budget shared by conversations and user-created scheduled tasks. Each turn or scheduled run can use at most three operations in total.
182
- - **Telegram voice**: Available only with the **OpenAI-compatible** provider. It automatically reuses that provider's endpoint and API key with the built-in `gpt-4o-mini-transcribe`, `gpt-4o-mini-tts`, and `alloy` defaults; there are no separate voice settings.
183
- - **Chat model compatibility**: The selected model must support the configured Chat Completions endpoint. Legacy completion-only models such as `gpt-3.5-turbo-instruct` are excluded when the model list is refreshed. If the provider rejects a custom temperature or token-limit parameter, KNX AI retries after removing or replacing only that incompatible field.
184
- - **Allow AI to read KNX states and control actuators**: Enables output 4 and is off by default. Every selected ETS object may be read; every selected object not marked **Read only** may be written. Unknown, DPT-mismatched, invalid or excessive operations and writes to read-only objects are rejected locally.
185
- - **Ask for confirmation before sending KNX commands**: Enabled by default. Shows the validated changes first and emits no KNX command until the same chat session confirms them. Whenever commands are awaiting confirmation, the response always appends the exact confirmation/cancellation instructions in the language of the current request. Commands are validated again immediately before output.
186
- - **Input/output message adapter**: Defaults to **No adapter**. Selecting an adapter loads its predefined input/output mapping pair; both mappings remain hidden in the editor.
187
- - **AI Education**: Fixed, authoritative node guidance edited only by the user and applied with Deploy. The model reads it but never writes it. Standing proactive-home policies belong here; facts and preferences requested in chat go to learned memory, while one-time or recurring plans, reminders, monitors and future commands go to the semantic scheduler without trigger phrases or intent routing.
188
- - Packaged help, README, changelog, wiki and example snippets are not included in Telegram, RedBot or custom CHAT prompts. They remain available only to the web Assistant for package-support questions.
189
- - **Refresh** button: Queries the provider and loads available model IDs. Its icon spins while loading; successful completion is intentionally silent.
190
-
191
- ### Ollama quick setup (local)
192
- - Choose **Provider = Ollama**.
193
- - Default endpoint: `http://localhost:11434/api/chat`.
194
- - If no local models are found, use:
195
- - **1) Download model**: opens the **Model library** page.
196
- - **2) Install it**: downloads and installs the model locally (for example `llama3.1`).
197
- - During model refresh/install, KNX AI also tries to auto-start the Ollama server when possible.
198
- - If install fails with connection errors, ensure Ollama is running (desktop app or `ollama serve`).
199
- - The maximum context reported by `/api/show` is used directly as `num_ctx`. KNX AI applies no smaller prompt budget and sends the deduplicated operational prompt without size-based compaction, never beyond the model's declared physical maximum.
200
- - If Node-RED runs in Docker, use `host.docker.internal` instead of `localhost` in the endpoint URL.
201
-
202
- ### Bionic LM Studio quick setup (local)
203
- - Choose **Provider = Bionic LM Studio**.
204
- - Start the LM Studio API server from the **Developer** page or with `lms server start`.
205
- - Default endpoint: `http://localhost:1234/v1/chat/completions`.
206
- - Click **Refresh** to load all models exposed by `/v1/models`; the first model is selected when none is configured.
207
- - When a model is already loaded, KNX AI preserves its active context length. KNX AI never loads an inactive Bionic model through the management API: the first chat request lets Bionic JIT-load it with its saved per-model defaults. Every available prompt context is sent without an application size budget; if it does not fit the active model window, the request fails explicitly.
208
- - An API key is optional unless authentication is enabled in the LM Studio server settings. In Docker, replace `localhost` with `host.docker.internal`.
209
-
210
- ## Security note
211
- If LLM is enabled, KNX traffic context can be sent to the configured endpoint. Use local providers if you need strict on-prem data handling. A command emitted on output 4 passed local validation and was forwarded to the flow; it is not proof that the actuator executed it. Use a KNX status GA when confirmation is required.
1
+ <script type="text/html" data-help-name="knxUltimateAI">
2
+ <p><b>This is a hidden legacy node retained only for existing flows.</b></p>
3
+ <p>For new installations use the standalone <b>Cerebrum Ultimate</b> node from <code>node-red-contrib-cerebrum-ultimate</code>. It replaces this node and uses KNX Ultimate as an optional compatible integration.</p>
4
+ <p><a href="https://github.com/Supergiovane/node-red-contrib-cerebrum-ultimate#readme" target="_blank">Open the Cerebrum Ultimate documentation</a>.</p>
212
5
  </script>
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "knxUltimateAI": {
3
- "title": "KNX AI (Traffic Analyzer)",
3
+ "title": "Legacy AI node — use Cerebrum Ultimate",
4
4
  "sections": {
5
5
  "groupAssistant": "AI assistant",
6
6
  "groupChatHome": "Cerebrum (BETA)",
@@ -35,8 +35,8 @@
35
35
  "webAccessEnabled": "Allow the AI to use the Web",
36
36
  "webMaxCallsPerHour": "Maximum Web calls per hour",
37
37
  "chatAdapterPreset": "Input/output message adapter",
38
- "chatInputCode": "Input mapping (chat → KNX AI)",
39
- "chatOutputCode": "Output mapping (KNX AI → chat)",
38
+ "chatInputCode": "Input mapping (chat → Cerebrum Ultimate)",
39
+ "chatOutputCode": "Output mapping (Cerebrum Ultimate → chat)",
40
40
  "aiEducation": "AI Education (user managed)"
41
41
  },
42
42
  "outputs": {
@@ -110,7 +110,7 @@
110
110
  "lmStudioContextConfigured": "Active model context",
111
111
  "lmStudioContextFailed": "Unable to configure the model context",
112
112
  "lmStudioContextCurrentlyLoaded": "currently loaded",
113
- "etsAccessHint": "Select the group addresses available to KNX AI. Every selected address is active and readable; every selected address not marked Read only is writable. Cloud providers receive the complete selected semantic ETS catalog; local models receive as much as fits their selected context window and can retrieve missing details locally.",
113
+ "etsAccessHint": "Select the group addresses available to Cerebrum Ultimate. Every selected address is active and readable; every selected address not marked Read only is writable. Cloud providers receive the complete selected semantic ETS catalog; local models receive as much as fits their selected context window and can retrieve missing details locally.",
114
114
  "etsFilterPlaceholder": "Filter by name, GA or DPT…",
115
115
  "etsSelected": "selected",
116
116
  "etsReadOnly": "Read only",
@@ -118,7 +118,7 @@
118
118
  "etsNoGateway": "Select a KNX gateway.",
119
119
  "etsNoGa": "No group addresses found. Import the ETS list in the KNX gateway.",
120
120
  "etsCsvError": "Unable to load the group address list from the gateway.",
121
- "reasoningEffortHint": "Optional preference for models that support reasoning effort. Automatic sends no preference; if a provider or model rejects the selected value, KNX AI retries without it.",
121
+ "reasoningEffortHint": "Optional preference for models that support reasoning effort. Automatic sends no preference; if a provider or model rejects the selected value, Cerebrum Ultimate retries without it.",
122
122
  "localContextBudget": "Local context window",
123
123
  "localContextHint": "Sets the maximum context sent to local models only. Maximum uses the selected model's known context window; unavailable sizes are hidden when the model limit is known. Cloud providers ignore this selector and receive the complete selected semantic ETS catalog.",
124
124
  "ollamaNotSupported": "Ollama local mode: API key not required. Default endpoint is http://localhost:11434/api/chat.",
@@ -194,7 +194,7 @@
194
194
  "ask": "Ask"
195
195
  },
196
196
  "empty": {
197
- "noNodes": "No KNX AI nodes found.",
197
+ "noNodes": "No Cerebrum Ultimate nodes found.",
198
198
  "noAnomalies": "No anomalies."
199
199
  },
200
200
  "chat": {
@@ -18,7 +18,7 @@ Use it to:
18
18
  - browse live **lights** detected from boolean-style KNX values
19
19
  - browse live **dimmers** detected from `DPT 5.001` style values
20
20
  - filter items, switch between Viewer nodes and keep the page auto-refreshed
21
- - get a UI visually aligned with **KNX AI**
21
+ - get a UI visually aligned with **Cerebrum Ultimate**
22
22
 
23
23
  The web page is served directly by Node-RED, so it follows the same authentication model used by the editor/admin endpoints.
24
24
 
@@ -1,200 +1,5 @@
1
- <script type="text/markdown" data-help-name="knxUltimateAI">
2
- Este nodo escucha **todos los telegramas KNX** del gateway KNX Ultimate seleccionado, genera estadísticas de tráfico, detecta anomalías y puede consultar opcionalmente un LLM.
3
-
4
- El editor utiliza dos pestañas horizontales: **Asistente IA** contiene configuración, conocimiento/contexto y límites del proveedor; **Conversaciones y hogar** contiene los pines de entrada y salida del chat, hogar proactivo y memoria limitada.
5
-
6
- ## Salidas
7
- 1. **Resumen/Estadísticas** (`msg.payload` JSON)
8
- 2. **Anomalías** (`msg.payload` JSON)
9
- 3. **Asistente IA** (`msg.payload` texto, con `msg.summary`)
10
- 4. **Operaciones KNX** (un mensaje Universal Mode por cada lectura o escritura validada)
11
- 5. **TTS Ultimate** (un mensaje de anuncio por cada texto hablado elegido por el modelo)
12
-
13
- Cada mensaje emitido por las salidas 3 y 4 también contiene una copia del mensaje de entrada original en `msg.inputMessage`. Así, el payload, el topic, los metadatos del chat y cualquier otra propiedad de entrada permanecen disponibles para los nodos posteriores. Los errores de clonación o envío se interceptan y notifican sin propagarse al runtime de Node-RED.
14
-
15
- ### Setup Doctor y primer inicio seguro
16
- El **Setup Doctor** automático comprueba el gateway seleccionado y la importación ETS, la activación de IA, el proveedor, el modelo y la clave API, la conectividad con el proveedor, el cableado del flow, las cámaras detectadas y la conexión TTS Ultimate opcional. Su comprobación previa gratuita del proveedor solo llama al endpoint que enumera los modelos: nunca envía una solicitud de chat ni consume tokens de inferencia. Las cámaras y TTS son opcionales, por lo que no utilizarlos no reduce la preparación básica.
17
-
18
- El inventario muestra el número exacto de señales KNX con dirección de grupo única, las áreas/grupos ETS y una estimación de las funciones lógicas. Deliberadamente no indica un número de dispositivos físicos, porque no puede obtenerse de forma fiable del CSV ETS. Setup Doctor lee el último flow desplegado: despliega cualquier cambio de proveedor, modelo, preajuste, gateway o cableado antes de pulsar **Actualizar** para repetir las comprobaciones.
19
-
20
- Envía `/start` o `/help` desde un chat para recibir en la salida de chat (salida 3) una bienvenida determinista y localizada, con estadísticas personalizadas de la instalación y hasta tres sugerencias seguras. Este onboarding no llama al LLM, no lee ni escribe KNX y no genera TTS. Con el preajuste de Telegram, las sugerencias aparecen como botones del teclado de respuesta y solo se ejecutan cuando el usuario selecciona o envía una de ellas de forma explícita. Tras esa selección explícita, una sugerencia inicial puede realizar lecturas KNX exactas cuando sean necesarias; las escrituras y rutinas KNX, las acciones de cámara, TTS, los cambios de memoria persistente y el aprendizaje de roles GA permanecen bloqueados.
21
-
22
- ### Inteligencia Web
23
- El acceso Web está desactivado de forma predeterminada. Cuando se activa **Permitir que la IA use la Web**, el modelo conversacional decide en cada solicitud actual si necesita información pública actualizada y puede elegir la herramienta Web estructurada sin palabras clave, lógica específica por tema ni clasificadores de intención. Cada turno del usuario o ejecución de una tarea programada creada por el usuario puede realizar como máximo tres operaciones Web en total. Todas las operaciones Web externas reales comparten el presupuesto horario deslizante configurado.
24
-
25
- KNX AI no inicia ningún ciclo fijo de consultas Web en segundo plano. Si un detalle esencial cambiaría sustancialmente la respuesta o la consulta—por ejemplo el tema, el alcance, el lugar, el intervalo temporal o el resultado deseado—el modelo hace una única pregunta concisa y no realiza ninguna operación Web hasta que el usuario responda. Las comprobaciones futuras o recurrentes se crean únicamente a partir de una solicitud explícita en lenguaje natural mediante el planificador.
26
-
27
- Cada respuesta basada en la Web contiene citas validadas por el runtime, con la URL de origen saneada y la hora de consulta, además de la hora de publicación cuando está disponible. El contenido externo son datos no confiables, nunca instrucciones, y no puede sustituir las reglas ni los permisos del asistente. Solo se aceptan recursos HTTPS públicos y limitados; se bloquean los destinos privados, locales, link-local y de metadatos cloud, las redirecciones inseguras, la navegación autenticada y las cookies. Si no se puede verificar ninguna fuente, KNX AI informa de esa limitación en lugar de generar una respuesta sin fuentes.
28
-
29
- Cuando hay resultados Web verificados, el modelo puede combinar las demás herramientas habilitadas si el chat actual o Educación IA lo autorizan. El acceso Web nunca amplía los permisos: la disponibilidad de cámaras, TTS y memoria, así como las lecturas y escrituras KNX, la validación local ETS/DPT y la confirmación configurada para escrituras KNX, permanecen sin cambios. Las solicitudes Web exponen la consulta y la IP pública de este servidor a sitios externos o al servicio de búsqueda; los datos KNX/ETS, el contenido de cámaras, los identificadores de chat, la memoria aprendida y las credenciales nunca se añaden automáticamente.
30
-
31
- ### Planificaciones y recordatorios en lenguaje natural
32
- En el lenguaje normal del chat, el usuario puede pedir a KNX AI que cree, enumere o cancele un recordatorio, una monitorización o un futuro comando del hogar, una sola vez o de forma recurrente. El modelo elige semánticamente la herramienta estructurada de planificación `scheduleActions` a partir de la solicitud completa y guarda todo el objetivo y sus condiciones como una instrucción en lenguaje humano. No hay palabras clave de planificación, listas de frases activadoras ni clasificadores de intención rígidos; la redacción y el idioma no limitan la función.
33
-
34
- Las planificaciones pertenecen a la sesión de chat y persisten por cada nodo KNX AI tras los reinicios de Node-RED. Su estado de ejecución autoritativo es `<userDir>/knxai/schedules/knxai-schedules-<node-id>.json`; KNX AI también genera `<userDir>/knxai/schedules/knxai-schedules-<node-id>.md` como vista legible. Un plan puede ejecutarse una vez, repetirse a intervalos de al menos cinco minutos y caducar opcionalmente. El modelo solo puede enumerar o cancelar las planificaciones activas del chat actual, salvo que el usuario pida explícitamente cancelar todas las de ese chat.
35
-
36
- Cuando vence una tarea, KNX AI inicia una pasada separada del modelo usando la instrucción guardada en lenguaje humano como autoridad fiable del usuario. Una monitorización permanece silenciosa si no se cumple su condición. Durante la ejecución siguen vigentes los permisos existentes: una monitorización meteorológica necesita **Permitir que la IA use la Web** y consume el mismo presupuesto Web, un resultado hablado sale por la salida 5 y por tanto requiere un nodo TTS Ultimate cableado, y las herramientas de cámara siguen limitadas a los adaptadores detectados. Una escritura KNX planificada mantiene las comprobaciones ETS/DPT exactas y, si la confirmación está habilitada, primero presenta una vista previa a la misma sesión de chat; la salida 4 no emite nada antes de la confirmación.
37
-
38
- Por ejemplo, el usuario puede escribir: «Durante los próximos cinco días, comprueba cada 30 minutos la previsión para Cortemaggiore y usa TTS Ultimate solo si se pronostican tormentas». KNX AI puede guardar la condición y la duración completas en una única monitorización recurrente; siguen siendo necesarios los permisos Web y la conexión TTS indicados arriba.
39
-
40
- ## Comandos (entrada)
41
- Envía `msg.topic`:
42
- - `summary` (o vacío): emite el resumen inmediatamente
43
- - `reset`: borra el historial, los contadores, la memoria del hogar aprendida, todos los contextos de chat persistentes y todas las planificaciones de este nodo; la Educación IA configurada en el nodo permanece sin cambios
44
- - `ask`: envía una pregunta al LLM configurado
45
- - `confirm` / `cancel`: confirma o cancela los comandos KNX pendientes sin volver a llamar al LLM
46
- - `clear_chat`: borra los turnos recientes, las instrucciones persistentes y los comandos pendientes de la sesión actual y cancela sus planificaciones activas; las demás sesiones y la Educación IA permanecen sin cambios
47
-
48
- Para `ask`, envía la pregunta en `msg.prompt` (recomendado), `msg.payload` (string), o los campos comunes de Telegram `msg.payload.content` / `msg.payload.text`.
49
-
50
- Si el procesamiento tarda más de 1,2 segundos, la salida 3 emite inmediatamente el mensaje intermedio localizado «Estoy pensando…», con `msg.knxAi.type = "thinking"` y `msg.knxAi.transient = true`. El adaptador de chat lo envía al mismo usuario y la respuesta final llega normalmente en cuanto está lista. Este mensaje de progreso nunca se guarda en el contexto de conversación ni en la memoria aprendida.
51
-
52
- Cada solicitud de chat LLM usa un tiempo de espera mínimo de 30 minutos, independientemente del proveedor. No hay ningún campo de tiempo de espera que gestionar en el editor. Es una espera máxima, no un retraso artificial: los modelos más rápidos siguen terminando en cuanto tienen lista la respuesta. Si también se alcanza este límite, KNX AI indica que el modelo no terminó y recomienda volver a intentarlo o reducir el contexto del prompt.
53
-
54
- KNX AI ya no ofrece un selector de tamaño de contexto en la aplicación. El catálogo ETS seleccionado completo permanece en el nodo y el modelo lo consulta mediante acciones limitadas de retrieval local; solo los objetos recuperados entran en el prompt. La búsqueda cubre direcciones exactas, nombres ETS, alias, jerarquía, áreas, semántica, DPT y etiquetas de valores, con ranking insensible a acentos y tolerante a errores, además de consulta exacta, navegación por áreas y descubrimiento de pares comando/estado. Sin un intervalo explícito, los eventos KNX y de adaptadores cubren los últimos 20 minutos. La ayuda, README, wiki, ejemplos y changelog incluidos nunca se incorporan; cuando sea necesario, el modelo puede consultar la documentación pública de GitHub mediante la herramienta Web. Los datos ETS recuperados, la solicitud actual y las filas del archivo aparecen una sola vez; en el bloque de análisis solo quedan agregados derivados del bus. El código Function completo solo se añade para una solicitud explícita de revisión. KNX AI no reintenta una solicitud demasiado grande compactando el prompt.
55
-
56
- Antes de cada solicitud a un modelo local, KNX AI reserva espacio para la respuesta en la ventana activa de 8K/16K. Limita automáticamente los turnos de conversación más recientes, las filas exactas del archivo, la memoria doméstica aprendida, los resultados Web, las planificaciones, el código Function solicitado, los objetos ETS recuperados y los metadatos de las cámaras. Es una construcción preventiva del prompt, no un reintento después de un error de tamaño, y el catálogo ETS seleccionado completo sigue disponible localmente mediante retrieval.
57
-
58
- ### Acceso a objetos ETS
59
- Esta sección reproduce el selector de direcciones de grupo del perfil MQTT de IoT Bridge. Filtra la lista importada, selecciona todo o nada y aplica solo lectura a las direcciones visibles en bloque o fila por fila. Solo las direcciones seleccionadas están disponibles para el modelo. Todas las direcciones seleccionadas están activas y se pueden leer; las de solo lectura siguen visibles, pero la validación local rechaza todo `GroupValue_Write` hacia ellas. No existe migración ni fallback heredado: tras actualizar, abre cada nodo KNX AI existente, guarda su selección explícita y haz Deploy; hasta entonces, su catálogo de IA estará vacío.
60
-
61
- El estado del nodo en el canvas está reservado deliberadamente para la última solicitud recibida y el mensaje localizado «Estoy pensando…» mientras se ejecuta el LLM. Los telegramas KNX, las actualizaciones del gateway, las tasas de tráfico, los mensajes ready y los resultados técnicos nunca lo sobrescriben; siguen disponibles mediante las salidas, los registros y los datos del Asistente.
62
-
63
- Cada sesión Ask/chat conserva sus últimos 8 turnos y hasta 20 instrucciones a largo plazo elegidas por el modelo, separadas por `msg.knxAi.sessionId`, `msg.sessionId` o el ID de chat Telegram detectado. El modelo decide semánticamente, mediante la herramienta de memoria estructurada, qué significado de una conversación debe recordar u olvidar; no se utiliza ninguna lista de palabras clave ni intents lingüísticos. Todos los nodos KNX AI que usan el mismo almacenamiento comparten este contexto en tiempo real y lo recargan tras reiniciar Node-RED desde `knxultimatestorage/knxai/memory/knxai-chat-context.knxctx`. El archivo se escribe de forma atómica y está limitado a 50 sesiones y 512 KB. Cuando el control KNX está habilitado, conecta la salida 3 al nodo emisor del chat y la salida 4 a un nodo KNX Ultimate en **modo universal**. Con la confirmación activa, la primera respuesta muestra GA, DPT y payload sin emitir escrituras; la misma sesión debe responder `CONFIRMAR` o `CANCELAR` en 5 minutos. Una solicitud nueva sustituye cualquier plan anterior. Cada comando confirmado contiene `msg.destination`, `msg.dpt`, `msg.payload` y `msg.event = "GroupValue_Write"`.
64
- La memoria reciente de la sesión se coloca inmediatamente junto a la solicitud actual para que los modelos locales conserven los datos proporcionados por el usuario, como su nombre preferido o idioma, incluso dentro de un prompt KNX grande. El modelo puede hacer persistentes los datos, preferencias e instrucciones duraderas mediante `memoryActions`; sigue siendo una elección semántica de herramienta, sin clasificadores de frases ni routing por intents. Las credenciales, códigos de seguridad y claves API nunca deben aprenderse.
65
-
66
- Para las escrituras DPT 1.xxx, los equivalentes seguros producidos por la IA `true`/`false`, `1`/`0` y `on`/`off` se normalizan a booleanos reales antes de la validación local y la salida.
67
-
68
- ### Lecturas KNX actualizadas
69
- Cuando el usuario solicita explícitamente un estado actual o actualizado, la IA puede consultar objetos exactos del catálogo ETS importado, incluidos objetos de estado y otros objetos de solo lectura. La salida 4 emite `msg.destination`, `msg.dpt`, `msg.event = "GroupValue_Read"` y `msg.readstatus = true`. El nodo espera hasta 6 segundos cada `GroupValue_Response` o escritura reciente, devuelve los valores decodificados por la salida 3 y expone los detalles en `msg.knxAi.readResults`. Las lecturas nunca requieren confirmación ni se convierten en escrituras. Si un modelo local pequeño omite el tipo de operación y el payload, los objetos ETS exactos se normalizan de forma segura como lecturas; un elemento con payload sigue siendo una escritura validada.
70
-
71
- ### Rutinas conversacionales de varios pasos
72
- Solicitudes como «Me voy», «Buenas noches» o «Modo cine» pueden coordinar una rutina basada en el estado actual sin añadir opciones al editor. En la primera pasada del LLM solo se aceptan lecturas ETS exactas (hasta 20); KNX AI las envía y proporciona los resultados actualizados de GA/DPT/valor a una segunda pasada de planificación aislada. Esta puede preparar hasta 12 escrituras validadas, pero no iniciar otro ciclo de lecturas. Con la confirmación activa, todo el plan requiere una sola confirmación localizada y antes no se emite ninguna escritura ni anuncio TTS solicitado. Tras confirmar, cada escritura se vuelve a validar, se envía en orden y se observa hasta 4 segundos para detectar una respuesta inmediata coincidente en el bus. La respuesta final distingue las respuestas observadas de las operaciones sin respuesta inmediata, sin declarar por ello un fallo del dispositivo. Los detalles están disponibles en `msg.knxAi.routine`, `readResults`, `verifiedCount` y `unverifiedCount`.
73
-
74
- ### Solicitud de confirmación para botones de chat
75
- Mientras un plan está pendiente, la salida 3 contiene `msg.knxAi.confirmationRequest`. El objeto incluye `required`, `status`, `sessionId`, `expiresAt`, `commandCount` y dos elementos en `actions`. Usa `action.label` como texto del botón de Telegram, `action.callbackData` como callback y devuelve `action.message` a KNX AI para confirmar o cancelar sin escribir texto.
76
-
77
- ### Adaptadores de mensajes de entrada/salida
78
- La sección **Pines de entrada y salida del chat** carga sus mapeos seleccionables desde `resources/KNXAIChatAdapterMappings.js`. Al elegir un adaptador se instalan internamente dos mapeos JavaScript síncronos predefinidos: uno antes de que KNX AI procese la entrada y otro antes de emitir por la salida 3. Los mapeos permanecen ocultos en el editor. Los errores de sintaxis y ejecución se capturan y notifican sin detener Node-RED.
79
-
80
- El preajuste incluido **windkh/node-red-contrib-telegrambot** sigue el contrato receiver/sender del paquete. Conecta directamente un `telegram receiver` a KNX AI y la salida 3 a un `telegram sender`. La confirmación usa un teclado de respuesta temporal de Telegram: al pulsar **Confirmar** o **Cancelar** se devuelve un mensaje localizado normal por el mismo receiver, por lo que no hacen falta un `telegram event` ni cableado callback. Los mensajes `callback_query` antiguos siguen siendo compatibles. El mapeo de entrada extrae `msg.payload.content`, `msg.payload.chatId` y el idioma de Telegram. El mapeo de salida crea `msg.payload.chatId`, `type` y `content`, y añade `options.reply_markup` desde `msg.knxAi.confirmationRequest` cuando una escritura espera confirmación. El paquete Telegram sigue siendo una dependencia opcional separada.
81
-
82
- Con este preajuste, los mensajes de voz de Telegram (`msg.payload.type = "voice"`) solo se procesan automáticamente cuando **Provider** está configurado como **OpenAI-compatible**. Antes de descargar nada, KNX AI comprueba el proveedor, reutiliza su **Endpoint URL** y su **API key**, y deriva `/audio/transcriptions` y `/audio/speech` de esa misma conexión. El enlace `msg.payload.weblink`, que contiene el token, se usa solo para la descarga limitada y se elimina antes de que el mensaje llegue a las salidas o al LLM. La entrada OGG/Opus se transcribe con el valor integrado `gpt-4o-mini-transcribe`; una solicitud correcta recibe una respuesta nativa de Telegram en OGG/Opus generada con `gpt-4o-mini-tts` y `alloy`, conservando el texto y el teclado de confirmación. Si se selecciona otro proveedor, el usuario recibe una indicación localizada para elegir OpenAI-compatible o enviar texto. Si la síntesis no está disponible, falla o supera el límite de voz, se envía como alternativa la respuesta completa en texto. El audio descargado y el texto de respuesta se envían al mismo proveedor seleccionado. Los mensajes de texto, las fotos y los mapeos Telegram antiguos guardados siguen siendo compatibles.
83
-
84
- La leyenda de cada respuesta de voz nativa comienza con el aviso localizado **Voz generada por IA**, visible para el destinatario de Telegram.
85
-
86
- El preajuste incluido **RedBot / node-red-contrib-chatbot (Telegram)** sigue el formato común de mensajes de RedBot. Conecta directamente `chatbot-telegram-receive` a KNX AI y la salida 3 a `chatbot-telegram-send`; no hace falta un nodo callback separado porque RedBot convierte los postbacks de los botones inline en mensajes de entrada normales. El texto y los postbacks usan el payload RedBot `message`. Un mensaje de voz nativo de Telegram llega como `type = "audio"` con el `Buffer` OGG/Opus ya descargado por RedBot: KNX AI aplica los límites de tamaño y duración sin volver a descargarlo, lo transcribe con el mismo proveedor OpenAI-compatible descrito arriba y responde con un payload RedBot `audio` nativo, el texto y el aviso localizado de voz generada por IA. Cuando una escritura KNX necesita confirmación, la respuesta se mantiene deliberadamente como payload de texto `inline-buttons`, porque RedBot no puede adjuntar esos botones al mismo mensaje de voz. El mapeo de salida conserva los datos de seguimiento RedBot `originalMessage`, `chat`, `api` y `client`; los mapeos RedBot antiguos guardados también se actualizan en tiempo de ejecución. RedBot sigue siendo una dependencia opcional separada.
87
-
88
- ### Adaptadores de cámara detectados automáticamente
89
- Los paquetes de cámaras instalados pueden publicar en tiempo de ejecución un adaptador para KNX AI. No hay selector ni nodo de cámara que conectar a KNX AI: los adaptadores, controladores y cámaras disponibles se detectan automáticamente y se incorporan al contexto del chat. `node-red-contrib-unifi-ultimate` es el primer proveedor compatible; otros paquetes, como `hikvision-ultimate`, pueden registrarse mediante el mismo contrato independiente del fabricante.
90
-
91
- El usuario puede pedir una captura actual o preguntar al modelo de visión qué se ve. Los preajustes de Telegram y RedBot envían la imagen como foto nativa con pie. También se pueden crear notificaciones persistentes por movimiento, cruce de una línea inteligente o entrada en una zona de intrusión/merodeo, limitadas opcionalmente a personas detectadas y a una línea o zona concreta por nombre. Estas reglas se guardan en el mismo archivo `knxai-chat-context.knxctx` y se restauran después de reiniciar Node-RED. Las suscripciones a eventos UniFi y las solicitudes de captura se realizan directamente a través del proveedor detectado; no interviene la salida 4 de KNX AI ni hace falta cableado intermedio en el flujo.
92
-
93
- Cada evento publicado por un adaptador detectado automáticamente se normaliza y se añade directamente, en el formato nativo compacto por filas de KNX AI, a un archivo diario `YYYY-MM-DD.knxctx` bajo `knxultimatestorage/knxai/adapter-history/<id-nodo>/`. El archivo de telegramas KNX usa el mismo formato compacto, sin serialización JSON intermedia. El archivo conserva 10 días, garantiza más de 24 horas de historial y guarda metadatos, pero no imágenes. Los archivos JSONL existentes no se leen ni se migran. El prompt usa las filas exactas más recientes del intervalo suministrado, limitadas automáticamente a la ventana activa del modelo local.
94
-
95
- ### Anuncios con TTS Ultimate
96
- Conecta la salida 5 a uno o más nodos `ttsultimate` del paquete opcional `node-red-contrib-tts-ultimate`. El cableado normal de Node-RED determina el destino y la distribución; usa Link Out/Link In si el nodo TTS está en otra pestaña del flow. Se han eliminado el selector anterior del nodo TTS y la inyección interna. Las posiciones de las salidas 1–4 no cambian, pero los flows actualizados deben conectar físicamente la salida 5 antes de que los anuncios de voz lleguen a TTS Ultimate.
97
-
98
- El modelo decide si prepara un anuncio razonando sobre la solicitud actual, las instrucciones persistentes del chat y la Educación IA gestionada por el usuario; no existe un intent de anuncio ni una lista de frases activadoras. Los valores KNX, eventos de adaptadores, imágenes y archivos siguen siendo datos y no instrucciones, aunque las indicaciones fiables del usuario pueden enseñar al modelo cómo actuar sobre ellos. La salida 5 emite el texto exacto que se debe pronunciar en `msg.payload`, define `msg.topic = "knx_ai_announcement"` y añade `msg.knxAi.type = "tts_announcement"` junto con `msg.knxAi.sourceNodeId`, `msg.knxAi.sessionId` y `msg.knxAi.reason`. TTS Ultimate gestiona después el reproductor, la voz, el volumen, el aviso inicial y la cola.
99
-
100
- ### Resumen del contexto del chat
101
- El editor del nodo muestra una tarjeta compacta con las fuentes disponibles para el chat: eventos KNX y de adaptadores de los últimos 20 minutos o de un intervalo explícito, catálogo ETS seleccionado completo consultable localmente del que solo se añaden los objetos recuperados a cada prompt, código Function bajo demanda, memoria de sesión y del hogar, Educación IA, planificaciones activas y cámaras detectadas. También muestra el contexto operativo máximo declarado por el modelo y el tamaño UTF-8 real del último prompt del chat; se usan los tokens de entrada exactos cuando el proveedor los informa y, de lo contrario, el recuento se marca como estimado. También enumera las rutas absolutas de los archivos de planificación JSON autoritativo y Markdown legible, junto con los archivos de telegramas KNX y eventos de adaptadores y el patrón diario `YYYY-MM-DD.knxctx`. La Educación IA se guarda en la configuración del nodo y, por tanto, no tiene un archivo de ejecución separado.
102
-
103
- El modelo recibe retrieval local del catálogo ETS, lecturas/escrituras KNX, adaptadores de cámara, anuncios TTS, memoria persistente, acceso Web y planificaciones/recordatorios como herramientas estructuradas. Puede seleccionarlas y combinarlas semánticamente a partir de la solicitud actual y de las indicaciones fiables aprendidas, sin routing por intents lingüísticos. El retrieval del catálogo es determinista y local; el runtime valida argumentos, disponibilidad de adaptadores de cámara y límites de seguridad, mientras las escrituras KNX conservan la validación ETS/DPT local completa y la confirmación configurada.
104
-
105
- El archivo de depuración local temporal `knxai-last-chat-prompt-<id-nodo>.txt` contiene el último texto exacto de los mensajes system/user, se sobrescribe antes de cada llamada de chat y no contiene claves API ni cabeceras HTTP.
106
-
107
- ### Edición y copia del aprendizaje CHAT
108
- La pestaña **Conversaciones y hogar** de la configuración Node-RED de KNX AI incluye el botón **Abrir aprendizaje del chat IA**, que abre la interfaz web Vue directamente en este editor para el nodo actual.
109
-
110
- En la interfaz web Vue, abre **Ajustes → Aprendizaje del chat IA** para ver y editar el archivo compartido exacto `knxai-chat-context.knxctx` y su ruta absoluta. El archivo se puede copiar, descargar como copia de seguridad o restaurar desde otro archivo `.knxctx`. **Reinicializar memoria**, protegido por una confirmación explícita, lo sustituye por un contexto nuevo y vacío y elimina las sesiones, instrucciones, vigilancias de cámara y confirmaciones de chat pendientes en todos los nodos KNX AI que usan el mismo almacenamiento. Los registros nativos separados por tabulaciones `KNXAI_CHAT_CONTEXT 3` son la referencia y se pueden editar directamente: `SESSION` contiene registros `INSTRUCTION`, `TURN` y `CAMERA_WATCH` hasta `END_SESSION`. Al guardar se validan y limitan estos registros, se reescribe el archivo de forma atómica y se actualiza el contexto activo de todos los nodos KNX AI que usan el mismo almacenamiento. Una comprobación de revisión evita sobrescribir o reinicializar aprendizaje modificado después de cargarlo en el editor.
111
-
112
- Solo se admite el formato nativo V3. Los archivos Markdown/JSON V2 y Base64 V1 anteriores no se leen, importan ni migran deliberadamente; el archivo `.md` antiguo se deja intacto y KNX AI inicia un contexto `.knxctx` nuevo. Se mantienen los límites de 50 sesiones y 512 KB.
113
-
114
- ### Acceso a objetos ETS
115
- El acceso a objetos ETS es la única autoridad operativa. Toda dirección seleccionada en **Acceso a objetos ETS** está activa y se puede leer; también se puede escribir salvo que esté marcada como **Solo lectura**. No se envía al modelo de chat ninguna clasificación de rol inferida ni se usa para autorizar una escritura.
116
-
117
- ## Inteligencia doméstica proactiva guiada por Educación y memoria limitada
118
- A partir de la jerarquía ETS, nombres, roles y DPT, el nodo crea un modelo semántico determinista. No existe un interruptor separado ni ajustes proactivos avanzados. Una notificación solo se evalúa si el LLM está activo y **Educación IA** la solicita explícitamente. Educación es la única política para condiciones, duración, horas silenciosas y repetición. Sin una regla explícita, o si el LLM no puede evaluarla, no se envía ningún mensaje.
119
-
120
- La última sesión de chat se recuerda como propietario y recibe los mensajes espontáneos. La salida 3 emite `msg.knxAi.type = "proactive_notification"` y `msg.inputMessage` conserva la sesión para el adaptador de chat. Un límite estricto de tres notificaciones proactivas por hora evita inundar el chat. La salida 4 nunca se usa de forma proactiva y KNX no se modifica de manera autónoma.
121
-
122
- La referencia aprendida compartida se carga al arrancar desde `<userDir>/knxai/memory/knxai-home-memory.md`, se reescribe atómicamente cada 15 minutos y siempre queda estrictamente limitada a 5 MB. Conserva como máximo 120 observaciones importantes, 80 hábitos agregados, 80 notificaciones y 300 objetos ETS semánticos, nunca un flujo ilimitado de telegramas raw. Los elementos antiguos y de menor prioridad se eliminan primero.
123
-
124
- **Educación IA** está limitada a 16.000 caracteres y es una propiedad fija guardada con el nodo en el flow de Node-RED. Solo el usuario la modifica en el editor y la aplica con Deploy. El modelo la lee como una instrucción autoritativa, pero nunca puede escribirla ni sobrescribirla. Los hechos y preferencias solicitados en el chat pertenecen a la memoria aprendida del chat; las planificaciones, recordatorios, monitorizaciones y comandos futuros, únicos o recurrentes, pertenecen al planificador semántico. El archivo de memoria aprendida no contiene intencionadamente el texto de Educación.
125
-
126
- ## Ejemplo práctico de configuración
127
- Escribe toda la política de notificación en **Educación IA** (`aiEducation`):
128
-
129
- ```text
130
- Llámame Alex y responde en el mismo idioma que uso.
131
- Responde brevemente, salvo que pida detalles técnicos.
132
- Avisa a mi último chat si una persiana, ventana o puerta sigue abierta al menos 120 minutos.
133
- No me avises entre las 23:00 y las 07:00 ni repitas la misma alerta antes de seis horas.
134
- La persiana del despacho puede permanecer abierta durante el día: no me avises.
135
- Si «luz del salón» es ambiguo, pregúntame a qué luz me refiero.
136
- Nunca afirmes que un actuador cambió hasta que lo confirme un objeto de estado KNX.
137
- ```
138
-
139
- Con estos ajustes, la salida 3 puede emitir una `proactive_notification` localizada después de 120 minutos para la persiana del salón, mientras que Educación suprime el aviso de la persiana del despacho. Si Alex pide después cerrar la persiana del salón, KNX AI prepara el comando ETS exacto, pero mantiene la validación y confirmación normales antes de la salida 4.
140
-
141
- Usa jerarquías y nombres de objetos ETS descriptivos, con roles de estado/comando correctos. Educación personaliza decisiones y texto, pero no puede inventar una dirección de grupo, cambiar un DPT ni evitar la validación KNX.
142
-
143
- ## Flujo rápido: control KNX
144
- 1. Importa el CSV de ETS en el gateway y configura el proveedor, el modelo y las credenciales LLM.
145
- 2. Activa **Asistente LLM** y **lectura de estados KNX y control de actuadores**; deja activada la confirmación.
146
- 3. Conecta la entrada del chat a KNX AI manteniendo un ID de sesión/chat estable.
147
- 4. Conecta la salida 3 a la respuesta del chat y la salida 4 a KNX Ultimate en **modo universal**.
148
- 5. El usuario envía una solicitud; los estados actuales se leen inmediatamente, mientras que las escrituras muestran primero GA, DPT y valor sin escribir en el bus.
149
- 6. En un plazo de 5 minutos, el mismo chat responde exactamente `CONFIRMAR` o `CANCELAR`.
150
- 7. Solo `CONFIRMAR` vuelve a validar y emite los comandos por la salida 4; verifica la ejecución mediante una GA de estado KNX.
151
-
152
- ## Campos de configuración
153
- Aquí tienes todos los campos tal como se muestran en el editor de KNX AI.
154
-
155
- ### General
156
- - **Gateway**: gateway/config node KNX Ultimate usado como fuente de telegramas.
157
- - **Name**: nombre del nodo y título del dashboard.
158
- - **Topic**: topic base usado en las salidas del nodo.
159
- - Botón **Open KNX AI Web**: abre el dashboard web (`/knxUltimateAI/sidebar/page`).
160
-
161
- ### Asistente IA
162
- - **Enable LLM assistant**: habilita funciones Ask/chat.
163
- - **Provider**: backend LLM (OpenAI-compatible, Anthropic, Ollama o Bionic LM Studio).
164
- - **Endpoint URL**: URL endpoint chat/completions.
165
- - **API key**: clave API (no requerida con Ollama local; opcional para Bionic LM Studio salvo que la autenticación del servidor esté activada).
166
- - **Model**: ID/nombre de modelo.
167
- - **Esfuerzo de razonamiento**: preferencia independiente del proveedor para modelos que permiten controlar el esfuerzo de razonamiento. **Automático** no envía ninguna preferencia y conserva el valor predeterminado del modelo/proveedor. Las opciones explícitas son `none`, `minimal`, `low`, `medium`, `high`, `xhigh` y `max`; la compatibilidad depende del protocolo de solicitud y del modelo, y KNX AI reintenta sin la preferencia si se rechaza.
168
- - **Permitir que la IA use la Web**: desactivado de forma predeterminada. Permite al modelo elegir semánticamente la herramienta Web general y devolver fuentes verificadas y citadas.
169
- - **Máximo de llamadas Web por hora**: presupuesto deslizante compartido por las conversaciones y las tareas programadas creadas por el usuario. Cada turno o ejecución programada puede usar como máximo tres operaciones en total.
170
- - **Voz de Telegram**: disponible únicamente con el proveedor **OpenAI-compatible**. Reutiliza automáticamente su endpoint y clave API con los valores integrados `gpt-4o-mini-transcribe`, `gpt-4o-mini-tts` y `alloy`; no existen ajustes de voz separados.
171
- - **Compatibilidad del modelo de chat**: el modelo seleccionado debe admitir el endpoint Chat Completions configurado. Los modelos antiguos disponibles solo mediante completions, como `gpt-3.5-turbo-instruct`, se excluyen al actualizar la lista. Si el proveedor rechaza un valor personalizado de temperatura o el parámetro de límite de tokens, KNX AI vuelve a intentarlo eliminando o sustituyendo únicamente el campo incompatible.
172
- - **Permitir que la IA lea estados KNX y controle actuadores**: habilita la salida 4 y está desactivado por defecto. Todos los objetos ETS seleccionados se pueden leer; todos los objetos seleccionados que no estén marcados como **Solo lectura** se pueden escribir. Las operaciones desconocidas, con DPT distinto, inválidas o excesivas, y las escrituras hacia objetos de solo lectura, se rechazan localmente.
173
- - **Pedir confirmación antes de enviar comandos KNX**: activado por defecto. Muestra primero los cambios validados y no emite comandos hasta que la misma sesión de chat los confirme. Cuando hay comandos pendientes, la respuesta añade siempre las instrucciones exactas para confirmar o cancelar en el idioma de la solicitud actual. Los comandos se validan de nuevo justo antes de la salida.
174
- - **Adaptador de mensajes de entrada/salida**: usa **Sin adaptador** por defecto. La selección carga el par predefinido de mapeos de entrada y salida; ambos permanecen ocultos en el editor.
175
- - **Educación de la IA**: instrucciones fijas y autoritativas del nodo, modificadas solo por el usuario y aplicadas con Deploy. El modelo las lee, pero nunca las escribe. Aquí se definen las políticas proactivas permanentes del hogar; los hechos y preferencias solicitados en el chat van a la memoria aprendida, mientras que las planificaciones, recordatorios, monitorizaciones y comandos futuros, únicos o recurrentes, van al planificador semántico sin frases activadoras ni routing por intents.
176
- - Los fragmentos incluidos con el paquete procedentes de la ayuda, README, changelog, wiki y ejemplos no se añaden a los prompts de Telegram, RedBot ni CHAT personalizados. Solo permanecen disponibles para el Asistente web en preguntas técnicas sobre el paquete.
177
- - Botón **Refresh**: consulta el provider y carga los modelos disponibles. El icono gira durante la carga; una finalización correcta no muestra ningún mensaje.
178
-
179
- ### Configuración rápida de Ollama (local)
180
- - Selecciona **Provider = Ollama**.
181
- - Endpoint por defecto: `http://localhost:11434/api/chat`.
182
- - Si no hay modelos locales:
183
- - **1) Download model**: abre la página **Model library**.
184
- - **2) Install it**: descarga e instala el modelo localmente (p. ej. `llama3.1`).
185
- - Durante refresh/instalación, KNX AI también intenta iniciar automáticamente el servidor Ollama.
186
- - Si la instalación falla con error de conexión, verifica que Ollama esté ejecutándose (app de escritorio o `ollama serve`).
187
- - El contexto máximo declarado por `/api/show` se usa directamente como `num_ctx`. KNX AI no aplica un presupuesto inferior y envía el prompt operativo sin duplicados ni compactación basada en el tamaño, sin superar nunca el máximo físico declarado por el modelo.
188
- - Si Node-RED se ejecuta en Docker, usa `host.docker.internal` en lugar de `localhost` en el endpoint.
189
-
190
- ### Configuración rápida de Bionic LM Studio (local)
191
- - Selecciona **Provider = Bionic LM Studio**.
192
- - Inicia el servidor API de LM Studio desde la página **Developer** o con `lms server start`.
193
- - Endpoint por defecto: `http://localhost:1234/v1/chat/completions`.
194
- - Pulsa **Refresh** para cargar todos los modelos expuestos por `/v1/models`; si no hay un modelo configurado se selecciona el primero.
195
- - Si un modelo ya está cargado, KNX AI conserva la longitud de contexto activa. KNX AI nunca carga un modelo Bionic inactivo mediante la API de gestión: la primera solicitud de chat permite que Bionic lo cargue mediante JIT con los valores predeterminados guardados para el modelo. Todo el contexto disponible se envía sin presupuesto de aplicación; si no cabe en la ventana activa, la solicitud falla explícitamente.
196
- - La clave API es opcional salvo que la autenticación esté activada en los ajustes del servidor LM Studio. En Docker, sustituye `localhost` por `host.docker.internal`.
197
-
198
- ## Nota de seguridad
199
- Si el LLM está habilitado, el contexto de tráfico KNX puede enviarse al endpoint configurado. Para privacidad on-premise, usa proveedores locales. Un comando emitido por la salida 4 superó la validación local y fue enviado al flow, pero no confirma que el actuador lo ejecutara. Usa una GA de estado KNX para confirmarlo.
1
+ <script type="text/html" data-help-name="knxUltimateAI">
2
+ <p><b>Este es un nodo heredado oculto, conservado únicamente para los flows existentes.</b></p>
3
+ <p>Para instalaciones nuevas, utiliza el nodo independiente <b>Cerebrum Ultimate</b> del paquete <code>node-red-contrib-cerebrum-ultimate</code>. Sustituye a este nodo y utiliza KNX Ultimate como integración compatible opcional.</p>
4
+ <p><a href="https://github.com/Supergiovane/node-red-contrib-cerebrum-ultimate#readme" target="_blank">Abrir la documentación de Cerebrum Ultimate</a>.</p>
200
5
  </script>