Sub topic 8
Instrumenting a Model Call
This chapter assumes you can write basic Python with context managers, have called a chat completion API, and have already set up the OpenTelemetry SDK with a tracer provider and an exporter. The goal is to wrap one model call in a span that carries the GenAI semantic convention attributes.
What a model call span represents
A model call is a request from your process to a remote service. OpenTelemetry models that as a client span, so you create it with SpanKind.CLIENT. The GenAI conventions give the span a name of the form {operation} {model}, such as chat example-model. A consistent name makes spans easy to group in a trace backend.
The span needs three things:
- A name and kind that describe the operation.
- Attributes that identify the operation and the model.
- Status and exception data if the call fails.
The instrumented function
The function below wraps a stand-in model call. Replace call_model with your real client.
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
tracer = trace.get_tracer("support_agent")
def call_model(messages):
# Stand-in for a real LLM client call.
return {"text": "Hello!", "input_tokens": 12, "output_tokens": 3}
def traced_chat(messages, model="example-model"):
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.request.model", model)
try:
result = call_model(messages)
except Exception as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, str(exc)))
raise
span.set_attribute("gen_ai.usage.input_tokens", result["input_tokens"])
span.set_attribute("gen_ai.usage.output_tokens", result["output_tokens"])
return result["text"]How it works
start_as_current_span starts the span and makes it the current span for the with block. When the block ends, the span ends and goes to the span processor. Any span started inside the block becomes its child.
Attributes set before the call, gen_ai.operation.name and gen_ai.request.model, describe the request. They are on the span even if the call fails. Attributes that depend on the response, such as token counts, can only be set after the call returns. That is why they come after the try block.
The except branch does three things. record_exception adds an exception event with the type, message and stack trace. set_status marks the span as an error so backends can filter and count failures. The bare raise then re-throws the original exception, so your application's own error handling still runs.
Common mistakes
- Setting the span name to the prompt. Names should have low variety. Put variable data in attributes.
- Forgetting the kind. Without
SpanKind.CLIENT, the span defaults to internal, and backends cannot tell it is an outbound call. - Setting token counts to
None. Check that the value exists before you set the attribute. Some providers omit usage on streamed responses. - Swallowing the exception. If you catch the error and return a default value, still record it on the span.
Checking the result
Run the Collector configuration from the previous chapter, call traced_chat([{"role": "user", "content": "Hi"}]), and look at the console output. You should see a span named chat example-model with kind Client and the three GenAI attributes.
Exercise
Why does the function set gen_ai.usage.input_tokens after the try block instead of at the start of the span?
Show answer
Token counts come from the model's response, so they are not known until the call returns. Setting them after the try block also means they are skipped when the call raises, which avoids recording values that do not exist.