Laminar logo
All blog posts

AI Agent Tracing with OpenTelemetry, Datadog or Grafana

Dec 2, 2026 · Laminar Team

AI agent tracing records an agent's model calls and tool executions as spans that you can correlate with a service request. If POST /triage takes seven seconds, request instrumentation alone might show the slow handler without explaining what the agent did inside it.

You can keep your existing service instrumentation and add agent spans. A Collector or Grafana Alloy can send those spans to both your existing backend and Laminar. A second option exports from separate providers in-process, preserving a shared trace ID but sending different span sets.

Local runs on December 2, 2026, used Grafana Tempo 3.0 and self-hosted Laminar, with real gpt-5-mini calls. For Datadog, the Collector configuration passed validation and reached its intake endpoint, but no traces were ingested into a Datadog account.

One trace ID, be9f0c02…a85a9, opened in two tools. Grafana Tempo shows the POST /triage request as a waterfall: triage_agent, two openai.chat calls of 3.19 s and 3.76 s and a search_runbooks call, 6.95 s in total. Laminar shows the same run as a transcript: two gpt-5-mini turns, the search_runbooks call with its query, and the answer, 766 tokens and $0.0009. Values from one local test run.

Values from one local run: Collector fan-out to Tempo 3.0 and self-hosted Laminar. Span durations as Tempo stored them; tokens and cost as Laminar's trace header reported them.

Choose full fan-out or correlated exports

Both setups retain your service's OpenTelemetry tracer provider. Laminar's SDK adds agent instrumentation and its own provider. Context inheritance joins the agent spans to the active request trace.

Choose Collector fan-out if you need the same agent spans in both backends. The in-process examples below provide correlation, not identical copies. Backend-specific filtering or sampling can also make the span sets differ after fan-out.

Collector or Alloy fan-outIn-process correlated exports
Routing pointCollector or AlloyApplication
Existing backend receivesRequest and agent spansRequest spans in these examples
Laminar receivesRequest and agent spansAgent spans in Python; request and agent spans in TypeScript
Laminar credentialsCollector or AlloyApplication
Backend-specific processingSeparate pipelinesDepends on provider and exporter configuration
Main reason to choose itAgent detail in both backendsNo additional routing service

Laminar isolates its context by default. Without the inheritance option shown below, these SDK versions create a separate agent trace ID: in the Python run without it, Tempo recorded the request as a3d38d0f… and Laminar recorded the agent run as 404e8a63…, so trace-ID lookup could not join the two halves. A shared ID also does not guarantee identical displayed hierarchy: the tested Python setup preserved the HTTP parent in Tempo, while Laminar treated the agent span as an agent-run root.

Fan out through a Collector

This configuration receives OTLP once and sends spans through two pipelines. It uses Collector Contrib 0.166.0 exporter names: otlp_grpc, rather than the older otlp.

receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

processors:
  batch: {}
  transform/agent_service:
    trace_statements:
      - context: span
        statements:
          - set(resource.attributes["service.name"], "triage-api") where instrumentation_scope.name == "lmnr.tracer"

exporters:
  otlp_grpc/tempo:
    endpoint: tempo:4317
    tls:
      insecure: true
  otlp_grpc/laminar:
    endpoint: api.lmnr.ai:8443
    headers:
      authorization: Bearer ${env:LMNR_PROJECT_API_KEY}

service:
  pipelines:
    traces/tempo:
      receivers: [otlp]
      processors: [transform/agent_service, batch]
      exporters: [otlp_grpc/tempo]
    traces/laminar:
      receivers: [otlp]
      processors: [batch]
      exporters: [otlp_grpc/laminar]

The cloud version passed configuration validation. End-to-end tests used the same routing with the Laminar exporter pointed at the local instance's gRPC port, 8001, with insecure TLS configuration. Laminar's OpenTelemetry documentation specifies cloud port 8443 and bearer authentication; the self-hosting guide covers local deployment.

Make Tempo's OTLP receiver reachable from the Collector. Tempo defaults to localhost, which will not serve a Collector in another container. Keep the example's unencrypted local connections inside a trusted development network.

The service-name transform applies only to the Tempo pipeline. It corrects an SDK resource default described below. OpenTelemetry permits a receiver in multiple pipelines and creates separate processor instances for each pipeline.

Instrument the Python service

This standalone FastAPI example supplies request instrumentation and adds Laminar's agent instrumentation. In an existing application, reuse your installed service provider rather than creating another service instrumentation stack.

import json

from fastapi import FastAPI
from openai import OpenAI
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

