Sub topic 8
Instrumenting a model call
A model call is the smallest unit of work in an LLM application, and it is the span you will create most often. This chapter shows how to wrap one call in a span that follows the OpenTelemetry GenAI semantic conventions. It assumes you can already create a tracer provider and a tracer, and that you know what attributes and span status are. Token counts, agent structure, and retry handling get their own chapters. Here we cover the span itself.
What one model-call span looks like
A model-call span describes a single request to a model and the response that came back. The conventions give it these properties:
- Name:
{operation} {model}, for examplechat example-model. A low-cardinality name groups well in a trace backend. - Kind:
CLIENT, because your process calls a remote service. UseINTERNALonly if the model runs inside your own process. - Attributes: the operation, the provider, the requested model, request parameters, and facts about the response.
- Status: left unset on success and set to
ERRORon failure.
The attributes to record
The GenAI conventions are still marked as in development, so attribute names can change between versions. Pin your instrumentation package versions and check the current names in the specification.
| Attribute | When to set | Example |
|---|---|---|
| `gen_ai.operation.name` | At start | `chat` |
| `gen_ai.provider.name` | At start | `openai` |
| `gen_ai.request.model` | At start | `example-model` |
| `gen_ai.request.temperature` | At start, if you set it | `0.2` |
| `gen_ai.request.max_tokens` | At start, if you set it | `512` |
| `gen_ai.response.model` | After the response | `example-model-2026-01` |
| `gen_ai.response.id` | After the response | `resp-123` |
| `gen_ai.response.finish_reasons` | After the response | `["stop"]` |
| `error.type` | On failure | `ValueError` |
Older versions of the conventions used gen_ai.system instead of gen_ai.provider.name. If your backend dashboards still query the old name, check which one your libraries emit.
Request and response model can differ. You may ask for an alias such as example-model, and the provider answers with a dated snapshot. Record both, because the snapshot is what explains a sudden change in behavior.
A complete, runnable example
This version prints spans to the console, so it runs without a Collector. You only need opentelemetry-sdk installed. The call_model function is a stand-in for a real client.
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.trace import SpanKind
provider = TracerProvider(resource=Resource.create({"service.name": "support-agent"}))
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support_agent")
def call_model(messages, model, temperature, max_tokens):
# Stand-in for a real LLM client call.
if not messages:
raise ValueError("messages must not be empty")
return {
"id": "resp-123",
"model": model + "-2026-01",
"text": "Hello!",
"finish_reason": "stop",
}
def traced_chat(messages, model="example-model", temperature=0.2, max_tokens=512):
with tracer.start_as_current_span(
f"chat {model}",
kind=SpanKind.CLIENT,
attributes={
"gen_ai.operation.name": "chat",
"gen_ai.provider.name": "example-provider",
"gen_ai.request.model": model,
"gen_ai.request.temperature": temperature,
"gen_ai.request.max_tokens": max_tokens,
},
) as span:
try:
result = call_model(messages, model, temperature, max_tokens)
except Exception as exc:
span.set_attribute("error.type", type(exc).__qualname__)
raise
span.set_attribute("gen_ai.response.model", result["model"])
span.set_attribute("gen_ai.response.id", result["id"])
span.set_attribute("gen_ai.response.finish_reasons", [result["finish_reason"]])
return result["text"]
if __name__ == "__main__":
print(traced_chat([{"role": "user", "content": "Hi"}]))
try:
traced_chat([])
except ValueError as exc:
print("failed:", exc)Run it and you get two spans. The first has the response attributes and an unset status. The second has error.type, an ERROR status, and an exception event.
Design decisions in this code
Pass request attributes at span start
Request attributes go into the attributes argument of start_as_current_span, not into later set_attribute calls. A sampler runs when the span starts, and it only sees attributes supplied at that moment. If you want a sampling rule such as "always keep spans for the expensive model", the model name must be present at creation. Response attributes cannot be known earlier, so they are set after the call.
Let the context manager handle exceptions
By default, start_as_current_span records an uncaught exception as an event and sets the status to ERROR. The explicit except block exists only to add error.type, then re-raises. Do not swallow the exception inside the span. If you catch it and return a fallback, the span looks successful, and that hides failures from the people reading traces.
If you set the status yourself, set it to ERROR on failure and leave it alone on success. Setting OK is reserved for cases where you want to override an error found elsewhere.
Keep the span name stable
The name chat example-model has two parts that take few distinct values. Do not put prompt text, user IDs, or request IDs in the name. Put them in attributes if you need them at all.
Common mistakes
- Opening the span after the call. The span then measures nothing. Start it before the request and end it after the response is fully read.
- Ending the span before a stream finishes. With streaming responses, the call returns before the work is done. Keep the span open until the last chunk arrives, and record finish reasons from the final chunk. Time to first token is worth adding as an event or a separate attribute.
- Using the wrong kind. An
INTERNALspan for a remote call is accepted, but backends useCLIENTto draw service maps and compute dependency latency. - Recording unset values. Do not call
set_attributewithNone. The SDK drops it with a warning. Check for the value first. - Relying on a global tracer before setup. If
set_tracer_providerhas not run,get_tracerreturns a no-op tracer, and spans silently vanish. Configure the provider at process start, before the first call. - Writing new names from memory. A typo such as
gen_ai.request.modleis accepted without any error. Define attribute names as constants in one module.
Checking the result
Look at the console output for each span and confirm four things:
- The
namematcheschat <model>. kindisSpanKind.CLIENT.- The
attributeshold both request and response fields on success. - The failing span has
status_code: ERRORand anexceptionevent.
When you later send spans through a Collector, the same checks apply to the debug exporter output. The next chapter adds gen_ai.usage.input_tokens and gen_ai.usage.output_tokens to this span.
Exercise
A teammate wraps the model call in a span but catches Exception, logs it, and returns the string "Sorry, something went wrong" from inside the with block. What will the trace show for that span, and how should the code change so failures remain visible?
Show answer
The span will have an unset status and no exception event, so it looks like a successful call even though the model request failed. To fix it, let the exception propagate out of the with block (or catch it outside the span), or, if a fallback is required inside the block, call span.record_exception(exc), set span.set_status(Status(StatusCode.ERROR, str(exc))), and set error.type before returning the fallback.
Exercise
Why should gen_ai.request.model be passed in the attributes argument when the span starts, instead of being set after the model call returns?
Show answer
Samplers decide whether to record a span when it starts, and they can only inspect the attributes available at that moment. Setting the model name later means a rule such as "always sample calls to a given model" cannot use it.