The KAGAMI mark КАГАМИ
kagami.bg/academy · lesson · machine-readable viewUPDATED 2026-10-03
IDENTITY
module
GX10-04-144 · Triage of alarm-system events with rules and a local model
series
GX10 (local AI server class: NVIDIA GB10, e.g. ASUS Ascent GX10 / DGX Spark)
level
Advanced
duration
2–3 h
prerequisites
A GB10-class machine with DGX OS, Ollama with the mistral model, PostgreSQL 14+, Python 3.10+, packages fastapi, uvicorn, asyncpg, httpx, pydantic v2; events from a monitoring system or invented test events
trust_label
UPDATED 2026-10-03 (rewritten against public Ajax Systems pages, Ollama docs and library page, FastAPI and PostgreSQL docs as of 2026-10-03) · NOT TESTED (no GB10 machine and no Ajax equipment or account; only rules.py was run, with the Python standard library; the other files were syntax-checked only)
versions
mistral 7B v0.3 (4.4 GB, 32K context, per ollama.com) · PostgreSQL 14+ (current: 18) · Python 3.10+ · packages not pinned (use current releases, then pin)
language
human view: en · bulgarian edition: /academy/gx10/ (same file name)
previous / next
GX10 series index / 04-145_Multi_Site_Security_Dashboard.html
PURPOSE

Build a small local service that ranks alarm events by priority for a human operator. Events arrive in a neutral own format from monitoring software (or as invented test events). Deterministic rules set the lowest allowed priority, a local model (Ollama, mistral) suggests a priority and a short reason under a JSON schema, and the final priority is the higher of the two; if the model fails, the final priority is at least MEDIUM. Everything is stored with the rule floor, the model suggestion and the final value for audit. A human operator decides and acknowledges; nothing is dispatched automatically. Ajax is mentioned only as a trademark of Ajax Systems to name the kind of system; the Enterprise API is not public and is not reproduced.

KEY CONCEPTS
COMMANDS / PATHS
CHECKLIST
NEXT MODULE

04-145 · A live multi-site dashboard (04-145_Multi_Site_Security_Dashboard.html) · series index: kagami.bg/en/academy/gx10/ · offer: Quick experiment (kagami.bg/stalbata/)

SOURCES
TAGS
gx10nvidia-gb10alarm-systemstriageollamastructured-outputfastapipostgresqln8nhuman-in-the-loop
UPDATED · 03.10.2026

Ajax Alarm Events and a Local AI: Event Triage

An alarm system such as Ajax produces many events and most of them are routine. We build a small helper on a local AI server: rules guard the floor, the model suggests a priority and a human decides. Nothing is sent and nobody is called automatically.

⏱ 2–3 h Advanced GX10 Ollama · FastAPI · PostgreSQL · n8n
Ollama (the mistral model)🔒 local FastAPI · PostgreSQL · n8n🔒 local Ajax Cloud and Ajax apps🌐 global
🔄
UPDATED · 03.10.2026 — what changed
The lesson was rewritten from the public documentation. The old version described a public REST address in the Ajax cloud for registering a webhook, with an API key and an HMAC signature. We could not find it in the manufacturer's public documentation: according to Ajax (03.10.2026) the Enterprise API is for large security and service companies, access is on request and the technical documents are given after the request. So we removed all such addresses, headers and signatures, as well as automatic calls, SMS messages to customers and notifying the police (a human takes those decisions), the claims about numbers of hubs, events per minute and milliseconds (never measured here), the old model tag (now mistral, checked on ollama.com) and the outdated n8n export. We added: the public ways for events to leave the system, our own neutral event format, rules that set the lowest priority (the model can only raise it), a model answer constrained by a schema, behaviour when the model fails, an audit table and a way to measure how often it is wrong.
⚠️
What we have not run ourselves
We had no GB10-class machine at hand, nor Ajax equipment or an Ajax account. We ran only rules.py (plain Python, no extra packages) with invented values. The other files were checked for syntax errors but were not run — which is why there is neither a "TESTED" nor a "VERIFIED" label. The table of event codes follows the common Contact ID style and was not checked against an Ajax document ⚠️. The quality of mistral in Bulgarian and the speed of the machine were not measured.

01What you'll learn

02Before you start

