Current section
Files
Jump to
Current section
Files
docs/guides/observability.md
# Observability
Agents call external models, invoke tools, spawn child runs and pause for human
approvals — without good traces and metrics, production latency spikes and cost
surprises are hard to explain. ExAgent emits standard `:telemetry` events out
of the box and plugs into **OpenTelemetry** (Langfuse, Opik, Grafana Tempo,
Datadog, Honeycomb) with privacy-first defaults.
**What ExAgent simplifies:**
- **Zero mandatory tracing dependencies:** `:telemetry` events work out of the
box with `Telemetry.Metrics` and Phoenix LiveDashboard; OpenTelemetry is
purely opt-in.
- **Privacy by default:** Prompts, answers and tool arguments are **never
exported** unless you explicitly opt in with a redaction function that runs
before any span leaves your node.
- **One clean span tree:** Runs, model requests, Fallback attempts, tools,
delegated children, compaction and checkpoints connect cleanly — and
`ExAgent.Observability.ReqLLM.attach/0` enriches spans without creating
duplicate generations.
- **Bounded exporter protection:** `ExAgent.Observability.BoundedProcessor`
prevents a stalled OTLP endpoint from backing up memory in your app.
> #### Need full span attribute catalogs, telemetry event tables or load benchmarks? {: .info}
>
> For every span attribute name, metric allowlist detail and offline benchmark
> table, see [Runtime & ops contracts](llm/runtime-and-ops-contracts.md).
## 1. Application setup
Add the OpenTelemetry dependencies when your application wants OTLP traces:
```elixir
{:opentelemetry_api, "~> 1.5.0"},
{:opentelemetry, "~> 1.7.0"},
{:opentelemetry_exporter, "~> 1.11.0"}
```
Your application owns the OpenTelemetry SDK and exporter lifecycle. For
production deployments, prefer the [Collector route](recipes/otlp-collector-transport.md)
or [isolated VM exporter](recipes/otlp-isolated-transport.md). Configure
`ExAgent.Observability.BoundedProcessor` before starting the SDK (keeping
exporter secrets in environment variables rather than supervisor args):
```elixir
import Config
config :opentelemetry,
processors: [
{ExAgent.Observability.BoundedProcessor,
%{
name: :exagent_export,
exporter: {:opentelemetry_exporter, %{}},
max_queue_size: 2048,
max_export_batch_size: 256,
scheduled_delay_ms: 1000,
exporting_timeout_ms: 2000,
shutdown_timeout_ms: 1000
}}
]
config :opentelemetry_exporter,
otlp_protocol: :http_protobuf,
otlp_traces_endpoint: System.fetch_env!("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")
```
Set `OTEL_SERVICE_NAME` and `OTEL_EXPORTER_OTLP_TRACES_HEADERS` in your host
environment.
## 2. Enable instrumentation
Opt in per agent, run, Server or Session by passing `observability:`
*(candidate)*:
```elixir
alias ExAgent.Observability.OpenTelemetry
tracing = OpenTelemetry.new()
agent = ExAgent.new(model: model, observability: tracing)
{:ok, result} = ExAgent.run(agent, "A request")
```
Spans automatically cover the run (`invoke_agent`), model requests, tools,
delegated child runs, compaction and Store checkpoints.
### ReqLLM and one owner for request spans
Attach the integrated ReqLLM bridge once at application startup (replacing any
separate `ReqLLM.OpenTelemetry.attach/1,2` call) so upstream request IDs, model
server addresses and time-to-first-chunk enrich ExAgent's existing model span
instead of creating duplicate spans:
```elixir
:ok = ExAgent.Observability.ReqLLM.attach()
```
### Fallback requests and provider attempts
When using `ExAgent.Models.Fallback`, one logical `exagent.model_request` span
wraps individual leaf attempt spans (`chat {model}` with
`exagent.attempt.dispatched=true`). Read logical totals from the parent span
and provider-specific attempts from each leaf span.
### Optional metrics
With `opentelemetry_api_experimental ~> 0.6.0` and
`opentelemetry_experimental ~> 0.6.0`, enable native GenAI duration and token
histograms with explicit cardinality allowlists:
```elixir
tracing =
ExAgent.Observability.OpenTelemetry.new(
metrics: [models: ["my-fixed-model"], agents: ["my-workflow"], tools: ["lookup"]]
)
```
### LiveDashboard and Telemetry.Metrics reporters
Using Phoenix LiveDashboard, Prometheus or StatsD without OpenTelemetry?
Attach `ExAgent.Telemetry.metrics/0` directly to your application's
`Telemetry.Metrics` supervisor to graph run durations, tool failures, queue
depth, checkpoints and usage counters immediately.
## 3. Privacy before export
Prompt text, model replies and tool payloads stay off by default (`content: false`).
To export content to a trusted observability backend, enable `content: true`
with an explicit `:redact` callback that runs *before* export and drops any
oversized or unredacted value cleanly:
```elixir
withhold = fn
%{"type" => "text"} = part -> %{part | "content" => "[content withheld]"}
%{"type" => "tool_call"} = part -> Map.put(part, "arguments", "[content withheld]")
%{"type" => "tool_call_response"} = part -> %{part | "response" => "[content withheld]"}
end
tracing = OpenTelemetry.new(
content: true,
redact: fn
:system_instructions, parts ->
{:ok, Enum.map(parts, withhold)}
field, messages when field in [:input_messages, :output_messages] ->
{:ok, Enum.map(messages, &Map.update!(&1, "parts", fn parts -> Enum.map(parts, withhold) end))}
_tool_field, _value ->
{:ok, "[content withheld]"}
end,
max_content_bytes: 4096,
max_content_input_bytes: 65_536
)
```
- Hidden reasoning tokens are never exported.
- For MCP HTTP pools, use `:headers_provider` with Mint so static credentials
never appear in Finch telemetry ([Rotate credentials](mcp.md#rotate-http-credentials)).
- To filter verbose streaming HTTP failure logs from ReqLLM's streaming failure
module on a specific Logger handler, attach a standard OTP Logger handler
filter.
## Propagate context across processes and pauses
### Application-owned process boundaries
ExAgent propagates trace context across its own tools, child runs and Server
queues automatically. When *your* code spawns a `Task` or background process,
capture and reattach the context explicitly:
```elixir
context = OpenTelemetry.capture_context()
Task.async(fn ->
OpenTelemetry.with_context(context, fn ->
ExAgent.run(agent, "Another request")
end)
end)
```
For cross-service MCP spans, see [MCP tracing setup](mcp.md#trace-mcp-requests).
### Link paused and resumed attempts
Opt into `ExAgent.Observability.OpenTelemetry.new(link_continuations: true)` on
**both** the paused and resumed attempts (the option defaults to `false`). When
enabled on both sides, ExAgent stores a fixed-width trace/span pair at the
confirmed pause and attaches an OpenTelemetry span link on resume so you can
follow long-lived approval timelines across deploys without persisting payloads
or actor data.
### Model attempts and logical requests
Distinguish logical admitted requests (`result.request_count` /
`[:exagent, :model, :request, :*]`) from physical provider HTTP attempts
(retries and Fallback leaves) when alerting on latency vs. quota usage.
### Continuation lease renewals
Lease expiry does not emit a dedicated `:telemetry` event — watch for
`RunError.reason == :continuation_lease_expired` and run periodic
`ExAgent.Continuation.census/2` checks to spot slow tools or overloaded
PostgreSQL pools before leases expire.
### Tracking maintenance
Subscribe to `[:exagent, :store, :postgres, :maintenance_failed]` *(candidate)*
for PostgreSQL Store maintenance errors and read
`ExAgent.Observability.ReqLLM.Maintenance.stats/0` *(candidate)* to monitor
background stale-span pruning.
## Connect Langfuse and Opik
Langfuse ingests standard GenAI OTLP spans directly via the
[Collector route](recipes/otlp-collector-transport.md). Remember that with
`content: false`, empty `Input` / `Output` previews are expected — inspect the
structured span attributes for run IDs, status, token availability and cost.
### Opik attribute presentation
Opik places unrecognized top-level attributes into input rather than metadata.
When exporting through the [isolated gRPC exporter](recipes/otlp-isolated-transport.md)
and [Collector bridge](recipes/otlp-collector-transport.md), project ExAgent's
diagnostic attributes under `opik.metadata.*` with a bounded projection module:
```elixir
defmodule MyApp.OpikProjection do
@model_keys ~w(gen_ai.operation.name gen_ai.provider.name gen_ai.request.model
gen_ai.usage.input_tokens gen_ai.usage.output_tokens)
def project(%{resource_spans: resources} = request) do
resources = for resource <- resources do
scopes = for scope <- resource.scope_spans do
spans = for span <- scope.spans do
native = span.attributes
diagnostic = Enum.map(native, &prefix(&1, "opik.metadata."))
resource_metadata = Enum.map(resource.resource.attributes,
&prefix(&1, "opik.metadata.resource."))
model = Enum.any?(native, &(&1.key == "exagent.operation" and
&1.value == %{value: {:string_value, "model"}}))
semantic = if model, do: Enum.filter(native, &(&1.key in @model_keys)), else: []
attributes = diagnostic ++ resource_metadata ++ semantic
true = length(attributes) <= 64
%{span | attributes: attributes}
end
%{scope | spans: spans}
end
%{resource | scope_spans: scopes}
end
%{request | resource_spans: resources}
end
defp prefix(attribute, prefix), do: %{attribute | key: prefix <> attribute.key}
end
```
## Performance and load envelopes
ExAgent ships reproducible offline load probes so you can measure runtime
overhead on your own hardware (point measurements are local baselines, never
production SLAs):
```sh
EXAGENT_OFFLINE=1 MIX_ENV=test ERL_FLAGS="+S 4:4" mix run test/support/load_probe.exs
EXAGENT_OFFLINE=1 MIX_ENV=test mix run test/support/postgres_load_probe.exs --segments
```
Reference figures below were measured offline on a 4-scheduler OTP 29 / Elixir
1.20 fixture (`TestModel` + PostgreSQL 17.4):
### Offline load measurements
Warmed `TestModel` runs measured ~117 µs (plain text) and ~379 µs (two-call,
4 KiB tool loop), leaving provider network latency as the dominant cost.
### PostgreSQL load measurements
PostgreSQL snapshot and continuation CAS timings scale with payload size and
pool headroom; keep connection pools sized for concurrent writers and verify
with `test/support/postgres_load_probe.exs`.
### Optional segmented store
Enabling `segments: true` on `ExAgent.Store.Postgres` reuses unchanged history
and attachment fragments across revisions: in a 42,000-change offline PG 17.4
probe (67.7 MB logical JSON), segmented storage used 303 MB vs. 1,344 MB inline
(WAL 598 MB vs. 1,516 MB).
### Model attempt and stream load
Demand delivery drained 4,096 phased streaming deltas in ~51 ms with a reader
mailbox depth of 0 at stall.
### Reviewed stream load
`Guardrail.stream/3` buffers bounded byte/time windows (`max_bytes:` /
`max_ms:`) before releasing deltas, adding minimal local latency while ensuring
unreviewed text is never emitted early.
### Continuation transition load
Atomic continuation CAS transitions commit intents and outcomes without holding
database locks during model IO; lease renewals write one ~196 B row per renewal
in offline 500-writer batches.
### Online evaluation under load
`ExAgent.Eval.Online` checks an ETS free-slot index on the caller process:
offline full-queue rejections measured ~2 µs median p95 at capacities 16, 64
and 256 so backpressure never stalls user responses.
API: `ExAgent.Telemetry`, `ExAgent.Observability.OpenTelemetry`,
`ExAgent.Observability.BoundedProcessor`, `ExAgent.Observability.ReqLLM`.