OpenAI Agents SDK Tracing: Correlate App Spans

The Agents SDK trace and your OpenTelemetry spans use different IDs. Join them with a run ID, the SDK trace ID and groupId, without copying prompts or outputs.

Ephraim Duncan

To correlate OpenAI Agents SDK tracing with OpenTelemetry, treat them as two separate systems and join them with attributes your application owns: a stable run ID, the SDK trace ID, and a groupId. The SDK does not adopt your OpenTelemetry trace context, and your spans do not carry the SDK's trace ID unless you put it there.

That is the whole trick, and it is cheap. You mint one run ID in your HTTP handler, stamp it on your OpenTelemetry span, pass it to the SDK as the trace's groupId, and write the SDK trace ID back onto your span. Now either side can find the other. Nothing from your prompts or outputs gets copied anywhere.

This post walks through that join in TypeScript, shows where a custom trace processor fits, and covers the failure modes: missing, split and duplicated runs. Don't assume the SDK exports to your OpenTelemetry backend on its own. It doesn't.

Two trace systems, not one: SDK tracing vs OpenTelemetry spans

The Agents SDK has its own tracing layer, and your OpenTelemetry instrumentation is a different layer with different IDs. The SDK's trace ID and your OpenTelemetry trace ID come from different providers and use different formats. They are not the same value, and neither system reads the other's context.

That has a practical consequence. Your HTTP handler span, your database spans and your queue spans live in the OpenTelemetry trace. The agent's generations, tool calls, handoffs and guardrails live in the SDK trace. Unless you link them, a slow request shows you a long agent.run span on one side and a detailed SDK trace on the other, and nothing says they are the same request.

So pick a join key you control. The rest of this post builds one from three pieces: a run ID you generate, the SDK trace ID, and groupId. If you want the broader picture of keeping parent and child links intact across async code, LLM Tracing: Fix Async Parent and Child Span Links covers that side.

What the Agents SDK traces by default (and where it goes)

By default, the SDK records a trace capturing the internal steps of an agent run. Each trace is a single end-to-end operation, made of spans for the individual steps inside it.

Out of the box, those traces go to OpenAI's tracing backend through the default OpenAI exporter, where you can view them in the OpenAI Traces dashboard. They do not go to your OpenTelemetry collector or any OTLP endpoint. Nothing in the default setup bridges the two worlds.

Two more defaults matter for correlation. First, one call to run() creates one trace unless you wrap several calls in a higher-level trace. Second, the trace has a name, a trace ID and an optional groupId. The groupId is the field built for linking multiple traces from one conversation or workflow, and it is the hook you will use to carry your own ID.

Create an application-owned run ID and span around the agent run

Generate the run ID yourself, at the edge, before the agent starts. A UUID is fine. You own it, it appears in your logs, and it exists even if the SDK trace never gets created.

Then open an OpenTelemetry span around the agent run and put the ID on it:

import { trace as otel, SpanStatusCode } from "@opentelemetry/api";
import { randomUUID } from "node:crypto";

const tracer = otel.getTracer("my-app");

export async function handleChat(conversationId: string, message: string) {
  const runId = randomUUID();
  return tracer.startActiveSpan("agent.run", async (span) => {
    span.setAttribute("app.run_id", runId);
    span.setAttribute("app.conversation_id", conversationId);
    try {
      return await runAgentWithSdkTrace(runId, conversationId, message);
    } catch (err) {
      span.recordException(err as Error);
      span.setStatus({ code: SpanStatusCode.ERROR });
      throw err;
    } finally {
      span.end();
    }
  });
}

Use startActiveSpan so the HTTP handler span becomes the parent and tool code you instrument later inherits the same trace. Keep attribute names in your own namespace (app.run_id) so they cannot collide with semantic convention keys.

Join the two with withTrace, groupId and shared attributes

Wrap the agent call in withTrace, pass your run ID as the groupId, then read the SDK trace ID and write it back onto your OpenTelemetry span. The SDK supports withTrace(name, callback, { groupId }) to group related runs under one trace, and a stable conversation or workflow ID is the intended groupId.

import { Agent, run, withTrace, getCurrentTrace } from "@openai/agents";
import { trace as otel } from "@opentelemetry/api";

async function runAgentWithSdkTrace(
  runId: string,
  conversationId: string,
  message: string,
) {
  return withTrace(
    "support-chat",
    async () => {
      const sdkTrace = getCurrentTrace();
      const span = otel.getActiveSpan();
      if (sdkTrace && span) {
        span.setAttribute("openai.agents.trace_id", sdkTrace.traceId);
        span.setAttribute("openai.agents.group_id", runId);
      }
      return run(agent, message);
    },
    { groupId: runId },
  );
}

Now the join works in both directions. From an OpenTelemetry span you read openai.agents.trace_id and open that trace in the SDK dashboard. From an SDK trace you read the groupId, which is your app.run_id, and search your OpenTelemetry backend for it.

If you want one trace to cover multiple run() calls, such as a plan step followed by an execute step, put them inside the same withTrace callback. Use the conversation ID as the groupId when you want every turn of a chat linked. Use the per-request run ID when you want one request per group. Pick one and stay consistent.

W3C traceparent propagation is a separate matter. It carries OpenTelemetry context across service boundaries, such as from your API to a worker. It does not make the SDK adopt that trace ID. Propagate traceparent for your own spans, and carry the run ID in the job payload so the worker can rebuild the same join. Generative AI Monitoring: Trace Queued Agent Jobs shows that pattern.

Add a custom trace processor without replacing default export

