Skip to content
mentoor

Topic 2 of 5 · 5 min read

Instrumenting agents with OpenTelemetry conventions

Goal: Add trace and span attributes to an agent pipeline so each agent's model, tokens and tool calls are recorded.

Instrument agents with the same span names and attribute keys everywhere, so any backend can show model, tokens and tool calls without custom parsing. OpenTelemetry (OTel) is the open standard for traces, and it has semantic conventions for generative AI that name those keys.

Check yourself · 1 of 3

Why use OpenTelemetry GenAI attribute names instead of your own?

Choose one answer

Why it matters

If one team logs tokens_in and another logs prompt_len, you cannot total cost or compare agents. Shared names let a dashboard group spans by agent and model, and let you switch backends without rewriting code. The GenAI conventions are still being developed, so pin the version you follow and expect renames.

Your options

  • Built-in tracing in an agent SDK. The OpenAI Agents SDK traces agent runs, generations, tool calls and handoffs by default, and can send them to other processors.
  • Auto-instrumentation libraries that wrap Anthropic, OpenAI or Gemini clients and emit spans for you.
  • Manual spans around your own code, such as the orchestration loop and custom tools.
  • Backends: Langfuse and Arize Phoenix are open-source tools that accept OTel traces; hosted vendors do the same.

What to record on each span

Following the conventions: the operation (chat, tool execution, agent invocation), the provider and request model, input and output token counts, the finish reason, the agent name, and for tools the tool name and call id. Add your own keys, such as run.id and agent.role, under your own prefix.

Before and after

Before, a worker calls a model with no trace:

reply = client.messages.create(model=MODEL, messages=msgs)

After, the call sits in a span with the attributes a reader needs:

from opentelemetry import trace

tracer = trace.get_tracer("support-agents")

with tracer.start_as_current_span("chat worker-policy") as span:
    span.set_attribute("gen_ai.operation.name", "chat")
    span.set_attribute("gen_ai.request.model", MODEL)
    span.set_attribute("app.agent.name", "worker-policy")
    reply = client.messages.create(model=MODEL, messages=msgs)
    span.set_attribute("gen_ai.usage.input_tokens", reply.usage.input_tokens)
    span.set_attribute("gen_ai.usage.output_tokens", reply.usage.output_tokens)

The parent span is whatever span is current, so the call lands under the agent that made it.

What goes wrong

  • Spans not closed on errors. Use the context manager so an exception still ends the span and records the error.
  • Attribute names invented per team. Costs cannot be summed.
  • Capturing full prompts by default. That fills storage and copies personal data into traces. See the privacy topic.
  • Sampling away the failures. Random head sampling drops most error runs; keep all failed runs.

Examples

Tool span with an error

with tracer.start_as_current_span("execute_tool orders.lookup") as span:
    span.set_attribute("gen_ai.tool.name", "orders.lookup")
    try:
        result = lookup(order_id)
    except TimeoutError as exc:
        span.record_exception(exc)
        span.set_status(trace.StatusCode.ERROR)
        raise

The failed lookup is now visible as an error span under the worker that made it.

Totalling cost per agent

Because every generation span carries app.agent.name and the two usage attributes, a backend query can group by agent and sum tokens. A planner that looks cheap per call but runs eight times per task shows up immediately.

Key points

  • OpenTelemetry GenAI conventions give shared names for operation, model, token counts and finish reason.
  • Agent SDKs such as the OpenAI Agents SDK trace runs, generations, tools and handoffs by default.
  • Wrap your own orchestration code and custom tools in manual spans under the current span.
  • Add app-specific keys such as run id and agent name under your own prefix.
  • Close spans with a context manager and keep every failed run when you sample.

Common mistakes

  • Each agent author picks different attribute names, so nothing can be summed or compared.
  • Recording the model call but not the tool calls, which are where many failures start.
  • Using start and end calls by hand so an exception leaves a span open forever.
  • Assuming the conventions are frozen and not noting which version the code follows.

Check yourself · 2 of 3

Your agent code calls a model inside a start_span call that is never ended when the call raises. What is the fix?

Choose one answer

Check yourself · 3 of 3

You want cost per agent role from traces. Which attributes must each generation span carry?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic