Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
27 changes: 27 additions & 0 deletions docs/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,33 @@ parts off. At session end the framework uploads the session report; an
`rtc_session(on_session_end=)` callback receives the `JobContext` first, and
`ctx.make_session_report()` builds the same `SessionReport`.

## Product statistics

Separately from your telemetry, an agent connected to LiveKit Cloud sends LiveKit
anonymous product statistics about the framework and its plugins, so LiveKit can
see how they behave across versions and providers. They are never shown in your
dashboard, never billed, and never contain customer data.

- What is sent, once a minute per process: the framework, Python and LiveKit
plugin versions, the OS and architecture, whether the process runs in
production, development or CI; per provider, model and kind (STT, TTS, LLM,
realtime, end of turn, VAD): request, failure (by error class), retry,
fallback and reconnect counts, and time to first byte or token and request
duration; job starts and outcomes; crashed job processes and event-loop
stalls (by function names only).
- What is never sent: transcripts, prompts, audio, tool arguments or any other
content; room, participant, job, thread or agent names; ids; hostnames, user
names or paths.
- Where: `https://<your LiveKit Cloud host>/productstats/agents/v0/metrics`,
signed with your project's key. Nothing is sent when `LIVEKIT_URL` is not a
LiveKit Cloud URL.
- Opt out with `LIVEKIT_PRODUCT_STATS=0` or `DO_NOT_TRACK=1`, read once when the
process starts. Opting out does not affect your observability data, and
turning observability off does not opt out.

Product statistics are Telemetry Data under section 7.2 of the LiveKit Terms of
Service.

## Diagnostics

`telemetry.diagnostics()` returns the process's export counters as a
Expand Down
3 changes: 3 additions & 0 deletions python/livekit-agents/livekit/agents/_core.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,9 @@ from ._generated._core_native_enums import (
SpanKind as SpanKind,
StatusCode as StatusCode,
)
from ._generated._core_productstats import (
_core_product_stats_plugin as _core_product_stats_plugin,
)
from ._generated._core_recorder import (
SessionRecorder as SessionRecorder,
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# GENERATED FILE -- DO NOT EDIT.
#
# Written by `cargo run -p lk-agents-codegen -- --write` (in `rust/`) from the
# `#[host(class)]` declarations of `lk-agents-abi`. `_core.pyi` re-exports it.

from __future__ import annotations

def _core_product_stats_plugin(package: str, version: str) -> None:
"""A plugin registered on import: a `livekit.plugins.*` package is listed on the resource of
every later export; another package is not.
"""
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,10 @@ 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) -> None:
def _core_telemetry_install(sdk_version: str, *, python_version: str | None = None) -> None:
"""Starts the process's exporter, stamping `sdk_version`, with the application endpoint from
the `OTEL_EXPORTER_OTLP_*` environment. Later calls do nothing.
the `OTEL_EXPORTER_OTLP_*` environment, and the process's product statistics unless they
are opted out of. Later calls do nothing.
"""

