# Agent observability in practice: Langfuse 5, OpenTelemetry GenAI spans, cost and latency

An agent run is a tree of model calls, tool calls and decisions. This guide shows how to record that tree with Langfuse 5.2 and the OpenTelemetry GenAI conventions, run it offline, and turn 1,000 simulated runs into latency percentiles, cost per run and a clear view of where time goes.

When a normal web request fails, a stack trace usually points at the bug. When an agent fails, the cause can sit anywhere in a run of five model calls and four tool calls: a vague tool description, a search that returned nothing, a context that grew too large, or a model that stopped too early. Observability for agents means recording each of those steps, with inputs, outputs, timing, tokens and cost, so you can see the whole run as one tree.

The tooling has settled on one idea: an agent run is a trace, and each step is a span. Langfuse, Arize Phoenix, LangSmith and the big cloud monitoring vendors all accept or emit OpenTelemetry data, and the OpenTelemetry project now has GenAI conventions that name the agent, model and tool spans. This article shows that span tree in Langfuse 5.2 and in plain OpenTelemetry, runs both offline, and turns a thousand simulated runs into the numbers you actually watch: p50 and p95 latency, cost per run and the share of time spent in tools.

## What happened

### Arize Phoenix 22 and new OpenInference instrumentation (20 to 21 November 2026)

Arize Phoenix 22.0.0 was published to PyPI on 20 November 2026 and 22.0.1 followed on 21 November. The OpenInference LangChain instrumentor, which Phoenix uses to trace LangChain and LangGraph apps, shipped four releases in a week, from 0.1.87 on 16 November to 0.1.90 on 21 November. Phoenix's client helper `arize-phoenix-otel` (0.17.3) provides `phoenix.otel.register`, which sets up an OpenTelemetry tracer provider pointed at a Phoenix server.

### Langfuse 5.2.0 (5 November 2026)

The Langfuse Python SDK reached 5.2.0 on 5 November 2026, after the 5.0 line in October. The SDK is built on OpenTelemetry. Its `start_as_current_observation` method takes an `as_type` of `span`, `generation`, `embedding`, `agent`, `tool`, `chain`, `retriever`, `evaluator` or `guardrail`, and the client constructor accepts a `span_exporter` argument. That last option is what makes the offline demo below possible.

### OpenTelemetry GenAI agent conventions add a plan span (development status)

The GenAI conventions now live in their own repository, `semantic-conventions-genai`. Its agent spans document defines `create_agent`, `invoke_agent` and a new `plan` span for "an agent planning or task decomposition phase". All are marked Development, which means names can still change. The Python package `opentelemetry-semantic-conventions` 0.66b2 (29 October 2026) exposes the operation names `chat`, `invoke_agent`, `execute_tool`, `retrieval`, `embeddings`, `create_agent` and `invoke_workflow`, among others. In that package the GenAI constants now carry a deprecation note saying they moved to the new GenAI repository, and `gen_ai.system` is marked as replaced by `gen_ai.provider.name`.

## The span tree of an agent run

Think of a trace as a parcel tracking page. The parcel is the user request. Each scan, at the depot, on the truck, at the door, is a span with a start time, an end time and some details. Child spans nest under the step that caused them.

For an agent the tree usually looks like this:

```text
invoke_agent support                    (root: whole run, 4.2 s)
├── chat model-x                        (model call 1: decides to call a tool)
├── execute_tool search_orders          (tool call)
├── chat model-x                        (model call 2: writes the answer)
```

The OpenTelemetry GenAI conventions attach standard attributes to these spans. The most useful ones are:

| Attribute | Example | Why you need it |
|---|---|---|
| `gen_ai.operation.name` | `chat`, `execute_tool`, `invoke_agent` | Groups spans by kind |
| `gen_ai.agent.name` | `support` | Splits metrics per agent in multi-agent systems |
| `gen_ai.request.model` | `model-x` | Cost and quality per model |
| `gen_ai.provider.name` | `openai`, `anthropic` | Replaces the older `gen_ai.system` |
| `gen_ai.usage.input_tokens` / `output_tokens` | 2020 / 120 | Cost calculation |
| `gen_ai.usage.cache_read.input_tokens` | 1500 | Shows prompt cache savings |
| `gen_ai.tool.name`, `gen_ai.tool.call.id` | `search_orders` | Links tool spans to the model's tool call |

