Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2b4c519
productstats: keys under lk.product.agents, with the runtime, runner …
theomonnom Nov 25, 2026
5e992d5
productstats: count every model's requests, usage and latency
theomonnom Nov 25, 2026
90d3b4a
productstats: count sessions at their end and voice sessions at their…
theomonnom Nov 25, 2026
3f7ec7f
Merge remote-tracking branch 'origin/v2.0' into theo/productstats-list
theomonnom Nov 25, 2026
5291ab9
productstats: count the sessions that used each feature
theomonnom Nov 25, 2026
dec9833
productstats: test each feature and the exact documented key set, doc…
theomonnom Nov 25, 2026
f357b15
productstats: mark an MCP toolset on its class, without importing the…
theomonnom Nov 25, 2026
206629f
productstats: one process singleton, the exporter in lk-agents-net
theomonnom Nov 26, 2026
af368be
productstats: Rust knows an MCP toolset by its lifecycle, nested and …
theomonnom Nov 26, 2026
dc4b592
productstats: a script or a test installs telemetry with no runner co…
theomonnom Nov 26, 2026
328bb58
productstats: recorded like observability and exported as a third des…
theomonnom Nov 26, 2026
72718df
productstats: tests observe a tracer of their own, the destination's …
theomonnom Nov 26, 2026
4938570
telemetry: one measure for both products, routed by the metric's decl…
theomonnom Nov 26, 2026
a7a6780
telemetry: a declaration's audience, name and module must agree at co…
theomonnom Nov 26, 2026
0a42d46
telemetry: doctests and an expansion test prove the compile-time audi…
theomonnom Nov 26, 2026
708282b
productstats: background audio counts each player started, with or wi…
theomonnom Nov 27, 2026
f12735e
cli: the runner command is parsed with the arguments and passed to th…
theomonnom Nov 27, 2026
14cadd3
productstats: a model switch names the kinds it went from and to
theomonnom Nov 27, 2026
6796fbf
wip: features as one-line measures
theomonnom Nov 28, 2026
1a7a743
productstats: each feature is one measure where it is used
theomonnom Nov 28, 2026
3d33959
productstats: a model declares its plugin, and its statistics copy it…
theomonnom Nov 28, 2026
339d632
docs: a model's identity names its plugin; product statistics copy it
theomonnom Nov 28, 2026
5d5701d
productstats: the plugin id is read from the host in HostInvoker's file
theomonnom Nov 28, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/internals/telemetry-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,13 @@ The worker's own instruments are not a job's: the worker process holds their cur
| `lk.agents.worker.idle_processes_target` | gauge | `{process}` | each change of the process pool |
| `lk.agents.worker.process_ready.duration` | histogram | s | each job process that became ready |

### Product statistics

