Trace Temporal Agents with CtrlB
This guide shows how to trace AI agents that run on Temporal. Each Workflow becomes one trace in CtrlB, with Temporal's client, Workflow and Activity spans, and the LLM calls your Activities make. The LLM spans follow the OpenTelemetry GenAI semantic conventions, so CtrlB's AI Observability pages show their model, provider and token use.
Temporal Worker (Temporal tracing + LLM spans) → OTLP/HTTP → CtrlB
SDKs: Python · Go · TypeScript · Java
To collect Temporal Cloud's own metrics (Workflow rates, backlogs, limits), see Temporal Cloud.
Overview
Every SDK section sets up the same three things:
- A tracer provider that sends spans to CtrlB over OTLP/HTTP.
- Temporal's tracing (a plugin or interceptors from the Temporal SDK). It creates spans named
StartWorkflow:<Workflow type>,RunWorkflow:<Workflow type>,StartActivity:<Activity name>andRunActivity:<Activity name>, and carries the trace context from the client to the Worker in Temporal's headers. - LLM spans around each model call, with
gen_ai.*attributes, inside an optional agent span.
A Workflow whose Activity runs one agent turn looks like this (the Activity is registered as ReviewOrder; in Python it would be review_order):
StartWorkflow:ReviewOrderWorkflow (process that starts the Workflow)
└─ RunWorkflow:ReviewOrderWorkflow (Worker)
└─ StartActivity:ReviewOrder
└─ RunActivity:ReviewOrder
└─ invoke_agent order-reviewer (agent span)
└─ chat gpt-4o-mini (LLM span)
CtrlB reads these attributes:
| Attribute | Example | Notes |
|---|---|---|
gen_ai.operation.name | chat, invoke_agent | Required. CtrlB's AI pages only include a dataset whose spans have it |
gen_ai.request.model | gpt-4o-mini | On LLM spans |
gen_ai.provider.name | openai | On LLM spans. Older instrumentations send gen_ai.system instead; CtrlB reads either |
gen_ai.usage.input_tokens, gen_ai.usage.output_tokens | 28, 12 | On LLM spans |
gen_ai.agent.name | order-reviewer | Optional. Set it on the invoke_agent span; CtrlB counts agent runs from these spans and groups the LLM calls inside them |
gen_ai.tool.name | lookup_order | Optional, on tool-call spans |
The examples use OpenAI's client libraries. Other providers work the same way if their spans carry these attributes.
In Every SDK
- Set up tracing in the Worker and in the process that starts Workflows. Without it, the
StartWorkflowspan is missing. - Flush spans before a short-lived process exits. Each section names the call.
- Make LLM calls in Activities, not in Workflow code.
- Turn off the LLM client's own retries, so Temporal's retry policy owns them. Each attempt then gets its own
RunActivityspan.
Versions Used
The examples use these versions:
| SDK | Versions |
|---|---|
| Python 3.14 | temporalio[opentelemetry] 1.37.0, OpenTelemetry SDK 1.45.2, opentelemetry-instrumentation-genai-openai 1.3b0, openai 3.60.0 |
| Go 1.27 | go.temporal.io/sdk v1.52.0, contrib/opentelemetry-v2 v0.2.0, OpenTelemetry Go v1.47.0, openai-go/v3 v3.108.0 |
| TypeScript, Node 24 | @temporalio/* 1.27.0, OpenTelemetry JS SDK 2.12.1, openai 7.65.0 |
| Java 21 | temporal-sdk and temporal-opentracing 1.41.1, OpenTelemetry instrumentation BOM 2.34.0-alpha, openai-java 4.106.0 |
Prerequisites
Before beginning the setup, ensure you have:
- Your CtrlB instance host and API token. If you don't have them, contact your CtrlB representative or check your onboarding documentation
- A stream name for the traces, for example
temporal_agents. CtrlB stores the spans in a dataset with this name - A Temporal application whose Worker you can change. The examples connect to Temporal Cloud with an API key. For a self-hosted server without API keys, leave out the API key and TLS settings
- An API key for your LLM provider. OpenAI's clients read
OPENAI_API_KEY
Connection Settings
Every section sends traces to:
- Endpoint:
https://<INSTANCE_HOST>/engine/api/default/v1/traces - Headers:
Authorization: Basic <API_TOKEN>andstream-name: <STREAM_NAME>
Python, Go and TypeScript read these from the standard OpenTelemetry variables. Set them in every process that traces:
export OTEL_EXPORTER_OTLP_ENDPOINT=https://<INSTANCE_HOST>/engine/api/default
export OTEL_EXPORTER_OTLP_HEADERS="stream-name=<STREAM_NAME>,Authorization=Basic%20<API_TOKEN>"
- The exporters append
/v1/tracestoOTEL_EXPORTER_OTLP_ENDPOINT. Do not add it yourself. %20is the percent-encoded space afterBasic. A plain space also works with these SDKs.
The examples also read these variables:
export TEMPORAL_ADDRESS=<TEMPORAL_ADDRESS> # your Namespace's gRPC endpoint
export TEMPORAL_NAMESPACE=<TEMPORAL_NAMESPACE> # for example my-namespace.a1b2c
export TEMPORAL_API_KEY=<TEMPORAL_API_KEY> # a Temporal Cloud API key with access to the Namespace
export OPENAI_API_KEY=<OPENAI_API_KEY>
export CTRLB_API_TOKEN=<API_TOKEN> # Java only; the other SDKs use OTEL_EXPORTER_OTLP_HEADERS
For CtrlB's general OpenTelemetry setup in each language, see OpenTelemetry SDKs.
Python
Step 1: Install
pip install "temporalio[opentelemetry]==1.37.0" \
opentelemetry-sdk==1.45.2 opentelemetry-exporter-otlp-proto-http==1.45.2 \
opentelemetry-instrumentation-genai-openai==1.3b0 opentelemetry-util-genai==1.3b0 \
openai==3.60.0
Use opentelemetry-instrumentation-genai-openai. At the versions above, the older opentelemetry-instrumentation-openai-v2 package (now deprecated) does not load with openai 3.x.
Step 2: Send Spans to CtrlB
Temporal's create_tracer_provider() gives Workflow spans deterministic IDs and exports nothing while a Workflow replays, so replays don't duplicate spans:
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from temporalio.contrib.opentelemetry import create_tracer_provider
def setup_tracing(service_name: str):
provider = create_tracer_provider(resource=Resource.create({SERVICE_NAME: service_name}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) # reads OTEL_EXPORTER_OTLP_*
trace.set_tracer_provider(provider)
return provider
Call it first thing in each process, before connecting to Temporal. In the Worker, also turn on the OpenAI instrumentation:
from opentelemetry.instrumentation.genai.openai import OpenAIInstrumentor
provider = setup_tracing("review-order-worker") # in the starter: setup_tracing("review-order-starter")
OpenAIInstrumentor().instrument() # Worker only
Step 3: Trace Temporal
Add the plugin to the client. Workers created from this client use it too:
import os
from temporalio.client import Client
from temporalio.contrib.opentelemetry import OpenTelemetryPlugin
client = await Client.connect(
os.environ["TEMPORAL_ADDRESS"],
namespace=os.environ["TEMPORAL_NAMESPACE"],
api_key=os.environ["TEMPORAL_API_KEY"],
tls=True,
plugins=[OpenTelemetryPlugin(add_temporal_spans=True)],
)
add_temporal_spans=True creates the Temporal spans. Without it, the plugin only passes the trace context along.
Step 4: Trace LLM Calls
With the instrumentation on, every OpenAI call becomes a chat <model> span. Wrap each agent turn in an invoke_agent span to name the agent:
from openai import AsyncOpenAI
from opentelemetry import trace
from temporalio import activity
tracer = trace.get_tracer(__name__)
_openai: AsyncOpenAI | None = None
def openai_client() -> AsyncOpenAI:
global _openai
if _openai is None:
_openai = AsyncOpenAI(max_retries=0) # reads OPENAI_API_KEY
return _openai
@activity.defn
async def review_order(order_id: str) -> str:
with tracer.start_as_current_span(
"invoke_agent order-reviewer",
attributes={"gen_ai.operation.name": "invoke_agent", "gen_ai.agent.name": "order-reviewer"},
):
response = await openai_client().chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": f"Review order {order_id}"}],
)
return response.choices[0].message.content or ""
- In Workflow code, import the Activities module inside
workflow.unsafe.imports_passed_through(), soopenaiis never loaded in the Workflow sandbox. - A normal exit flushes the provider. If the process can be stopped abruptly, call
provider.force_flush()before it exits. - Prompts and replies are not recorded by default. The instrumentation can record them; see its documentation for
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT.
OpenTelemetryPlugin and create_tracer_provider() are marked experimental by Temporal, and the GenAI instrumentation is in beta.
Go
Step 1: Install
go get go.temporal.io/sdk@v1.52.0 go.temporal.io/sdk/contrib/opentelemetry-v2@v0.2.0 \
go.opentelemetry.io/otel@v1.47.0 go.opentelemetry.io/otel/sdk@v1.47.0 \
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp@v1.47.0 \
github.com/openai/openai-go/v3@v3.108.0
Step 2: Send Spans to CtrlB
Use Temporal's replay-safe tracer provider as the global provider. Call this first in each process:
import (
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.41.0"
temporalotel "go.temporal.io/sdk/contrib/opentelemetry-v2"
)
func InitTracing(ctx context.Context, serviceName string) (*temporalotel.ReplaySafeTracerProvider, error) {
exporter, err := otlptracehttp.New(ctx) // reads OTEL_EXPORTER_OTLP_*
if err != nil {
return nil, err
}
res, err := resource.New(ctx, resource.WithAttributes(semconv.ServiceName(serviceName)))
if err != nil {
return nil, err
}
tp := temporalotel.NewReplaySafeTracerProvider(sdktrace.WithBatcher(exporter), sdktrace.WithResource(res))
otel.SetTracerProvider(tp)
return tp, nil // defer tp.Shutdown(ctx) to flush spans on exit
}
Step 3: Trace Temporal
import (
"os"
"go.temporal.io/sdk/client"
temporalotel "go.temporal.io/sdk/contrib/opentelemetry-v2"
"go.temporal.io/sdk/interceptor/tracing"
"go.temporal.io/sdk/worker"
)
plugin, err := temporalotel.NewPlugin(temporalotel.PluginOptions{
TracerOptions: tracing.TracerOptions{AddTemporalSpans: true},
})
if err != nil {
return err
}
c, err := client.Dial(client.Options{
HostPort: os.Getenv("TEMPORAL_ADDRESS"),
Namespace: os.Getenv("TEMPORAL_NAMESPACE"),
Credentials: client.NewAPIKeyStaticCredentials(os.Getenv("TEMPORAL_API_KEY")), // also turns on TLS
Plugins: []client.Plugin{plugin},
})
if err != nil {
return err
}
w := worker.New(c, "<TASK_QUEUE>", worker.Options{}) // inherits the plugin
AddTemporalSpans: true creates the Temporal spans. Without it, the plugin only passes the trace context along, and the LLM span becomes a trace of its own.
Step 4: Trace LLM Calls
This guide writes the LLM span by hand: wrap each call in a span with the GenAI attributes. Pass the Activity's ctx, so the span sits under the Activity:
import (
"context"
"github.com/openai/openai-go/v3"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.41.0"
"go.opentelemetry.io/otel/trace"
)
var llmTracer = otel.Tracer("llm")
func ChatCompletion(ctx context.Context, llm openai.Client,
params openai.ChatCompletionNewParams) (*openai.ChatCompletion, error) {
model := string(params.Model)
ctx, span := llmTracer.Start(ctx, "chat "+model,
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
semconv.GenAIOperationNameChat,
semconv.GenAIProviderNameOpenAI,
semconv.GenAIRequestModel(model),
))
defer span.End()
resp, err := llm.Chat.Completions.New(ctx, params)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return nil, err
}
span.SetAttributes(
semconv.GenAIResponseModel(resp.Model),
semconv.GenAIUsageInputTokens(int(resp.Usage.PromptTokens)),
semconv.GenAIUsageOutputTokens(int(resp.Usage.CompletionTokens)),
)
return resp, nil
}
In the Activity, wrap the agent turn in an invoke_agent span. Create the client with openai.NewClient(option.WithMaxRetries(0)) (github.com/openai/openai-go/v3/option); it reads OPENAI_API_KEY:
type Activities struct{ LLM openai.Client }
func (a *Activities) ReviewOrder(ctx context.Context, orderID string) (string, error) {
ctx, span := llmTracer.Start(ctx, "invoke_agent order-reviewer",
trace.WithAttributes(semconv.GenAIOperationNameInvokeAgent, semconv.GenAIAgentName("order-reviewer")))
defer span.End()
resp, err := ChatCompletion(ctx, a.LLM, openai.ChatCompletionNewParams{
Model: openai.ChatModelGPT4oMini,
Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("Review order " + orderID)},
})
if err != nil {
return "", err
}
return resp.Choices[0].Message.Content, nil
}
- Import the GenAI constants from
semconv/v1.41.0. At the versions above, later Go semconv packages no longer include thegen_aikeys. NewPluginpanics if the global provider was not created byNewReplaySafeTracerProvider.- In Workflow code, create spans with
temporalotel.Tracer(...), neverotel.Tracer. - Use the v2 plugin rather than the older
contrib/opentelemetryinterceptor, which uses random span IDs, so a replay can leave spans whose parent is never exported.
contrib/opentelemetry-v2 is marked experimental by Temporal.
TypeScript
Step 1: Install
npm install --save-exact @temporalio/client@1.27.0 @temporalio/worker@1.27.0 @temporalio/workflow@1.27.0 \
@temporalio/interceptors-opentelemetry-v2@1.27.0 \
@opentelemetry/api@1.9.1 @opentelemetry/sdk-trace-node@2.12.1 @opentelemetry/resources@2.12.1 \
@opentelemetry/exporter-trace-otlp-proto@0.223.2 openai@7.65.0
Keep these exact versions. @temporalio/interceptors-opentelemetry-v2 targets the OpenTelemetry JS SDK 2.x (sdk-trace-node, resources), and an unpinned install now pulls in SDK 3.x packages.
Step 2: Send Spans to CtrlB
Create instrumentation.ts and load it before anything else, for example node --require ./lib/instrumentation.js lib/worker.js. Use it in the Worker and in the process that starts Workflows, with a different OTEL_SERVICE_NAME for each:
import { NodeTracerProvider, BatchSpanProcessor } from '@opentelemetry/sdk-trace-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { resourceFromAttributes } from '@opentelemetry/resources';
export const resource = resourceFromAttributes({
'service.name': process.env.OTEL_SERVICE_NAME ?? 'review-order-worker',
});
export const spanProcessor = new BatchSpanProcessor(new OTLPTraceExporter()); // reads OTEL_EXPORTER_OTLP_*
const provider = new NodeTracerProvider({ resource, spanProcessors: [spanProcessor] });
provider.register();
export const shutdownTracing = () => provider.shutdown(); // flushes spans; call before exit
Step 3: Trace Temporal
One plugin covers the client, the Activities and the Workflows. Workflow code needs no tracing code: its spans leave the Workflow sandbox through a sink and reach spanProcessor, so pass the same resource and spanProcessor:
import { Client, Connection } from '@temporalio/client';
import { NativeConnection, Worker } from '@temporalio/worker';
import { OpenTelemetryPlugin } from '@temporalio/interceptors-opentelemetry-v2';
import { resource, spanProcessor } from './instrumentation';
import * as activities from './activities';
const otel = new OpenTelemetryPlugin({ resource, spanProcessor });
const address = process.env.TEMPORAL_ADDRESS!;
const namespace = process.env.TEMPORAL_NAMESPACE!;
const apiKey = process.env.TEMPORAL_API_KEY!;
// Worker
const connection = await NativeConnection.connect({ address, tls: true, apiKey });
const worker = await Worker.create({
connection,
namespace,
taskQueue: '<TASK_QUEUE>',
workflowsPath: require.resolve('./workflows'),
activities,
plugins: [otel],
});
// Process that starts Workflows
const client = new Client({
connection: await Connection.connect({ address, tls: true, apiKey }),
namespace,
plugins: [otel],
});
Step 4: Trace LLM Calls
This guide writes the spans by hand. Add a helper for the LLM span and one for the agent span:
import { trace, SpanKind, SpanStatusCode } from '@opentelemetry/api';
import type OpenAI from 'openai';
const tracer = trace.getTracer('llm');
export function tracedChat(openai: OpenAI, params: OpenAI.Chat.ChatCompletionCreateParamsNonStreaming) {
return tracer.startActiveSpan(
`chat ${params.model}`,
{
kind: SpanKind.CLIENT,
attributes: {
'gen_ai.operation.name': 'chat',
'gen_ai.provider.name': 'openai',
'gen_ai.request.model': params.model,
},
},
async (span) => {
try {
const res = await openai.chat.completions.create(params);
span.setAttribute('gen_ai.response.model', res.model);
if (res.usage) {
span.setAttribute('gen_ai.usage.input_tokens', res.usage.prompt_tokens);
span.setAttribute('gen_ai.usage.output_tokens', res.usage.completion_tokens);
}
return res;
} catch (err) {
span.setStatus({ code: SpanStatusCode.ERROR, message: String(err) });
throw err;
} finally {
span.end();
}
},
);
}
export function invokeAgent<T>(agentName: string, fn: () => Promise<T>): Promise<T> {
return tracer.startActiveSpan(
`invoke_agent ${agentName}`,
{ attributes: { 'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': agentName } },
async (span) => {
try {
return await fn();
} catch (err) {
span.setStatus({ code: SpanStatusCode.ERROR, message: String(err) });
throw err;
} finally {
span.end();
}
},
);
}
In the Activity:
import OpenAI from 'openai';
import { invokeAgent, tracedChat } from './genai';
const openai = new OpenAI({ maxRetries: 0 }); // reads OPENAI_API_KEY
export async function reviewOrder(orderId: string): Promise<string> {
const res = await invokeAgent('order-reviewer', () =>
tracedChat(openai, { model: 'gpt-4o-mini', messages: [{ role: 'user', content: `Review order ${orderId}` }] }),
);
return res.choices[0]?.message.content ?? '';
}
For openai 4.19 to 6.x, @opentelemetry/instrumentation-openai 0.21.0 creates the LLM spans without the tracedChat helper. Install it with @opentelemetry/instrumentation@0.223.2 (an unpinned install conflicts with the versions above) and register it with registerInstrumentations() in instrumentation.ts. At version 0.21.0 it does not patch openai 7.x.
- Call
shutdownTracing()before a short-lived process exits. Node does not flush spans on exit by itself. - If you bundle Workflow code with
bundleWorkflowCode, pass the samepluginsthere. - Don't switch from the older
@temporalio/interceptors-opentelemetryto the-v2package while Workflows are running: the two are not replay-compatible.
@temporalio/interceptors-opentelemetry-v2 is marked experimental by Temporal.
Java
Step 1: Add Dependencies
Temporal's Java SDK traces through OpenTracing. OpenTelemetry's OpenTracing shim turns those spans into OpenTelemetry spans. Add to pom.xml:
<dependencyManagement>
<dependencies>
<!-- Temporal and openai-java pull in different Jackson versions; pin one -->
<dependency>
<groupId>com.fasterxml.jackson</groupId>
<artifactId>jackson-bom</artifactId>
<version>2.18.12</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Also sets the OpenTelemetry SDK versions (1.68.0) -->
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-instrumentation-bom-alpha</artifactId>
<version>2.34.0-alpha</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.temporal</groupId>
<artifactId>temporal-sdk</artifactId>
<version>1.41.1</version>
</dependency>
<dependency>
<groupId>io.temporal</groupId>
<artifactId>temporal-opentracing</artifactId>
<version>1.41.1</version>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-sdk</artifactId>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-otlp</artifactId>
<exclusions>
<!-- openai-java uses OkHttp 4; use the JDK sender instead of the OkHttp 5 one -->
<exclusion>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-sender-okhttp</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-sender-jdk</artifactId>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-opentracing-shim</artifactId>
</dependency>
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.106.0</version>
</dependency>
<dependency>
<groupId>io.opentelemetry.instrumentation</groupId>
<artifactId>opentelemetry-openai-java-1.1</artifactId>
</dependency>
<!-- A logging binding, so Temporal's logs appear -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.36</version>
<scope>runtime</scope>
</dependency>
</dependencies>
Step 2: Send Spans to CtrlB
Configure the exporter in code, reading the token from CTRLB_API_TOKEN. Use it in the Worker and in the process that starts Workflows:
OtlpHttpSpanExporter exporter = OtlpHttpSpanExporter.builder()
.setEndpoint("https://<INSTANCE_HOST>/engine/api/default/v1/traces")
.addHeader("Authorization", "Basic " + System.getenv("CTRLB_API_TOKEN"))
.addHeader("stream-name", "<STREAM_NAME>")
.build();
OpenTelemetrySdk otel = OpenTelemetrySdk.builder()
.setTracerProvider(SdkTracerProvider.builder()
.setResource(Resource.getDefault().merge(Resource.create(
Attributes.of(AttributeKey.stringKey("service.name"), "review-order-worker"))))
.addSpanProcessor(BatchSpanProcessor.builder(exporter).build())
.build())
// Required: Temporal passes the trace context in its headers through these propagators
.setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance()))
.build();
// call otel.close() on shutdown to flush spans
Step 3: Trace Temporal
OpenTracingOptions tracing = OpenTracingOptions.newBuilder()
.setTracer(OpenTracingShim.createTracerShim(otel))
.build();
WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(
WorkflowServiceStubsOptions.newBuilder()
.setTarget(System.getenv("TEMPORAL_ADDRESS"))
.setEnableHttps(true)
.addApiKey(() -> System.getenv("TEMPORAL_API_KEY"))
.build());
// Client (Worker and the process that starts Workflows)
WorkflowClient client = WorkflowClient.newInstance(service, WorkflowClientOptions.newBuilder()
.setNamespace(System.getenv("TEMPORAL_NAMESPACE"))
.setInterceptors(new OpenTracingClientInterceptor(tracing))
.build());
// Worker only
WorkerFactory factory = WorkerFactory.newInstance(client, WorkerFactoryOptions.newBuilder()
.setWorkerInterceptors(new OpenTracingWorkerInterceptor(tracing))
.build());
Step 4: Trace LLM Calls
Wrap the OpenAI client with OpenTelemetry's instrumentation and give the wrapped client to your Activities. Each call becomes a chat <model> span:
OpenAIClient openai = OpenAITelemetry.builder(otel).build()
.wrap(OpenAIOkHttpClient.builder().fromEnv().maxRetries(0).build()); // reads OPENAI_API_KEY
In the Activity, wrap the agent turn in an invoke_agent span:
public String reviewOrder(String orderId) {
Span agent = otel.getTracer("llm").spanBuilder("invoke_agent order-reviewer")
.setAttribute("gen_ai.operation.name", "invoke_agent")
.setAttribute("gen_ai.agent.name", "order-reviewer")
.startSpan();
try (Scope scope = agent.makeCurrent()) {
ChatCompletion completion = openai.chat().completions().create(
ChatCompletionCreateParams.builder()
.model(ChatModel.GPT_4O_MINI)
.addUserMessage("Review order " + orderId)
.build());
return completion.choices().get(0).message().content().orElse("");
} finally {
agent.end();
}
}
- Without the W3C propagator, the spans from the client and the Worker end up in separate traces.
- When a Worker evicts a Workflow from its cache and replays it, the trace gets a second
RunWorkflowspan. This is how Temporal's OpenTracing interceptor works. - The OpenTelemetry Java agent's OpenAI instrumentation is declared for
openai-java1.1 to 2.x. Use the library wrapper above. - OpenTelemetry has deprecated the OpenTracing shim's public API. It is still the route Temporal's Java SDK uses.
opentelemetry-openai-java-1.1 is an alpha release.
View the Traces in CtrlB
- Open AI Observability → Traces. Each Workflow run that called a model is a row, with its LLM calls, tokens, model and service
- Filter by CtrlB dataset (your stream name), Model, Provider or Agent
- Open a row and select Trace to see the Temporal spans around the agent and LLM spans
The full traces, including Workflows that made no LLM calls, are on the Traces page.
Troubleshooting
No Traces Arrive
- Check
OTEL_EXPORTER_OTLP_ENDPOINTends at/engine/api/default, without/v1/traces(Java: the full/v1/tracesURL) - Check the
stream-nameheader is set - Check the API token and the
Basicprefix in theAuthorizationheader
The Dataset Is Missing from AI Observability
- The spans need
gen_ai.operation.name. Spans that use other conventions, such as OpenInference'sllm.*attributes, are not counted as AI spans
Agents Don't Appear as Agent Runs
- CtrlB counts agent runs from
invoke_agentspans withgen_ai.agent.name. A name set only on thechatspan is not an agent run
Spans Are Split into Several Traces
- Python: add
OpenTelemetryPlugin(add_temporal_spans=True)to the client, and callsetup_tracing()before connecting - Go: set
AddTemporalSpans: true, and pass the Activity'sctxto the LLM call - TypeScript: load
instrumentation.tswith--requirebefore other modules - Java: set the W3C propagator on the OpenTelemetry SDK
The Worker Fails at Startup
- Python raises
ValueErrorand Go panics if another global tracer provider was set first, for example by an OpenTelemetry auto-instrumentation launcher. Install Temporal's replay-safe provider as the only global provider
The StartWorkflow Span Is Missing
- The process that starts Workflows needs the same tracing setup, and must flush its spans before it exits