ExAgent.Observability.OpenTelemetry (ExAgent v3.0.0)

View Source

Optional native OpenTelemetry instrumentation, using the application's tracer.

Stability — Stable.

tracing = ExAgent.Observability.OpenTelemetry.new()
agent = ExAgent.new(model: model, observability: tracing)

Add :opentelemetry_api, an SDK and an exporter in the host application and configure ExAgent.Observability.BoundedProcessor for finite admission and observable drops/export failures (see docs/guides/observability.md). The native SDK's batch processor has a soft queue threshold rather than that hard bound. This module never starts or replaces a tracer provider, configures an exporter, or performs network IO. :tracer may be an application-supplied native tracer; otherwise the instrumentation scope is :exagent, version "1".

Profile exagent.gen_ai.v3

This profile uses OpenTelemetry GenAI semantic conventions v0.1.0. Spans record the tag's commit as exagent.gen_ai.revision.

SpanKindgen_ai.*
invoke_agent {gen_ai.agent.name}internaloperation.name, agent.name, conversation.id (the Server agent_id or the Session session_id)
invoke_workflow {gen_ai.agent.name}internaloperation.name, agent.name (the Flow or Composition definition ID)
chat {gen_ai.request.model}clientoperation.name, provider.name, request.model, request.stream, response.model, response.finish_reasons, conversation.compacted, usage.input_tokens, usage.output_tokens, usage.cache_read.input_tokens, usage.cache_write.input_tokens, usage.reasoning.output_tokens
embeddings {gen_ai.request.model}clientoperation.name, provider.name, request.model, request.encoding_formats, embeddings.dimension.count, usage.input_tokens
exagent.rerank {gen_ai.request.model}clientprovider.name, request.model
exagent.media.{operation} {gen_ai.request.model}clientprovider.name, request.model
execute_tool {gen_ai.tool.name}internaloperation.name, tool.name, tool.type (function), agent.name
plan {gen_ai.agent.name}internaloperation.name, agent.name
search_memory, create_memory, upsert_memory, update_memory, delete_memoryclientoperation.name, memory.record.count when known

The span and attribute variants for candidate integrations follow their tier, including embeddings, rerank, Plan, compacted context and the ReqLLM bridge.

A failed span carries error.type. A name without a known agent, model or tool is the bare operation (invoke_agent). exagent.delegation, exagent.compaction and exagent.checkpoint are internal diagnostics. The compacted-context indicator is true only on inference with evidence of compaction. Fallback and cassette replay use exagent.model_request for the logical total. Every dispatch has exagent.attempt.dispatched=true and an exagent.attempt.id equal to the corresponding Telemetry span context. A redactor can exhaust the deadline before dispatch. exagent.* keeps the IDs, exagent.operation, exagent.status (including paused), the inclusive run accounting and exagent.continuation.*. ExAgent responses carry no provider response identity, so this module never sets gen_ai.response.id; the attached ExAgent.Observability.ReqLLM bridge copies ReqLLM's bounded gen_ai.response.id onto the same model span.

exagent.call_ref carries the opaque invocation reference used in events. Function and output tool span names use the declared name. Memory spans describe built-in tool commands and preload. Plan spans cover the checklist update within write_todos. These spans report bounded metadata.

gen_ai.usage.* appears on model requests only, and only for dimensions the request reported (unknown is absent, never zero). Run totals use exagent.usage.* and are inclusive of descendants; do not sum them with generation usage. Costs are estimates in cents from the existing execution ledger, not a second pricing callback or an authoritative bill. A cost with exagent.cost.availability=partial carries exagent.cost.known_subtotal_cents when a known subtotal exists. The candidate option service_tier: true enables the draft gen_ai.response.service_tier attribute on model spans with a known returned tier. It defaults to false while the profile is pinned to v0.1.0. gen_ai.usage.input_tokens is the inclusive input total, set only when the input semantics are known. ExAgent.Models.ReqLLM states them per profile: Chat, OpenRouter and Responses input is inclusive, and Anthropic input is cache-exclusive, normalized here by adding the reported cache read and write counts (absent when either is unreported). :text_v1 and custom models have unknown semantics: their input remains in exagent.usage.reported_input_tokens instead of claiming a GenAI total. Run aggregates retain the existing ledger's provider-native token semantics. A durable pause ends its run span with exagent.status=paused, without an OTel error. Resume creates a new attempt/span under the same run identity. With link_continuations: true on both attempts, the pause stores the recording run span's trace ID and span ID. The resumed span uses its current parent context and links to the saved span. The option defaults to false. Run usage and host request/tool counts are cumulative lifetime snapshots. Use the latest snapshot for the run's totals and the effect journal for confirmed effects. exagent.continuation.* contains only the validated public reference identity and numeric version/revision, never approval actors, tokens or stored records. A Server terminal synthesized after abort/worker loss has only its last progress snapshot: exagent.usage.source=last_progress, partial usage and an unknown total cost. Observed token/count subtotals are retained, and any known monetary subtotal uses exagent.cost.known_subtotal_cents instead of claiming a complete exagent.cost.cents. Normal core results keep their reported status.