The conventions also specify span names (`invoke_agent {gen_ai.agent.name}`, `plan {gen_ai.agent.name}`) and span kinds (`INTERNAL` for an in-process agent invocation or a plan, `CLIENT` for `create_agent`, which usually calls a remote service). Because these are standard, a span emitted by one library can be read by any compatible backend.

## Tracing an agent with Langfuse 5.2, offline

Langfuse normally exports spans to a Langfuse server. Passing an OpenTelemetry `InMemorySpanExporter` as `span_exporter` keeps them in memory instead, so you can inspect exactly what would be sent. The model below is a stub that sleeps for 50 ms and returns token counts.

```python
# pip install langfuse==5.2.0 opentelemetry-sdk==1.45.2
import time
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from langfuse import Langfuse

exporter = InMemorySpanExporter()                     # keep spans in memory instead of sending them
lf = Langfuse(public_key="pk-lf-local", secret_key="sk-lf-local", base_url="http://localhost:3000",
              span_exporter=exporter, flush_at=1)

def fake_llm(step):                                   # stands in for a real model call
    time.sleep(0.05)
    return {"input": 1200 + 400 * step, "output": 90}

with lf.start_as_current_observation(name="support-agent", as_type="agent", input={"q": "Where is order 1042?"}) as agent:
    for step in range(2):
        with lf.start_as_current_observation(name=f"llm-step-{step}", as_type="generation", model="model-x") as gen:
            u = fake_llm(step)
            gen.update(usage_details=u, cost_details={"input": round(u["input"] * 3e-6, 6), "output": round(u["output"] * 15e-6, 6)})
        if step == 0:
            with lf.start_as_current_observation(name="lookup_order", as_type="tool", input={"order_id": 1042}) as t:
                time.sleep(0.12)
                t.update(output={"status": "shipped"})
    agent.update(output="Order 1042 shipped yesterday.")
lf.flush()

spans = sorted(exporter.get_finished_spans(), key=lambda s: s.start_time)
names = {s.context.span_id: s.name for s in spans}
for s in spans:
    a = s.attributes
    print(f"{s.name:13} {a.get('langfuse.observation.type'):10}"
          f"{(s.end_time - s.start_time) / 1e6:6.0f} ms  parent={names.get(s.parent.span_id) if s.parent else '-'}"
          f"  usage={a.get('langfuse.observation.usage_details', '')}  cost={a.get('langfuse.observation.cost_details', '')}")
gen = next(s for s in spans if s.name == "llm-step-1")
print(sorted(k for k in gen.attributes if k.startswith("langfuse.observation")))
```

```text
support-agent agent        223 ms  parent=-  usage=  cost=
llm-step-0    generation    50 ms  parent=support-agent  usage={"input": 1200, "output": 90}  cost={"input": 0.0036, "output": 0.00135}
lookup_order  tool         121 ms  parent=support-agent  usage=  cost=
llm-step-1    generation    51 ms  parent=support-agent  usage={"input": 1600, "output": 90}  cost={"input": 0.0048, "output": 0.00135}
['langfuse.observation.cost_details', 'langfuse.observation.model.name', 'langfuse.observation.type', 'langfuse.observation.usage_details']
```

What the trace tells you, step by step:

1. **The root span covers the run.** The agent span took 223 ms, which is the sum of its children (50 + 121 + 51 ms) plus a little overhead.
2. **The tool dominates latency.** The tool span alone is 121 ms, more than half the run. In a real system this is where you would look first.
3. **Input tokens grow per step.** The second model call reads 1,600 input tokens against 1,200 for the first, because the tool result was appended to the context.
4. **Cost is per generation.** The run cost 0.0036 + 0.00135 + 0.0048 + 0.00135 = 0.0111 USD at the example prices of 3 USD per million input tokens and 15 USD per million output tokens. If you omit `cost_details`, Langfuse can infer costs from model price definitions on the server instead.
5. **Everything is an OpenTelemetry span.** The Langfuse-specific details are attributes like `langfuse.observation.type`, so the same span can be sent to another backend.

