Skip to main content
All posts
Engineering

Tracing for agentic applications: a developer's guide

Dr. Harry Cruz

Dr. Harry Cruz

• 15 min read

Tracing for agentic applications: a developer's guide

The bug that returns HTTP 200

You ship an LLM-powered feature. It passes your test suite, handles edge cases well, and the demo goes fine. Two weeks later, users start reporting wrong answers. Not errors, wrong answers. The API returns HTTP 200, latency looks normal, your monitoring dashboards are green.

You open the logs. Nothing useful. The "bug" isn't a null pointer or a failed assertion. It's a hallucination buried inside a chain of LLM calls, retrieval steps, and tool invocations. You can't console.log your way through this because the logic lives in prompts, not in code.

For decades, software bugs were logical errors traceable to a specific line. Same input, same output. LLM applications break that assumption. Same prompt, different day, different output. The model updated. The retrieved context changed. The temperature setting drifted. I think of this as the "determinism gap," and it's why traditional debugging falls apart for AI applications.

Tracing bridges this gap. It captures LLM calls, tool invocations, retrieval steps, with the full content that went in and came out. It makes LLM applications debuggable. And the complexity of what you need to trace grows fast as you move from simple calls to agents to multi-agent systems.

What tracing means for LLM apps (vs. traditional APM)

APM — Application Performance Monitoring — is the practice of tracking how your software behaves in production: response times, error rates, throughput, database query latency. Tools like Datadog, New Relic, and Honeycomb have been doing this for over a decade. If you already run one of these, you might wonder why you can't just use it for LLM apps. The short answer: they were built for a different problem.

A single LLM call costs $0.01–$0.50, which is 10–500x what a database query costs. Traditional APM doesn't track per-request cost because for most services, the marginal cost of one more HTTP call is effectively zero. For LLM apps, it's the number you care about most.

You also can't debug a hallucination without reading the prompt. Traditional traces store HTTP status codes and response times, not 10KB prompts and completions. As the Langfuse team put it, "metrics like cost, latency, and quality cannot be purely derived from traces as they are in traditional applications." On top of that, execution is non-deterministic — same input, different output — so you need the full context (prompt, model parameters, temperature) to have any hope of reproducing an issue. And the data volume is just different: prompts and completions are 10–100KB each, not 200-byte HTTP payloads, which creates storage problems that traditional span stores weren't built for.

DimensionTraditional APMLLM Tracing
Key metricLatency, error rateTokens, cost, quality
Payload size~200 bytes10–100KB
Debugging needsStack traceFull prompt + completion
Cost modelCompute timePer-token pricing
DeterminismSame input → same outputSame input → different output

Traditional APM vs LLM tracing: what each cares about.

The landscape: tools that exist today

The tooling splits into three camps, organized by how they approach the problem rather than by feature checklist. For broader comparisons, see the landscape surveys from Comet, LangWatch, Braintrust, and AIMultiple.

Framework-native tools

LangSmith comes from the LangChain team. If you're already using LangChain or LangGraph, setup is a single environment variable. It captures every step with a visual trace view, a prompt playground, and automated evals. Free tier gives you 5k traces/month; Plus runs $39/user/month. The catch: the best experience requires LangChain. Cloud SaaS only (self-hosting is an Enterprise add-on). If you migrate away from LangChain, your observability investment goes with it.

Open-source platforms

Langfuse is the open-source leader with 19k+ GitHub stars (MIT license). It's self-hostable, ships native SDKs for Python and JavaScript, and has 50+ framework integrations. The team recently adopted OpenTelemetry as their data model. Free cloud tier gives you 50k observations/month. The tradeoffs: self-hosting requires ClickHouse + Redis + S3, and benchmarks show roughly 15% overhead in multi-step pipelines.

Arize Phoenix has been OTel-native from day one (7.8k+ stars). It runs in notebooks or as a single Docker container, and is particularly strong on embeddings analysis and LLM-as-judge evals. It uses its own OTel-compatible instrumentation layer called OpenInference. The tradeoff: it leans more toward evaluation than production monitoring, and the collaboration features are less polished than Langfuse.

Integrate-with-existing

Traceloop/OpenLLMetry (6.6k+ stars) is a set of pure OTel instrumentation libraries. If you already run Datadog, Honeycomb, or Grafana, this pipes LLM traces directly into your existing stack. The tradeoff: it's a thin layer, and you still need a backend to actually make sense of the traces.

Datadog LLM Observability natively supports OTel GenAI Semantic Conventions (v1.37+). Enterprise-grade, ties LLM performance to infrastructure metrics. The tradeoff: it's expensive, heavy, and overkill for most AI-native teams.