💡
About the brand
Ajax is a trademark of Ajax Systems. This lesson is not affiliated with the company or endorsed by it; the name is used only to say which kind of system we mean.
⚖️
Data, responsibility and the legal side
Alarm events show when and where there was movement and who came and went. Linked to people, they are personal data, and processing them (legal basis, information, retention, access, rights of the people concerned) falls under the GDPR and national law. Recommendation: before you run a system with real sites, check with a lawyer and write down the decisions. This lesson is technical and is not legal advice. This helper only gives hints to an operator: it is not a certified safety system and must not be the only protection.

03Steps

  1. Where the events come from

    Our layer does not talk to the hub directly. It sits after the monitoring software and receives the events from it. That way we do not depend on undocumented addresses and we change nothing in the alarm system itself. Ajax's public information (03.10.2026) shows these routes:

    RouteWhat it is (per Ajax)Protocols and notes
    Ajax PRO Desktopan app for monitoring and handling alarmsalarms are handled inside the app
    Ajax Translator PRO / Translatortranslates events for the station softwareSIA DC-09, Contact ID (SurGard), Manitou, MASXML and others — see Ajax's table
    Ajax Cloud Signalingevents go through the Ajax cloud, with no server of your own at the stationSIA DC-09, SurGard (Contact ID), Manitou, MASXML and others
    Direct connectionTCP/IP or a serial portSIA DC-09 (SIA-DCS)
    Enterprise APIan interface for large companies with thousands of systemsaccess on request; the documentation is provided after the request — we do not reproduce it here

    The practical way: if your monitoring software (or Ajax PRO Desktop) can forward or export events — over HTTP, into a file or through n8n — feed them to the service from step 6. If you have access to the Enterprise API, Ajax gives you the documentation and it overrides this lesson. If you have neither, carry on with invented events: everything below works that way.

  2. An event in your own neutral format

    Whatever the source, you reduce the event to a small set of fields. That way the service does not change when you change the software.

    FieldWhat it isExample (invented)
    site_refyour own internal site numbersite-001
    event_codethe event code from the monitoring software130
    qualifierE — new event, R — restore (Contact ID style)E
    zonezone or roomnorth entrance
    device_typedevice typemotion detector
    occurred_atwhen it happened (time with zone)2026-10-03T02:30:00+03:00
    sourcewhere it came fromtest
    ✅
    No names in the event
    Use only an internal site number. A customer name, an address or a person in the event is not needed and increases the risk.
  3. The tables

    We keep separately what the rules say (rule_floor), what the model suggested (model_pri) and the final priority (priority). That way you can always explain why a decision was made.

    sql · schema.sql
    -- Needs PostgreSQL 14 or newer
    CREATE TABLE sites (
        site_ref   TEXT PRIMARY KEY,           -- your own neutral id, e.g. 'site-001'
        tz         TEXT NOT NULL DEFAULT 'Europe/Sofia',
        open_time  TIME NOT NULL DEFAULT '08:00',
        close_time TIME NOT NULL DEFAULT '20:00'
    );
    
    CREATE TABLE alarm_events (
        id          BIGSERIAL PRIMARY KEY,
        received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        occurred_at TIMESTAMPTZ NOT NULL,
        site_ref    TEXT NOT NULL,
        source      TEXT NOT NULL,             -- 'cms-export' | 'enterprise-api' | 'test'
        event_code  TEXT NOT NULL,             -- e.g. a Contact ID style code: '130'
        qualifier   TEXT,                      -- 'E' new event, 'R' restore
        zone        TEXT,
        device_type TEXT,
        rule_floor  TEXT NOT NULL,             -- lowest priority the rules allow
        model_pri   TEXT,                      -- what the model suggested (NULL if it failed)
        priority    TEXT NOT NULL,             -- final = the higher of the two
        ai_reason   TEXT,
        status      TEXT NOT NULL DEFAULT 'new',   -- new | acknowledged | closed
        handled_by  TEXT,
        handled_at  TIMESTAMPTZ
    );
    CREATE INDEX ON alarm_events (site_ref, received_at DESC);
    CREATE INDEX ON alarm_events (status, received_at DESC);

    Events are not deleted by the system on their own; you decide the retention period with your lawyer.

  4. The rules — the floor

    We run simple rules first. They answer the question "how low can this priority go?". Why before the model: a model can be wrong or fail; a rule cannot. An unknown code is never ignored, and an event outside business hours is raised by one level (except the periodic test).

    CodeMeaningLowest
    110 · 120fire · panicCRITICAL
    130 · 137 · 140burglary · tamper · general alarmHIGH
    301 · 302 · 350 · 381mains loss · low system battery · communication trouble · lost radio deviceMEDIUM
    384 · 401 · 602device low battery · open/close by a user · periodic testLOW
    anything elseunknown codeMEDIUM
    python · rules.py
    from datetime import datetime, time
    from zoneinfo import ZoneInfo
    
    ORDER = ["LOW", "MEDIUM", "HIGH", "CRITICAL"]
    
    # Lowest priority per event code. Codes follow the common Contact ID style;
    # use the codes your monitoring software really sends.
    FLOOR = {
        "110": "CRITICAL",  # fire
        "120": "CRITICAL",  # panic
        "130": "HIGH",      # burglary alarm
        "137": "HIGH",      # tamper
        "140": "HIGH",      # general alarm
        "301": "MEDIUM",    # mains power loss
        "302": "MEDIUM",    # low system battery
        "350": "MEDIUM",    # communication trouble
        "381": "MEDIUM",    # loss of supervision (radio device)
        "384": "LOW",       # radio device, low battery
        "401": "LOW",       # open/close by user
        "602": "LOW",       # periodic test report
    }
    UNKNOWN_FLOOR = "MEDIUM"   # an unknown code is never ignored
    
    
    def floor_for(code: str) -> str:
        return FLOOR.get(code, UNKNOWN_FLOOR)
    
    
    def at_least(a: str, b: str) -> str:
        """Return the higher of two priorities."""
        return a if ORDER.index(a) >= ORDER.index(b) else b
    
    
    def bump(level: str) -> str:
        return ORDER[min(ORDER.index(level) + 1, len(ORDER) - 1)]
    
    
    def outside_hours(when: datetime, tz: str, opens: time, closes: time) -> bool:
        local = when.astimezone(ZoneInfo(tz)).time()
        return not (opens <= local <= closes)
    ⚠️
    The codes are not checked against Ajax
    The table follows the common Contact ID style. What exactly your hub sends and by which route, see in the Translator manual or in your monitoring software, and fix FLOOR.
  5. The model suggests

    We pull the model and call it through the Ollama API. We ask for an answer that follows a schema: the format parameter accepts a JSON schema, so the priority is always one of the four values. Temperature 0 makes the answers more repeatable (it does not guarantee identical ones).

    bash
    ollama pull mistral
    python · triage.py
    import json
    import os
    
    import httpx
    
    from rules import ORDER
    
    OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://localhost:11434")
    MODEL = os.environ.get("TRIAGE_MODEL", "mistral")
    
    SCHEMA = {
        "type": "object",
        "properties": {
            "priority": {"type": "string", "enum": ORDER},
            "reason": {"type": "string"},
            "false_alarm_likelihood": {"type": "string", "enum": ["low", "medium", "high"]},
        },
        "required": ["priority", "reason", "false_alarm_likelihood"],
    }
    
    SYSTEM = (
        "You help a human operator triage events from a monitored alarm system. "
        "You only suggest a priority; a human decides what to do. "
        "Priorities: LOW (routine), MEDIUM (needs a look), HIGH (likely real, act soon), "
        "CRITICAL (act now). Use the context. If unsure, choose the higher priority. "
        "Reply with JSON only."
    )
    
    
    async def ask_model(ctx: dict, lang: str = "Bulgarian"):
        """Return a dict with priority/reason, or None if the model is unavailable or answers badly."""
        user = (
            f"Event context:\n{json.dumps(ctx, ensure_ascii=False)}\n"
            f"Write the reason in {lang}, at most 25 words."
        )
        payload = {
            "model": MODEL,
            "stream": False,
            "format": SCHEMA,
            "options": {"temperature": 0, "num_predict": 200},
            "messages": [
                {"role": "system", "content": SYSTEM},
                {"role": "user", "content": user},
            ],
        }
        try:
            async with httpx.AsyncClient(timeout=60) as client:
                r = await client.post(f"{OLLAMA_URL}/api/chat", json=payload)
                r.raise_for_status()
                out = json.loads(r.json()["message"]["content"])
            if out.get("priority") not in ORDER:
                return None
            return out
        except Exception:
            return None

    If the model does not answer, or answers in a way that cannot be read, ask_model returns None and the final priority is at least MEDIUM. The instructions are in English, and the reason is asked for in the operator's language. How mistral copes with Bulgarian we did not measure — try it on your own examples (step 10).

  6. The service

    A small FastAPI service puts it all together: it takes an event, computes the floor, asks the model, takes the higher value and stores it. It listens only on 127.0.0.1; the key is long and random. Startup and shutdown of the resources are in lifespan — the way the FastAPI documentation recommends.

    python · app.py
    import hmac
    import os
    from contextlib import asynccontextmanager
    from datetime import datetime, time, timezone
    from typing import Optional
    
    import asyncpg
    from fastapi import FastAPI, Header, HTTPException
    from pydantic import BaseModel, Field
    
    from rules import at_least, bump, floor_for, outside_hours
    from triage import ask_model
    
    DB_DSN = os.environ["DB_DSN"]      # postgresql://<user>:<password>@localhost/alarms
    API_KEY = os.environ["API_KEY"]    # a long random string
    
    
    @asynccontextmanager
    async def lifespan(app: FastAPI):
        app.state.pool = await asyncpg.create_pool(DB_DSN, min_size=1, max_size=5)
        yield
        await app.state.pool.close()
    
    
    app = FastAPI(title="Alarm triage", lifespan=lifespan)
    
    
    def check_key(key: Optional[str]) -> None:
        if not key or not hmac.compare_digest(key, API_KEY):
            raise HTTPException(status_code=401, detail="bad key")
    
    
    class EventIn(BaseModel):
        site_ref: str = Field(min_length=1, max_length=64)
        event_code: str = Field(min_length=1, max_length=8)
        qualifier: Optional[str] = Field(default=None, max_length=1)
        zone: Optional[str] = Field(default=None, max_length=64)
        device_type: Optional[str] = Field(default=None, max_length=64)
        source: str = Field(default="test", max_length=32)
        occurred_at: Optional[datetime] = None
    
    
    class AckIn(BaseModel):
        operator: str = Field(min_length=1, max_length=64)
    
    
    @app.post("/events")
    async def add_event(ev: EventIn, x_api_key: Optional[str] = Header(default=None)):
        check_key(x_api_key)
        when = ev.occurred_at or datetime.now(timezone.utc)
        if when.tzinfo is None:
            when = when.replace(tzinfo=timezone.utc)
    
        async with app.state.pool.acquire() as con:
            site = await con.fetchrow(
                "SELECT tz, open_time, close_time FROM sites WHERE site_ref = $1", ev.site_ref)
            recent = await con.fetchval(
                "SELECT count(*) FROM alarm_events "
                "WHERE site_ref = $1 AND received_at > now() - interval '15 minutes'", ev.site_ref)
    
            tz = site["tz"] if site else "Europe/Sofia"
            opens = site["open_time"] if site else time(8, 0)
            closes = site["close_time"] if site else time(20, 0)
    
            # 1) rules first: they set the lowest allowed priority
            floor = floor_for(ev.event_code)
            after_hours = outside_hours(when, tz, opens, closes)
            if after_hours and ev.event_code != "602":      # 602 = routine test report
                floor = bump(floor)
    
            # 2) the model may only raise the priority, never lower it
            ctx = {
                "event_code": ev.event_code, "qualifier": ev.qualifier,
                "zone": ev.zone, "device_type": ev.device_type,
                "outside_business_hours": after_hours,
                "events_from_this_site_last_15_min": recent,
            }
            ai = await ask_model(ctx)
            model_pri = ai["priority"] if ai else None
            final = at_least(floor, model_pri) if model_pri else at_least(floor, "MEDIUM")
    
            row_id = await con.fetchval(
                "INSERT INTO alarm_events (occurred_at, site_ref, source, event_code, qualifier, "
                "zone, device_type, rule_floor, model_pri, priority, ai_reason) "
                "VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING id",
                when, ev.site_ref, ev.source, ev.event_code, ev.qualifier, ev.zone,
                ev.device_type, floor, model_pri, final, ai["reason"] if ai else None)
    
        return {"id": row_id, "priority": final, "rule_floor": floor,
                "model_priority": model_pri, "reason": ai["reason"] if ai else None,
                "model_available": ai is not None}
    
    
    @app.get("/events/open")
    async def open_events(x_api_key: Optional[str] = Header(default=None)):
        check_key(x_api_key)
        async with app.state.pool.acquire() as con:
            rows = await con.fetch(
                "SELECT id, received_at, site_ref, event_code, priority, ai_reason "
                "FROM alarm_events WHERE status = 'new' "
                "ORDER BY CASE priority WHEN 'CRITICAL' THEN 1 WHEN 'HIGH' THEN 2 "
                "WHEN 'MEDIUM' THEN 3 ELSE 4 END, received_at DESC LIMIT 100")
        return [dict(r) for r in rows]
    
    
    @app.post("/events/{event_id}/ack")
    async def ack(event_id: int, body: AckIn, x_api_key: Optional[str] = Header(default=None)):
        check_key(x_api_key)
        async with app.state.pool.acquire() as con:
            n = await con.execute(
                "UPDATE alarm_events SET status='acknowledged', handled_by=$2, handled_at=now() "
                "WHERE id=$1 AND status='new'", event_id, body.operator)
        if n != "UPDATE 1":
            raise HTTPException(status_code=404, detail="not found or already handled")
        return {"ok": True}
    bash
    python3 -m venv .venv && . .venv/bin/activate
    pip install fastapi "uvicorn[standard]" asyncpg httpx pydantic
    psql "postgresql://<user>:<password>@localhost/alarms" -f schema.sql
    export DB_DSN="postgresql://<user>:<password>@localhost/alarms"
    export API_KEY="$(openssl rand -hex 32)"
    uvicorn app:app --host 127.0.0.1 --port 8001

    First create an empty database alarms and a user in your usual way. Replace the placeholders in angle brackets with your own values.

  7. Try it with invented events

    From the same terminal send four invented events: a burglary alarm, a low battery, a periodic test and an unknown code.

    bash
    for body in \
      '{"site_ref":"site-001","event_code":"130","zone":"north entrance","device_type":"motion detector"}' \
      '{"site_ref":"site-001","event_code":"384","device_type":"door sensor"}' \
      '{"site_ref":"site-002","event_code":"602"}' \
      '{"site_ref":"site-002","event_code":"999"}'
    do
      curl -s -X POST http://127.0.0.1:8001/events \
        -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" -d "$body"
      echo
    done

    For each event you expect JSON with priority, rule_floor, model_priority, reason and model_available. The priority is never below rule_floor. Stop Ollama and repeat: model_available becomes false and the priority does not fall below MEDIUM. What exactly the model will suggest we do not promise — we have not run it.

  8. n8n: notifying a human

    n8n takes no decisions; it only carries the message to the human. The workflow:

    1. a Webhook node (or a schedule) receives an event from your source;
    2. an HTTP Request node sends it with POST to /events, with the key as a credential (not in the text of the workflow);
    3. an If node: if priority is HIGH or CRITICAL, continue;
    4. a message to the duty operator (email or chat) that starts with the word "SUGGESTION" and contains the priority, the reason and the event number.

    If n8n runs in a container (lesson 04-01), localhost is the container itself: put the service in the same Compose network and use its name. The operator confirms with POST /events/{id}/ack.

  9. The human decides

    WhoWhat it does
    Rulesset the lowest priority; they do not get confused or tired
    Modelsuggests a priority and a short reason; it may only raise it
    Humandecides whether to call, send a patrol or alert an authority
    ✅
    What we do not do
    We do not automatically call the police, a guard or a customer, and we do not close an event without a human. The model gives a recommendation; the action has a real effect and so a human approves it.
  10. How often it is wrong

    Do not trust a feeling. Measure.

    1. Collect 30–50 of your own past events (no names) and feed them to the service.
    2. Have two people independently say what the correct priority was.
    3. Count the most important thing: how many times the final priority was lower than the correct one. Those are the misses — and they cost the most.
    4. Repeat after every change of model, rules or prompt; do not trust a single number.
  11. Security — the minimum

    • The key is long and random, not in Git, and in n8n it sits as a credential.
    • The service listens only on 127.0.0.1; if you need access from outside, put it behind a reverse proxy with HTTPS.
    • There are no names, addresses or frames in the events — only internal numbers.
    • You back up the database and keep the retention period agreed with the lawyer.
    • The rules and the model are under version control: you know what was running on the day of the event.

04Check

Quiz

1. Why do the rules come before the model?

2. What happens if Ollama is down?

3. Where is the Enterprise API documentation?

4. Who decides whether to call a guard or the police?

05What's next

06Sources

  1. Ajax: connecting the intrusion alarm to monitoring software — routes, protocols, Translator, Cloud Signaling, direct connection.
  2. Ajax: Enterprise API — who it is for and how access is requested.
  3. Ajax: system integrations — which integrations are publicly described.
  4. Ollama: mistral — size, context, version 0.3 🔒 local.
  5. Ollama: chat API — the format parameter (JSON or schema) and options 🔒 local.
  6. FastAPI: lifespan — startup and shutdown of resources.
  7. PostgreSQL: documentation — the current version, 18.