> ## Documentation Index
> Fetch the complete documentation index at: https://docs.videodb.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Alerts and Callbacks

> Wire events to delivery channels for real-time notifications

Alerts connect events to delivery channels. Choose WebSocket for real-time dashboards or webhooks for server-to-server notifications.

## Quick Example

<CodeGroup>
  ```python Python theme={null}
  # Create alert with webhook delivery
  alert_id = scene_index.create_alert(
      event_id=event_id,
      callback_url="https://your-backend.com/alerts"
  )

  # Or with WebSocket delivery
  ws = conn.connect_websocket()
  await ws.connect()

  alert_id = scene_index.create_alert(
      event_id=event_id,
      ws_connection_id=ws.connection_id
  )
  ```

  ```javascript Node.js theme={null}
  // Create alert with webhook delivery
  const alertId = await sceneIndex.createAlert(
      eventId,
      "https://your-backend.com/alerts"
  );

  // Or with WebSocket delivery
  const ws = conn.connectWebsocket();
  await ws.connect();

  const alertId = await sceneIndex.createAlert(
      eventId,
      null,  // no webhook
      ws.connectionId
  );
  ```
</CodeGroup>

***

## Delivery Methods

| Method    | Latency   | Use Case                     |
| :-------- | :-------- | :--------------------------- |
| WebSocket | Real-time | Dashboards, live UI updates  |
| Webhook   | Under 1s  | Server-to-server, automation |

You can use both simultaneously for redundancy.

***

## Webhook Delivery

### Create Webhook Alert

<CodeGroup>
  ```python Python theme={null}
  alert_id = scene_index.create_alert(
      event_id=event_id,
      callback_url="https://your-backend.com/webhooks/alerts"
  )
  ```

  ```javascript Node.js theme={null}
  const alertId = await sceneIndex.createAlert(
      eventId,
      "https://your-backend.com/webhooks/alerts"
  );
  ```
</CodeGroup>

### Webhook Payload

When an event triggers, you receive a POST request:

```json theme={null}
{
  "event_id": "event-3fd4174feceb6162",
  "label": "traffic_violation",
  "confidence": 0.95,
  "explanation": "A red sedan ran through the intersection while the light was red",
  "timestamp": "2024-01-15T10:30:45Z",
  "start_time": 1234.5,
  "end_time": 1238.0,
  "stream_url": "https://stream.videodb.io/v3/...",
  "player_url": "https://console.videodb.io/player?url=..."
}
```

### Payload Fields

| Field         | Type   | Description                                   |
| :------------ | :----- | :-------------------------------------------- |
| `event_id`    | string | ID of the triggered event                     |
| `label`       | string | Human-readable event label                    |
| `confidence`  | float  | Detection confidence (0-1)                    |
| `explanation` | string | AI-generated description of what was detected |
| `timestamp`   | string | ISO 8601 timestamp                            |
| `start_time`  | float  | Video timestamp where event starts (seconds)  |
| `end_time`    | float  | Video timestamp where event ends (seconds)    |
| `stream_url`  | string | HLS stream URL for the clip                   |
| `player_url`  | string | Web player URL                                |

***

## WebSocket Delivery

### Connect and Listen

<CodeGroup>
  ```python Python theme={null}
  ws = conn.connect_websocket()
  await ws.connect()

  # Pass connection ID when creating alerts
  alert_id = scene_index.create_alert(
      event_id=event_id,
      ws_connection_id=ws.connection_id
  )

  # Listen for events
  async for event in ws.stream():
      if event.get("channel") == "alert":
          print(f"Alert: {event['data']['label']}")
          print(f"Confidence: {event['data']['confidence']}")
  ```

  ```javascript Node.js theme={null}
  const ws = conn.connectWebsocket();
  await ws.connect();

  // Pass connection ID when creating alerts
  const alertId = await sceneIndex.createAlert(
      eventId,
      null,
      ws.connectionId
  );

  // Listen for events
  for await (const event of ws.stream()) {
      if (event.channel === "alert") {
          console.log(`Alert: ${event.data.label}`);
          console.log(`Confidence: ${event.data.confidence}`);
      }
  }
  ```
</CodeGroup>

### WebSocket Channels

| Channel       | Source               | Content             |
| :------------ | :------------------- | :------------------ |
| `alert`       | Event triggers       | Alert notifications |
| `transcript`  | `start_transcript()` | Real-time speech    |
| `scene_index` | `index_visuals()`    | Visual analysis     |
| `audio_index` | `index_audio()`      | Audio analysis      |

***

## Managing Alerts

### List Alerts

<CodeGroup>
  ```python Python theme={null}
  alerts = scene_index.list_alerts()
  for alert in alerts:
      print(f"{alert.id}: {alert.event_id} - {alert.status}")
  ```

  ```javascript Node.js theme={null}
  const alerts = await sceneIndex.listAlerts();
  for (const alert of alerts) {
      console.log(`${alert.id}: ${alert.eventId} - ${alert.status}`);
  }
  ```
</CodeGroup>

### Enable/Disable Alerts

<CodeGroup>
  ```python Python theme={null}
  # Temporarily disable
  scene_index.disable_alert(alert_id)

  # Re-enable
  scene_index.enable_alert(alert_id)
  ```

  ```javascript Node.js theme={null}
  // Temporarily disable
  await sceneIndex.disableAlert(alertId);

  // Re-enable
  await sceneIndex.enableAlert(alertId);
  ```
</CodeGroup>

### Delete Alert

<CodeGroup>
  ```python Python theme={null}
  scene_index.delete_alert(alert_id)
  ```

  ```javascript Node.js theme={null}
  await sceneIndex.deleteAlert(alertId);
  ```
</CodeGroup>

***

## Dual Delivery Pattern

Use both channels for critical alerts:

<CodeGroup>
  ```python Python theme={null}
  # WebSocket for real-time UI
  ws = conn.connect_websocket()
  await ws.connect()

  # Create alert with both delivery methods
  alert_id = scene_index.create_alert(
      event_id=event_id,
      callback_url="https://your-backend.com/alerts",  # webhook
      ws_connection_id=ws.connection_id  # websocket
  )
  ```

  ```javascript Node.js theme={null}
  // WebSocket for real-time UI
  const ws = conn.connectWebsocket();
  await ws.connect();

  // Create alert with both delivery methods
  const alertId = await sceneIndex.createAlert(
      eventId,
      "https://your-backend.com/alerts",  // webhook
      ws.connectionId  // websocket
  );
  ```
</CodeGroup>

**Benefits:**

* WebSocket delivers instantly to connected clients
* Webhook provides reliable server-side processing
* If WebSocket disconnects, webhook still works

***

## Latency Profile

| Event Type         | Typical Latency |
| :----------------- | :-------------- |
| Alert trigger      | Under 1s        |
| Transcript event   | 1-2s            |
| Visual index event | 2-5s            |
| Audio index event  | 2-5s            |

***

## Delivery Guarantees

| Method    | Guarantee     | Notes                                   |
| :-------- | :------------ | :-------------------------------------- |
| WebSocket | At-most-once  | May miss events if disconnected         |
| Webhook   | At-least-once | May receive duplicates; use idempotency |

***

## Next Steps

<CardGroup cols={2}>
  <Card icon="webhook" title="Webhooks and Reliability" href="/pages/act/live-action/webhooks-and-reliability">
    Handle webhooks at scale with idempotency
  </Card>

  <Card icon="image" title="Event Detection Patterns" href="/pages/act/live-action/event-detection-patterns">
    Create effective detection rules
  </Card>
</CardGroup>
