Sub topic 13
Recording errors, retries and timeouts
This chapter assumes you can create spans with start_as_current_span and set attributes on them, as covered earlier in this tutorial.
What counts as an error
A span has a status: UNSET, OK or ERROR. Set ERROR when the operation failed from the caller's point of view. Exceptions, HTTP 429 and 5xx responses, and timeouts all count. A model reply that is wrong or unhelpful is not a span error. The call succeeded, so record quality problems as attributes or evaluations instead.
Record two things on a failed span:
- An exception event, from
span.record_exception(exc). It stores the type, message and stack trace. - An error status, from
span.set_status(Status(StatusCode.ERROR, message)).
The GenAI conventions also define error.type, a short, low-cardinality string such as RateLimited or timeout. Use it to group failures in your backend.
One span per attempt
Wrap each retry attempt in its own span, under a parent span that covers the whole operation. A trace then shows how many attempts ran, how long each took, and how much time went to backoff sleeps.
import time
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
tracer = trace.get_tracer("support_agent")
class RateLimited(Exception):
pass
def call_model(messages):
# Stand-in for a real client that always fails.
raise RateLimited("429 too many requests")
def chat_with_retries(messages, model="example-model", max_attempts=3):
with tracer.start_as_current_span("chat_with_retries") as outer:
for attempt in range(1, max_attempts + 1):
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)
span.set_attribute("app.retry.attempt", attempt)
try:
return call_model(messages)
except (RateLimited, TimeoutError) as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, str(exc)))
span.set_attribute("error.type", type(exc).__name__)
if attempt == max_attempts:
outer.set_status(Status(StatusCode.ERROR, "retries exhausted"))
raise
time.sleep(0.5 * 2 ** (attempt - 1))app.retry.attempt is a custom name. Keep custom attributes under your own prefix so they cannot collide with standard ones.
flowchart TD
A[Start chat_with_retries] --> B[Attempt span]
B -->|success| C[Return text]
B -->|retryable error| D[Mark attempt span ERROR]
D --> E{Attempts left?}
E -->|yes| F[Sleep with backoff]
F --> B
E -->|no| G[Mark parent ERROR and raise]Rendered as a diagram block, the same flow looks like this:
Timeouts
Always set a client-side timeout on model and tool calls. Without one, a hung call produces a span that stays open for minutes. When the timeout fires, treat it like any other failure: record the exception and set error.type to timeout. Record the configured limit in a custom attribute such as app.timeout_seconds, so a reader can tell a 30-second timeout from a 5-second one.
Common mistakes
- Marking only the parent span as an error. The failed attempt is then hard to find.
- Setting
OKon a span after catching an error that you then retry. Leave a successful attempt asUNSET. - Putting the full error message in
error.type. That creates a new value for every message and breaks grouping. - Logging a retry without a span. The sleep time disappears from the trace.
The SDK already records an exception and sets ERROR when an exception escapes a with block. Explicit calls are needed when you catch the exception inside the block, as above.
Exercise
A model call times out twice and succeeds on the third try. With one span per attempt, how many chat spans appear in the trace, and which of them should have ERROR status?
Show answer
Three chat spans appear under the parent span. The first two have ERROR status, an exception event and error.type set to timeout. The third is left UNSET. The parent span also stays non-error, because the operation finally succeeded.