Observability: tracing LLM and agent runs

Spans for model and tool calls, token and cost attributes, structured logs, redaction and debugging from a trace.

Advanced about 5 h

The picture

  1. 01

    Run id

    correlates everything

  2. 02

    Spans

    llm, tool, retrieval

  3. 03

    Attributes

    tokens, cost, model

  4. 04

    Redact

    before export

  5. 05

    Dashboards

    p95, errors, cost

Why standard logging is not enough

An agent run is a tree: a model call, three tool calls, another model call, a retrieval, a retry. When a user says "it gave a weird answer yesterday", you need to open that exact run and see every prompt, every tool argument, every result and every token count. Tracing records that tree.

Instrument with OpenTelemetry

OpenTelemetry is vendor-neutral, and most LLM observability tools ingest it.

import time, uuid, json
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter

provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))   # swap for an OTLP exporter in production
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("my-agent")

PRICES = {"claude-sonnet-5-5": (3.0, 15.0)}          # USD per million tokens (placeholders)

def traced_llm_call(client, model, messages, **kw):
    with tracer.start_as_current_span("llm.call") as span:
        span.set_attribute("gen_ai.request.model", model)
        t0 = time.perf_counter()
        resp = client.messages.create(model=model, messages=messages, **kw)
        pin, pout = PRICES.get(model, (0, 0))
        u = resp.usage
        span.set_attribute("gen_ai.usage.input_tokens", u.input_tokens)
        span.set_attribute("gen_ai.usage.output_tokens", u.output_tokens)
        span.set_attribute("app.cost_usd", (u.input_tokens * pin + u.output_tokens * pout) / 1e6)
        span.set_attribute("app.latency_ms", int((time.perf_counter() - t0) * 1000))
        span.set_attribute("gen_ai.response.stop_reason", resp.stop_reason)
        return resp

def traced_tool(name, fn, args):
    with tracer.start_as_current_span(f"tool.{name}") as span:
        span.set_attribute("tool.name", name)
        span.set_attribute("tool.args", json.dumps(args)[:2000])
        try:
            out = fn(**args)
            span.set_attribute("tool.ok", True)
            return out
        except Exception as e:
            span.record_exception(e)
            span.set_attribute("tool.ok", False)
            raise

def run_agent(goal):
    with tracer.start_as_current_span("agent.run") as span:
        span.set_attribute("run.id", str(uuid.uuid4()))
        span.set_attribute("agent.goal", goal[:500])
        ...                                           # your loop, using the two wrappers above

Name attributes after the GenAI semantic conventions where they exist, so tools recognise them.

What to record

  • Per model call: model, parameters, input and output tokens, cached tokens, latency, stop reason, cost, prompt version.
  • Per tool call: name, arguments, result size, success or error, latency.
  • Per run: run id, user or tenant id (hashed), final status, total cost, step count.
  • Retrieval: query, k, ids and scores of the chunks returned.

Store prompt and completion content when you need to debug, but treat it as sensitive.

Privacy: redact before export

import re
PATTERNS = {
    "email": re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"),
    "card":  re.compile(r"\b(?:\d[ -]?){13,16}\b"),
    "key":   re.compile(r"\b(sk|pk|api)[-_][A-Za-z0-9_-]{16,}\b"),
}
def redact(text: str) -> str:
    for label, rx in PATTERNS.items():
        text = rx.sub(f"[{label}]", text)
    return text

Regex redaction is a baseline; for personal data use a dedicated detector such as Microsoft Presidio, apply it in a span processor so nothing sensitive is exported, set retention limits, and restrict who can read traces.

Operate on it

  • Dashboards: p50 and p95 latency, error rate, cost per run, tokens per run, tool error rate, refusal rate.
  • Alerts: cost spikes, error bursts, latency regressions, a sudden change in average steps (a regression signal).
  • Sampling: keep 100 percent of failures and a sample of successes to control cost.
  • Link to evals: every bad production trace becomes a candidate test case.

Common mistakes

  • Logging full prompts with customer data to a shared console.
  • No run id, so logs from concurrent runs interleave.
  • Tracking tokens but not cost, or cost without the prompt version that caused it.

Exercises

  1. Instrument your agent from the earlier stage and find the most expensive span in a typical run.
  2. Add a redaction processor and prove with a test that an email address never appears in exported spans.

You are done when you can…

  • Instrument an agent so every run is one trace with a span per model call and tool call
  • Record tokens, latency and estimated cost as span attributes
  • Redact sensitive fields before telemetry leaves your boundary