Exported only to LiveKit Cloud's product statistics collector, never to a customer's
destination. Keys, values and definitions: [telemetry.md](../telemetry.md#what-is-collected).
The generated registry (`rust/otel/registry`) lists them under `lk.product.agents.*`;
`the_declared_keys_are_exactly_the_documented_list` fails on a stray or missing key.

### Report records

| Scope | Body | Timestamp | Attributes |
Expand Down
81 changes: 70 additions & 11 deletions docs/internals/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,58 @@ the usage ledger. `lk_agents_net::export` aggregates measurements per destinatio
exports them on a fixed interval with delta temporality to Cloud and the
temporality the user endpoint requests (cumulative by default).

### Product statistics

LiveKit's own statistics, never customer data; the list is
[telemetry.md](../telemetry.md#what-is-collected). They are laid out like observability:

- Declared in `abi::productstats` (`models`, `sessions`, `features`, `runner`), every key under
`lk.product.agents.`, with `audience = ProductStats`.
- Recorded through the one recording API: `measure(cx, &metric, value)` in async code and
`Trace::measure(&metric, value)` in a sans-I/O machine take a metric of either audience. The
metric's declared audience chooses the record (`Record::Measurement` or
`Record::ProductStat`); no argument does. The one emitter machines and async code
share (`ModelUsage::measure`) takes either as a `Measure`.
- Exported by `lk_agents_net::export::otlp`, as the exporter's third destination
(`otlp/product_stats.rs`): see [Destinations](#destinations).
- Models: `ModelId::of(kind, &ProviderId)` copies the four labels from the identity the model
declares, parsing and mapping nothing. `ProviderId.plugin` is filled once per host by its
base classes (Python: `_bindings.plugin_id`, from the class's package) and by a Rust-native
provider itself; a LiveKit Inference model keeps `provider`/`model` as customer metrics and
usage name them (`livekit`, `deepgram/nova-3:en`) and declares the vendor and model it runs
in `upstream_provider`/`upstream_model`, which `ModelId` prefers. Requests, tokens,
characters, audio and first-output times are recorded where the request's span ends
(`lk-agents-inference/src/telemetry.rs`, `stt/retrying.rs`); what only a session knows (the
audio its STT reported, a realtime response, the transcription delay, its own start) in
`lk-agents-voice/src/agent_session/product_stats.rs`.
- Sessions: one line where a call ends (`count_session_end`, when the voice machine's spans
close) and one where a text request ends (`runtime/src/a2a/mod.rs::run_message`).
- Features: each is one `measure` where the feature is used, counting uses. Nothing is carried,
summarised or deduplicated. The sites: a handoff landing and a model switch in the voice
machine (`handoff.rs`, `product_stats.rs`), a language change where the recogniser's
`last_language` moves, `update_options`/`override_options` at the session owner, an MCP
toolset's lifecycle setup, a background audio player's start, a local agent called as a tool
(`delegation/local` `run`, and a text session's child invocation start) and a `RemoteAgent`
call (`delegation/remote` `run`).
- Model switch: the voice machine keeps the model installed in each slot (STT, TTS, LLM,
realtime), the fact a switch is told from. An empty slot, the same identity, or an adapter
over an adapter (`adapter` on the model's ref: its own label differs from its identity's) is
no switch.
- Tests record under a tracer of their own (`testkit::Recorded`), or read the machine's drained
records.

What keeps the two audiences apart, now that one function records both:

| Guarantee | Enforced by |
| --- | --- |
| A declaration's audience, name prefix and module agree, both ways; so do its keys | compile time: `#[span]`/`#[event]`/`#[metric]` expand to `decl::declared::<A>(name, module_path!())`, `#[derive(Attrs)]` to `decl::key_declared(..)`; `lk-agents-codegen --check` repeats it |
| A product statistic carries closed enums and bounded labels only | compile time: its fields must be `decl::Bounded`, a sealed marker implemented by `BoundedLabel`, closed `SpanValue` enums and `#[derive(Bounded)]` groups. `BoundedLabel` has one constructor: a value of at most 64 ASCII letters, digits and `. - _ / : +` is kept, any other is `unknown`. The customer's `Label` is unchanged |
| There are two audiences | compile time: `Audience` is sealed |
| The audience alone routes a measurement | compile time: `Audience::record` makes the record; `ProductStat` has no constructor outside ABI |
| Spans and events are observability only | compile time: `Audience = Observability` bounds on `start`, `Trace::open`, `event` |
| A `ProductStat` reaches its destination only, under its own policy | the exporter's typed split and its tests (`otlp/product_stats_tests.rs`) |


### Report records

Chat history items, session options, the usage summary and evaluation results
Expand Down Expand Up @@ -285,17 +337,24 @@ the recording decision separately from the application endpoint's admission.

## Destinations

| | LiveKit Cloud | User endpoint |
| --- | --- | --- |
| Enabled by | hosted or Cloud-connected job | `OTEL_EXPORTER_OTLP_*` or `telemetry.configure(...)` |
| Signals | traces, metrics, report logs | traces, metrics |
| Scope | per job: a record is exported only while its job is registered and recording that signal | process |
| Before the recording decision | spans of the job are held, bounded, and released or dropped with the decision | exported |
| Content | sent as recorded, keyed for Cloud's redaction ([reference](telemetry-reference.md#cloud-ingest-and-redaction)) | `allow_pii` |
| Identity | the job's identity on every span, log and measurement, and on the resource (below) | the same on spans; measurements carry only declared labels |
| Batching | one job per request: a request never mixes jobs, so Cloud's per-batch session flags apply to one session | any |
| Temporality | delta | cumulative unless configured |
| Transport | OTLP/HTTP protobuf, gzip, with the job's Cloud token | OTLP/HTTP protobuf with configured headers |
One exporter (`lk_agents_net::export::otlp::Exporter`: one task loop, one flush, one shutdown)
with three destinations. Each has its own queue or aggregator and its own policy.

| | LiveKit Cloud | User endpoint | Product statistics |
| --- | --- | --- | --- |
| Whose data | the customer's | the customer's | LiveKit's |
| Enabled by | hosted or Cloud-connected job | `OTEL_EXPORTER_OTLP_*` or `telemetry.configure(...)` | on unless `LIVEKIT_PRODUCT_STATS=0` or `DO_NOT_TRACK=1`; sent only to a LiveKit Cloud host |
| Takes | spans, measurements, report logs | spans, measurements | `Record::ProductStat` only, and no other destination takes one |
| Signals | traces, metrics, report logs | traces, metrics | metrics |
| Scope | per job: a record is exported only while its job is registered and recording that signal | process | process: no job, no recording decision, no project observability flag |
| Before the recording decision | spans of the job are held, bounded, and released or dropped with the decision | exported | not applicable; before a credential, the last window is held |
| Content | sent as recorded, keyed for Cloud's redaction ([reference](telemetry-reference.md#cloud-ingest-and-redaction)) | `allow_pii` | closed enums and bounded labels only, by declaration |
| Identity | the job's identity on every span, log and measurement, and on the resource (below) | the same on spans; measurements carry only declared labels | none; its own resource (framework, runtime, platform, runner, storage), never the customer's |
| Batching | one job per request: a request never mixes jobs, so Cloud's per-batch session flags apply to one session | any | one window per request; an empty window is no request |
| Interval | spans each second or per full batch, metrics every 30 s | the same | one minute |
| Temporality | delta | cumulative unless configured | delta |
| Transport | OTLP/HTTP protobuf, gzip, with the job's Cloud token | OTLP/HTTP protobuf with configured headers | OTLP/HTTP protobuf, gzip, to `/observability/productstats/agents/metrics/otlp/v0` with the project key's observability bearer |
| A refusal | a 401 "recording disabled" stops that job's Cloud export | logged | dropped; neither product's failure stops the other |

The identity stamp is the one place job identity is written. It uses protocol's
shared keys, and also the spellings Cloud's consumers read today, until they read
Expand Down
8 changes: 8 additions & 0 deletions docs/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,14 @@ model given a `base_url` or a client without a vendor reports `"unknown"`. Telem
that id as declared: `gen_ai.provider.name` and the `model_provider` label are the model's
`provider`, with no translation.

A model's identity also names its plugin, the code that runs. A plugin author writes nothing:
the base class declares it from the class's package (`livekit.plugins.deepgram` is `deepgram`,
`livekit.plugins.boson_avatar` is `boson-avatar`), a LiveKit Inference class is
`livekit-inference`, and a class outside `livekit.plugins` is `custom`. A Node base class
declares the same id from its package name. A LiveKit Inference model keeps `provider`
`livekit` and its model string (what metrics and usage name) and declares beside them the
vendor and model it runs. [Product statistics](telemetry.md#what-is-collected) copy these.

An STT or TTS declares every fact fixed at construction in its `STTCapabilities` or
`TTSCapabilities`, passed to the base constructor (`super().__init__(capabilities=...)`);
`update_options` never changes one. An LLM has no such facts: everything it does is chosen
Expand Down
50 changes: 28 additions & 22 deletions docs/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,8 @@ people use.
the model string. The model name is the vendor's id as the application gave it; nothing
is renamed or grouped, so a dated snapshot (`gpt-4o-mini-2024-07-18`) stays itself.
- A model that declares no provider, like a plugin given only a base URL, is `unknown`:
its host name is never sent.
its host name is never sent. So is any declared value that is not a short identifier (at
most 64 ASCII letters, digits and `. - _ / : +`): free text never leaves the process.
- A plugin id is the last part of the package name, the same in every language:
`livekit-plugins-deepgram` in Python and `@livekit/agents-plugin-deepgram` in Node are
both `deepgram`.
Expand Down Expand Up @@ -256,14 +257,11 @@ session's VAD ended the speech, `stt` when the STT detects the end of speech its

**Sessions**

`sessions` counts sessions, once each when the session ends. Its labels are read
together, so the combinations are visible.
`sessions` counts sessions, once each when the session ends. It has one label.

| Label | Values |
| --- | --- |
| `session.entrypoint` | `rtc_session`, `a2a_session` |
| `session.topology` | `single`: one agent for the whole session; `handoff`: one agent replaced another; `agent_as_tool`: a local agent was called as a tool; `both`: a handoff and an agent as a tool |
| `session.delegation` | `none`: everything ran in this process; `remote`: a `RemoteAgent` was called |

**Voice sessions**

Expand All @@ -279,25 +277,33 @@ configuration it starts with.

**Features**

One counter per feature, each counting the sessions that used it. A session adds 1 to a
counter the first time it uses that feature, and never more than 1. The counters are
independent: a session that used MCP and `override_options` adds 1 to each of those two,
and nothing to the others.
One counter per feature. Each counter counts uses of the feature. A session that calls
`update_options` three times adds 3.

| Metric | Counts the sessions that |
| Metric | Counts each time |
| --- | --- |
| `feature.mcp` | ran an agent that has an MCP toolset |
| `feature.update_options` | called `session.update_options(...)` |
| `feature.override_options` | entered `session.override_options(...)` |
| `feature.background_audio` | played background audio |
| `feature.language_switch` | heard the person change language: the STT reported a different language than earlier in the session |
| `feature.model_switch` | changed a model while running: a different STT, TTS, LLM or realtime model than the one they started with |

A feature that needs more than a count gets labels on its own counter. One does so far:
`feature.model_switch.kind` is the kind of model that changed, `stt`, `tts`, `llm` or
`realtime`. A session adds 1 for each kind it changed, however the switch is made
(`update_options`, `override_options`, or an agent that brings its own model): one that
swapped its TTS twice and its LLM once adds 1 under `tts` and 1 under `llm`.
| `feature.handoff` | an agent replaced another in a voice session |
| `feature.agent_as_tool` | a local agent was called as a tool |
| `feature.remote_agent` | a `RemoteAgent` was called |
| `feature.mcp` | an MCP toolset was set up |
| `feature.update_options` | `session.update_options(...)` was called |
| `feature.override_options` | `session.override_options(...)` was entered |
| `feature.background_audio` | a background audio player was started, with or without a session |
| `feature.language_switch` | the STT reported a different language than the one before |
| `feature.model_switch` | a model was replaced with another while a session ran |

A feature that needs more than a count gets labels on its own counter. One does so far.
`feature.model_switch` says which kind of model was replaced by which, in two labels:
`feature.model_switch.from.kind` and `feature.model_switch.to.kind`, each `stt`, `tts`, `llm`,
`realtime` or `duplex`. No provider and no model name is recorded.

- A different TTS in place of the TTS is `tts -> tts`. A session that moves from a realtime
model to a duplex one is `realtime -> duplex`.
- "From" is the model installed just before, however the switch is made (`update_options`,
`override_options`, or an agent that brings its own model). A model installed where the
session had none is not a switch, and neither is the same model installed again or a
fallback adapter moving to another of its members.
- Each switch adds 1: a session that swapped its TTS three times adds 3 under `tts -> tts`.

**Never collected**

Expand Down
20 changes: 20 additions & 0 deletions python/livekit-agents/livekit/agents/_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,26 @@ def proxy_overrides(cls: type, hooks: tuple[str, ...]) -> None:
cls._core_proxied = True # type: ignore[attr-defined]


def plugin_id(cls: type) -> str:
"""The id of the plugin a model class belongs to, which its identity declares.

A class of ``livekit.plugins.<name>`` is ``<name>`` with hyphens, as its package spells it
(``boson_avatar`` is ``boson-avatar``); a LiveKit Inference class is ``livekit-inference``;
any other class is ``custom``. A framework class that stands for a plugin's model names it
in ``_plugin``.
"""
return getattr(cls, "_plugin", None) or plugin_of(cls.__module__)


def plugin_of(module: str) -> str:
"""The plugin id of the class path or module ``module``."""
if module.startswith("livekit.plugins."):
return module.split(".")[2].replace("_", "-")
if (module + ".").startswith("livekit.agents.inference."):
return "livekit-inference"
return "custom"


def _framework(cls: type) -> bool:
return cls.__module__ == "livekit.agents" or cls.__module__.startswith("livekit.agents.")

Expand Down
2 changes: 2 additions & 0 deletions python/livekit-agents/livekit/agents/_core.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,8 @@ from ._generated._core_metrics import (
)
from ._generated._core_native_enums import (
Role as Role,
RunnerCmd as RunnerCmd,
Runtime as Runtime,
SpanKind as SpanKind,
StatusCode as StatusCode,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,7 @@ class OpenAIRealtimeModel:
conn_options: APIConnectOptions | None = None,
dialect: RealtimeProvider | None = None,
label: str | None = None,
plugin: str | None = None,
gateway: InferenceGateway | None = None,
) -> None:
"""Not given, `model`, `voice` and the session options are the dialect's defaults. The key
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
# GENERATED FILE -- DO NOT EDIT.
from enum import Enum

class Runtime(Enum):
Python = ...
Node = ...
Bun = ...

class RunnerCmd(Enum):
Dev = ...
Console = ...
Simulation = ...
Start = ...
NoCommand = ...

class StatusCode(Enum):
Unset = ...
Ok = ...
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ from typing import Literal, Self
from opentelemetry.trace import SpanKind as HostSpanKind, StatusCode as HostStatusCode
from opentelemetry.util.types import AttributeValue

from livekit.agents._core import SpanKind, StatusCode
from livekit.agents._core import RunnerCmd, Runtime, SpanKind, StatusCode

from .telemetry import EndedSpan, EvaluationRecord, Outcome, ReportTag, SessionReport, SpanContext

Expand Down Expand Up @@ -53,10 +53,16 @@ class TelemetrySpan:
def end(self, end_time: int | None = None) -> None:
"""Ends the span; later calls do nothing."""

def _core_telemetry_install(sdk_version: str, *, python_version: str | None = None) -> None:
def _core_telemetry_install(
sdk_version: str,
runtime: Runtime,
runtime_version: str,
runner_cmd: RunnerCmd,
) -> None:
"""Starts the process's exporter, stamping `sdk_version`, with the application endpoint from
the `OTEL_EXPORTER_OTLP_*` environment, and the process's product statistics unless they
are opted out of. Later calls do nothing.
are opted out of, which name the host's `runtime`, its version and the command that started
the process. Later calls do nothing.
"""

def configure(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ from __future__ import annotations
from collections.abc import Awaitable, Callable, Mapping, Sequence
from typing import Self

from livekit.agents._core import Role
from livekit.agents._core import Role, RunnerCmd
from livekit.agents.http import AgentRoutes
from livekit.agents.ipc import JobLauncher
from livekit.agents.ipc.child import _JobProc
Expand Down Expand Up @@ -132,7 +132,7 @@ class IpcClient:
def __new__(
cls,
fd: int,
initialize: Callable[[str | None], None],
initialize: Callable[[str | None, RunnerCmd], None],
*,
process: bool = False,
) -> Self:
Expand Down
6 changes: 6 additions & 0 deletions python/livekit-agents/livekit/agents/_generated/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
from typing import TYPE_CHECKING, Literal, TypeAlias

if TYPE_CHECKING:
from livekit.agents._core import RunnerCmd

from .worker_options import ProcessOptions, ServerOptions

LogLevel: TypeAlias = Literal["trace", "debug", "info", "warn", "error", "fatal", "off"]
Expand All @@ -25,6 +27,10 @@ class CliArgsStart:
dev: bool
cli_addr: str | None
simulation: bool
runner_cmd: RunnerCmd
"""The command as product statistics name it: `simulation` for a simulation, else `dev`
with `--dev`, else `start`. The parser derives it; nothing else does.
"""
options: ServerOptions
"""The server options the command line gives (`--url`, `--api-key`, `--api-secret`,
`--shutdown-timeout`, `--drain-timeout`), over the `AgentServer`'s own.
Expand Down
Loading
Loading