In a LangChain or LangGraph app you rarely write these spans by hand. Langfuse's `langfuse.langchain.CallbackHandler` records each chain, model and tool call, and `propagate_attributes(user_id=..., session_id=...)` stamps every span in a block with the user and session so you can filter traces by them later.

## From spans to numbers: latency and cost at scale

A single trace explains one failure. Dashboards need aggregates. The script below uses plain OpenTelemetry with GenAI attributes to simulate 1,000 runs, each with one to four model calls and a tool call between each pair. Each tool result adds 400 tokens to the context, and each answer adds 120.

```python
# pip install opentelemetry-sdk==1.45.2
import random, statistics
from collections import defaultdict
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter

exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer("agent-demo")
PRICE_IN, PRICE_OUT = 3.00 / 1e6, 15.00 / 1e6          # example prices in USD per token
rng = random.Random(7)

def run_agent(t0):
    """Simulate one agent run: 1-4 model calls with a tool call between each pair."""
    steps = rng.choice([1, 2, 2, 3, 3, 4])
    t, ctx_tokens = t0, 1500
    root = tracer.start_span("invoke_agent support", start_time=t0,
                             attributes={"gen_ai.operation.name": "invoke_agent", "gen_ai.agent.name": "support"})
    parent = trace.set_span_in_context(root)
    for i in range(steps):
        dur = int(rng.uniform(0.6, 2.5) * 1e9)
        s = tracer.start_span("chat model-x", context=parent, start_time=t, attributes={
            "gen_ai.operation.name": "chat", "gen_ai.provider.name": "example", "gen_ai.request.model": "model-x",
            "gen_ai.usage.input_tokens": ctx_tokens, "gen_ai.usage.output_tokens": 120})
        t += dur; s.end(end_time=t)
        ctx_tokens += 120
        if i < steps - 1:
            dur = int(rng.uniform(0.1, 1.5) * 1e9)
            s = tracer.start_span("execute_tool search_orders", context=parent, start_time=t, attributes={
                "gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": "search_orders"})
            t += dur; s.end(end_time=t)
            ctx_tokens += 400                              # tool result appended to the context
    root.end(end_time=t)

for k in range(1000):
    run_agent(k * 10**11)

runs = defaultdict(lambda: {"cost": 0.0, "lat": 0.0, "calls": 0, "tool_s": 0.0})
for s in exporter.get_finished_spans():
    r, a = runs[s.context.trace_id], s.attributes
    if a["gen_ai.operation.name"] == "invoke_agent":
        r["lat"] = (s.end_time - s.start_time) / 1e9
    elif a["gen_ai.operation.name"] == "chat":
        r["calls"] += 1
        r["cost"] += a["gen_ai.usage.input_tokens"] * PRICE_IN + a["gen_ai.usage.output_tokens"] * PRICE_OUT
    else:
        r["tool_s"] += (s.end_time - s.start_time) / 1e9

lat = sorted(r["lat"] for r in runs.values()); cost = sorted(r["cost"] for r in runs.values())
q = lambda xs, p: xs[int(p * (len(xs) - 1))]
print(f"runs={len(runs)} spans={len(exporter.get_finished_spans())}")
print(f"latency p50={q(lat, .5):.2f}s p95={q(lat, .95):.2f}s")
print(f"cost/run mean=${statistics.mean(cost):.4f} p95=${q(cost, .95):.4f}  total=${sum(cost):.2f}")
by_calls = defaultdict(list)
for r in runs.values(): by_calls[r["calls"]].append(r["cost"])
for c in sorted(by_calls): print(f"  {c} model calls: {len(by_calls[c])} runs, mean ${statistics.mean(by_calls[c]):.4f}")
tool_share = sum(r["tool_s"] for r in runs.values()) / sum(r["lat"] for r in runs.values())
print(f"share of wall time spent in tools: {tool_share:.0%}")
```

```text
runs=1000 spans=4992
latency p50=4.79s p95=9.21s
cost/run mean=$0.0194 p95=$0.0346  total=$19.38
  1 model calls: 171 runs, mean $0.0063
  2 model calls: 342 runs, mean $0.0142
  3 model calls: 307 runs, mean $0.0236
  4 model calls: 180 runs, mean $0.0346
share of wall time spent in tools: 23%
```