provider = TracerProvider(resource=Resource.create({"service.name": "triage-api"}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)

from lmnr import Laminar, observe

Laminar.initialize()

app = FastAPI()
FastAPIInstrumentor.instrument_app(app)
client = OpenAI()

RUNBOOKS = {
    "disk": "Runbook DB-7: expand the volume, then vacuum. Page the DBA if usage exceeds 95%.",
    "latency": "Runbook API-3: check the connection pool, then recent deploys.",
}
TOOLS = [{
    "type": "function",
    "function": {
        "name": "search_runbooks",
        "description": "Search the on-call runbooks by keyword.",
        "parameters": {
            "type": "object",
            "properties": {"query": {"type": "string"}},
            "required": ["query"],
        },
    },
}]


@observe(span_type="TOOL")
def search_runbooks(query: str) -> list[str]:
    return [text for key, text in RUNBOOKS.items() if key in query.lower()]


@observe(name="triage_agent", preserve_global_context=True)
def triage_agent(alert: str) -> str:
    messages = [
        {"role": "system", "content": "You triage alerts. Search the runbooks, then give the next step in one sentence."},
        {"role": "user", "content": alert},
    ]
    while True:
        response = client.chat.completions.create(
            model="gpt-5-mini", messages=messages, tools=TOOLS
        )
        message = response.choices[0].message
        if not message.tool_calls:
            return message.content
        messages.append(message)
        for call in message.tool_calls:
            result = search_runbooks(**json.loads(call.function.arguments))
            messages.append(
                {"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)}
            )


@app.post("/triage")
def triage(body: dict):
    return {"next_step": triage_agent(body["alert"])}

The tested environment used Python 3.12, lmnr 0.9.4, openai 3.62.2, OpenTelemetry SDK and gRPC exporter 1.45.3, FastAPI instrumentation 0.66b3 and FastAPI 0.165.0.

Supply your model credentials separately. Ensure LMNR_PROJECT_API_KEY is absent from the application environment, then start the service:

OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 uvicorn app:app

Send POST /triage a JSON body containing an alert string. This is a demonstration loop; add execution limits before using it for production triage.

With no Laminar key, this SDK's exporter reads OTEL_EXPORTER_OTLP_ENDPOINT and OTEL_EXPORTER_OTLP_HEADERS. Both providers therefore send to the Collector. Setting a Laminar key in the application instead selects Laminar's direct export path.

preserve_global_context=True joins the top-level agent span to the active FastAPI context. The observe reference documents this option.

What arrived in each backend

One local request produced trace be9f0c025352b5e7bd47f6ed672a85a9 in both backends:

  • Tempo stored POST /triage, its child triage_agent, and the agent's two openai.chat spans and search_runbooks span. Model spans included token counts and full message histories in GenAI attributes.
  • Laminar stored the HTTP and agent spans under the same trace ID. It stored triage_agent with a null parent and retained its nested children. Its transcript view showed both model turns and the intervening tool call.

The transcript reported turns of 3.19 and 3.76 seconds, with 160/159 and 221/226 input/output tokens respectively. Its header reported 6.95 seconds, 766 tokens and $0.0009. The two model turns accounted for nearly all the reported duration; the transcript also exposed what each turn received and returned.

Use Grafana Alloy instead

This Alloy configuration implements the same basic fan-out:

otelcol.receiver.otlp "default" {
  grpc {
    endpoint = "0.0.0.0:4317"
  }
  output {
    traces = [otelcol.processor.batch.default.input]
  }
}

otelcol.processor.batch "default" {
  output {
    traces = [
      otelcol.exporter.otlp.tempo.input,
      otelcol.exporter.otlp.laminar.input,
    ]
  }
}

otelcol.exporter.otlp "tempo" {
  client {
    endpoint = "tempo:4317"
    tls {
      insecure = true
    }
  }
}

otelcol.exporter.otlp "laminar" {
  client {
    endpoint = "api.lmnr.ai:8443"
    headers = {
      "authorization" = "Bearer " + sys.env("LMNR_PROJECT_API_KEY"),
    }
  }
}

Alloy v1.22.0 passed validation, and the local-endpoint version delivered the trace to both backends. This minimal configuration leaves SDK service names unchanged. A separately tested otelcol.processor.transform before the Tempo exporter applied the Collector example's OTTL rename successfully.

Add a Laminar branch to Datadog's Collector configuration

Datadog's current guide, "Set Up the OpenTelemetry Collector", uses an otlp_http exporter with a dd-api-key header. Its span_metrics and forward/traces_sample connectors separate metrics computation from trace sampling.

Retain that configuration and merge these additions into the existing sections. Do not replace the existing pipelines or duplicate a batch definition you already have.

processors:
  batch: {}

exporters:
  otlp_grpc/laminar:
    endpoint: api.lmnr.ai:8443
    headers:
      authorization: Bearer ${env:LMNR_PROJECT_API_KEY}

service:
  pipelines:
    traces/laminar:
      receivers: [otlp]
      processors: [batch]
      exporters: [otlp_grpc/laminar]

The merged configuration passed Collector Contrib 0.166.0 validation. With placeholder credentials, the Datadog endpoint returned HTTP 403 and Laminar returned Unauthenticated. Those responses establish endpoint reachability in that test, not successful ingestion, attribute retention or display in either cloud account.

Before deploying this branch, submit a known trace with valid credentials and inspect it in your Datadog account. Confirm its span count, hierarchy and attributes rather than treating validation as an ingestion test.

If you use the Datadog Agent's OTLP receiver, retain its host-local deployment: Datadog documents sending data from another host to an Agent as unsupported. Either introduce an appropriate Collector route or keep exporting request spans to the local Agent and use the correlated in-process setup below.

Export in-process without a Collector

Python: correlate separate span sets

Keep the Python code above, point its service exporter at your existing OTLP destination, and supply Laminar's key:

OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 \
LMNR_PROJECT_API_KEY=your-project-key \
uvicorn app:app

In the local test, Tempo received HTTP spans and Laminar received agent spans, both under trace 056ac55b9aea36838b31027bd516f280. Tempo did not receive the agent spans. Use Collector fan-out when that detail must also land in your existing backend.

TypeScript: share the Laminar span processor

This initialization was tested with Node 24.22.2, @lmnr-ai/lmnr 0.9.9, @opentelemetry/sdk-node 0.301.2 and @opentelemetry/sdk-trace 3.1.1. For in-process exports, set LMNR_PROJECT_API_KEY in the application and point OTEL_EXPORTER_OTLP_ENDPOINT at the existing backend, as in the Python setup.

import { NodeSDK } from "@opentelemetry/sdk-node";
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-grpc";
import { HttpInstrumentation } from "@opentelemetry/instrumentation-http";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { Laminar, LaminarSpanProcessor } from "@lmnr-ai/lmnr";
import OpenAI from "openai";

const laminarProcessor = new LaminarSpanProcessor();

const sdk = new NodeSDK({
  resource: resourceFromAttributes({ "service.name": "triage-api" }),
  spanProcessors: [
    new BatchSpanProcessor({ exporter: new OTLPTraceExporter() }),
    laminarProcessor,
  ],
  instrumentations: [new HttpInstrumentation()],
});
sdk.start();

Laminar.initialize({
  spanProcessor: laminarProcessor,
  inheritGlobalContext: true,
  instrumentModules: { OpenAI },
});

Wrap the agent and tool with observe, naming the agent triage_agent and setting the tool's spanType to TOOL. The TypeScript instrumentation reference documents the initialization options.

Context inheritance alone produced correct raw parent IDs but flattened agent nesting in Laminar in the tested version. Sharing one LaminarSpanProcessor between NodeSDK and Laminar fixed the displayed hierarchy: POST → triage_agent → model and tool spans. Tempo received the request span with the same trace ID and additional Laminar attributes.

For Collector fan-out instead, remove the BatchSpanProcessor, point OTEL_EXPORTER_OTLP_ENDPOINT at the Collector and omit the Laminar key. This variant delivered the full nested tree to both local backends.

Keep the constructor shown: sdk-trace 3.1.1 takes new BatchSpanProcessor({ exporter }). The positional-exporter form failed during export in the test.

Match the trace across tools

Laminar displayed the first trace ID as be9f0c02-5352-b5e7-bd47-f6ed672a85a9. Removing the dashes gives its 32-character hexadecimal representation for Tempo lookup.

In the tested Tempo version, search output omitted leading zeros. Restore them to obtain 32 characters before converting to UUID form. The tested self-hosted Laminar route was /project/<project_id>/traces/<uuid>.

Datadog documents 32-character hexadecimal IDs for its pruned-trace API, which is marked unstable. That documentation does not establish a tested UI jump from this example.

For follow-up investigation, see Laminar's SQL editor. For agents crossing service or queue boundaries, see distributed tracing for AI agents.

Check sampling, resources and payloads

Head sampling affects the providers differently. With the Python application sampler set to ParentBased(TraceIdRatioBased(0)), Laminar received no agent spans. With the tested TypeScript provider sampled at zero, Laminar still received agent spans, but the missing HTTP parent broke the displayed nesting.

If Laminar needs every agent run while APM receives a sample, keep the necessary spans at the application and sample only the APM Collector pipeline. In the local test, a zero-percent Tempo sampler left Tempo empty while Laminar stored all eight spans. Review the resulting traffic volume before applying this policy broadly.

Check service.name on agent spans. In these SDK versions, Python used sys.argv[0]; TypeScript used laminar-tracer-resource. The service provider's name did not automatically carry over. The Collector transform above corrected the name in Tempo. Replace its hard-coded triage-api value appropriately when adapting it to multiple services.

Fan-out copies payloads as well as timing. Tempo received full model histories. These statements, added to the Tempo pipeline's transform, removed the two message attributes from its copy while leaving Laminar's copy intact:

          - delete_key(attributes, "gen_ai.input.messages")
          - delete_key(attributes, "gen_ai.output.messages")

This is field removal, not comprehensive redaction. Review tool data and other attributes for sensitive content. Datadog's exporter documentation also specifies a 3.2 MB trace-intake limit and warns about HTTP 413 responses from oversized batches.

Check authentication separately from routing. Laminar requires authorization: Bearer <project API key>. Laminar's OpenTelemetry docs note that the Python OpenTelemetry gRPC exporter requires a lowercase authorization key. A valid configuration file does not validate the project key.

Decide whether you need another backend

Datadog and Grafana also offer agent-oriented tooling. Datadog LLM Observability accepts supported GenAI or OpenInference spans; its OpenTelemetry documentation specifies dd_llmobs_enabled=true to enable conversion and notes attribute-conversion rules and a possible 3 to 5 minute delay. Grafana Cloud documents OpenLIT-based AI observability covering prompts, token usage, costs, agent invocations and evaluations.

Evaluate those offerings before adding another store. If your agent makes a few model calls per request and the same on-call team debugs it alongside the service, one backend can be enough.

Add Laminar when its transcript and trace-based checks fit your team's debugging workflow. In the local run, Laminar opened the request as a transcript with model inputs, outputs and tool activity. Beyond reading single runs, Laminar's Signals run a check you write in plain language, such as "the agent recommended a runbook it never retrieved", over finished traces and record each match as an event you can alert on. Keep latency and error alerts in Datadog or Grafana. Collector fan-out adds the agent view without replacing service instrumentation, but it duplicates selected trace data across stores, so account for retention, access and ingestion costs.

For background beyond the wiring, see OpenTelemetry for AI agents and agent observability.

FAQ

Can I keep an existing OpenAI instrumentor?

Yes, but choose one instrumentor for each client to avoid duplicate model spans. The tested Python SDK exposes disabled_instruments and Instruments.OPENAI for disabling its OpenAI integration. These runs used Laminar's OpenAI instrumentation; they do not establish transcript compatibility with every alternative library or model provider. Compare emitted fields with the span attribute reference and the GenAI semantic conventions guide.

Can Laminar receive only the agent spans?

Yes, a Collector filter can send only agent spans to Laminar while retaining other spans in your existing backend. In the tested Python setup, a filter in the Laminar pipeline dropped spans whose instrumentation scope was not lmnr.tracer. Laminar then received four agent spans while Tempo received eight total spans, retaining the shared trace ID. Treat that scope name as an instrumentation-specific routing rule, and recheck it when changing SDKs or instrumentors.

Can Laminar alert my team in Slack when an agent fails?

Yes, when a Signal identifies a failure and Slack notifications are configured. Laminar's alerts fire on Signal events and post to the in-app notification center and, if configured, to Slack and email. A Slack message carries the signal name, the extracted payload fields and a link to the trace, so the on-call engineer can inspect the failing run. Alert timing depends on when the Signal evaluates a finished trace. End-to-end alert latency was not measured in these tests; check it on your own traffic. Keep service-health alerts in Datadog or Grafana.

What happens when Laminar is unreachable?

Short local failures did not stop request handling or delivery to Tempo in the tested setups. In a local Collector failure test, the Laminar exporter logged retries while Tempo still stored all eight spans. In the Python in-process test, a refused Laminar connection logged a retry and the request returned HTTP 200. These observations do not establish lossless delivery or isolation during a prolonged outage. Monitor exporter failures and queue behavior, and test your deployment's outage limits.