def configure(
Expand Down
29 changes: 29 additions & 0 deletions python/livekit-agents/livekit/agents/_generated/semconv.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,21 @@
LK_PLAYOUT_POSITION: Final = "lk.playout.position"
LK_PRE_CONNECT_AUDIO_DURATION: Final = "lk.pre_connect_audio.duration"
LK_PREVIOUS_AGENT_LABEL: Final = "lk.previous_agent_label"
LK_PRODUCTSTATS_ARCH: Final = "lk.productstats.arch"
LK_PRODUCTSTATS_CRASH_SIGNATURE: Final = "lk.productstats.crash.signature"
LK_PRODUCTSTATS_DROP_REASON: Final = "lk.productstats.drop.reason"
LK_PRODUCTSTATS_ERROR_TYPE: Final = "lk.productstats.error.type"
LK_PRODUCTSTATS_FRAMEWORK_VERSION: Final = "lk.productstats.framework.version"
LK_PRODUCTSTATS_JOB_OUTCOME: Final = "lk.productstats.job.outcome"
LK_PRODUCTSTATS_MODEL: Final = "lk.productstats.model"
LK_PRODUCTSTATS_OPERATION: Final = "lk.productstats.operation"
LK_PRODUCTSTATS_OS: Final = "lk.productstats.os"
LK_PRODUCTSTATS_PLUGINS: Final = "lk.productstats.plugins"
LK_PRODUCTSTATS_PROVIDER: Final = "lk.productstats.provider"
LK_PRODUCTSTATS_PYTHON_VERSION: Final = "lk.productstats.python.version"
LK_PRODUCTSTATS_RUNNER_KIND: Final = "lk.productstats.runner.kind"
LK_PRODUCTSTATS_RUNNER_LAUNCH: Final = "lk.productstats.runner.launch"
LK_PRODUCTSTATS_STALL_SIGNATURE: Final = "lk.productstats.stall.signature"
LK_PROVIDER_REQUEST_IDS: Final = "lk.provider_request_ids"
LK_PROVIDER_TOOLS: Final = "lk.provider_tools"
LK_REALTIME_MODEL_METRICS: Final = "lk.realtime_model_metrics"
Expand Down Expand Up @@ -202,6 +217,7 @@
ROOM_ID: Final = "room_id"
RPC_METHOD: Final = "rpc.method"
SDK_VERSION: Final = "sdk_version"
SERVICE_NAME: Final = "service.name"
SESSION_OPTIONS: Final = "session.options"
SESSION_REPORT_TIMESTAMP: Final = "session.report_timestamp"
SESSION_TAGS: Final = "session.tags"
Expand Down Expand Up @@ -330,6 +346,19 @@
METRIC_LK_AGENTS_WORKER_JOBS: Final = "lk.agents.worker.jobs"
METRIC_LK_AGENTS_WORKER_LOAD: Final = "lk.agents.worker.load"
METRIC_LK_AGENTS_WORKER_PROCESS_READY_DURATION: Final = "lk.agents.worker.process_ready.duration"
METRIC_LK_PRODUCTSTATS_EVENT_LOOP_STALLS: Final = "lk.productstats.event_loop.stalls"
METRIC_LK_PRODUCTSTATS_EXPORT_DROPPED: Final = "lk.productstats.export.dropped"
METRIC_LK_PRODUCTSTATS_JOB_ENDS: Final = "lk.productstats.job.ends"
METRIC_LK_PRODUCTSTATS_JOB_STARTS: Final = "lk.productstats.job.starts"
METRIC_LK_PRODUCTSTATS_PROCESS_CRASHES: Final = "lk.productstats.process.crashes"
METRIC_LK_PRODUCTSTATS_PROVIDER_DURATION: Final = "lk.productstats.provider.duration"
METRIC_LK_PRODUCTSTATS_PROVIDER_FAILURES: Final = "lk.productstats.provider.failures"
METRIC_LK_PRODUCTSTATS_PROVIDER_FALLBACKS: Final = "lk.productstats.provider.fallbacks"
METRIC_LK_PRODUCTSTATS_PROVIDER_RECONNECTS: Final = "lk.productstats.provider.reconnects"
METRIC_LK_PRODUCTSTATS_PROVIDER_REQUESTS: Final = "lk.productstats.provider.requests"
METRIC_LK_PRODUCTSTATS_PROVIDER_RETRIES: Final = "lk.productstats.provider.retries"
METRIC_LK_PRODUCTSTATS_PROVIDER_TTFB: Final = "lk.productstats.provider.ttfb"
METRIC_LK_PRODUCTSTATS_PROVIDER_TTFT: Final = "lk.productstats.provider.ttft"

# Report record scopes
LOG_SCOPE_CHAT_HISTORY: Final = "chat_history"
Expand Down
3 changes: 3 additions & 0 deletions python/livekit-agents/livekit/agents/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import logging
import threading

from . import _core


class Plugin:
"""A provider package, registered on import with ``Plugin.register_plugin(...)``."""
Expand All @@ -26,6 +28,7 @@ def register_plugin(cls, plugin: Plugin) -> None:
if threading.current_thread() != threading.main_thread():
raise RuntimeError("Plugins must be registered on the main thread")
cls.registered_plugins.append(plugin)
_core._core_product_stats_plugin(plugin.package, plugin.version)

@property
def package(self) -> str:
Expand Down
3 changes: 2 additions & 1 deletion python/livekit-agents/livekit/agents/telemetry.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import asyncio
import platform
import threading
import traceback
from collections.abc import Iterator, Mapping, Sequence
Expand Down Expand Up @@ -31,7 +32,7 @@ def _install() -> None:
global _provider_adopted
from .version import __version__

_core._core_telemetry_install(__version__)
_core._core_telemetry_install(__version__, python_version=platform.python_version())
if _provider_adopted:
return
_provider_adopted = True
Expand Down
28 changes: 28 additions & 0 deletions rust/ai_slop/lk-agents-codegen/src/telemetry/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ use std::collections::BTreeMap;

/// The ABI module the wire types and markers live in.
const DECL: [&str; 2] = ["telemetry", "decl"];
/// The ABI module of LiveKit's product statistics.
const PRODUCT_STATS: &str = "productstats";
/// The ABI module of the dependency registries' constants, one submodule per registry.
const SEMCONV: [&str; 2] = ["telemetry", "semconv"];

Expand Down Expand Up @@ -56,6 +58,8 @@ pub struct Attr {
pub label: Option<String>,
/// The type is bounded (`Label`, an enum, `BoolString`): it may be a metric label.
pub bounded: bool,
/// A `Vec` of bounded values.
pub bounded_items: bool,
pub metric: Option<String>,
pub brief: String,
/// The module of the struct that declares the field (`telemetry::spans::job`).
Expand Down Expand Up @@ -246,6 +250,9 @@ impl Reader<'_> {
let here = format!("{}::{}", self.krate.display(module), st.ident);
let brief = brief(&st.attrs);
let attrs = self.attrs(*key)?;
if self.krate.modules[module].path.first().map(String::as_str) == Some(PRODUCT_STATS) {
product_stat(&attrs, &here)?;
}
unique(&attrs, &here)?;
note(&attrs, &mut r)?;
if brief.is_empty() && (decl.role.is_some() || !groups.contains(key)) {
Expand Down Expand Up @@ -537,6 +544,7 @@ impl Reader<'_> {
unmeasured: ty.measured.then_some(attr.unmeasured),
label,
bounded: ty.label,
bounded_items: ty.bounded_items,
metric,
brief: brief(&field.attrs),
declared_in: self.krate.display(module).replacen("crate::", "", 1),
Expand Down Expand Up @@ -678,6 +686,7 @@ impl Reader<'_> {
return Ok(Ty {
wire: Wire::Array(Box::new(inner.wire)),
shape: inner.shape,
bounded_items: inner.label,
..Ty::default()
});
}
Expand Down Expand Up @@ -894,6 +903,8 @@ struct Ty {
measured: bool,
/// Bounded: may be a metric label.
label: bool,
/// A `Vec` of bounded values.
bounded_items: bool,
shape: Option<Shape>,
}

Expand Down Expand Up @@ -974,6 +985,23 @@ fn check(r: &Registry) -> Result<(), String> {
Ok(())
}

/// A product statistics declaration writes only bounded values (closed enums, `Label`s or
/// `Vec`s of them), never content or a key under `lk.pii.*`: its export is LiveKit's, and no
/// customer data may reach it.
fn product_stat(attrs: &[Attr], here: &str) -> Result<(), String> {
for a in attrs {
let pii = a.key.split('.').take(2).eq(["lk", "pii"]);
if a.content.is_some() || pii || !(a.bounded || a.bounded_items) {
return Err(format!(
"{here} (`{}`): a product statistic is a closed enum or a bounded `Label`, never \
content, free text or an `lk.pii.*` key",
a.key
));
}
}
Ok(())
}

/// Two fields of one attribute set under the same key.
fn unique(attrs: &[Attr], here: &str) -> Result<(), String> {
for (i, a) in attrs.iter().enumerate() {
Expand Down
30 changes: 30 additions & 0 deletions rust/ai_slop/lk-agents-codegen/src/telemetry/telemetry_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,36 @@ fn registry_rules_refuse_mistakes() {
}
}

// Catches: a product statistic carrying content, free text or an `lk.pii.*` key: its export is
// LiveKit's and must never hold customer data.
#[test]
fn product_statistics_hold_only_bounded_values() {
let read = |decl: &str| {
let decl = format!("use crate::telemetry::decl::{{Content, Label}};\n{decl}");
let krate = Crate::from_files(
"abi",
&[
("lib.rs", "pub mod telemetry; pub mod productstats;"),
("telemetry/mod.rs", "pub mod decl; pub mod semconv;"),
("telemetry/decl.rs", DECL),
("telemetry/semconv.rs", SEMCONV),
("productstats.rs", &decl),
],
)?;
telemetry::read(&krate)
};
let group = |field: &str| format!("/// R.\n#[derive(Attrs)]\npub struct R {{ {field} }}");
read(&group("/// P.\n#[attr(\"lk.productstats.p\")] pub p: Vec<Label>, /// V.\n#[attr(\"lk.productstats.v\")] pub v: Label,")).unwrap();
for field in [
"/// T.\n#[attr(\"lk.productstats.t\")] pub t: String,",
"/// T.\n#[attr(\"lk.productstats.t\")] pub t: Vec<String>,",
"/// T.\n#[attr(\"lk.pii.t\")] pub t: Content<String>,",
] {
let error = read(&group(field)).err().unwrap_or_else(|| panic!("accepted: {field}"));
assert!(error.contains("a product statistic is a closed enum"), "{error}");
}
}

// Catches: an output missing a declaration or misreporting it, a dependency key redefined in
// the Weaver registry, or the pins lost.
#[test]
Expand Down
13 changes: 13 additions & 0 deletions rust/crates/lk-agents-abi/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,19 @@ pub enum CliArgs {
},
}

impl CliArgs {
/// The command, as the process's runner reads it.
pub fn launch(&self) -> crate::telemetry::runner::Launch {
use crate::telemetry::runner::Launch;
match self {
CliArgs::Start { simulation: true, .. } => Launch::Simulation,
CliArgs::Start { dev: true, .. } => Launch::Dev,
CliArgs::Start { .. } => Launch::Start,
CliArgs::Console { .. } => Launch::Console,
}
}
}

/// Parsing never prints or exits the hosting process.
#[derive(Clone, PartialEq)]
#[crate::host(record(module = "cli", emit))]
Expand Down
1 change: 1 addition & 0 deletions rust/crates/lk-agents-abi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub mod invoke;
pub mod llm;
pub mod media;
pub mod metrics;
pub mod productstats;
pub mod recorder;
pub mod resources;
pub mod session;
Expand Down
Loading
Loading