# SPDX-FileCopyrightText: Copyright (c) 2025-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ # SIMPLIFIED ALERT AGENT CONFIGURATION # ============================================================================ # This configuration supports the simplified alert processing flow: # JSON Input → Entity Building → VIOS/VST Clip Resolution → VLM Verification → Enhanced JSON Output # Base directory for media used during alert review (optional) # If set, components can resolve relative media paths against this base dir ALERT_REVIEW_MEDIA_BASE_DIR: "" # VST Configuration vst_config: # Base URL for general VST APIs already used elsewhere in the codebase base_url: "http://localhost:30888" sensor_list_endpoint: "/vst/api/v1/sensor/streams" segment_anchor: "end" # enable end-anchored window segment_duration_seconds: 10 # M (already used today) add_overlay: false # Storage service configuration (separate base URL and endpoint) storage: base_url: "http://localhost:30888" # Endpoint to fetch media file path by VST id media_file_path_by_id_endpoint: "/api/v1/storage/file/path" # General Kafka Configuration - Message Processing kafka: bootstrap_servers: "localhost:9092" group_id: 'kafka-incidents-dumper' # Output topic for incidents max_poll_records: 10 # Process one record at a time (immediate processing) auto_offset_reset: 'latest' enable_auto_commit: false poll_timeout: 100 # Kafka consumer poll wait timeout in milliseconds message_type: "Incident" # Protobuf message type: "Behavior" or "Incident" max_poll_interval_ms: 60000 # 60 seconds session_timeout_ms: 10000 # 10 seconds heartbeat_interval_ms: 3000 # 3 seconds # Commit offsets once per poll batch (highest offset per partition) instead # of once per message, removing one commit call per message from the # GIL-bound consume thread. This does NOT make the pipeline at-least-once: # the batch is flushed before any message is dispatched, so in-flight work # is lost on a crash either way. It opens a redelivery window of one poll # batch, entered only when a crash lands inside the poll loop. Enable only # where duplicates within that window are tolerated. batch_commit: false #VLM Configuration vlm: base_url: "http://localhost:30082/v1" model: "nvidia/cosmos3-nano-reasoner" max_tokens: 4096 request_timeout: 5 # VLM Media Source: how to send video to VLM endpoint # false (default) - Pass video URL to VLM (VLM fetches from URL) # true - Download video locally, base64-encode, upload to VLM vlm_media_source_using_base64: false # Response format: auto | cosmos-reason | json | other | (default: auto) # # Case 1 — Auto-detect (default, no change needed): # "auto" detects from model name: cosmos-reason1/2 or cosmos3 → cosmos-reason, else → other. # # Case 2 — Cosmos Reason (explicit): # "cosmos-reason" handles both -tagged and bare verdict formats from any # Cosmos Reason model (CR1, CR2, or CR3). Use when model name doesn't match auto-detect. # "cr1", "cr2", and "cr3" are accepted as aliases. # # Case 3 — JSON output (field names configurable via json_parser): # Set response_format: "json". Prompt must ask VLM to return JSON. # All json_parser fields are optional; defaults shown below. # For nested fields use dot-notation (e.g. "hazard_detection.is_hazardous"). # For non-string verdicts (boolean/integer) add verdict_mapping. # # Case 4 — Custom parser: # 1. Create a Python module that calls register_parser("name", fn) # 2. Set custom_parser_module to its dotted import path # 3. Set response_format to the registered name # Example: # response_format: "xml-verdict" # custom_parser_module: "custom_parsers.xml_verdict_parser" # The module is auto-imported at startup. The parser function must accept # (text: str, json_config: Optional[Dict]) and return a VLMResponse. # response_format: "auto" # custom_parser_module: "custom_parsers.my_parser" # dotted Python module path # Pluggable response parser: external parser class for custom use cases. # When set, it fully replaces the default CR1/CR2 verification parsing. # The class must expose parse(raw_response: str) -> dict; its output is # JSON-stringified into info["vlm_response"] with info["verdict"] = "". # Parser modules live outside the AB repo; AB loads the class at startup. # IMPORTANT: parser classes MUST be thread-safe — Alert Bridge shares one # instance across all worker threads + the async dispatcher. # # Output-schema contract: # * When UNSET (default) — output schema is unchanged; VLM free-form # text lands in info["reasoning"] via the built-in verification path. # * When SET — output schema swaps: parser JSON lands in # info["vlm_response"] instead of info["reasoning"]. This is the only # way to opt into the new field name; deployments that never set this # key see zero wire change. # # response_parser: "my_package.parsers.FireClassifier" # ─ Precedence note ──────────────────────────────────────── # When both `custom_parser_module` and `response_parser` are set, Alert # Bridge emits a startup WARN. `response_parser` always wins on the # default VLM path; `custom_parser_module` is still consulted anywhere # VLMResponse.model_validate_text is called directly. Prefer # `response_parser` for new integrations. # JSON parser config (only used when response_format: "json"). # The prompt must ask the VLM to return JSON with matching field names. # # json_parser: # verdict_field: "prediction_answer" # default; or "hazard_detection.is_hazardous" for nested # reasoning_fields: # first match wins # - "reasoning" # - "thinking" # - "explanation" # - "video_description" # verdict_mapping: # optional; map non-string values to YES/NO # "true": "YES" # "false": "NO" # Media Processing Parameters Toggle # When true: Alert Bridge omits these parameters, letting VLM use its server-side defaults # (e.g., VLM defaults: 4 FPS, larger pixel limits for models like CR2) use_vlm_media_defaults: false # Custom media processing parameters (only used when use_vlm_media_defaults: false) # CR2 recommended: 0.6 (with reasoning/think tags), 0.7 (without reasoning) temperature: 0.6 # do_resize: when true (default) Alert Bridge sends mm_processor_kwargs.size built from # min_pixels/max_pixels. When false, the size kwarg is omitted and the model uses its # server-side default size — useful when the caller-supplied bounds hurt accuracy. # Note: the model's per-frame token cost is much higher without size; long high-resolution # clips can exceed the NIM's 1B-pixel cap and return 400. do_resize: true # Beware that these parameters need to be set in accordance with the VLM max context window min_pixels: 1568 max_pixels: 345600 num_frames: 5 enable_sampling: false sampling_fps: 4 # Warmup tuning — override defaults for slow GPUs or large models # warmup: # poll_timeout: 300 # seconds to wait for NIM readiness # poll_interval: 10 # seconds between readiness polls # inference_timeout: 120 # seconds for first (cold) inference # num_requests: 3 # number of warmup inferences to send # Event Bridge Configuration - Kafka transport (Redis has been removed). event_bridge: sourceType: "kafka" sinkType: "kafka" kafka_source: group_id: 'alert-bridge-vlm-group' topics: incident: 'mdx-incidents' alert: 'mdx-alerts' prompt: prefer_payload_prompt: false override_prompts_on_start: true default_system_prompt: "You are a helpful assistant." # Alert Type Configuration alert_type_config_file: "alert_type_config.json" # Alert Agent Configuration - Processing Settings alert_agent: # Number of independent pipeline processes (positive integer). The GIL is # per-process, so this — not num_workers — is what lets one instance use # more than ~1 core: each process runs its own consume loop, its own event # loop and its own clients. Dedup stays correct without coordination because # mdx-incidents is partitioned by sensorId, so a whole cohort lands on one # process. # # Above 1 the value is validated at startup rather than adjusted: it # requires pipeline_mode: event_loop, and it must not exceed the partitions # on ANY ONE source topic, or startup fails. Per topic, not summed: each # process runs one consumer per topic in the same group, so Kafka assigns # each topic independently and a topic with fewer partitions than there are # processes leaves the difference holding none of it. With N replicas the # constraint is replicas x processes <= partitions, per topic. processes: 1 # The whole of startup -- topic metadata, prompt seeding, VLM warmup and # every pipeline joining its group -- shares this one budget. Raise it where # the default cannot be met: topics created by a Job that races this # deployment, or several processes building their stores at once. startup_timeout_seconds: 60 num_workers: 10 # Number of worker threads max_allowed_stream_size: 2 # Maximum stream size in minutes default_stream_interval: 1 # Default stream interval in minutes vst_pass_through_mode: false # Use local media files instead of VST stream lookup # In-process event filtering / dedup tuning (no external store). event_filters: dedup_ttl_seconds: 300 # Categories listed here retain the incident end timestamp when building # the dedup key. Any category not listed omits the end timestamp. end_time_in_dedup_key_categories: [] # Protect confirmed VLM verdicts from being re-verified (Elasticsearch-backed). protect_confirmed_verdicts: enabled: false # Master switch ttl_seconds: 600 # TTL for confirmed markers (10 minutes) # Cooldown (s) before retrying the verdict-protection ES client after a # construction failure. Fails open + retries; never a permanent disable. es_retry_backoff_seconds: 30 # Retention reaper for expired ``ab-confirmed-verdicts`` markers. retention_interval_seconds: 3600 # hourly delete-by-query pass retention_requests_per_second: 50 # throttle to bound cluster impact # End time delta filter: blocks incidents unless end time changed significantly. end_time_delta_filter: enabled: false threshold_seconds: 5 ttl_seconds: 3600 metrics: # Requires PROMETHEUS_METRICS_ENABLED=true (env var) to have any effect. # On-demand HTTP metrics use the separate alert_bridge_ondemand_* namespace # and are aggregate-only; per_sensor_labels applies to Kafka metrics. # When false (default), the *_BY_SENSOR metric variants are never observed # (zero cardinality cost). When true, each distinct sensor ID mints ~12 # additional Prometheus series per histogram — only enable for deployments # with a bounded sensor fleet and a known series budget (~10k per target). per_sensor_labels: false # OpenTelemetry tracing. The ENABLE_OTEL_MONITORING env var is the on/off # switch; this block is the tuning, mirroring how metrics.per_sensor_labels # above pairs with PROMETHEUS_METRICS_ENABLED. tracing: # Fraction of traces sampled, 0.0-1.0, applied with ParentBased so a sampled # caller keeps its whole trace. This controls export volume and backend # storage cost, not CPU: the sampler decides inside start_span, so an event # whose trace is dropped has already paid for building the attributes. A # measured run put 0.1 within ~1 point of 1.0 on throughput, so reaching for # this key to recover headroom under load will not find any - turn the # feature off instead. sampling_ratio: 0.1 # When false, prompt text, VLM responses and video URLs never reach a span. # Alert data may contain PII, so turning this on is a decision about one # specific environment - which is why it has no env-var shortcut. include_content: false # Applies only when include_content is true; the suffix counts against it. # A second ceiling can apply past this one: where a deployment sets # OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT the SDK cuts at that without leaving the # "+N chars" marker. The compose and Helm surfaces set it to 4096; this file # is a CONFIG_PATH target that neither mounts, so unless the environment # carries it the SDK limit is unlimited here. max_content_chars: 512 # Pipeline execution mode: sync | thread_bridge | event_loop. # An invalid value fails startup. Also accepted at async_io.pipeline_mode. # event_loop runs one coroutine per message on a persistent event loop with # async clients per stage (VLM: AsyncOpenAI, VST: httpx, sink/verdict: # AsyncElasticsearch), so Kafka consumption stays decoupled from VLM latency. # Each mode has exactly one throughput knob: # sync num_workers # thread_bridge async_dispatch_workers # event_loop async_io.max_vlm_concurrent # pipeline_mode: event_loop async_io: external_timeout_seconds: 30 # Timeout for async-submitted VST/Elastic/dedup operations # max_vlm_concurrent MUST stay at or below the benchmarked concurrency # ceiling of the VLM backend (see README "VLM concurrency ceiling # benchmark") — above it, requests pile onto the backend and its latency # balloons instead of throughput improving. # max_vlm_concurrent: 8 # # Derived unless set; the formulas below are the defaults, and each key is # still honoured when present: # async_dispatch_workers = num_workers # async_dispatch_max_in_flight = 2 x async_dispatch_workers # async_io.max_vst_concurrent = async_dispatch_workers # async_io.sink_warn_in_flight = async_dispatch_max_in_flight # URL Transformation - transforms internal IPs to external for VLM/UI access url_transform: enabled: true # Enable URL transformation (default: true) media_download: enabled: false # Enable direct media URL processing max_media_count: 5 # Maximum number of media URLs per request timeout_seconds: 30 # Download timeout per file max_size_mb: 50 # Maximum file size to download allow_private_urls: true # Allow private/local URLs (development only, SSRF risk) use_verdict: false # VLM response mode: true=verdict-based (parse structured response), false=freestyle (store raw response) # Enrichment Processing Configuration enrichment: enabled: false # Master switch for enrichment processing # Always-on VLM alert rules — controls the POST /api/v1/realtime/always-on # endpoint. When false (default), the endpoint short-circuits with # 503 ALWAYS_ON_DISABLED so the feature can be rolled back without a # code change. When true, the rules YAML pointed at by # ALWAYS_ON_RULES_CONFIG is validated at application startup and a # malformed/missing config fails app boot (instead of only surfacing # the error on the first camera event). always_on: false # RTVI VLM Configuration - Real-time VLM alert management # Alert Bridge calls this service to start/stop real-time RTSP analysis rtvi_vlm: base_url: "http://localhost:8018/v1" # RTVI VLM microservice URL (env: RTVI_VLM_BASE_URL) timeout: 10 # HTTP request timeout (seconds) default_model: "nim_nvidia_cosmos3-nano-reasoner_bf16-final" # Default VLM model id (must match what RTVI VLM has loaded — query GET /v1/models to confirm) captions_ack_timeout: 2.0 # Seconds to wait for generate_captions initial HTTP ack # Stream readiness probe: after the captions ack window expires # (streaming mode) the create path polls GET /streams/get-stream-info # every ``stream_readiness_poll_interval`` seconds until either the # stream id appears in the registry (positive readiness signal) or # ``stream_readiness_max_wait`` elapses. The probe is skipped when # the rule reused an already-registered stream — existence was just # confirmed at resolve time. # Total worst-case response latency: captions_ack_timeout + # stream_readiness_max_wait (default ~4 s, down from the previous # 12 s readiness window). Late caption-task failures are still # caught asynchronously via the captions task done callback. stream_readiness_poll_interval: 0.2 stream_readiness_max_wait: 2.0 # ``stream_readiness_timeout`` is deprecated. The realtime service # logs a warning and ignores it — set the two probe knobs above. rules_collection: "alert-realtime-rules" # ES collection name for durable rule storage pending_ttl_seconds: 300 # Stale pending rules older than this are cleaned at startup health_check_interval_seconds: 30 # RTVI /ready poll interval; triggers reconcile on recovery # Rollback switch for the realtime-rules persistence + replay feature. # When false, POST/DELETE on /api/v1/realtime do not write to # Elasticsearch and POST /api/v1/realtime/replay returns 501. # Independent of `persistence.enabled`: the global flag turns the whole # persistence layer (alert configs, prompts, realtime) off, while this # one only disables the realtime-rules path. enable_realtime_persistence: true # Realtime alert consolidation — group repeated VLM positives from the same # camera and alert type into a single event. Controlled per request via the # `consolidate` query param on GET /api/v1/realtime/incidents (omitted/false = # raw chunk-level documents; true = consolidated). The keys below only tune the grouping. consolidation: max_inter_alert_gap_seconds: 60 # a positive arriving after this gap starts a new event max_event_duration_seconds: 300 # cap on a single consolidated event (null = unbounded) representative: "latest" # chunk that supplies the representative fields: latest | longest_reasoning # Webhook Notification — fire-and-forget POST on VLM-verified incidents # When enabled, every successfully verified incident is POSTed to the # configured URL (e.g. OpenClaw). No retry / no queue / no dead-letter. webhook: openclaw: enabled: false # Master switch (default OFF) url: "http://localhost:9090/webhook/alert-notify-slack" # OpenClaw webhook endpoint topic: "mdx-vlm-incidents" # Kafka topic to consume and forward to webhook group_id: "openclaw-webhook-group" # Kafka consumer group (independent from main AB consumer) timeout_seconds: 5 # HTTP POST timeout max_pending: 100 # Max queued deliveries before dropping cors: enabled: true allow_origins: ['*'] allow_methods: ['*'] allow_headers: ['*'] allow_credentials: false elastic: enabled: true hosts: - http://localhost:9200 # Persistence layer — durable storage for configs and prompts persistence: enabled: true backend: "elasticsearch" # Only "elasticsearch" supported for now index_prefix: "ab-" # Indices created as ab-{collection} # DEV/LOCAL ONLY. When persistence.enabled is false, a non-dev deployment # fails readiness. Set this true to explicitly opt a dev/local profile # into the non-durable in-process alert-config store instead. dev_allow_in_memory: false # elasticsearch: # Optional: override hosts (defaults to elastic.hosts above) # hosts: # - http://localhost:9200 vlm_enhanced_sink: incident: type: "elastic" elastic: index: "mdx-vlm-incidents" alert: type: "elastic" elastic: index: "mdx-vlm-alerts" # vlm_enhanced_sink: # type: "kafka" # incident: # kafka: # topic: "mdx-vlm-incidents" # message_type: "incident" # key_field: "id" # alert: # kafka: # topic: "mdx-vlm-alerts" # message_type: "alert" # key_field: "id" # vlm_enhanced_incident_sink: # type: "kafka" # kafka: # topic: "mdx-vlm-incidents" # message_type: "incident" # key_field: "id" logging: level: "DEBUG" # Log level: DEBUG, INFO, WARNING, ERROR, CRITICAL (applies to all components) format: "%(asctime)s - %(threadName)s - %(name)s - %(levelname)s - %(message)s" third_party_level: "WARNING" # Level for urllib3/httpcore/httpx/elasticsearch, etc. truncate_base64: true # Truncate base64 data URLs in logs to prevent long output (env: LOG_TRUNCATE_BASE64)