[Confident AI](https://www.confident-ai.com/) is a managed AI quality platform that integrates with existing models, frameworks, and application stacks. It combines tracing with online evals, production signals, native red teaming, and AI governance. The tradeoff: it is closed source and geared toward enterprise-wide AI quality rather than lightweight standalone tracing.

Helicone takes a proxy-based approach, sitting between your app and the LLM provider. Simple setup, but it adds latency, only works for HTTP-based LLM calls, and can't trace internal tool calls or agent logic.

Worth mentioning: W&B Weave (experiment tracking lineage), Braintrust (purpose-built query engine), Opik by Comet (fastest logging benchmarks in recent comparisons).

Here's how they compare at a glance:

ToolApproachOTel supportSelf-hostFree tierMain limitation
Arize PhoenixOpen-source platformNativeYesOpen-sourceEvaluation-focused
Confident AIEnterprise AI quality platformYesEnterpriseYesClosed-source managed platform
Datadog LLM ObsEnterprise APMYesNoNoExpensive
HeliconeProxyNoNoYesCan't trace agent logic
LangfuseOpen-source platformYesYes50k obs/moSelf-hosting complexity
LangSmithFramework-nativeNoEnterprise only5k traces/moLocked to LangChain
OpenLLMetryOTel librariesNativeN/AOpen-sourceNo backend included

LLM observability tools at a glance.

The question developers should actually ask: "Will I still be using the same framework in 12 months?" Framework churn is real. 2022 was vanilla OpenAI, 2023 was LangChain, 2024–25 brought LangGraph, CrewAI, AutoGen, and plenty of custom implementations. Your observability shouldn't be coupled to today's framework choice.

OpenTelemetry: foundation or overhead?

OpenTelemetry gets presented as the obvious answer for LLM tracing. The reality is messier than that.

What OTel gives you:

  • A vendor-neutral trace format (OTLP). Send traces to Jaeger, Grafana, Datadog, or your own backend.
  • An ecosystem of exporters, processors, and samplers.
  • Context propagation across service boundaries, which is critical for distributed agents.
  • Growing adoption: Datadog, Langfuse, and Arize all support or build on OTel.

What OTel doesn't give you yet:

The GenAI semantic conventions exist but are at various stages of maturity:

Convention areaStatusNotes
LLM spansDevelopmentAttributes change between versions; tools must opt in via OTELSEMCONVSTABILITYOPTIN
Prompt/completion contentOpt-in sensitiveNo consensus on storing large payloads; OTel recommends span events over attributes
Cost trackingNot specifiedNo primitives in the spec
Agent spansDraftCovers agent creation and invocation; based on Google's AI agent whitepaper
Agentic systemsProposalIssue #2664, still under active discussion

GenAI semantic conventions: current maturity (early 2026).

On top of the maturity gaps, different tools use different attribute names for the same concepts (ai.tokens.input vs gen_ai.usage.input_tokens), which defeats the point of having conventions. The OTel community is actively working on evolving these standards, but as of early 2026, they're not production-stable.

The honest take: OTel is the right foundation. It's a data format and transport protocol, not an observability solution by itself. The value is portability: your traces aren't locked into one vendor's format. The cost is verbosity and the need to build your own semantic layer on top until the conventions stabilize.

How we approached this at Rhesis: We built on OTel for transport but defined our own semantic conventions (ai.llm.invoke, ai.tool.invoke, ai.agent.invoke) as typed constants because the official ones weren't ready. When OTel conventions stabilize, migration is a constant rename, not a schema rewrite. We deliberately chose primitive operation names over framework concepts, ai.llm.invoke instead of ai.langchain.chain, so traces remain comparable regardless of which framework generated them.

From simple to complex: what traces tell you at each level

Each level of complexity adds new questions that only traces can answer.

Level 1: single LLM call

[ai.llm.invoke] ── 1.2s, 150 in / 80 out tokens, $0.012, model=gpt-4

Even this simple trace answers useful questions: is this call slow? Are the prompts bloated? Did the model stop naturally or hit the max_tokens cutoff? What did it actually cost?

Here's a concrete example. Users report slow responses. You pull traces and see the system prompt is 3,000 tokens — 10x what's needed. Trim it, and latency drops 40%, costs drop 60%.

With Rhesis, instrumenting this is one decorator:

from rhesis.sdk import observe
@observe.llm(provider="openai", model="gpt-4")
def summarize(text: str) -> str:
return client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": text}]
).choices[0].message.content

