Sub topic 1
Why LLM Apps and Agents Need Tracing
LLM applications are difficult to debug from logs alone. A single user request can include several model calls, retrieval queries, tool calls, retries, and delays. Tracing records this work as one connected operation so you can find the slow or failed step.
Prerequisites
Assume you know basic Python, functions, context managers, HTTP, and the difference between logs and metrics. You should also understand the basic shape of an LLM chat API request.
Traces and Spans: The Core Model
A trace represents one complete request. A span represents one timed operation inside that request. Spans form a parent-child tree. For example, an agent span can contain model, retrieval, and tool-call spans.
A trace shows both duration and order. This helps distinguish a slow model response from a slow database query or a repeated tool call.
Attributes, Events, and Status
A span has:
- Attributes, which are searchable key-value data such as the model name or token count.
- Events, which are timestamped points such as a retry or timeout.
- Status, which indicates whether the operation succeeded or failed.
Use stable attribute names. OpenTelemetry’s GenAI semantic conventions define names such as gen_ai.request.model and gen_ai.usage.input_tokens.
Setting Up the OpenTelemetry SDK
The OpenTelemetry SDK creates spans and sends them to an exporter. A resource identifies the service that produced the telemetry. A batch processor groups spans before export.
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
resource = Resource.create({"service.name": "support-agent"})
provider = TracerProvider(resource=resource)
provider.add_span_processor(
BatchSpanProcessor(
OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces")
)
)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support-agent")
with tracer.start_as_current_span("agent request") as span:
span.set_attribute("gen_ai.operation.name", "invoke_agent")Exporting with OTLP Through a Collector
OTLP is OpenTelemetry’s transport protocol. A Collector receives telemetry, processes it, and forwards it to a storage or observability backend. This keeps application code independent of the final backend.
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
exporters:
debug:
verbosity: detailed
service:
pipelines:
traces:
receivers: [otlp]
exporters: [debug]Exercise
In a trace containing an agent span, a model span, and a tool span, which span should record a tool timeout?
Show answer
The tool span should record the exception and error status. The parent agent span can also be marked failed if the timeout prevents the request from completing.