Tracing and Observability: Seeing Inside a Failing AI Feature

Learn how to log every LLM call, token count, and tool result so that when your AI feature breaks in production, you can actually figure out why.

When AI Features Fail Silently

Here's a scenario I lived through: I shipped an AI feature that summarized customer support tickets. It worked great in testing. Then one morning I got a Slack message — "the summaries are garbage, it's just repeating the ticket back verbatim." I looked at the logs. All I had was POST /summarize 200 OK. No prompt. No response. No token count. Nothing.

That's the AI observability gap. Regular web requests fail loudly — 500 errors, stack traces, something to work with. AI features fail quietly. The request succeeds, but what comes back is wrong. And without tracing, you have no idea whether the problem was the prompt, the retrieved context, the model's response, or some tool call in the middle.

This article is about fixing that. We're going to add real observability to an AI feature so that when something breaks — not if, when — you can actually debug it.

What You Actually Need to Log

Before writing any code, let's talk about what matters. I've seen people log too little (just the final response) and too much (every internal variable on every frame). Neither helps.

For an AI feature, you want to capture these things per request:

  • The full prompt sent to the model — including any injected context or retrieved chunks
  • The model's raw response — before you parse or transform it
  • Token counts — input tokens, output tokens, and cached tokens if applicable
  • Tool calls and their results — every function the model invoked and what came back
  • Latency at each step — total time, plus time per tool call
  • A correlation ID — so you can tie a user complaint to a specific trace
  • Model and version — which model was used (this matters when you're experimenting)

That's your minimum viable trace. Without any of these, you're flying blind.

Building a Simple Trace Logger

Let's start with something you can drop into any project today — a lightweight wrapper that captures trace data around every AI call.

trace_logger.py
# A minimal trace logger for AI calls
import time
import uuid
import json
import logging
from dataclasses import dataclass, field
from typing import Optional, List, Any

logger = logging.getLogger("ai.trace")

@dataclass
class ToolCallTrace:
name: str
input: Any
output: Any
duration_ms: float
error: Optional[str] = None

@dataclass
class AITrace:
trace_id: str = field(default_factory=lambda: str(uuid.uuid4()))
model: str = ""
prompt: str = ""
system_prompt: str = ""
response: str = ""
input_tokens: int = 0
output_tokens: int = 0
cache_read_tokens: int = 0
total_duration_ms: float = 0
tool_calls: List[ToolCallTrace] = field(default_factory=list)
error: Optional[str] = None
metadata: dict = field(default_factory=dict)

def emit(self):
# Emit as structured JSON for log aggregators
logger.info(json.dumps({
"trace_id": self.trace_id,
"model": self.model,
"input_tokens": self.input_tokens,
"output_tokens": self.output_tokens,
"cache_read_tokens": self.cache_read_tokens,
"total_duration_ms": self.total_duration_ms,
"tool_calls": len(self.tool_calls),
"error": self.error,
"metadata": self.metadata,
# Full prompt/response logged at DEBUG to avoid noise
"prompt_preview": self.prompt[:200],
"response_preview": self.response[:200],
}))

The key design decision here: we log a preview of the prompt and response at INFO level, but store the full versions. This keeps your logs readable without throwing away detail you'll need later.

Wrapping Your Claude Calls

Now let's wrap an actual Claude API call so tracing happens automatically:

traced_client.py
import anthropic
import time
from trace_logger import AITrace, ToolCallTrace

client = anthropic.Anthropic()

def traced_call(system: str, user_message: str,
model: str = "claude-opus-4-5",
tools: list = None,
metadata: dict = None) -> AITrace:

trace = AITrace(
model=model,
system_prompt=system,
prompt=user_message,
metadata=metadata or {},
)

start = time.monotonic()

try:
messages = [{"role": "user", "content": user_message}]
kwargs = {"model": model, "max_tokens": 1024,
"system": system, "messages": messages}
if tools:
kwargs["tools"] = tools

# Agentic loop — handles tool calls automatically
while True:
response = client.messages.create(**kwargs)

# Capture token usage on every turn
trace.input_tokens += response.usage.input_tokens
trace.output_tokens += response.usage.output_tokens
if hasattr(response.usage, 'cache_read_input_tokens'):
trace.cache_read_tokens += response.usage.cache_read_input_tokens

if response.stop_reason == "end_turn":
trace.response = response.content[0].text
break

if response.stop_reason == "tool_use":
# Process each tool call and trace it
tool_results = []
for block in response.content:
if block.type == "tool_use":
t_start = time.monotonic()
result = execute_tool(block.name, block.input)
t_end = time.monotonic()

tc = ToolCallTrace(
name=block.name,
input=block.input,
output=result,
duration_ms=(t_end - t_start) * 1000,
)
trace.tool_calls.append(tc)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": str(result),
})

# Continue the conversation with tool results
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
kwargs["messages"] = messages

except Exception as e:
trace.error = str(e)
raise
finally:
trace.total_duration_ms = (time.monotonic() - start) * 1000
trace.emit()

return trace

The finally block is important — it emits the trace even when things go wrong. That's exactly when you need the data most.

Adding a Trace ID to Your API Responses

One thing that changed my debugging life: including the trace ID in your API response. When a user reports a bad response, they give you the trace ID and you can pull the exact call from your logs instantly.

