An agent is not a chatbot with more permissions: it is code that decides with a model
A property manager receives dozens of messages a day: a leaking tap, a late rent payment, a forgotten key. Automating part of this with a language model is reasonable, but the project has two opposite weak points that are best separated at once. The first is the agent: the loop that reads a message, asks the model what to do, runs tools (opening a work order, checking a payment) and reports the result. The second is predictive maintenance, which does not need a language model and does far less harm if you set it up with a simple statistic. This article treats both, with executed listings.
A declaration to avoid misunderstandings: in the first listing the model is simulated.
There was no key or service to call on the test machine, and the point I want to show is not the quality of
a model's answers, but everything the code around the model must do so as not to trust it. The message
format is that of the OpenAI-compatible API, which the OpenRouter documentation also describes: the model
returns an assistant message with tool_calls, and the results come back as messages with the
tool role.
The agent loop: the defences needed around the model
A naive agent loop is written in ten lines: call the model, if it asks for a tool run it, call the model again, until it answers in text. It works in the demo and breaks in production in several ways, which the listing below tackles one by one and which I wanted to see executed before describing them.
// The "model" here is SIMULATED: it returns messages in the form of the OpenAI-compatible API
// (assistant with tool_calls, replies as role "tool"). That way the loop runs without a network.
type ToolCall = { id: string; name: string; arguments: string };
type Messaggio =
| { role: 'user' | 'system'; content: string }
| { role: 'assistant'; content: string | null; tool_calls?: ToolCall[] }
| { role: 'tool'; tool_call_id: string; content: string };
const URGENZE = ['emergenza', 'urgente', 'normale', 'bassa'] as const;
// The tools are our own functions. Each validates its own arguments: the model is not reliable.
const strumenti: Record<string, (a: Record<string, unknown>) => unknown> = {
crea_intervento: (a) => {
if (typeof a.unita !== 'string' || !/^[A-Z]\d{2}$/.test(a.unita)) throw new Error('unita non valida (atteso es. B07)');
if (!URGENZE.includes(a.urgenza as never)) throw new Error(`urgenza non valida: ${String(a.urgenza)}`);
return { intervento: `INT-${a.unita}-001`, urgenza: a.urgenza };
},
passa_a_persona: (a) => ({ ticket: 'ESC-001', motivo: String(a.motivo) }),
};
const MAX_GIRI = 4;
async function gestisci(messaggioUtente: string, modello: (m: Messaggio[]) => Messaggio) {
// Safety rule in the CODE, before the model: it does not depend on the prompt.
if (/\b(gas|fumo|incendio|allagamento)\b/i.test(messaggioUtente)) {
return { esito: 'escalation immediata (regola nel codice)', giri: 0 };
}
const msgs: Messaggio[] = [{ role: 'user', content: messaggioUtente }];
for (let giro = 1; giro <= MAX_GIRI; giro++) {
const r = modello(msgs);
msgs.push(r);
if (r.role !== 'assistant' || !r.tool_calls?.length) {
return { esito: `risposta: ${r.role === 'assistant' ? r.content : ''}`, giri: giro };
}
for (const c of r.tool_calls) {
let out: string;
try {
const args = JSON.parse(c.arguments); // the model can produce broken JSON
const f = strumenti[c.name];
if (!f) throw new Error(`strumento sconosciuto: ${c.name}`);
out = JSON.stringify(f(args));
} catch (e) {
out = JSON.stringify({ errore: (e as Error).message }); // the error goes back to the model, which can correct itself
}
msgs.push({ role: 'tool', tool_call_id: c.id, content: out });
}
}
return { esito: `interrotto dopo ${MAX_GIRI} giri: passa a una persona`, giri: MAX_GIRI };
}
// Three fake models: one correct, one that gets an argument wrong and then corrects itself, one that never stops.
const corretto = (m: Messaggio[]): Messaggio =>
m.length === 1
? { role: 'assistant', content: null, tool_calls: [{ id: 'c1', name: 'crea_intervento', arguments: '{"unita":"B07","urgenza":"normale"}' }] }
: { role: 'assistant', content: 'Ho aperto INT-B07-001, ti contatteremo.' };
const sbaglia = (m: Messaggio[]): Messaggio => {
const ultimo = m[m.length - 1];
if (ultimo.role === 'tool' && ultimo.content.includes('errore')) return corretto([m[0]]);
if (ultimo.role === 'tool') return { role: 'assistant', content: 'Fatto.' };
return { role: 'assistant', content: null, tool_calls: [{ id: 'c1', name: 'crea_intervento', arguments: '{"unita":"B7","urgenza":"alta"}' }] };
};
const nonSmette = (): Messaggio => ({ role: 'assistant', content: null, tool_calls: [{ id: 'cx', name: 'crea_intervento', arguments: '{}' }] });
(async () => {
console.log('1', await gestisci('Il rubinetto di B07 perde', corretto));
console.log('2', await gestisci('Il rubinetto di B07 perde', sbaglia));
console.log('3', await gestisci('Il rubinetto di B07 perde', nonSmette));
console.log('4', await gestisci('Sento odore di gas in cucina', corretto));
})();
// Output:
// 1 { esito: 'risposta: Ho aperto INT-B07-001, ti contatteremo.', giri: 2 }
// 2 { esito: 'risposta: Fatto.', giri: 3 }
// 3 { esito: 'interrotto dopo 4 giri: passa a una persona', giri: 4 }
// 4 { esito: 'escalation immediata (regola nel codice)', giri: 0 }
The first defence is in the crea_intervento function: it validates its own arguments (the unit
must have the form B07, the urgency must be one of the four allowed) and throws an error if
they are not. The model is probabilistic and can invent a value. The second is in the loop's
try/catch block: the error does not stop everything, it goes back to the model as the tool's
result, and the model can correct itself. Scenario 2 shows it: the fake model asks for unit "B7" (and an
urgency "alta" that does not exist), receives the error on the unit, retries with the right values and
finishes in 3 turns. The third is MAX_GIRI: in scenario 3 the model asks for the same tool
forever with empty arguments, and the loop stops after 4 turns and hands the case to a person. Without
that limit the cost would be unbounded.
The fourth defence is the most important, and it is the last line before the loop: if the user's message contains "gas", "fumo" (smoke), "incendio" (fire) or "allagamento" (flooding), the case is escalated without consulting the model (scenario 4, zero turns). The naive version entrusts this rule to the prompt, with a sentence like "for emergencies, escalate immediately". A prompt is an instruction that the model may not follow; a rule in the code cannot be ignored. The list of words in the listing is the idea, not the coverage: in your system it will be much wider, in several languages, and it will still sit alongside the model, never replaced by it.
The fifth defence is not visible in the listing and is a product matter: the user must know they are talking to an automated system. Regulation (EU) 2024/1689 on artificial intelligence, in Article 50, paragraph 1, provides that systems intended to interact directly with natural persons must be designed so that those persons are informed they are interacting with an AI system, unless this is obvious from the context. Who must comply and when the obligation applies should be verified on the text in force and with a lawyer: the regulation in general fixes application from 2 August 2026, but there have been proposals to amend it that I have not verified.
What the listing leaves out: the conversation memory (it must be saved in a database, with an expiry, not in an in-memory map that disappears at restart), the tenant's authentication (the agent must always work for the authenticated user, never for an identifier that the model invents or that the user types) and the logging of every tool call. In the real system the tenant identifier must be passed by the code to the tools, not asked of the model as an argument.
Predictive maintenance: a statistic first, then (if needed) a model
The common story is that a deep learning model "predicts failures". Such a model, however, requires a history of labelled failures for each type of machine, and a building has few. An honest starting point is much humbler: detect when a quantity (the vibration of a pump) departs from its normal behaviour. Exponentially weighted moving average (EWMA) control charts are the classic tool: the NIST Handbook of Statistical Methods describes them as a statistic that gives progressively less weight to data as it gets older.
// Two detectors on a vibration. The series has an isolated spike (minutes 250-252) and, from 400,
// a slow drift (a bearing wearing out). All values are simulated with a fixed seed.
function prng(seed: number) {
let s = seed >>> 0;
return () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 2 ** 32);
}
const rnd = prng(7);
const gauss = () => Math.sqrt(-2 * Math.log(rnd() + 1e-12)) * Math.cos(2 * Math.PI * rnd());
const serie = Array.from({ length: 600 }, (_, t) => {
const picco = t >= 250 && t <= 252 ? 1.0 : 0;
const deriva = t > 400 ? (t - 400) * 0.004 : 0;
return 2.0 + gauss() * 0.15 + picco + deriva;
});
// A) ADAPTIVE baseline: compares each minute with a mean that updates itself.
function adattivo(v: number[], sigma: number): number[] {
let media = v[0];
let varianza = 0.02;
const alpha = 0.02;
const allarmi: number[] = [];
for (let t = 1; t < v.length; t++) {
const scarto = v[t] - media;
if (t >= 100 && scarto > sigma * Math.sqrt(varianza)) { allarmi.push(t); continue; }
media += alpha * scarto;
varianza = (1 - alpha) * (varianza + alpha * scarto * scarto);
}
return allarmi;
}
// B) FROZEN reference: mean and deviation of the first 100 minutes (commissioning),
// then we look at the mean of the last 30 minutes, with the standard error of the mean.
function congelato(v: number[], soglia: number): number[] {
const ref = v.slice(0, 100);
const mu = ref.reduce((a, b) => a + b, 0) / ref.length;
const sd = Math.sqrt(ref.reduce((a, b) => a + (b - mu) ** 2, 0) / ref.length);
const allarmi: number[] = [];
for (let t = 130; t < v.length; t++) {
const m30 = v.slice(t - 29, t + 1).reduce((a, b) => a + b, 0) / 30;
if ((m30 - mu) / (sd / Math.sqrt(30)) > soglia) allarmi.push(t);
}
return allarmi;
}
const riassunto = (nome: string, a: number[]) => {
const sulPicco = a.some((t) => t >= 250 && t <= 252);
const prima = a.filter((t) => t <= 400 && !(t >= 250 && t <= 252)).length;
const deriva = a.find((t) => t > 400);
console.log(`${nome}: picco visto=${sulPicco}, falsi allarmi=${prima}, primo allarme sulla deriva=${deriva ?? 'mai'}`);
};
riassunto('adattivo 4 sigma ', adattivo(serie, 4));
riassunto('congelato soglia 5', congelato(serie, 5));
// Output:
// adattivo 4 sigma : picco visto=true, falsi allarmi=0, primo allarme sulla deriva=mai
// congelato soglia 5: picco visto=false, falsi allarmi=0, primo allarme sulla deriva=447
The simulated series has two events. An isolated three-minute spike (250-252), like a shock or a transient, and from minute 400 a slow drift of 0.004 units per minute, like a wearing bearing. The adaptive detector (A) compares each minute with a mean that updates itself: it sees the spike, gives no false alarms, and never sees the drift, because its baseline chases it. The frozen-reference detector (B) fixes mean and deviation on the first 100 minutes, those of commissioning, and looks at the mean of the last 30: it does not see the spike, which dilutes over 30 minutes, but flags the drift at minute 447, 47 minutes after it begins.
The lesson is that the two detectors respond to different failures and that the choice of what to look at matters more than the choice of model. The NIST document on CUSUM charts says in the same vein that cumulative charts are more efficient than Shewhart charts at detecting small shifts in the mean (2 sigma or less), which is the case of wear. The numbers in the listing (447, zero false alarms) depend on the seed, on the noise I chose and on the threshold; they do not tell you how much advance warning you will have on your plant. To know that you need the real history of a failure on an identical machine, and until then it is best to declare the alarm as "to be checked", not as "failure predicted in N days": that number of days, in some examples found online, is computed from a formula with no foundation, and I do not report it.
Why there are no savings tables here
Around the web you find tables of hours and costs saved, and percentages of downtime reduction attributed to commercial products. I did not find a primary source that supports them, so I do not report them: the saving from an automation is measured on your portfolio, with a reference period and a test period under the same conditions, it is not taken from a table. Dynamic rental pricing is not covered in this article because it touches local contractual and regulatory constraints that deserve an analysis of their own; the estimate of a property's value is in the article on automated valuation.
Where the rest of the series connects
The machine readings come from the gateway described in the article on smart building IoT, and they arrive with duplicates and delays, as the real-time pipeline explains. When the agent must take a decision that concerns a person (denying a service, starting a procedure), the cautions of the article on privacy and compliance apply. The IFC object identifier that ties a machine to its room is explained in the article on BIM. Where the same readings are stored to compute their statistics, with the gaps flagged, is shown by the article on sensor time series in PostgreSQL.
What you can do now
You can write the loop of an agent that does not trust the model: it validates the arguments, returns the errors for correction, has a turn limit and applies the safety rules in the code. You know why an adaptive detector can hide slow wear and how a frozen reference uncovers it, and you have seen the difference in numbers on a series declared simulated. What remains to be done with a real model is to measure its errors on your messages, and with a real machine to build the failure history that does not exist today.
In this series, the next article is Geospatial Search & Location Services with PostGIS.
Sources
- OpenRouter, Tool & Function Calling - the format of tool_calls and of messages with the tool role, and the requirement to send the list of tools with every request, accessed on 2026-11-12
- Regulation (EU) 2024/1689 on artificial intelligence, Article 50(1) and Article 113 - the obligation to inform people interacting with an AI system and the general date of application, accessed on 2026-11-12
- NIST/SEMATECH e-Handbook of Statistical Methods, 6.3.2.4 EWMA Control Charts - the definition of the exponentially weighted moving average, accessed on 2026-11-12
- NIST/SEMATECH e-Handbook of Statistical Methods, 6.3.2.3 CUSUM Control Charts - the efficiency of cumulative charts for small shifts in the mean, accessed on 2026-11-12
The two listings were run with Node 24 on 2026-11-12. The language model in the first listing is simulated and the data of the second is generated with a fixed seed: no figure describes a real plant or service.

Commenti
Caricamento commenti...
Sign in to comment