Check the cost lines by hand. A one-call run reads 1,500 input tokens and writes 120: 1,500 × 3 / 1,000,000 + 120 × 15 / 1,000,000 = 0.0045 + 0.0018 = 0.0063 USD. A four-call run reads 1,500, 2,020, 2,540 and 3,060 input tokens, 9,120 in total, so it costs 0.02736 + 4 × 0.0018 = 0.0346 USD. Four calls cost 5.5 times as much as one, not 4 times, because each call rereads a longer context. The [agent loop token cost simulation](/ai-simulations/agent-loop-token-cost) shows the same growth.

Three lessons come out of these numbers:

- **Report percentiles, not averages.** The p95 latency (9.21 s) is nearly twice the median (4.79 s). Users remember the slow runs.
- **Slice cost by step count.** The step count explains almost all the cost spread here. In production, a rising share of four-step runs is an early warning of tool failures or confused prompts.
- **Find where time goes.** Tools take 23% of wall time in this simulation; the rest is model time. That tells you whether to optimise prompts and models or tools. See [cost and latency budgets](/tools/cost-and-latency-budgets) for setting limits.

## Debugging one bad run, step by step

Aggregates tell you that something is wrong. A single trace tells you why. Suppose the dashboard shows that the share of four-step runs rose from 18% to 30% after a release. A practical debugging routine looks like this:

1. **Filter to the change.** Select traces from the new release with four or more model calls and compare them with traces from the old release for similar requests.
2. **Read the first divergence.** Open one bad trace and walk the spans in order. Look for the first step where the run differs from a good one: usually a tool input with a wrong argument, or a tool output that is empty or an error.
3. **Check the model's view.** Open the model span just before the bad step and read the full input. Often the tool description changed, a retrieved document is missing, or an earlier tool result was truncated.
4. **Confirm with counts.** Group the bad traces by the suspected cause, for example by tool name and error status, and check that it explains most of them rather than one case.
5. **Turn it into a test.** Save the failing input as an evaluation case, so the fix can be checked before the next release.

This is where consistent attributes pay off. If every tool span carries `gen_ai.tool.name` and an error status, step 4 is one query. If tool names are free text inside span names, it is an afternoon of manual reading. In multi-agent systems, also group by `gen_ai.agent.name`, because one misbehaving worker can inflate the cost of the whole run.

## Choosing a backend

| Backend | How data gets in | Strengths | Notes |
|---|---|---|---|
| [Langfuse](/tools/langfuse) | Langfuse SDK (OpenTelemetry-based), LangChain callback, OTLP | Open source, self-hostable, prompts, datasets and scores in the same tool | Typed observations: agent, tool, generation and more |
| [Arize Phoenix](/tools/phoenix) | `phoenix.otel.register` plus OpenInference instrumentors | Open source, local-first, strong evaluation features | Uses OpenInference attribute names alongside OpenTelemetry |
| [LangSmith](/tools/langsmith) | LangChain native tracing, `@traceable`, OpenTelemetry | Deep LangGraph integration, evaluation and review queues | See [our LangSmith 0.16 guide](/articles/langsmith-0-16-tracing-offline-evaluation) |
| Any OTLP backend | OpenTelemetry SDK and GenAI conventions | Reuses existing APM, alerting and retention | Less LLM-specific UI |

The practical advice is to instrument once with OpenTelemetry-compatible tooling, so you can change backends or send to two at once. The [OpenTelemetry tool page](/tools/opentelemetry) covers collectors and exporters.

## What it means in practice

Agent observability has two jobs. The first is debugging: open one bad run and see each prompt, tool input and output in order. Langfuse, Phoenix and LangSmith all do this well, and the [agent trace simulation](/ai-simulations/agent-trace) walks through reading one. The second is operations: aggregate spans into latency percentiles, cost per run, error rates per tool and token growth per step, and alert on drift. That second job is where the standard GenAI attributes pay off, because your dashboards keep working when you swap a framework or model.

Traces are also the raw material for evaluation. Scores from LLM judges or user feedback attach to traces, and failing traces become new test cases. Treat the trace store as the start of your evaluation loop, not just a log.

## What to do now

