Instana

Instana

The community for performance and observability professionals to learn, to share ideas, and to connect with others.

 View Only

Enabling Gen AI Observability in IBM Instana with Manual OpenTelemetry Instrumentation

By Adharsh H posted 09/02/26 10:41 AM

  

As organizations adopt agentic AI applications, observability becomes a critical challenge. Agentic workflows involve dynamic interactions between multiple agents, LLMs, tools, and decision steps — often with iterative execution paths. Without observability, you cannot determine which agents and tools ran, which model was used, how many tokens were consumed, where latency originated, or why a particular execution path was taken.

You must capture telemetry across each component involved in the execution to gain visibility into these workflows. OpenTelemetry instrumentation provides a standardized approach for capturing traces, spans, attributes, and metrics from agent activities, LLM calls, and tool invocations. This telemetry gives you the context to trace the complete workflow, monitor performance, troubleshoot issues, and understand agent behavior.

 This article demonstrates how to manually instrument an agentic AI application using OpenTelemetry and export the resulting telemetry to IBM Instana. The instrumentation covers agent activities, LLM interactions, tool calls, token usage, and operation latency, enabling end-to-end GenAI observability and making the agentic workflow traceable, measurable, and easier to optimize.

Application overview

This section describes an AI-powered research assistant that demonstrates agentic observability. For every user question, the application performs three steps:

 1. Research the topic using Tavily Search.

2. Generate an answer using a Groq-hosted LLM.

3. Evaluate the generated answer and decide whether to approve or revise it.

LangGraph orchestrates the workflow through three specialized agents:

 - Research Agent gathers relevant information using Tavily Search.

- Answer Agent uses the research results and a Groq-hosted LLM to generate an answer.

- Critic Agent evaluates the answer for accuracy, completeness, and unsupported claims.

If the Critic Agent identifies issues, the workflow routes back to the Answer Agent with the critic's feedback. The process continues until the answer is approved or the maximum revision limit is reached.

The instrumentation covers agent execution, LLM calls, tool invocations, and interactions between workflow steps. This lets you capture traces, inputs and outputs, execution latency, token usage, and other telemetry needed to understand and monitor end-to-end agent behavior.

The following diagram illustrates the conceptual workflow.

Prerequisites

Before you begin, make sure that you have met the following conditions:

  • Python 3.11 or later installed
  • A Tavily Search API key — create one from the Tavily dashboard
  • A Groq API key — create and manage keys from the Groq Console

Setup manual OpenTelemetry instrumentation

Rather than relying on automatic instrumentation, this example uses manual OpenTelemetry instrumentation to capture telemetry from the agentic workflow.

Manual instrumentation gives you greater control over how the workflow appears in telemetry. You can explicitly instrument agent activities, tool invocations, LLM interactions, and GenAI-specific metrics, and you can define the spans and attributes that provide context for each operation.

The instrumentation in this example covers three main areas:

  1. Create the tracer and meter to generate traces and record metrics
  2. Define the OpenTelemetry resource to identify the application generating the telemetry
  3. Configure trace and metric providers and OTLP exporters to process and export telemetry

Create the tracer and meter

The first step creates the OpenTelemetry Tracer and Meter, which you use throughout the application to generate traces and record metrics.

TRACER_NAME = "<tracer-name>"  # For example: genai-agent-observability
METER_NAME = "<meter-name>"    # For example: genai-agent-observability

tracer = trace.get_tracer(TRACER_NAME)
meter = metrics.get_meter(METER_NAME)

Use the Tracer to create spans that represent operations within the agentic workflow:

  • Overall workflow execution
  • Agent execution
  • Tool invocations
  • LLM calls

Use the Meter to create metric instruments that record measurements such as:

  • LLM token usage
  • LLM operation duration

These instrumentation interfaces are the foundation for capturing telemetry in the subsequent steps.

Define the OpenTelemetry resource
Define an OpenTelemetry
Resource to provide contextual information about the application generating the telemetry.

def build_resource() -> Resource:
    return Resource.create(
        {
            "service.name": <service name>,
            "INSTANA_PLUGIN": "genai",
        }
    )

The service.name attribute identifies the application and associates its telemetry with the corresponding service in IBM Instana. Set INSTANA_PLUGIN to genai to identify the telemetry as GenAI-related for Instana. Associate the same resource with both the TracerProvider and MeterProvider to ensure that traces and metrics share a consistent application context throughout the observability pipeline.

Configure trace providers, metric providers, and OTLP exporters

After you define the OpenTelemetry resource, configure the TracerProvider and MeterProvider and connect them to OTLP exporters.

The TracerProvider processes and exports spans. The MeterProvider manages metric instruments and exports their measurements. The application supports both OTLP gRPC and OTLP HTTP protocols.

Configure the trace provider

OpenTelemetry supports multiple OTLP transport protocols, allowing you to configure the exporter according to your use case.

# For HTTP
exporter = OTLPHttpSpanExporter(
    endpoint=endpoint,
    headers=headers,
)

# For gRPC
exporter = OTLPGrpcSpanExporter(
    endpoint=endpoint,
    headers=headers,
    insecure=not (
        endpoint.startswith("https://")
        or endpoint.startswith("grpcs://")
    ),
)

