Telemetry API

kavalai.Telemetry is the interface through which the engine, the function kernel and the token accumulator report a run to a tracing system. Every method of the base class does nothing. kavalai.otel.OtelTelemetry implements it over OpenTelemetry. kavalai.otel is not re-exported from kavalai, because it needs the otel extra and import kavalai has to work without it.

For what is exported and why, read Exporting to OpenTelemetry.

Copyright 2026 OÜ KAVAL AI (registry code 17393877)

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

The seam through which a run is reported to a tracing system.

Telemetry is the interface the workflow engine, the function kernel and the token accumulator call. Every method of the base class does nothing, so the engine holds one unconditionally and a deployment that passes none behaves exactly as before. kavalai.otel.OtelTelemetry is the OpenTelemetry implementation; it lives in a module of its own because this one has to import under Pyodide, where there is no collector to send spans to.

The module imports nothing outside the base install.

class kavalai.telemetry.Telemetry[source]

Bases: object

Receives the life cycle of runs, nodes, tool calls and model calls.

The engine treats a span as an opaque handle: it receives one from start_run() or start_node() and hands it back to the matching end_* method and to within(). An implementation holds no per-run state of its own, so one instance serves every concurrent run of an engine.

A subclass overrides the methods it needs. None of them may raise for an ordinary run: telemetry is an observer, and a run does not fail because it could not be observed.

start_run(*, workflow: str, agent_id: str | None, session_id: str | None, run_id: str | None, external_id: str | None, invocation_id: str) → Any[source]

Open the span of one run and return its handle.

Called once per run, after the run row exists, so the ids are known; they are None for an engine without an AgentService.

end_run(span: Any, *, status: str, error: str | None, token_usage: dict | None, duration_seconds: float | None) → None[source]

Close a run’s span. Called exactly once per start_run().

status is the run’s final WorkflowState.status and error its error text — also for a run that timed out or whose consumer went away.

start_node(*, name: str, node_type: str, seq: int | None) → Any[source]

Open the span of one node visit and return its handle.

end_node(span: Any, *, error: BaseException | None = None, attributes: dict[str, Any] | None = None) → None[source]

Close a node’s span.

attributes carries what a node reports about itself; today that is a branch node’s taken and matched.

within(span: Any, events: AsyncIterator[Any]) → AsyncIterator[Any][source]

Relay events with span current while each one is produced.

The base class returns events unchanged. An implementation must make the span current only for the duration of one step of the iterator and never across a yield: between two events the consumer’s own code runs, and it must not see the engine’s span.

tool_call(tool_uri: str) → AbstractContextManager[Any][source]

A context manager entered around one tool call.

model_call(stats: ModelCallStat) → None[source]

Report one finished model call, successful or failed.

Copyright 2026 OÜ KAVAL AI (registry code 17393877)

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

OpenTelemetry export: a run as a trace, and a small set of metrics.

OtelTelemetry implements kavalai.telemetry.Telemetry over the OpenTelemetry API. Passed to a WorkflowEngine it emits one trace per run — run, node, tool call and model call spans — and the histograms listed below. configure_sdk() installs process-global providers that export over OTLP/HTTP; a host that has configured OpenTelemetry already does not call it.

The module is not imported by kavalai/__init__.py and needs the otel extra. It reads no environment variable: the OTLP exporters read the standard OTEL_EXPORTER_OTLP_* variables themselves.

Names follow the OpenTelemetry GenAI semantic conventions where one exists and carry a kavalai. prefix where none does. The conventions have Development status, so every name this module emits is one of the constants below and a rename is a change to this block. SEMCONV_VERSION is the semantic-conventions release they were taken from: 1.41.0, the last one before the GenAI conventions moved to a repository of their own.

PROVIDER_NAMES maps a Kaval.AI provider prefix onto the convention’s gen_ai.provider.name value where the two differ. TOKEN_BUCKETS and DURATION_BUCKETS are the histogram boundaries the conventions advise.

