Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Trace an agent with OpenTelemetry

Instrument an agent loop with OpenTelemetry GenAI spans, one per model call and tool call, and send the traces to Langfuse or Arize Phoenix.

By Intermediate50 min hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

When an agent gives a wrong answer, the question is always “what did it see, and what did it do?” A trace answers that: one record per run, made of nested spans for each model call and each tool call, with timings, token counts and, if you choose, the inputs and outputs.

OpenTelemetry (OTel) is the vendor-neutral way to produce traces. It has a set of GenAI semantic conventions that name the attributes for model calls, tool calls and agents, so any backend that understands them can show token usage and tool calls without custom parsing. This tutorial instruments a small agent by hand, so you can see exactly what goes into a span, and sends the result to Langfuse or Phoenix.

The span layout

The conventions define three span types that matter for agents:

Span Name Key attributes
Agent run invoke_agent {gen_ai.agent.name} gen_ai.operation.name = invoke_agent, gen_ai.agent.name, gen_ai.conversation.id
Model call {gen_ai.operation.name} {gen_ai.request.model}, e.g. chat claude-haiku-5-5 gen_ai.provider.name, gen_ai.request.model, gen_ai.response.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.response.finish_reasons
Tool call execute_tool {gen_ai.tool.name} gen_ai.tool.name, gen_ai.tool.call.id, and opt-in gen_ai.tool.call.arguments / gen_ai.tool.call.result

A run produces a tree like this:

invoke_agent notes-agent                 2.9 s
├── chat claude-haiku-5-5                0.8 s   in 612  out 41
├── execute_tool search_notes            0.01 s
├── chat claude-haiku-5-5                0.7 s   in 701  out 38
├── execute_tool read_note               0.01 s
└── chat claude-haiku-5-5                1.3 s   in 1240 out 156

Prompts, completions, tool arguments and tool results are sensitive, so the conventions make recording them opt-in. That is a good default. Turn content capture on in development, and think hard before turning it on in production.

1. Install

python -m venv .venv && source .venv/bin/activate
pip install "anthropic>=2.11" "opentelemetry-sdk>=1.45" "opentelemetry-exporter-otlp-proto-http>=1.45"

2. Choose a backend

Both options accept OTLP over HTTP. Set the standard OTel environment variables and the exporter picks them up.

Arize Phoenix, locally. Start it in a second terminal:

pip install arize-phoenix
phoenix serve

The UI is at http://localhost:6006. Point the exporter at it:

export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:6006

Langfuse. Create a project, copy its public and secret keys, then:

export LANGFUSE_AUTH=$(printf '%s' "pk-lf-...:sk-lf-..." | base64 -w 0)   # macOS: drop -w 0
export OTEL_EXPORTER_OTLP_ENDPOINT=https://cloud.langfuse.com/api/public/otel   # US region: https://us.cloud.langfuse.com/api/public/otel
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic ${LANGFUSE_AUTH},x-langfuse-ingestion-version=4"

Langfuse accepts OTLP over HTTP (JSON or protobuf) but not gRPC, which is why we install the HTTP exporter. The x-langfuse-ingestion-version=4 header makes traces appear within seconds rather than minutes.

3. Set up the tracer

Create tracing.py:

# tracing.py
import os

from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

CAPTURE_CONTENT = os.environ.get("CAPTURE_CONTENT") == "1"