Attach the selected exporter to the TracerProvider using a BatchSpanProcessor:

trace_provider = TracerProvider(
    resource=resource,
)

trace_provider.add_span_processor(
    BatchSpanProcessor(exporter)
)

trace.set_tracer_provider(trace_provider)

The BatchSpanProcessor collects spans and exports them in batches rather than sending each span individually.

Configure the metrics provider

Metrics use a separate OTLP exporter and MeterProvider. Configure the exporter based on your selected OTLP transport protocol:

# For HTTP
exporter = OTLPHttpMetricExporter(
    endpoint=endpoint,
    headers=headers,
)

# For gRPC
exporter = OTLPGrpcMetricExporter(
    endpoint=endpoint,
    headers=headers,
    insecure=not (
        endpoint.startswith("https://")
        or endpoint.startswith("grpcs://")
    ),
)

Attach the configured metric exporter to a PeriodicExportingMetricReader which periodically collects and exports the recorded metric data through the MeterProvider:

reader = PeriodicExportingMetricReader(exporter)

provider = MeterProvider(
    resource=resource,
    metric_readers=[reader],
)

metrics.set_meter_provider(provider)

This configuration separates the trace pipeline from the metric pipeline. Both pipelines share the same OpenTelemetry resource and export telemetry to Instana using OTLP.

Trace view in Instana

Trace View gives you a complete view of an application’s execution path, showing how individual operations connect and how the application progresses from one step to the next. It captures interactions such as LLM calls, database queries, HTTP requests, internal service calls, and other application operations within a single trace. Use Trace View to understand the end-to-end flow and identify where time is spent or where issues occur.

The following example shows how to manually instrument a research agent using OpenTelemetry. The agent is represented by a parent span, while the tool invocation and LLM call are represented by child spans. Because these spans are created within the agent’s span context, OpenTelemetry automatically maintains the parent-child relationship in the trace.

The example instruments a research agent that uses a Tavily search tool and a Groq LLM:

search_tool = TavilySearchResults(
    max_results=TAVILY_MAX_RESULTS,
)

def research_agent(question):

    # Research Agent span
    with tracer.start_as_current_span(
        "research_agent.task"
    ) as agent_span:

        agent_span.set_attribute(
            "gen_ai.operation.name",
            "execute_task",
        )

        agent_span.set_attribute(
            "gen_ai.task.name",
            "research_agent",
        )

        # Tool invocation
        with tracer.start_as_current_span(
            "tavily.search.tool"
        ) as tool_span:

            tool_span.set_attribute(
                "gen_ai.tool.name",
                "tavily_search",
            )

            tool_span.set_attribute(
                "gen_ai.tool.type",
                "search",
            )

            tool_span.set_attribute(
                "gen_ai.tool.call.arguments",
                question,
            )

            results = search_tool.invoke(question)

            tool_span.set_attribute(
                "gen_ai.tool.call.result",
                str(results),
            )

        agent_span.set_attribute(
            "gen_ai.task.status",
            "completed",
        )

    return results

def answer_agent(question, research_results):

    # Answer Agent span
    with tracer.start_as_current_span(
        "answer_agent.task"
    ) as agent_span:

        agent_span.set_attribute(
            "gen_ai.operation.name",
            "execute_task",
        )

        agent_span.set_attribute(
            "gen_ai.task.name",
            "answer_agent",
        )

        # LLM invocation
        with tracer.start_as_current_span(
            "ChatGroq.chat"
        ) as llm_span:

            llm_span.set_attribute(
                "gen_ai.operation.name",
                "chat",
            )

            llm_span.set_attribute(
                "gen_ai.provider.name",
                "groq",
            )

            llm_span.set_attribute(
                "gen_ai.request.model",
                GROQ_MODEL,
            )

            llm_span.set_attribute(
                "gen_ai.input.messages",
                str(research_results),
            )

            response = llm.invoke(
                f"""
                Question: {question}

                Research results:
                {research_results}
                """
            )

            llm_span.set_attribute(
                "gen_ai.response.model",
                response.response_metadata.get(
                    "model_name",
                    GROQ_MODEL,
                ),
            )

            llm_span.set_attribute(
                "gen_ai.output.messages",
                str(response.content),
            )

        agent_span.set_attribute(
            "gen_ai.task.status",
            "completed",
        )

        return response

tracer.start_as_current_span() manually instruments each operation, and set_attribute() adds the required span attributes. The research_agent.task span represents the Research Agent execution, with the tavily.search.tool child span capturing the tool invocation — including its name, type, input, and result. The answer_agent.task span represents the Answer Agent execution, with the ChatGroq.chat child span capturing the LLM operation and relevant GenAI attributes such as the operation, provider, and model.

The following screenshot shows the trace view of the instrumented application, displaying the captured agent task, tool calls, and LLM interactions.

Task hierarchy view in Instana

When a trace contains GenAI operations, Instana Task View provides a focused view of the GenAI and agentic interactions within that trace. Use Task View to understand:

  • LLM calls
  • Agent tasks
  • Tool interactions