The candidate :metrics option enables native histograms when the host supplies the experimental OTel meter SDK. Each allowlist under metrics: [models: [...], agents: [...], tools: [...]] accepts up to 32 labels and defaults to empty. Other model labels become "other". Unlisted agent and tool names are omitted. Attempt duration uses the Telemetry dispatch interval. Token histograms use qualified totals when available. Run, workflow and tool duration use their span endpoints.

Content

Content is off by default. Opting in requires both content: true and redact: fn field, data -> {:ok, data} | :drop end. The fields are

fieldattributespans
:system_instructionsexagent.content.system_instructionschat
:input_messagesexagent.content.input_messageschat (the projection sent), invoke_agent (the prompt)
:output_messagesexagent.content.output_messageschat (the response), invoke_agent (the final output)
:tool_argumentsexagent.content.tool_argumentsexecute_tool
:tool_resultexagent.content.tool_resultexecute_tool, successful calls with visible content

A withheld result carries exagent.tool.content_withheld=true on a completed tool span. Its status describes the effect. For Frame3 tool-output guards, tool spans end before final settlement and record receipt metadata only.

The callback receives plain data in the pinned semconv message schema: messages are %{"role" => role, "parts" => parts} with roles "system", "user", "assistant" and "tool", and parts %{"type" => "text", "content" => text}, %{"type" => "tool_call", "id" => id, "name" => name, "arguments" => args} or %{"type" => "tool_call_response", "id" => id, "response" => value}; system instructions are a list of parts; tool arguments and results are their JSON values. Hidden reasoning, signatures, binary attachments, model structs, dependencies, configuration, exceptions and stacktraces never reach it. The returned data must keep that shape. The Erlang span API accepts scalar and homogeneous array attributes, so the redacted JSON uses ExAgent's namespace. GenAI v0.1.0 requires structured values for its message fields. Values over max_content_input_bytes (65536) are not sent to the redactor; a field whose JSON exceeds max_content_bytes (4096, up to three fields per span), an invalid or raising callback and a result outside the schema drop the entire field and emit content_dropped. No prefix of unredacted content is exported. Redactors are trusted local callbacks and should be fast; they are not sandboxed. Labels/IDs are bounded to 256 bytes. Use non-secret identifiers for agent, tool, model and correlation names. Arbitrary metadata, baggage, provider bodies, exception messages and stacktraces are never attributes.

capture_context/0 and with_context/2 propagate only span context and this configuration across application-owned tasks. These handles are ephemeral, not snapshot/JSON data. Server queues capture context at admission; a public lazy stream captures it at enumeration, unless trace_context: is supplied. Every attachment restores both prior OTel context and Logger metadata.

Native SDK span storage provides idempotent completion. A monitor per recording operation also closes its span when the executing process dies (including :kill), without another tracing registry or export queue. Hard termination cannot recover unreported usage and is marked partial. SDK shutdown or VM death can lose spans. Arbitrary synchronous processors/samplers installed by the host can block instrumentation; use the bounded batch setup in the example.

Instrumentation failures emit [:exagent, :observability, :failure] with a numeric count and a fixed stage. Redaction drops emit [:exagent, :observability, :content_dropped], without content or raw errors.

Summary

Functions

Capture a runtime-only span context; baggage and arbitrary context values are excluded.

Build an opt-in instrumentation configuration without changing the SDK. Unknown or duplicate options and invalid values raise ArgumentError, which names the option without its value.

Run a function under a captured context, restoring the caller even on exceptions.

Types

context()

@opaque context()

t()

@type t() :: %ExAgent.Observability.OpenTelemetry{
  content: term(),
  link_continuations: term(),
  max_content_bytes: term(),
  max_content_input_bytes: term(),
  metrics: term(),
  redact: term(),
  service_tier: term(),
  tracer: term()
}

Functions

capture_context()

@spec capture_context() :: context() | nil

Capture a runtime-only span context; baggage and arbitrary context values are excluded.

new(opts \\ [])

@spec new(keyword()) :: t()

Build an opt-in instrumentation configuration without changing the SDK. Unknown or duplicate options and invalid values raise ArgumentError, which names the option without its value.

with_context(arg1, fun)

@spec with_context(context() | nil, (-> result)) :: result when result: var

Run a function under a captured context, restoring the caller even on exceptions.