That single line handles span creation, status management (OK on success, ERROR on exception), and token capture. The equivalent raw OpenTelemetry code runs about 18 lines with manual try/except, setstatus, and recordexception calls.

Level 2: RAG pipeline

[function.answer_question] ── 2.3s total
├─ [ai.embedding.generate] ── 50ms, 12 tokens
├─ [ai.retrieval] ── 200ms, top_k=5, backend=pinecone
└─ [ai.llm.invoke] ── 2.0s, 1200 in / 150 out, $0.045

Now you can see where time is actually spent (retrieval vs. generation), whether you're stuffing too many documents into the prompt, and what each step costs individually.

This matters in practice. Say answer quality degrades. You pull traces and the retrieval step is returning irrelevant documents, inflating the prompt with noise. The LLM is fine; your vector search is the problem. Without per-step traces, you'd blame the model.

Level 3: agentic loop (ReAct, tool-use)

[function.agent_task] ── 8.5s total, $0.23
├─ [ai.llm.invoke] "planning" ── 1.5s
├─ [ai.tool.invoke] "web_search" ── 2.0s
├─ [ai.llm.invoke] "reasoning" ── 1.8s
├─ [ai.tool.invoke] "calculator" ── 0.1s
├─ [ai.llm.invoke] "reasoning" ── 1.5s
└─ [ai.llm.invoke] "final_answer" ── 1.6s

This is where costs start to bite. Agents can 10x your spend through unnecessary iterations, and without traces you won't know why. The trace shows you the loop count (is the agent stuck?), tool selection quality, and the full reasoning chain visible in each LLM span's prompt and completion content.

A real example: a customer support agent takes 30 seconds and costs $2 per request. Traces show it calls the search tool 8 times with slightly rephrased queries, each returning roughly the same results. Add a cache, and the cost drops to $0.30.

One design point worth calling out: the spans here are ai.llm.invoke and ai.tool.invoke, not ai.agent.step or ai.react.iteration. Primitive operations, not framework abstractions. If you switch from LangChain's ReAct to a custom implementation, the trace structure stays the same. The orchestration changes; the operations don't. This is what "name operations, not orchestrations" means in practice.

Level 4: multi-agent system

[ai.agent.invoke] "coordinator" ── 15s total, $0.89
├─ [ai.agent.invoke] "researcher" ── 6s
│ ├─ [ai.llm.invoke] ── 1.5s
│ ├─ [ai.tool.invoke] "web_search" ── 2s
│ └─ [ai.llm.invoke] ── 2.5s
├─ [ai.agent.handoff] researcher → analyst
├─ [ai.agent.invoke] "analyst" ── 5s
│ ├─ [ai.llm.invoke] ── 2s
│ └─ [ai.llm.invoke] ── 3s
└─ [ai.agent.invoke] "writer" ── 4s
└─ [ai.llm.invoke] ── 4s

Now the questions get harder. Did the right context transfer between agents? Which agent is the bottleneck? Where is the cost concentrating? One bad output from an early agent cascades downstream through every agent that follows. Each handoff adds 100–500ms of latency and multiplies token consumption because the receiving agent needs to digest the sender's output.

Consider a multi-agent content pipeline that produces inconsistent quality. Traces show the "researcher" agent passes raw search results to the "analyst" instead of synthesized findings. The handoff content, captured as ai.agent.input and ai.agent.output events, reveals the gap. Without traces, you'd spend hours guessing which agent was at fault.

The hard problem here is that you need both the tree structure (which agent spawned which) AND the handoff content (what was passed between agents). Most tools give you one but not both. An analysis of multi-agent failures found that fewer than 10% of companies successfully scale beyond single-agent deployments, and coordination, monitoring, and cost control are the walls they hit.

Summary: what each level adds

LevelExampleWhat traces revealTypical cost per request
Single LLM callSummarizationLatency, token count, cost, finish reason~$0.01
RAG pipelineQ&A with retrievalPer-step timing, context window usage, cost breakdown~$0.05
Agentic loopTool-use agentLoop count, tool selection quality, reasoning chain~$0.23
Multi-agentCoordinator + specialistsHandoff quality, per-agent cost, failure propagation~$0.89

What each complexity level adds: what traces reveal and typical cost.

What to actually do with traces

Traces are useful only if you act on them. Here are concrete workflows, not abstract "insights."

Start with cost. Sort traces by total_cost descending and look at the top 10% most expensive requests. Often one or two prompt engineering changes cut costs by half. A bloated system prompt or unnecessary few-shot examples can multiply costs by 10x. This is usually the highest-ROI thing you can do with traces.