For an agentic application, Task View answers the question: “What happened during the GenAI and agentic interactions?”

Note: Task View currently supports agentic applications built with LangChain, LangGraph, and CrewAI.

Task View supports the following commonly used LLM operation patterns:

  • chat.completions.create
  • WatsonxLLM.completion
  • watsonx.generate
  • Methods that end with .chat, such as ChatWatsonx.chat, openai.chat, and ChatOpenAI.chat

The following screenshot shows an example of Instana Task View displaying GenAI and agentic interactions within a trace.

Capturing LLM input and output in Task View

To capture LLM input and output messages in Task View, include the following attributes in the corresponding span:

  • gen_ai.input.messages
  • gen_ai.output.messages

These attributes allow Task View to display the messages exchanged during the LLM operation, giving you visibility into the prompt sent to the model and the response the model generates.

Additionally, include the gen_ai.provider.name attribute in the span. This attribute identifies the span as a GenAI operation and allows Instana to recognize and process it as a GenAI trace.

Capturing tool calls in Task View

To capture tool-related operations in Task View, end the span name with .tool. For example: search.tool.

To display the tool input arguments and output result in Task View, add the following attributes to the span:

  • gen_ai.tool.call.arguments
  • gen_ai.tool.call.result

Capturing agent task spans

For agentic applications, you can represent individual agent executions as task spans. These spans allow Task View to identify and display the work each agent performs within the overall workflow.

Include the following GenAI attributes in each agent task span:

  • gen_ai.operation.name — set to execute_task to identify the operation as an agent task
  • gen_ai.provider.name — identifies the framework or provider executing the task
  • gen_ai.task.name — identifies the specific agent executing the task

LLM metrics in the GenAI dashboard

Tracing shows what happened and in what order. Metrics show the performance and consumption characteristics of LLM operations.

Instana presents the following LLM metrics in the GenAI dashboard:

  • Token usage — the number of input and output tokens consumed
  • Cost — the calculated input, output, and total LLM cost
  • LLM calls — the number of LLM operations
  • LLM latency — the time taken to complete LLM operations

You can analyze metrics by model or GenAI service to understand LLM consumption and performance.

For cost calculation, Instana uses the recorded input and output token usage together with model-specific prices you configure in the Pricing configuration tab. This produces input cost, output cost, and total cost.

To populate these metrics in the GenAI dashboard, your application must record the appropriate OpenTelemetry GenAI metrics and attributes.

Define GenAI metrics

Instana uses the following OpenTelemetry metrics to monitor LLM consumption and performance:

  • gen_ai.client.token.usage — measures the number of input and output tokens consumed during an LLM operation
  • gen_ai.client.operation.duration — measures the time taken to complete an LLM operation

Define both metrics as OpenTelemetry histograms:

TOKEN_USAGE = meter.create_histogram(
    name="gen_ai.client.token.usage",
    description="Number of tokens used in a GenAI operation",
    unit="{token}",
)

OPERATION_DURATION = meter.create_histogram(
    name="gen_ai.client.operation.duration",
    description="Duration of a GenAI operation",
    unit="s",
)

Record GenAI metrics with attributes

Recording only the metric value provides limited context. For example, a token usage value shows how many tokens were consumed, but not which provider or model was responsible.

Record GenAI attributes alongside each metric measurement to provide this context:

attributes = {
    "gen_ai.provider.name": provider,
    "gen_ai.response.model": model,
}

These attributes allow you to analyze metrics by GenAI provider and response model. For example, you can distinguish token usage from two different models even when they use the same metric.

For token usage, use the gen_ai.token.type attribute to to distinguish between input and output tokens.

TOKEN_USAGE.record(
    input_tokens,
    attributes={
        **attributes,
        "gen_ai.token.type": "input",
    },
)

TOKEN_USAGE.record(
    output_tokens,
    attributes={
        **attributes,
        "gen_ai.token.type": "output",
    },
)

This lets Instana differentiate between the tokens sent to the model and the tokens the model generates.

For LLM operation duration, apply the same provider and response model attributes:

start_time = perf_counter()
response = llm.invoke(messages)

duration = perf_counter() - start_time

OPERATION_DURATION.record(
    duration,
    attributes=attributes,
)

Conclusion

Manual OpenTelemetry instrumentation gives you a flexible and precise way to enable GenAI observability in agentic AI applications. By capturing agent tasks, LLM calls, tool interactions, token usage, and latency, and exporting this telemetry to IBM Instana, you gain end-to-end visibility through Trace View and Task View. This helps you understand agent execution flows, monitor LLM performance, troubleshoot issues, and optimize GenAI applications.

References

The complete instrumented application is available in the LangGraph Research Agent repository. Follow the README for instructions on configuring the environment, installing the required dependencies, and running the application.

For more information about Instana backend OTLP endpoints for different SaaS environments, see Endpoints of the Instana backend OTLP acceptor.


#OpenTelemetry
#Tracing
#LLM

1 comment
25 views

Permalink

Comments

9 days ago

Really useful, while i was enabling gen ai observability for HCP terraform, thanks for sharing ❤️