api_handler.py
# In your FastAPI/Flask route:
@app.post("/summarize")
async def summarize_ticket(ticket: Ticket):
trace = traced_call(
system=SUMMARIZE_SYSTEM_PROMPT,
user_message=ticket.body,
metadata={"ticket_id": ticket.id, "user_id": ticket.user_id}
)
return {
"summary": trace.response,
"trace_id": trace.trace_id, # ← send this to the client
}

Show Trace IDs in Your UI

Even if users never see it, show the trace ID in your internal admin UI or support tool. When someone says "the summary was wrong at 2pm," you search your logs for their user ID in that time window and grab the trace ID — then replay the exact call.

Using OpenTelemetry for Proper Tracing

The home-rolled logger above is great for getting started, but once you're in production you'll want spans, parent-child relationships, and something you can visualize. OpenTelemetry is the standard here, and it plugs into Datadog, Honeycomb, Jaeger, and others.

otel_tracing.py
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter

# Wire up the provider once at startup
provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("ai.feature")

def traced_call_otel(system: str, user_message: str):
with tracer.start_as_current_span("llm.call") as span:
span.set_attribute("llm.model", "claude-opus-4-5")
span.set_attribute("llm.prompt_preview", user_message[:200])

response = client.messages.create(
model="claude-opus-4-5",
max_tokens=1024,
system=system,
messages=[{"role": "user", "content": user_message}]
)

span.set_attribute("llm.input_tokens", response.usage.input_tokens)
span.set_attribute("llm.output_tokens", response.usage.output_tokens)
span.set_attribute("llm.response_preview", response.content[0].text[:200])

return response.content[0].text

With OTEL in place, every AI call shows up as a child span under your HTTP request span. You get a visual waterfall — HTTP request → LLM call → tool call A → tool call B → LLM call 2. When something's slow or wrong, you can see exactly where in the chain it happened.

Dedicated AI Observability Tools

If you don't want to wire up OpenTelemetry yourself, there are purpose-built tools for LLM observability that are worth knowing about:

  • Langfuse — open source, self-hostable, has a great UI for browsing traces and running evals. This is what I'd reach for first on a new project.
  • LangSmith — LangChain's platform, works without LangChain, good if you're already in that ecosystem.
  • Helicone — a proxy that sits in front of the API and captures everything automatically. Zero code changes needed to get started.
  • Braintrust — combines tracing with evals, good if you want both in one place.

Helicone deserves a special mention for getting started fast. You literally change one line:

helicone_setup.py
# Before (direct to Anthropic)
client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)

# After (via Helicone proxy — zero other changes)
client = anthropic.Anthropic(
api_key=ANTHROPIC_KEY,
base_url="https://anthropic.helicone.ai",
default_headers={"Helicone-Auth": f"Bearer {HELICONE_KEY}"}
)

Every call now shows up in Helicone's dashboard with full prompt/response logging, latency, and token costs. It's genuinely the fastest path from "I have no visibility" to "I can see everything."

What to Alert On

Logging is only half of observability. The other half is knowing when to wake up. After going through a few production incidents, here's what I actually alert on for AI features:

  • High output token counts — if a call that normally returns 200 tokens suddenly returns 1800, something went wrong with the prompt or the model started rambling
  • Latency spikes — a call that normally takes 2 seconds taking 20 seconds means a tool call hung or the model is making too many steps
  • Tool call loops — if the same tool is called 5+ times in one request, your agent is probably stuck
  • Elevated error rates — obvious, but specifically watch for rate limit errors (429s) which often show up as a cascade when traffic spikes
  • Response length dropping to near-zero — the model returned something but it's basically empty, which often means a refusal or a parsing issue upstream

Log the Full Prompt on Errors

Keep the full prompt at INFO level by default if your data policies allow it, but definitely log it on any error. The number of times I've found the bug in the prompt itself — not the code — is embarrassing. You need to see exactly what the model received.

The Debugging Workflow That Actually Works

When a production AI issue lands in my lap, here's my actual process now that I have tracing in place:

1. Grab the trace ID from the user report or find it by searching logs for the user/time window. 2. Pull the full trace — look at the prompt first. Is the context correct? Is the system prompt what I expect? 3. Check tool calls — did they all succeed? What did they return? A tool returning an empty result or an error message is often the culprit. 4. Look at the response — is it cut off? Does it start confidently and then trail off? That's a max tokens issue. 5. Check token counts — are we near the context window limit? Long conversations sometimes eat up context and the model starts ignoring earlier instructions. 6. Compare against a known-good trace — find a trace where the feature worked correctly and diff the two side by side.

That last step — comparing a good trace against a bad one — is something I didn't think to do until a Langfuse demo showed it to me. It immediately revealed that a "bad" request was sending truncated context because of a chunking bug I'd introduced two days earlier. Without traces, I would have blamed the model for weeks.

AI features are going to fail in weird, non-obvious ways. That's just the nature of probabilistic systems. Tracing doesn't prevent failures — but it turns "I have no idea what happened" into "I can see exactly what the model received and what it said back." That's the difference between a two-hour debug session and a two-week mystery.

Keep going

More tutorials in this category, or explore the full field guide.

More Claude Code Tutorials Official Docs ↗