# Analytics & Observability

Workspace-level analytics, call management, recording access, and a review queue for quality assurance.

{% @mermaid/diagram content="%%{init: {"flowchart": {"useMaxWidth": true, "nodeSpacing": 20, "rankSpacing": 30}, "theme": "base", "themeVariables": {"primaryColor": "#D4E2E7", "primaryTextColor": "#100F0F", "primaryBorderColor": "#083241", "lineColor": "#575452", "textColor": "#100F0F", "clusterBkg": "#F1EAE7", "clusterBorder": "#D7D2D0"}}}%%
flowchart LR
subgraph Sources
C\[Calls & Recordings]
P\[Pipeline Events]
T\[Tool Executions]
end
subgraph Processing
CI\[Call Intelligence]
A\[Aggregation Engine]
end
subgraph Outputs
D\[Dashboards]
API\[Analytics API]
SS\[Event Stream SSE]
end

```
C --> CI --> A
P --> A
T --> A
A --> D
A --> API
A --> SS

style C fill:#D4E2E7,stroke:#083241,color:#100F0F,stroke-width:2px
style P fill:#D4E2E7,stroke:#083241,color:#100F0F,stroke-width:2px
style T fill:#D4E2E7,stroke:#083241,color:#100F0F,stroke-width:2px
style CI fill:#F0DDD9,stroke:#AA412A,color:#100F0F,stroke-width:2px
style A fill:#F0DDD9,stroke:#AA412A,color:#100F0F,stroke-width:2px
style D fill:#DDE3DB,stroke:#2c3827,color:#100F0F,stroke-width:2px
style API fill:#DDE3DB,stroke:#2c3827,color:#100F0F,stroke-width:2px
style SS fill:#DDE3DB,stroke:#2c3827,color:#100F0F,stroke-width:2px" %}
```

## Analytics

* **Usage summary**: Event counts by type with daily breakdown
* **Call statistics**: Volume and duration metrics
* **Event breakdown**: Distribution by type and source
* **Data quality**: Confidence distribution and review pipeline stats

## Call Intelligence

Per-call intelligence summaries are computed from in-memory session state at call end and persisted for analytics use. Each record includes a composite quality score (0-100), emotion summary, risk assessment, latency metrics, conversation shape, tool performance, safety matches, and operator data. See [Voice Agent - Call Intelligence Persistence](https://docs.amigo.ai/developer-guide/platform-api/voice-agent#call-intelligence-persistence) for field details and scoring rules.

### Call Intelligence Analytics (6 Endpoints)

Six endpoints under `/v1/{workspace_id}/analytics/` aggregate call intelligence data for dashboard visualizations.

**Common parameters** (all endpoints):

| Parameter    | Type               | Default | Description                          |
| ------------ | ------------------ | ------- | ------------------------------------ |
| `days`       | integer (1-90)     | 30      | Lookback window if no explicit dates |
| `date_from`  | date               | -       | Start of range (inclusive)           |
| `date_to`    | date               | -       | End of range (inclusive)             |
| `interval`   | `1h` / `1d` / `1w` | `1d`    | Time bucket for trend data           |
| `service_id` | string             | -       | Filter to a specific service         |

**Endpoints:**

| Endpoint                              | Response Shape                                                                                                                                                                                          |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /analytics/call-quality`         | `summary` (avg/p50/p95 quality, total calls, escalation rate, avg duration) + `trend` (per-bucket avg quality, call count, escalation count) + `quality_distribution` (excellent/good/fair/poor counts) |
| `GET /analytics/emotion-trends`       | `emotion_distribution` (emotion name + count, sorted by frequency) + `trend` (per-bucket call count, avg valence, avg arousal)                                                                          |
| `GET /analytics/safety-trends`        | `summary` (escalation count/rate, total safety matches, avg risk) + `trend` (per-bucket escalations, safety matches) + `risk_distribution` (low/medium/high/critical counts)                            |
| `GET /analytics/latency`              | `summary` (per-component p50/p95/p99) + `trend` (per-bucket component percentiles)                                                                                                                      |
| `GET /analytics/tool-performance`     | `summary` (total calls, overall failure rate) + `tools` (per-tool invocations, failures, failure rate, avg ms) + `trend` (per-bucket tool calls, failure rate)                                          |
| `GET /analytics/operator-performance` | `summary` (escalation count/rate, avg connect time, avg quality for escalated vs non-escalated) + `trend` (per-bucket escalation counts)                                                                |

All endpoints require `viewer+` permissions and are workspace-scoped. Quality distribution tiers: excellent (90-100), good (70-89), fair (50-69), poor (0-49). Risk levels: low (<0.3), medium (0.3-0.6), high (0.6-0.8), critical (>0.8).

## Calls & Recordings

* **Call listing**: Filter by date, status, and duration. Each call includes quality score and final state from call intelligence. Supports `continuation_token` for cursor-based pagination alongside `offset`.
* **Call detail**: Full call detail with turns, timeline, and playback data (proxied from the voice agent for rich conversation reconstruction)
* **Call intelligence**: Per-call intelligence profile with emotion trajectory, risk timeline, latency waterfall, and tool performance
* **Active call intelligence**: Live intelligence overlay for all active calls (current emotion, risk score, turn count, escalation status)
* **Phone volume**: Call volume per phone number over a time window
* **Recordings**: Time-limited signed URLs for audio playback, plus recording metadata

## Review Queue

A quality assurance pipeline for reviewing conversation events, transcript corrections, and flagged items. Reviewers can approve, correct, or reject items. Dashboard and statistics endpoints provide aggregate views.

## Pipeline Health

Nine read-only endpoints under `/v1/{workspace_id}/pipeline/` provide real-time connector runner observability for the pipeline dashboard:

* **Pipeline status** - Overall health (`healthy`/`degraded`/`starting`/`unavailable`), active polls, total events/entities, per-source status, all loop states
* **Source listing** - Each data source with live health, last poll info, and event counts
* **Source history** - Event ingestion bucketed by hour or day for a specific source
* **Source events** - Paginated event stream per source with sorting
* **Outbound summary** - Per-sink sync status: synced/failed/pending counts
* **Outbound log** - Paginated sync log per outbound sink
* **Entity resolution** - Total merges, recent merge activity, resolution loop status
* **Review metrics** - Queue depth, pending by priority, approval/rejection counts (7d), average review time
* **Throughput** - Event throughput time series across all sources

Degrades gracefully when the connector runner is unavailable - database-backed metrics remain visible. See [Connector Runner - Pipeline Observability](https://docs.amigo.ai/developer-guide/platform-api/connector-runner#pipeline-observability) for full endpoint reference.

## Command Center

`GET /v1/{workspace_id}/command-center` - Single-pane workspace health dashboard.

Aggregates metrics from five domains concurrently, each failing independently:

| Section        | Response Model         | Key Fields                                                                                                                                               |
| -------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `voice`        | `VoiceMetrics`         | `active_calls`, `active_escalated`, `calls_today`, `avg_quality_score_today`, `escalation_rate_today`                                                    |
| `pipeline`     | `PipelineMetrics`      | `sources_total`, `sources_healthy`, `sources_degraded`, `sources_failing`, `events_last_hour`, `outbound_pending`, `outbound_failed`, `connector_status` |
| `data_quality` | `DataQualityMetrics`   | `pending_reviews`, `approval_rate_7d`, `avg_confidence`, `entities_total`, `entities_merged_7d`                                                          |
| `identity`     | `IdentityMetrics`      | `active_api_keys`, `active_sessions`, `failed_auths_1h`, `locked_accounts`, `mfa_coverage_pct`                                                           |
| `alerts`       | `CommandCenterAlert[]` | `level` (warning/critical), `code`, `message`, `section`                                                                                                 |

Additional response fields: `degraded_sections` (list of section names that failed to load), `generated_at`, `cached`.

**Caching**: Cached with 15s TTL. **Alerts**: Derived from 7 threshold checks on the aggregated metrics. **Permissions**: `viewer+`.

## Percentile Analytics

**`GET /analytics/calls/advanced`** - Percentile-based call metrics.

| Parameter               | Type               | Default | Description                       |
| ----------------------- | ------------------ | ------- | --------------------------------- |
| `days`                  | integer (1-90)     | 30      | Lookback window                   |
| `date_from` / `date_to` | date               | -       | Explicit date range               |
| `interval`              | `1h` / `1d` / `1w` | `1d`    | Time bucket                       |
| `service_id`            | string             | -       | Filter by service                 |
| `direction`             | string             | -       | Filter by `inbound` or `outbound` |

Returns: `summary` (p50/p95/p99 for duration + quality), `trend` (per-bucket with p95 latency), `by_service` breakdown, `by_direction` breakdown.

**`GET /analytics/calls/comparison`** - Period-over-period comparison.

| Parameter                       | Type   | Required | Description       |
| ------------------------------- | ------ | -------- | ----------------- |
| `current_from` / `current_to`   | date   | Yes      | Current period    |
| `previous_from` / `previous_to` | date   | Yes      | Previous period   |
| `service_id`                    | string | No       | Filter by service |

Returns: `current` metrics, `previous` metrics, `delta` (absolute + percentage change for each KPI).

## Entity Intelligence

Five endpoints under `/v1/{workspace_id}/world/`:

**`GET /world/entities/{entity_id}/graph`** - One-level relationship graph.

Returns `center` (entity metadata) + `edges[]` (edge type, confidence) + `neighbors[]` (entity metadata for connected nodes). 404 if entity not found.

**`GET /world/entities/{entity_id}/provenance`** - Data provenance and confidence history.

Returns `sources[]` (contributing data sources), `confidence_history[]` (score over time), `merge_history[]` (entity resolution events). 404 if entity not found.

**`GET /world/entities/{entity_id}/lineage`** - Full data lineage.

Composes provenance with outbound sync sinks and review queue history. Returns `provenance` (sources, confidence, merges), `outbound_sinks` (sync destinations and status), `review_history` (review queue items and verdicts). 404 if entity not found.

**`GET /world/entities/duplicates`** - Suspected duplicate entities.

| Parameter        | Type        | Default | Description              |
| ---------------- | ----------- | ------- | ------------------------ |
| `entity_type`    | string      | -       | Filter by entity type    |
| `confidence_max` | float (0-1) | 1.0     | Max confidence threshold |

Returns same\_as edges sorted by ascending confidence (lowest = most uncertain).

**`GET /world/search`** - Enhanced entity search.

| Parameter        | Type            | Default  | Description                          |
| ---------------- | --------------- | -------- | ------------------------------------ |
| `q`              | string          | Required | Search text (ILIKE on display\_name) |
| `entity_type`    | string          | -        | Filter by entity type                |
| `source`         | string          | -        | Filter by event source               |
| `confidence_min` | float (0-1)     | -        | Min confidence threshold             |
| `limit`          | integer (1-100) | 20       | Page size                            |
| `offset`         | integer         | 0        | Pagination offset                    |

Returns `results[]` + `total` count.

## World Sync Events

**`GET /world/sync`** - Paginated outbound sync events filtered by status.

| Parameter            | Type            | Default | Description                                                              |
| -------------------- | --------------- | ------- | ------------------------------------------------------------------------ |
| `status`             | string          | -       | Filter by sync status (`pending`, `failed`)                              |
| `data_source_id`     | string          | -       | Filter to a specific outbound data source                                |
| `source_system`      | string          | -       | Filter to a specific source system                                       |
| `fhir_resource_type` | string          | -       | Filter to a specific FHIR resource type (e.g., `Patient`, `Appointment`) |
| `fhir_resource_id`   | string          | -       | Filter to a specific FHIR resource ID                                    |
| `limit`              | integer (1-200) | 50      | Page size                                                                |
| `offset`             | integer         | 0       | Pagination offset                                                        |

Returns sync events with entity display names. Use `status=pending` for the pending events table or `status=failed` for the retry table.

## Real-Time Event Stream

`GET /v1/{workspace_id}/events/stream` - Server-Sent Events for real-time workspace updates.

Subscribes to the workspace event channel and streams events as they occur:

| Event Type                | When It Fires                 |
| ------------------------- | ----------------------------- |
| `call.started`            | New call begins               |
| `call.ended`              | Call completes                |
| `call.escalated`          | Operator escalation triggered |
| `pipeline.sync_completed` | Data source poll finished     |
| `pipeline.error`          | Pipeline error detected       |
| `review.submitted`        | Review queue item processed   |
| `alert`                   | Alert threshold crossed       |

**Protocol details:**

* Media type: `text/event-stream`
* Heartbeat: Comment every 30s to keep connection alive
* Reconnection: Send `Last-Event-ID` header on reconnect for replay of recent events
* Backpressure: Oldest events dropped when the event buffer is full
* Falls back to error event if the event system is unavailable

**Permissions**: `viewer+`.

## Tasks

Track asynchronous task state (e.g., skill executions, sync jobs) by task ID or call session.

## API Reference

* [Analytics](https://docs.amigo.ai/api-reference/readme/platform/analytics)
* [Calls](https://docs.amigo.ai/api-reference/readme/platform/calls)
* [Recordings](https://docs.amigo.ai/api-reference/readme/platform/recordings)
* [Review Queue](https://docs.amigo.ai/api-reference/readme/platform/review-queue)
* [Command Center](https://docs.amigo.ai/api-reference/readme/platform/command-center)
* [Entity Intelligence](https://docs.amigo.ai/api-reference/readme/platform/entity-intelligence)
* [Event Stream](https://docs.amigo.ai/api-reference/readme/platform/event-stream)
