Best practices for custom instrumentation of Java LLM applications
The com.alibaba.loongsuite:otel-util-genai library provides custom instrumentation capabilities with GenAI semantics for Java LLM applications. It supports two scenarios: supplementing higher-level Spans (Agent, Tool, Workflow) on top of Application Real-Time Monitoring Service (ARMS) automatic instrumentation, or manually creating and reporting all GenAI Spans from scratch using the OpenTelemetry Java SDK. This topic introduces the basic Span types, key configurations, and step-by-step instrumentation examples.
Business scenarios
The otel-util-genai is applicable to the following two scenarios:
Integrated with ARMS Application Monitoring: Automatic instrumentation is already in place and Chat Spans are automatically collected by the agent. You need to supplement custom GenAI Spans and Attributes for Agent, Tool, Workflow, and other operations.
Fully manual instrumentation: No automatic agents are used, or the custom framework cannot collect data automatically. You need to manually create and report all GenAI Spans using the OpenTelemetry Java SDK and otel-util-genai.
The following table summarizes the differences between the two scenarios:
Step | With ARMS automatic instrumentation | Fully manual instrumentation |
Install dependencies | Required | Required |
Obtain Handler and Tracer | Required | Required |
Create Chat Span | Usually skipped (agent collects automatically) | Required |
Create Agent/Tool/Workflow Spans | Required | Required |
Key configurations | Required | Required |
Architecture
otel-util-genai creates various Invocations through the factory methods of GenAiTelemetryHandler. Each Invocation corresponds to a well-known gen_ai.operation.name:
Span type | Operation name | Span name | SpanKind | Factory method | Description |
LLM Chat | chat | chat {model} | CLIENT | handler.inference(provider, model) | Text chat model calls, default operation name |
Content generation | generate_content | generate_content {model} | CLIENT | handler.inference(..., "generate_content") | Non-chat model calls such as ASR, TTS |
Embedding | embeddings | embeddings {model} | CLIENT | handler.embedding(provider, model) | Vector embedding |
Tool | execute_tool | execute_tool {name} | INTERNAL | handler.tool(name) | Tool/function execution, records input parameters and return results |
Local Agent | invoke_agent | invoke_agent {name} | INTERNAL | handler.invokeLocalAgent(provider, model, name) | Local Agent orchestration, can aggregate Token usage |
Remote Agent | invoke_agent | invoke_agent {name} | CLIENT | handler.invokeRemoteAgent(...) | Calls remote Agent services |
Workflow | invoke_workflow | invoke_workflow {name} | INTERNAL | handler.workflow(name) | Root Span for multi-step orchestration, child Spans are automatically nested |
Retrieval | retrieval | retrieval {dataSourceId} | CLIENT | handler.retrieval(provider, dataSourceId, ...) | RAG retrieval |
Create Agent | create_agent | create_agent {name} | CLIENT | handler.createAgent(...) | Creates an Agent instance |
Typical call chain structure:
invoke_workflow {name} # Root orchestration Span
├─ invoke_agent {name} # Agent Span (optional)
│ ├─ chat {model} # LLM call
│ └─ execute_tool {name} # Tool call
├─ retrieval {dataSourceId} # Retrieval (optional)
└─ embeddings {model} # Embedding (optional)The OpenTelemetry Context automatically propagates nested Spans, so you do not need to manually set parent-child relationships. If LLM calls are already automatically collected by the ARMS agent, you typically only need to add upper-layer Spans, such as Agent, Tool, and Workflow, to your business code.
Implementation steps
This section describes how to implement instrumentation for different types of spans. Each step includes a separate code snippet. For a complete, runnable code example, see the "Complete example" section at the end of this topic.
Install dependencies
Before you start, ensure that the following prerequisites are met:
You have connected to Application Monitoring or configured the OpenTelemetry SDK to export traces and metrics to CMS application performance management (APM).
JDK 8 or later.
Maven 3.8 or later, or Gradle.
Replace ${otel-util-genai.version} and ${opentelemetry.version} with the latest published versions from Maven Central and opentelemetry-bom, respectively.
Maven
Maven
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-bom</artifactId>
<version>${opentelemetry.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.loongsuite</groupId>
<artifactId>otel-util-genai</artifactId>
<version>${otel-util-genai.version}</version>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-sdk</artifactId>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-otlp</artifactId>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-sdk-extension-autoconfigure</artifactId>
</dependency>
</dependencies>Gradle
Gradle
implementation platform("io.opentelemetry:opentelemetry-bom:${opentelemetryBomVersion}")
implementation "com.alibaba.loongsuite:otel-util-genai:${otelUtilGenaiVersion}"
implementation 'io.opentelemetry:opentelemetry-sdk'
implementation 'io.opentelemetry:opentelemetry-exporter-otlp'
implementation 'io.opentelemetry:opentelemetry-sdk-extension-autoconfigure'The otel-util-genai depends only on the OpenTelemetry API. It does not produce telemetry data if the SDK and Exporter are not configured.
Get the handler and tracer
Obtain the handler using GenAiTelemetryHandler.create() and the tracer using openTelemetry.getTracer(). You can use the handler to create GenAI spans and the tracer to create custom business spans.
import com.alibaba.loongsuite.otel.util.genai.GenAiTelemetryHandler;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
OpenTelemetry openTelemetry =
AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk();
GenAiTelemetryHandler handler = GenAiTelemetryHandler.create(openTelemetry);
Tracer tracer = openTelemetry.getTracer("my-genai-app");The handler can be used in two ways:
try-with-resources (
try (var inv = handler.inference(...))): This is the recommended method. It automatically ends the span on normal exit.*Run()callback (handler.inferenceRun(...)): This is suitable for scenarios that require automatic exception catching.
Java's try-with-resources does not automatically call fail() when an exception occurs. If an exception occurs, you must explicitly call inv.fail(e) or use the *Run() callback.
Create a Chat span
The handler.inference() method defaults to gen_ai.operation.name = chat. Before you call the large language model (LLM), set inputMessages. After the call is complete, set outputMessages and record the token usage.
import com.alibaba.loongsuite.otel.util.genai.InferenceInvocation;
import com.alibaba.loongsuite.otel.util.genai.types.*;
try (InferenceInvocation inv =
handler.inference("dashscope", "qwen-plus", "dashscope.aliyuncs.com", 443, null)) {
inv.setInputMessages(List.of(
new InputMessage("user", List.of(new TextPart(userMessage)))));
inv.setTemperature(0.7);
inv.setMaxTokens(1024L);
// Call the LLM client
ChatCompletion completion = client.chat().completions().create(params);
String content = extractContent(completion);
inv.setOutputMessages(List.of(
new OutputMessage("assistant", List.of(new TextPart(content)), "stop")));
inv.setResponseModel(completion.model());
inv.setInputTokens(completion.usage().promptTokens());
inv.setOutputTokens(completion.usage().completionTokens());
}If the ARMS agent automatically captures the LLM call, you do not need to manually create a Chat span. You can add higher-level spans, such as Agent and Tool spans.
Create an Agent span
Use invokeLocalAgent to create an Agent span that records the agent name and total token usage. Chat and Tool calls within the agent are automatically nested as child spans.
import com.alibaba.loongsuite.otel.util.genai.AgentInvocation;
try (AgentInvocation inv = handler.invokeLocalAgent("dashscope", "qwen-plus", "research-agent")) {
inv.setAgentDescription("research-assistant");
inv.setInputMessages(List.of(
new InputMessage("user", List.of(new TextPart(task)))));
// Core agent logic (internal LLM / Tool calls generate child spans)
AgentResult result = runAgent(task);
inv.setOutputMessages(List.of(
new OutputMessage("assistant", List.of(new TextPart(result.text())), "stop")));
inv.setInputTokens(result.inputTokens());
inv.setOutputTokens(result.outputTokens());
}Create a Tool span
When the model returns a tool call, create a Tool span for each tool call. Record the tool name, input parameters, and the result.
import com.alibaba.loongsuite.otel.util.genai.ToolInvocation;
try (ToolInvocation inv = handler.tool("get_weather", toolCallId, "function", "get_weather")) {
inv.setArguments("{\"city\": \"Hangzhou\"}");
String result = weatherService.getWeather("Hangzhou");
inv.setToolResult(result);
}Create a Workflow span
Use Workflow spans to orchestrate multi-step LLM or Tool calls. The outer span records the overall input and output, and inner spans automatically become child spans.
import com.alibaba.loongsuite.otel.util.genai.WorkflowInvocation;
try (WorkflowInvocation wf = handler.workflow("data-analysis")) {
wf.setInputMessages(List.of(
new InputMessage("user", List.of(new TextPart(userInput)))));
// Step 1: LLM analysis
chat(userInput);
// Step 2: Tool query
executeTool("query_db", "{}");
// Step 3: LLM synthesis
String answer = chat("Generate final report");
wf.setOutputMessages(List.of(
new OutputMessage("assistant", List.of(new TextPart(answer)), "stop")));
}Create a generate_content span (ASR/TTS)
For audio models such as ASR and TTS, use operation_name = "generate_content". The input can use BlobPart to contain the audio data. The output is a TextPart for ASR or a BlobPart for TTS.
import com.alibaba.loongsuite.otel.util.genai.types.BlobPart;
// ASR: Input audio, output recognized text
try (InferenceInvocation inv =
handler.inference("dashscope", "fun-asr-realtime", serverHost, 443, "generate_content")) {
inv.setOutputType("text");
inv.setInputMessages(List.of(
new InputMessage("user", List.of(new BlobPart("audio/pcm", pcmBytes)))));
String transcript = asrClient.transcribe(pcmBytes);
inv.setOutputMessages(List.of(
new OutputMessage("assistant", List.of(new TextPart(transcript)), "stop")));
}
// TTS: Input text, output audio
try (InferenceInvocation inv =
handler.inference("dashscope", "cosyvoice-v3-plus", serverHost, 443, "generate_content")) {
inv.setOutputType("speech");
inv.setInputMessages(List.of(
new InputMessage("user", List.of(new TextPart(replyText)))));
byte[] audio = ttsClient.synthesize(replyText);
inv.setOutputMessages(List.of(
new OutputMessage("assistant", List.of(new BlobPart("audio/mpeg", audio)), "stop")));
}Set the token fields only when the model API returns them. Do not estimate gen_ai.usage.* based on audio duration or character count.
Create Embedding and Retrieval spans
import com.alibaba.loongsuite.otel.util.genai.EmbeddingInvocation;
import com.alibaba.loongsuite.otel.util.genai.RetrievalInvocation;
// Embedding
try (EmbeddingInvocation inv = handler.embedding("dashscope", "text-embedding-v3", serverHost, 443)) {
CreateEmbeddingResponse resp = client.embeddings().create(params);
inv.setResponseModel(resp.model());
inv.setInputTokens(resp.usage().promptTokens());
inv.setDimensionCount((long) resp.data().get(0).embedding().size());
}
// Retrieval (retrieval-augmented generation)
try (RetrievalInvocation inv = handler.retrieval("dashscope", "kb-01", serverHost, 443)) {
inv.setQueryText(query);
inv.setTopK(5.0);
inv.setDocuments(documents);
}Create custom spans using the OpenTelemetry SDK
In addition to GenAI spans, you can use the Tracer to create custom business spans alongside GenAI spans. To view these spans, switch the call chain to the full view in the console.
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.context.Scope;
Span span = tracer.spanBuilder("duplicate_tool_detection").startSpan();
try (Scope scope = span.makeCurrent()) {
span.setAttribute("gen_ai.loop_detection.detected", hasDuplicates);
span.setAttribute("gen_ai.loop_detection.duplicate_tools", duplicates.toString());
} finally {
span.end();
}Error handling
// Explicit fail (for scenarios where inv is declared outside try-with-resources)
InferenceInvocation inv = handler.inference("dashscope", "qwen-plus");
try {
inv.setInputMessages(messages);
// ...
inv.stop();
} catch (Exception e) {
inv.fail(e);
throw e;
} finally {
inv.close();
}
// Automatic exception catching with a callback (recommended)
handler.inferenceRun("dashscope", "qwen-plus", inv -> {
inv.setInputMessages(messages);
// Automatically fails on exception
});Complete example
For complete instrumentation examples and runnable code, refer to the GitHub open-source repository alibaba/loongsuite-java.
FAQs
Message content is not visible in the console?
Confirm that OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT is set, and that setInputMessages/setOutputMessages were called before the Span ended.
My application does not appear in the AI Application Observability list?
Confirm that OTEL_RESOURCE_ATTRIBUTES includes acs.arms.service.feature=genai_app and gen_ai.instrumentation.sdk.name=loongsuite-genai-utils, and that Traces have been successfully exported.
Span status remains OK after an exception?
Java's try-with-resources does not automatically call fail(). Call inv.fail(e) in the catch block, or use handler.inferenceRun() instead.