nemoguardrails.telemetry
Module Contents
Classes
Functions
Data
_CONFIG_BUILTIN_FEATURE_ALIASES
API
Bases: enum.Enum
How the NeMo product was invoked.
Mirrors the shared nemo-telemetry definition. library covers
direct LLMRails / Guardrails use in user code, api is
the FastAPI server, cli is the interactive chat command.
sdk and nmp are inherited from the shared enum and are
valid values guardrails does not produce itself.
Bases: enum.Enum
Bases: TelemetryEvent
Usage event for NeMo Guardrails.
Emitted at each LLMRails or IORails instantiation and as
periodic heartbeats from a single daemon thread per process. The
Guardrails wrapper emits through whichever runtime engine it
constructs. All events from one process share a session ID. Contains
no user content, model names, or request-level data.
Bases: enum.Enum
The NeMo product that created the event.
Mirrors the shared nemo-telemetry definition so the guardrails event
plugs into the same definitions/types block other NeMo products
(DataDesigner, Safe Synthesizer, Agent Toolkit, etc.) already share.
Bases: enum.Enum
Bases: BaseModel
Abstract base for telemetry events.
Subclasses must define _event_name as a ClassVar. The optional
_schema_version ClassVar is used by the payload builder to set
eventSchemaVer in the NVIDIA telemetry envelope.
Raises:
TypeError: If a subclass fails to define_event_name.
Wrap a TelemetryEvent in the inner event dict for the NVIDIA envelope.
Always injects nemoSource="guardrails" into the parameters so
the backend can route the event correctly.
Parameters:
The Pydantic event instance to serialize.
Optional Unix timestamp for the ts field; uses current
time if None.
Returns: Dict[str, Any]
A dict with ts, name, and parameters keys, ready to
Build the outer NVIDIA telemetry envelope that wraps one or more events.
All envelope fields other than clientVer, sessionId,
eventSchemaVer, sentTs, cpuArchitecture, and events
are hardcoded to "undefined" or "None" per the NVIDIA
telemetry protocol spec. eventSchemaVer is read from the first
event’s _schema_version ClassVar.
Parameters:
Non-empty list of telemetry events to include.
Version string of the calling product, set as
clientVer (typically the package version).
Session identifier set as sessionId in the envelope.
Optional per-event Unix timestamps. If None,
each event is timestamped with the current time.
Returns: Dict[str, Any]
The complete envelope as a dict, ready to be JSON-serialized
Raises:
ValueError: Ifeventsis empty.
Collect anonymous usage data into a GuardrailsUsageEvent.
Always populates system fields (version, platform, Python version).
When config is provided, additionally populates config-derived
fields: LLM provider names, rail types in use, built-in features,
custom flow count, and feature flags. Never reads model names,
prompts, or user content.
Parameters:
The RailsConfig to inspect, or None for a
system-only event (e.g. from the server startup context).
How guardrails was deployed, e.g. "library",
"api", or "cli". Coerced to
DeploymentTypeEnum.UNDEFINED if falsy.
Returns: GuardrailsUsageEvent
A fully populated GuardrailsUsageEvent.
Detect which built-in NeMo Guardrails library features are active.
Uses two signals: (1) fields on RailsConfigData that differ from
their defaults (explicit config), and (2) exact-match flow names
against a known set of built-in library flows. Only our own feature
names are ever reported, never user-defined flow names.
Parameters:
The RailsConfig instance to inspect.
Returns: List[str]
Sorted list of active built-in feature names (e.g.
Return the local audit JSONL path, honoring test overrides.
Return the telemetry config directory, honoring test overrides.
Return the do-not-track marker path, honoring test overrides.
Return the heartbeat interval, falling back safely on bad env values.
Format a Unix timestamp as an ISO 8601 UTC string with millisecond precision.
Parameters:
Unix timestamp (seconds since epoch). If None, uses
the current UTC time.
Returns: str
ISO 8601 formatted string ending with "Z", e.g.
Return the telemetry server URL, honoring runtime env overrides.
Run the heartbeat loop forever in a daemon thread.
Started exactly once per process (gated by _heartbeat_started).
Sleeps at least _HEARTBEAT_INTERVAL_S seconds, then emits a
heartbeat event tied to the process’s session ID. The heartbeat
reuses a copy of the first startup event’s metadata and changes
only event, timestamp, and sessionId. The thread is a
daemon so it dies with the main process; no explicit shutdown is
required.
Parameters:
The first startup event emitted by this process.
The process-stable session ID, mirrored into the
heartbeat event’s session_id field and the envelope.
Value to set as clientVer in the envelope.
Check whether usage reporting is enabled.
Opt-out signals, any of which disables reporting:
NEMO_GUARDRAILS_NO_USAGE_STATS=1/trueenv var (product-specific).DO_NOT_TRACK=1/trueenv var (industry-standard).~/.config/nemoguardrails/do_not_trackfile present.CIenv var truthy (set by GitHub Actions, GitLab CI, CircleCI, Travis, Buildkite, etc.). Suppresses telemetry from automated test runs that are not real deployments. HonoringCIis the same convention used by Homebrew, npm, conda, and others.PYTEST_CURRENT_TESTenv var present, orpytestalready loaded in the process. Catches the case of a developer running tests locally withoutCI=true, including collection/import phases wherePYTEST_CURRENT_TESTis not set, and suppresses any telemetry that would otherwise leak from a downstream user’s test suite that happens to import nemoguardrails.
The intent is that adoption metrics reflect real deployments only, not synthetic test/CI traffic.
Returns: bool
True if reporting should proceed, False if any opt-out is active.
Return the documented feature id for a RailsConfigData field.
Clear module state in a forked child so it starts a fresh session.
Registered via os.register_at_fork(after_in_child=...) at module
import time on POSIX platforms. Without this, workers spawned by
gunicorn --preload (or any other fork-based runtime) would
inherit the parent’s session ID and its _heartbeat_started
flag, but lose the actual heartbeat thread (POSIX fork() only
duplicates the calling thread). The result would be silent: every
worker would report under the parent’s session and never emit
heartbeats. After this hook runs, the child’s first report_usage
call generates a fresh session UUID and starts its own heartbeat.
The deployment-type override is intentionally preserved so a forked
API or CLI worker keeps the attribution claimed by its parent.
Rotate the local audit file when it exceeds the size cap.
The current usage_stats.json is renamed to usage_stats.json.1,
overwriting any previous backup. This bounds on-disk usage at
approximately 2 * _AUDIT_FILE_MAX_BYTES. Errors are silently
logged at DEBUG level.
Return the user’s home directory without raising at import time.
Write a single event to the audit file and POST it.
Used as the target of a one-shot daemon thread spawned by
report_usage. Fire-and-forget: errors are swallowed at DEBUG
level inside _write_audit_file and _send_report.
Parameters:
The telemetry event to record and transmit.
Full HTTPS URL of the telemetry endpoint.
Value to set as clientVer in the envelope.
Value to set as sessionId in the envelope.
POST a single telemetry event to the configured server.
Fire-and-forget: a single attempt with a 5-second timeout, no retries, all exceptions silently logged at DEBUG level. Runs in a daemon thread so it never blocks the main process.
Parameters:
The telemetry event to send.
Full HTTPS URL of the telemetry endpoint.
Value to set as clientVer in the envelope.
Value to set as sessionId in the envelope.
Start a daemon thread and report whether startup succeeded.
Append a payload to the local audit file as a JSON line.
Creates the config directory if it does not exist. Rotates the
audit file when it exceeds _AUDIT_FILE_MAX_BYTES. All errors
(permission denied, disk full, etc.) are silently logged at DEBUG
level so telemetry never disrupts the main process.
Parameters:
Serialized event payload (already converted to a dict
via model_dump(by_alias=True)).
Emit one anonymous usage event for the given config.
Each call produces a single event tied to the process’s session ID (lazily generated on first call, reused thereafter). The heartbeat daemon thread is started exactly once per process. All work happens off the calling thread so this function returns immediately.
The effective deployment type is resolved as: the value previously
passed to set_deployment_type if any, else the function argument.
This lets the server lifespan or CLI command claim the deployment
context once, and downstream LLMRails.__init__ /
Guardrails.__init__ calls inherit it without coordination.
Respects the triple opt-out (env vars and file).
Parameters:
RailsConfig to introspect. When None, only
system-level fields are populated.
How guardrails was deployed (e.g. "library",
"api", "cli"). Overridden by set_deployment_type.
Which engine class is in use (e.g. "LLMRails",
"IORails"). Ignored if empty.
Set the deployment type that subsequent report_usage calls will use.
Called by the FastAPI server lifespan ("api") and the
nemoguardrails chat CLI command ("cli") before LLMRails
is constructed. Takes precedence over the deployment_type argument
passed by LLMRails.__init__ and Guardrails.__init__, so the
same library-internal call sites emit the correct value depending on
how the process was invoked.
Invalid values are silently ignored (logged at DEBUG level), so a bad caller never crashes the host process.
Parameters:
One of the DeploymentTypeEnum string values
(e.g. "api", "cli", "library").