AAnvio
Monitoring

Tracing

OpenTelemetry tracing setup for Anvio, including self-hosted Langfuse ingestion of the same OTLP pipeline.

4 min read

Anvio emits traces via OpenTelemetry (OTLP), implemented in packages/observability/src/index.ts using @opentelemetry/sdk-node. Langfuse can ingest the exact same pipeline for LLM-focused observability dashboards — no separate instrumentation is needed. This is the initObservability() entry point used by the API and worker processes.

How it's wired

// packages/observability/src/index.ts
export function initObservability(options: ObservabilityOptions): NodeSDK | null {
  const enabled =
    options.enabled ??
    (process.env.ANVIO_OTEL_ENABLED === 'true' || !!process.env.OTEL_EXPORTER_OTLP_ENDPOINT);
  if (enabled === false) return null;

  const endpoint = options.otlpEndpoint ?? process.env.OTEL_EXPORTER_OTLP_ENDPOINT;

  sdk = new NodeSDK({
    resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: options.serviceName }),
    traceExporter: endpoint
      ? new OTLPTraceExporter({ url: `${endpoint.replace(/\/$/, '')}/v1/traces` })
      : undefined,
    instrumentations: [getNodeAutoInstrumentations()],
  });

  sdk.start();
  return sdk;
}

Key behavior: tracing auto-enables the moment OTEL_EXPORTER_OTLP_ENDPOINT is set — you don't need a separate ANVIO_OTEL_ENABLED=true unless you want to force it on/off explicitly. getNodeAutoInstrumentations() from @opentelemetry/auto-instrumentations-node covers standard Node.js instrumentation (HTTP, etc.) automatically.

A withSpan() helper wraps custom application spans with automatic status/error recording:

export async function withSpan<T>(
  name: string,
  attributes: Record<string, string | number | boolean>,
  fn: () => Promise<T>,
): Promise<T> {
  const tracer = trace.getTracer('anvio');
  return tracer.startActiveSpan(name, async (span) => {
    try {
      for (const [key, value] of Object.entries(attributes)) span.setAttribute(key, value);
      const result = await fn();
      span.setStatus({ code: SpanStatusCode.OK });
      return result;
    } catch (error) {
      span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error) });
      throw error;
    } finally {
      span.end();
    }
  });
}

Enabling OTLP export

export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_SERVICE_NAME=anvio
export OTEL_TRACES_EXPORTER=otlp
export OTEL_METRICS_EXPORTER=otlp

HTTP/protobuf endpoint (port 4318) is the default for local collectors and Langfuse's OTLP ingress.

Self-hosted or cloud Langfuse

Docker or Langfuse Cloud.

In Langfuse project settings, copy the OTLP endpoint plus public/secret keys.

export OTEL_EXPORTER_OTLP_ENDPOINT=https://cloud.langfuse.com/api/public/otel
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic $(echo -n 'pk-lf-...:sk-lf-...' | base64)"

What gets traced

SpanSource
Agent runDefaultAgentRuntime
Tool callsTool gateway + MCP bridge
MCP server healthanvio mcp health
Channel harnessInbound/outbound when enabled

Token usage itself is not part of the trace payload — it's written separately to the workspace audit ledger, queryable via anvio usage stats (see Metrics and Logging).

Local dev stack

A minimal local collector + Langfuse pair for testing, as a Compose snippet:

services:
  otel-collector:
    image: otel/opentelemetry-collector-contrib
    ports: ['4318:4318']
  langfuse:
    image: langfuse/langfuse:latest
    ports: ['3000:3000']

Forward collector → Langfuse using Langfuse's own docs for your installed version — Anvio doesn't ship a preconfigured collector config for this hop.

This snippet publishes Langfuse on host port 3000, which collides with Anvio's own api service port (API_PORT=3000 — see Environment Variables). Run them on separate hosts, or remap one of the two port bindings, if you're combining this snippet with the production Docker Compose stack.

Dashboard checklist

From docs/72-observability-langfuse.md, the operational checklist to build into any tracing dashboard:

  • Trace latency p50/p95 per agent
  • Tool error rate by anvio_tools__* vs anvio_mcp__*
  • MCP first-call approval wait time
  • Channel reply vs suppressed raw-output ratio (harness)

The shipped Langfuse dashboard template (configs/observability/langfuse-dashboard.json) implements this checklist as concrete panels:

{
  "title": "Agent run latency (p95)",
  "query": "histogram_quantile(0.95, sum(rate(anvio_agent_run_duration_bucket[5m])) by (le))"
},
{
  "title": "Tool calls by surface",
  "query": "sum by (tool_prefix) (rate(anvio_tool_calls_total[5m]))",
  "labels": ["anvio_tools", "anvio_mcp", "anvio_channel"]
},
{
  "title": "MCP first-call approval wait",
  "query": "histogram_quantile(0.95, sum(rate(anvio_mcp_approval_wait_seconds_bucket[5m])) by (le))"
},
{
  "title": "Harness channel replies vs suppressed raw",
  "query": "sum(rate(anvio_harness_channel_reply_total[5m])) / sum(rate(anvio_harness_inbound_total[5m]))"
},
{
  "title": "Token usage by agent",
  "query": "sum by (agent_name) (increase(anvio_tokens_total[24h]))"
}

Variables defined for filtering: agent (label_values(anvio_agent_run_duration_bucket, agent_name)) and channel (label_values(anvio_harness_inbound_total, channel)).

Import this JSON directly into Langfuse — it was shipped in Phase P14 (docs/69-post-v1.17-gap-register.md, item O3).

Some metric names referenced by the dashboard (anvio_agent_run_duration_bucket, anvio_harness_channel_reply_total, anvio_harness_inbound_total, anvio_mcp_approval_wait_seconds_bucket) come from OTel span/metric instrumentation, not from the simpler in-process MetricsRegistry counters covered in Metrics (which only implements token-usage and MCP-restart counters directly). Verify these are actually emitted by your running version before wiring alerts against them.

packages/core also carries telemetry helper code referenced alongside @anvio/observability — check there for any additional span attributes or trace context propagation beyond what's documented here.

Edit on GitHub

Last updated on

On this page