provider = TracerProvider(resource=Resource.create({"service.name": "notes-agent"}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)

tracer = trace.get_tracer("notes-agent")

OTLPSpanExporter() with no arguments reads OTEL_EXPORTER_OTLP_ENDPOINT and OTEL_EXPORTER_OTLP_HEADERS, and appends /v1/traces to the endpoint. BatchSpanProcessor sends spans in the background so tracing does not slow the agent.

4. Instrument the agent

Create agent.py. The agent searches and reads a folder of notes, as in the build your first agent tutorial, but every step opens a span:

# agent.py
import json
import sys
import uuid
from pathlib import Path

import anthropic
from opentelemetry.trace import SpanKind, Status, StatusCode

from tracing import CAPTURE_CONTENT, provider, tracer

MODEL = "claude-haiku-5-5"
NOTES = Path("notes").resolve()
TOOLS = [
    {"name": "search_notes", "description": "Find note file names containing a word.",
     "input_schema": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}},
    {"name": "read_note", "description": "Read one note by file name.",
     "input_schema": {"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}},
]


def run_tool(name: str, args: dict) -> str:
    if name == "search_notes":
        q = args["query"].lower()
        return json.dumps([p.name for p in NOTES.glob("*.md") if q in p.read_text().lower()])
    if name == "read_note":
        path = (NOTES / args["name"]).resolve()
        if not path.is_relative_to(NOTES) or not path.exists():
            raise FileNotFoundError(args["name"])
        return path.read_text()
    raise ValueError(f"unknown tool {name}")


def chat(client, messages):
    with tracer.start_as_current_span(f"chat {MODEL}", kind=SpanKind.CLIENT) as span:
        span.set_attribute("gen_ai.operation.name", "chat")
        span.set_attribute("gen_ai.provider.name", "anthropic")
        span.set_attribute("gen_ai.request.model", MODEL)
        resp = client.messages.create(model=MODEL, max_tokens=2048, tools=TOOLS, messages=messages)
        span.set_attribute("gen_ai.response.model", resp.model)
        span.set_attribute("gen_ai.response.id", resp.id)
        span.set_attribute("gen_ai.response.finish_reasons", [resp.stop_reason])
        span.set_attribute("gen_ai.usage.input_tokens", resp.usage.input_tokens)
        span.set_attribute("gen_ai.usage.output_tokens", resp.usage.output_tokens)
        return resp


def execute_tool(block) -> str:
    with tracer.start_as_current_span(f"execute_tool {block.name}") as span:
        span.set_attribute("gen_ai.operation.name", "execute_tool")
        span.set_attribute("gen_ai.tool.name", block.name)
        span.set_attribute("gen_ai.tool.call.id", block.id)
        if CAPTURE_CONTENT:
            span.set_attribute("gen_ai.tool.call.arguments", json.dumps(block.input))
        try:
            result = run_tool(block.name, block.input)
        except Exception as exc:
            span.record_exception(exc)
            span.set_status(Status(StatusCode.ERROR, str(exc)))
            span.set_attribute("error.type", type(exc).__name__)
            return f"error: {exc}"
        if CAPTURE_CONTENT:
            span.set_attribute("gen_ai.tool.call.result", result[:4000])
        return result


def run(question: str, max_turns: int = 6) -> str:
    client = anthropic.Anthropic()
    with tracer.start_as_current_span("invoke_agent notes-agent") as span:
        span.set_attribute("gen_ai.operation.name", "invoke_agent")
        span.set_attribute("gen_ai.agent.name", "notes-agent")
        span.set_attribute("gen_ai.conversation.id", str(uuid.uuid4()))
        messages = [{"role": "user", "content": question}]
        for _ in range(max_turns):
            resp = chat(client, messages)
            messages.append({"role": "assistant", "content": resp.content})
            if resp.stop_reason != "tool_use":
                return "".join(b.text for b in resp.content if b.type == "text")
            results = [
                {"type": "tool_result", "tool_use_id": b.id, "content": execute_tool(b)}
                for b in resp.content if b.type == "tool_use"
            ]
            messages.append({"role": "user", "content": results})
        span.set_status(Status(StatusCode.ERROR, "max_turns"))
        return "Stopped: too many steps."


if __name__ == "__main__":
    try:
        print(run(" ".join(sys.argv[1:]) or "How do I roll back a deploy?"))
    finally:
        provider.shutdown()   # flush spans before the process exits

Points worth noticing:

  • Spans nest automatically. start_as_current_span makes each span the parent of anything opened inside it, so the model and tool spans become children of the invoke_agent span without passing IDs around.
  • Tool errors are recorded on the span (record_exception, status ERROR, error.type) and also returned to the model as text. The trace shows the failure even when the agent recovers.
  • Content is behind a flag. With CAPTURE_CONTENT unset you still get the full shape, timings and token counts.
  • provider.shutdown() flushes the batch. Without it, a short script can exit before its spans are sent.

5. Run it

mkdir -p notes && printf "# Rollback\nRun ./deploy --rollback, then check the health page.\n" > notes/rollback.md
CAPTURE_CONTENT=1 python agent.py "How do I roll back a deploy?"

Open Phoenix at http://localhost:6006 or your Langfuse project’s Traces page. You should see one trace with the tree shown earlier. Click a chat span to see token counts; click an execute_tool span to see the arguments and result. Now try a question that makes a tool fail:

CAPTURE_CONTENT=1 python agent.py "Read the note called missing.md"

The execute_tool read_note span is marked as an error with the exception attached, and you can see what the model did next.

6. What to do with the traces

Traces earn their keep when you use them routinely:

  • Debug single failures. When a user reports a bad answer, find the trace by conversation ID and read what the agent saw.
  • Find patterns. Filter for traces with error spans, or with more than N model calls. Long traces are usually loops.
  • Track cost per task. Sum gen_ai.usage.* per trace. Langfuse and Phoenix calculate cost from model prices for you.
  • Feed evals. Turn interesting traces into test cases, as described in Evaluate AI agents.

Auto-instrumentation

Writing spans by hand is the clearest way to learn the conventions, and it is often the right choice for a custom agent loop. For framework code, instrumentation libraries do it for you. OpenTelemetry’s contrib project publishes GenAI instrumentations for several provider SDKs, Phoenix ships OpenInference instrumentors, and many agent frameworks (OpenAI Agents SDK, Pydantic AI, LangGraph through LangSmith or Langfuse) emit traces natively. Check which attribute names a library emits before mixing it with hand-written spans: some still use older names or their own namespaces, and backends map them differently.

MCP servers can join the same trace. The 2026-07-28 MCP specification documents passing W3C trace context (traceparent, tracestate) in request _meta, so a server’s spans can attach to the agent’s execute_tool span.

Pitfalls

Capturing everything in production. Prompts contain customer data. Capture content in development, sample or redact it in production, and agree retention with whoever owns data protection.

Missing flush. Short scripts and serverless functions exit before the batch processor sends. Call shutdown() or force_flush().

High-cardinality span names. Put IDs and user input in attributes, never in span names. execute_tool read_note is a good name; read_note(rollback.md) is not.

Tracing without looking. A dashboard nobody opens finds nothing. Put a weekly half hour in the calendar to read twenty traces.

Next steps

Covers

Check your understanding

Trace an agent with OpenTelemetry quiz

GenAI semantic conventions and their status, agent, model and tool spans, opt-in content capture, OTLP exporters for Langfuse and Phoenix, flushing, error spans and span naming.

8 questions · pass mark 70%

Question 1 of 80 answered
  1. What does following OpenTelemetry's GenAI semantic conventions give you?
Back to top