Use addTraceProcessor when you want your own code to observe SDK traces while default export keeps working. addTraceProcessor(processor) adds a processor alongside the default OpenAI exporter. setTraceProcessors([processor]) replaces the configured processors, so default OpenAI export stops unless your processor sends traces there itself.

A processor is a good place to do the join mechanically. On trace start, record the pair of SDK trace ID and groupId. On span end, copy only metadata you chose, such as span type, duration and error flag, onto an OpenTelemetry span or metric.

import { addTraceProcessor } from "@openai/agents";

addTraceProcessor({
  async onTraceStart(t) { /* record t.traceId and t.groupId */ },
  async onTraceEnd(t) {},
  async onSpanStart(s) {},
  async onSpanEnd(s) { /* emit span type, duration, error flag only */ },
  async shutdown() {},
  async forceFlush() {},
});

Community and vendor integrations exist that ship SDK traces to other backends as external tracing processors, and the SDK docs list them. If you use one, still add the app-owned run ID, because it is the one key you control.

A related note for the Python side: OpenInference publishes instrumentation for the OpenAI Agents SDK that emits OpenTelemetry spans, and Logfire documents its own Agents SDK support. Both get SDK activity into OpenTelemetry. They solve export. The run ID join in this post solves correlation, and you want it either way.

Keep prompts and outputs out of the correlation layer

The join needs identifiers, never content. A run ID, a trace ID and a groupId are enough to link systems, so there is no reason to copy prompts, tool arguments or model outputs onto your application spans.

Turn off sensitive data in SDK spans with traceIncludeSensitiveData: false in the run configuration. That omits model-generation and function-call inputs and outputs from the relevant spans. Set it deliberately and test it, because it only controls spans and your own logging can still leak content around it.

A few rules keep the correlation layer clean:

  • Attribute values are IDs, counts, durations and enum-like labels. Not free text.

  • Do not use the user's message as a span name. Use fixed names like agent.run and tool.lookup_order.

  • If you must record content for debugging, do it in a separate, access-controlled path with its own retention.

On the telemetry.dev side, prompt capture can be turned off per environment before storage, and redaction patterns apply but cannot catch all sensitive data. So the safest design is the one above: never put the content on the span in the first place. For how capture behaves before export, see OpenTelemetry GenAI Prompt Capture: Inspect Before Export.

Verify the join in your OpenTelemetry backend, including telemetry.dev via OTLP/HTTP

Verify with a single request: run it, copy the run ID from your response logs, and confirm both sides resolve from that one value. Any OTLP/HTTP-capable backend works for the OpenTelemetry half. telemetry.dev is LLM observability for AI apps and agents built on OpenTelemetry, and it accepts spans from any OTLP/HTTP exporter or OpenTelemetry Collector, so your agent.run spans, tool spans and attributes can be sent there like any other OTLP source. That does not make the SDK's own traces appear there. Only the spans your application creates go through your exporter.

A minimal check:

  1. Send one request through your handler and note the app.run_id.

  2. In your backend, search spans for app.run_id = <that value>. You should find exactly one agent.run span with openai.agents.trace_id set.

  3. Open that trace ID in the OpenAI Traces dashboard and confirm its groupId equals the run ID.

  4. Confirm that no span in your backend carries prompt or output text.

If you run an OpenTelemetry Collector in front, check exports as well. OpenTelemetry LLM Observability: Verify Exported Spans covers confirming spans actually left the process.

On semantic conventions: the OpenTelemetry GenAI conventions define attribute names for model calls and agent operations. Where a convention fits, such as model name or token usage, use it. Keep join keys like app.run_id in your own namespace, since they are your correlation contract and not a standard.

Troubleshooting: missing, split or duplicated runs

Most correlation bugs come down to three shapes: a trace you cannot find, one run split into several, or one run counted twice.

Missing SDK trace ID on your span. getCurrentTrace() returns nothing outside a trace. Read it inside the withTrace callback, not before it. Also check that tracing is not disabled in the environment or run config.

Missing runs in the dashboard of a short-lived worker. The default batch processor exports in the background every few seconds. In a serverless handler or a worker that exits right after the run, flush before shutdown (OpenAI Agents Python docs describe the batching and immediate-export behavior). Missing OpenTelemetry spans have a different cause: sampling or an unflushed exporter. See LLM Trace Sampling: Diagnose Missing Runs.

One request split into several SDK traces. Each run() creates its own trace unless wrapped. Wrap multi-call workflows in one withTrace, or rely on a shared groupId so they still join by your run ID.

Duplicated runs. Two causes show up. You called addTraceProcessor in module scope that executes twice, so every span is processed twice. Or you stacked an export integration and your own processor, both emitting to the same backend. Register processors once at startup.

Replaced default export by accident. If SDK traces vanished from the OpenAI dashboard after adding a processor, you probably called setTraceProcessors. Switch to addTraceProcessor, or include an OpenAI exporter in the list.

For agents that fan out tool calls, see Parallel Tool Calls: Trace Slow Agent Fan-Out and Agent Handoff Tracing: Follow Work Across Agents for keeping parentage clear.

Own the run ID, and the two trace systems stop being a problem

The Agents SDK's tracing and your OpenTelemetry spans will stay separate, and that is fine. What makes them useful together is a run ID you generate, the SDK trace ID written onto your span, and the same ID passed as groupId, with no prompt or output text crossing between them. Add that join to one handler this week, send the application spans to telemetry.dev over OTLP/HTTP from the free plan (30k units), and confirm a single request resolves on both sides.

Share this article

Related posts