class kavalai.otel.OtelTelemetry(*, tracer_provider: TracerProvider | None = None, meter_provider: MeterProvider | None = None, capture_content: bool = False, max_content_bytes: int = 8192)[source]

Bases: Telemetry, ModelStatsReceiver

Reports runs to OpenTelemetry as traces and metrics.

One trace per run:

invoke_workflow {workflow}
  {node_type} {node_name}
    chat {model} | embeddings {model}
    execute_tool {function}

A run’s span is a child of whatever span is current when the run starts, and everything a node starts — an outbound HTTP request of a tool, a provider SDK’s own instrumentation — is a child of the node’s span. Every span of a run carries its position in the trace; the run span carries kavalai.run.id and the session id, which is how a trace is found from a recorded run.

A model-call span is created when the call has finished, from its ModelCallStat, with the start time computed from the duration. Each attempt of a retried call is a span of its own.

The instance is also a ModelStatsReceiver, so make_client(model, stats_receiver=OtelTelemetry()) traces a client used outside a workflow.

Parameters:
tracer_provider: TracerProvider | None = None

Provider the spans are created from. Defaults to the process-global one, as every OpenTelemetry instrumentation does.

meter_provider: MeterProvider | None = None

Provider the histograms are created from. Defaults to the process-global one.

capture_content: bool = False

Whether a model call’s request and response are attached to its span. Off by default: spans then carry names, timings, token counts and error types, and no prompt, answer, tool argument or tool result. An OTLP endpoint is commonly operated by a third party, which is why the default differs from the task logger’s.

max_content_bytes: int = 8192

Cap on each captured payload; a larger one is replaced by the marker the task logger uses.

start_run(*, workflow: str, agent_id: str | None, session_id: str | None, run_id: str | None, external_id: str | None, invocation_id: str) → _Handle[source]

Open the span of one run and return its handle.

Called once per run, after the run row exists, so the ids are known; they are None for an engine without an AgentService.

end_run(span: _Handle, *, status: str, error: str | None, token_usage: dict | None, duration_seconds: float | None) → None[source]

Close a run’s span. Called exactly once per start_run().

status is the run’s final WorkflowState.status and error its error text — also for a run that timed out or whose consumer went away.

start_node(*, name: str, node_type: str, seq: int | None) → _Handle[source]

Open the span of one node visit and return its handle.

end_node(span: _Handle, *, error: BaseException | None = None, attributes: dict[str, Any] | None = None) → None[source]

Close a node’s span.

attributes carries what a node reports about itself; today that is a branch node’s taken and matched.

async within(span: _Handle, events: AsyncIterator[Any]) → AsyncIterator[Any][source]

Relay events with span current during each step only.

The context is attached and detached around one __anext__ — in one resumption of one task — so the consumer never runs with an engine span current and a generator finalised from another task has nothing left to detach. Tasks the step creates copy the context and so inherit the span.

tool_call(tool_uri: str) → AbstractContextManager[Any][source]

A context manager entered around one tool call.

model_call(stats: ModelCallStat) → None[source]

Report one finished model call, successful or failed.

receive_model_stats(stats: ModelCallStat) → None[source]
kavalai.otel.configure_sdk(*, service_name: str, traces: bool = True, metrics: bool = True) → None[source]

Install process-global providers that export over OTLP/HTTP.

For an entry point that owns the process, such as python -m kavalai.server. A host that has configured OpenTelemetry for the rest of its service does not call this; it passes telemetry=OtelTelemetry() and the spans go where its own do.

The exporters read the standard variables themselves — OTEL_EXPORTER_OTLP_ENDPOINT and its per-signal forms, OTEL_EXPORTER_OTLP_HEADERS — and OTEL_SERVICE_NAME takes precedence over service_name. Both providers flush when the interpreter exits.

Parameters:
service_name: str

The service.name resource attribute, unless the environment sets one.

traces: bool = True

Whether to install a tracer provider.

metrics: bool = True

Whether to install a meter provider.