1. **Instrument the root and the leaves.** Make sure every run has one root agent span and every model and tool call is a child of it.
2. **Record tokens on every model span.** Capture input, output and cached input tokens so cost and cache savings can be computed later.
3. **Add user and session IDs.** Use `propagate_attributes` in Langfuse, or equivalent attributes elsewhere, so you can follow one user's experience.
4. **Name agents and tools consistently.** Stable `gen_ai.agent.name` and `gen_ai.tool.name` values make dashboards and alerts possible.
5. **Track p50, p95 and cost per run.** Slice them by model, agent, step count and release version.
6. **Test your tracing offline.** Use an in-memory exporter in unit tests to assert that the expected spans and attributes are emitted.
7. **Mask sensitive data.** Use the Langfuse `mask` option or a collector processor before prompts and tool outputs leave your network.
8. **Sample with care.** Keep all error traces and a fixed fraction of successes; the Langfuse client has a `sample_rate` option.

## Risks and open questions

**Traces contain sensitive data.** Prompts, tool outputs and retrieved documents often include personal or confidential information. Decide what is stored, for how long and who can read it.

**Conventions are still moving.** The GenAI agent conventions are in Development status, and attributes have already been renamed once (`gen_ai.system` to `gen_ai.provider.name`). Pin versions and expect migrations.

**Cost numbers can be wrong.** Prices change, cached tokens are billed differently, and reasoning tokens may be reported separately. Reconcile your trace-based cost estimates with provider invoices.

**Volume adds up.** A long agent run can emit hundreds of spans with large payloads, which costs storage and can slow exports. Batch exports and truncate large attributes.

**Watch next:** adoption of the new `plan` span by framework instrumentations, and whether trace backends converge on the GenAI conventions rather than vendor-specific attribute names.

## Frequently asked questions

### What is the difference between logging and tracing for agents?

Logs are separate lines of text. A trace links every step of one run into a tree with timing, so you can see that a slow answer came from the third tool call, and what the model saw before it. For agents with many steps, traces are far easier to debug.

### Do I need Langfuse if I already use OpenTelemetry?

Not strictly. Any OpenTelemetry backend can store GenAI spans. Langfuse, Phoenix and LangSmith add LLM-specific views such as prompt and completion rendering, token and cost tracking, datasets and evaluation scores.

### How do I compute the cost of an agent run?

Sum the cost of each model call in the trace: input tokens times the input price plus output tokens times the output price, with cached and reasoning tokens priced as your provider bills them. In the demo a four-call run cost 0.0346 USD because each call reread a longer context.

### Why is p95 latency more useful than the average?

Agent latency has a long tail, because some runs take more steps or hit slow tools. In the simulation the p95 was 9.21 seconds against a median of 4.79 seconds. An average hides those slow runs, which are the ones users complain about.

### Can I test tracing without a server?

Yes. The Langfuse client accepts a `span_exporter`, and the OpenTelemetry SDK provides an `InMemorySpanExporter`. Both demos in this article run fully offline and print the spans that would have been exported.

## Summary

Agent observability records each run as a tree of spans: one root for the agent, children for model calls and tool calls, with tokens, cost and timing as attributes. Langfuse 5.2, Phoenix 22 and LangSmith all build on OpenTelemetry, and the GenAI conventions give these spans standard names such as `invoke_agent`, `chat`, `execute_tool` and the new `plan`. The offline demos showed a single trace where a tool took more than half the run, and 1,000 simulated runs with a p95 latency of 9.21 seconds and a four-call run costing 5.5 times a one-call run. Instrument once with standard attributes, track percentiles and cost per run, and protect the sensitive data your traces contain.

## Sources

- [OpenTelemetry: Semantic conventions for GenAI agent and framework spans](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-agent-spans.md)
- [Langfuse Docs: Observation types](https://langfuse.com/docs/observability/features/observation-types)
- [Langfuse Docs: Instrumentation](https://langfuse.com/docs/observability/sdk/instrumentation)
- [Arize Phoenix Docs: LangChain tracing](https://arize.com/docs/phoenix/integrations/python/langchain/langchain-tracing)
- [PyPI: langfuse](https://pypi.org/project/langfuse/)
- [PyPI: arize-phoenix](https://pypi.org/project/arize-phoenix/)
- [PyPI: openinference-instrumentation-langchain](https://pypi.org/project/openinference-instrumentation-langchain/)
- [PyPI: opentelemetry-semantic-conventions](https://pypi.org/project/opentelemetry-semantic-conventions/)
