Sub topic 15
Instrumentation libraries and auto-instrumentation
You have written spans by hand. This chapter covers the other route: instrumentation libraries that create spans for you. It assumes you know the SDK setup from earlier chapters (provider, resource, processor, exporter) and the GenAI span attributes. It also assumes you can read a parent-child span tree.
What an instrumentation library does
An instrumentation library is a package that adds telemetry to another library without changing that library's source. For Python it usually does this by wrapping or patching the target's functions at runtime. When your code calls the wrapped function, the wrapper starts a span, calls the original, records the result or error, and ends the span.
The wrapper uses the same API you use by hand: get_tracer, start_as_current_span and set_attribute. So its spans join whatever trace is current, and they go through whatever provider you configured. The library only produces spans. The SDK still decides where they go.
Three ways to get spans
| Approach | How | Best for | Main cost |
|---|---|---|---|
| Zero-code | `opentelemetry-instrument` command wraps your process | Quick start, many services | Little control, hard to debug |
| Programmatic | Call `SomeInstrumentor().instrument()` in your code | Normal production use | You must call it early and once |
| Manual | `tracer.start_as_current_span(...)` | Agent steps, business logic | More code to write |
These combine well. A typical agent uses a GenAI instrumentor for model calls, HTTP instrumentors for the network, and manual spans for the agent loop, because no library knows what your "agent run" is.
Zero-code instrumentation
The opentelemetry-instrument command starts your program with instrumentors already applied and the SDK configured from environment variables.
pip install opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install
export OTEL_SERVICE_NAME=support-agent
export OTEL_TRACES_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
opentelemetry-instrument python agent.pyopentelemetry-bootstrap -a install scans the packages installed in your environment and installs a matching instrumentor for each one it recognizes. Run it again after you add dependencies. To switch off one instrumentor, list it in OTEL_PYTHON_DISABLED_INSTRUMENTATIONS, for example OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=requests.
In this mode you do not write the provider setup from the SDK chapter. The agent builds it from the environment variables.
Programmatic instrumentation
When you already configure the SDK in code, call each instrumentor yourself. This example uses the requests instrumentor and a console exporter, so you can run it without a Collector. Install opentelemetry-sdk, opentelemetry-instrumentation-requests and requests first.
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
from opentelemetry.instrumentation.requests import RequestsInstrumentor
provider = TracerProvider(resource=Resource.create({"service.name": "support-agent"}))
provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
RequestsInstrumentor().instrument() # call after the provider is set
import requests
tracer = trace.get_tracer("support_agent")
with tracer.start_as_current_span("invoke_agent support-agent"):
requests.get("https://example.com") # becomes a child CLIENT span
provider.shutdown() # flush before the process exitsThe console output shows two spans sharing one trace ID. The HTTP span's parent is invoke_agent support-agent. You wrote one span and the library wrote the other, and context propagation joined them.
GenAI instrumentation libraries
Instrumentors for model SDKs follow the same pattern. There are two families:
- OpenTelemetry contrib packages, such as
opentelemetry-instrumentation-openai-v2. They emit spans using the GenAI semantic conventions. - Third-party projects, such as OpenLLMetry and OpenInference. They cover more frameworks (agent frameworks, vector stores) but may use their own attribute names.
from openai import OpenAI
from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
OpenAIInstrumentor().instrument() # before creating the client
client = OpenAI() # needs OPENAI_API_KEY
reply = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Hello"}],
)
print(reply.choices[0].message.content)Run this after the provider setup from the previous example. The call produces a client span named like chat gpt-4o-mini. It carries gen_ai.operation.name, gen_ai.request.model and the token usage attributes without any set_attribute calls from you.
Gotchas
Most auto-instrumentation problems are one of these.
- Instrumenting too late. Patching replaces attributes on a module or class. If you imported a function directly (
from lib import call) or created a client beforeinstrument()ran, you may hold a reference to the unwrapped original. Callinstrument()first, then create clients. - Two providers. Using
opentelemetry-instrumentand also callingtrace.set_tracer_providerin your code gives a warning that overriding the provider is not allowed. The first provider wins. Pick one setup route. - Duplicate spans. A model call can produce a GenAI span from the OpenAI instrumentor and an HTTP span from an
httpxinstrumentor underneath it. That is correct nesting. If it is noise, disable the HTTP instrumentor for that library. - Pre-fork servers. Batch processors run a background thread, and threads do not survive
fork(). With servers like Gunicorn, create the provider in a post-fork hook, not at import time in the parent. - Spans missing at exit. Short scripts can end before the batch processor flushes. Call
provider.shutdown()orforce_flush(). - Unstable conventions. The GenAI conventions are still marked experimental. Attribute names can change between package versions, so pin versions and read the changelog before upgrading. The contrib packages use an opt-in environment variable,
OTEL_SEMCONV_STABILITY_OPT_IN, to choose between convention versions.
Choosing between them
Use an auto-instrumentor when the library is a well-known client and you want standard attributes with minimal code. Write a manual span when the operation is your own logic: the agent loop, a planning step, a guardrail check. Some frameworks wrap many steps in one call, and then the instrumentor's spans may be too coarse or too fine for your debugging. Look at a real trace before deciding. If the span names and attributes already answer "which step was slow, and why did it fail?", you do not need manual spans there.
You can also enrich auto-created spans. Inside a with block, trace.get_current_span() returns the active span, so you can add an attribute such as a customer tier to a span the library started, as long as you run before it ends.
Exercise
Your service uses OpenAIInstrumentor().instrument(), but traces show no GenAI spans. The code at the top of agent.py is from llm_helpers import client, and llm_helpers.py creates client = OpenAI() at import time. The instrumentor is called later in main(). What is the likely cause, and how do you fix it?
Show answer
The client was created before instrument() ran, so it may use the unwrapped methods. Call OpenAIInstrumentor().instrument() before llm_helpers is imported (or create the client lazily after instrumenting). Also confirm that the tracer provider is set before the call.