For latency, filter traces where duration > P95 and look at the span breakdown. Is the bottleneck the LLM call, the retrieval, or a tool invocation? High total latency often comes from slow retrieval rather than slow model inference, which points you toward database indexing instead of model selection.

Quality regressions are trickier. When users report "it used to work better," compare traces from last week to today. Did a prompt change? Did the retrieval context change? Did you switch models? Pick a few evals you'll actually act on: groundedness against retrieved docs, policy compliance, answer format validity. Splunk's guide on using traces for hallucination detection covers this workflow well.

For agentic apps specifically, set an alert when loop_count > N. Agents that reason too many times are usually stuck in a think-act cycle with no new information, burning tokens and user patience.

One workflow I keep coming back to is test-to-trace linking. Run your test suite, link each test result to its trace. When a test fails, click through to the exact LLM calls, prompts, and responses. You go from 30-minute debugging sessions to 30-second ones. We built this at Rhesis — traces automatically link to test executions via foreign keys, regardless of whether the test used the SDK, REST, or WebSocket endpoints. Patronus has a good walkthrough of similar debugging workflows.

Tracing with Rhesis

Everything discussed in this post — the semantic layer, the @observe decorators, the framework integrations — is available in the Rhesis SDK. Here's a quick look at what it gives you in practice.

The @endpoint decorator is where most people start. It combines tracing with remote testability: one decorator gives you OpenTelemetry spans and registers the function as a remotely-callable endpoint for automated testing.

from rhesis.sdk import endpoint
@endpoint(
request_mapping={"user_message": "{{ input }}"},
response_mapping={"output": "$.result.text"},
)
def chat(input: str, session_id: str = None):
return {"output": generate_response(input)}

If you use @observe.llm() or @observe.tool() inside the function, those spans nest automatically under the endpoint span. If you don't want the testing side and just want tracing, @observe works on its own.

For LangChain and LangGraph, auto-instrumentation is a single call:

from rhesis.sdk.telemetry import auto_instrument
auto_instrument("langchain", "langgraph")

After that, all LLM calls, tool invocations, and graph executions produce traces without touching your application code. More framework integrations are in progress.

Conversation tracing groups multi-turn interactions into a single trace. Pass a conversation_id when invoking an endpoint and all turns share the same root trace, so you can follow an entire conversation from first message to last.

Once traces land in the Rhesis platform, you get two ways to look at them. The Sequence View shows chronological call-and-return interactions between participants (agents, tools, LLMs) as a sequence diagram. The Graph View renders the execution as a directed graph with node relationships and animated playback, which is particularly useful for multi-agent flows where you want to see the coordination structure at a glance.

Graph View for a trace in the Rhesis Platform
Graph View for a trace in the Rhesis Platform

For full setup instructions, see the tracing documentation.

Design principles that held up

Building Rhesis's tracing taught us a few things that apply regardless of which tool you use.

The most important one: name operations, not orchestrations. ai.llm.invoke survives framework migrations. ai.langchain.chain doesn't. Your span naming is your data model; treat it as an API contract. We enforce this server-side: span names containing framework concepts (chain, workflow, pipeline) are rejected with HTTP 422 and a clear error message. It feels strict, but it prevents data model pollution that would make cross-framework analysis impossible.

Second, store everything and filter later. Storage costs about $0.10 per 1,000 traces. LLM costs run $1–10 per 1,000 requests. Storage is 1–10% of LLM cost. You can't debug what you didn't capture. We store prompts and completions as span events, separate from metadata attributes. This lets you apply retention policies to content without losing operational data.

Third, make tracing invisible. If it requires more than two lines per function, developers won't use it. @observe.llm(provider="openai", model="gpt-4") is one line. It handles span status, I/O capture, sync, async, and generator functions. The raw OpenTelemetry equivalent is about 18 lines of try/except blocks and manual set_status calls.

And finally, build on standards but extend with opinion. Use OTel for transport and format. But don't wait for committees to define your semantic layer. The GenAI conventions are still in Development status and changing between versions. Define your own typed constants and migrate when the standards stabilize. At Rhesis, every semantic string is a class constant (AIOperationType.LLMINVOKE, AIAttributes.MODELNAME) so migration is changing the constant value, not running find-and-replace across the codebase.

Where this leaves us

Once you move from demos to production, tracing stops being optional. The specific tool matters less than the approach: capture primitive operations, store the content, and make instrumentation easy enough that developers don't skip it. Whether that's Rhesis, Langfuse, or raw OpenTelemetry with your own semantic layer, the architecture should outlast whatever framework you're using today.

References

OpenTelemetry specifications and proposals:

Tool-specific:

Landscape comparisons:

Multi-agent challenges:

Practical guides: