Why AI Agents Need Observability
Learn why AI agents fail silently and how to add tracing, logging, and metrics to debug and improve them.
The invisible failure
Your agent just spent 40 seconds and $0.30 in API calls to return a plausible but wrong answer. No error was thrown, no log line was written, and the user is staring at a confidently incorrect result. This is the everyday reality of building AI agents: they fail in ways that are invisible to traditional monitoring.
Unlike a typical web service where a 500 error is obvious, an agent can silently take a wrong tool call, loop forever, or produce a subtly wrong final answer. Without observability, you are flying blind. In this article, I will show you why standard logging is not enough and how to add real observability to your agent: tracing every step, logging every tool call, and measuring cost and latency.
- Traditional metrics (CPU, memory, error rate) miss the real failure modes of agents.
- Agents have non-deterministic control flow: the same prompt can take different paths.
- You need to see the chain of reasoning and tool calls to debug effectively.
What observability means for agents
Observability for AI agents means you can answer three questions about any run: What did the agent do? Why did it do it? How much did it cost? This goes beyond simple logging. You need structured traces that capture the full sequence of model calls, tool invocations, and intermediate thoughts.
In practice, this means instrumenting your agent loop to emit events at every step. Each event should include a trace ID, a timestamp, the model used, the prompt and completion (or at least a hash), the tool called, its input and output, and the duration. You also want to record token usage and cost.
Step 1: Instrument the agent loop
Start with a minimal agent loop. Here is a simple Python implementation using the OpenAI API. We will add tracing hooks that print structured JSON to stdout. In production, you would send these to a tracing backend like Langfuse, Phoenix, or even a simple log aggregator.
import json
import time
from openai import OpenAI
client = OpenAI()
def run_agent(user_input):
trace_id = str(time.time_ns())
messages = [{"role": "user", "content": user_input}]
steps = []
for step in range(5):
start = time.time()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools_schema,
)
duration = time.time() - start
message = response.choices[0].message
steps.append({
"trace_id": trace_id,
"step": step,
"model": "gpt-4o-mini",
"duration_s": round(duration, 3),
"tokens": response.usage.total_tokens,
"tool_calls": [tc.model_dump() for tc in message.tool_calls or []],
"content": message.content,
})
print(json.dumps(steps[-1]))
if message.tool_calls:
messages.append(message)
for tc in message.tool_calls:
result = execute_tool(tc.function.name, json.loads(tc.function.arguments))
messages.append({
"role": "tool",
"tool_call_id": tc.id,
"content": json.dumps(result)
})
else:
break
return steps
- Each step logs a trace ID so you can group all steps of one run.
- Record duration and token usage to compute cost later.
- Log tool calls and their results to see the agent's reasoning path.
Step 2: Add a tracing backend
Then initialize the client and wrap your agent calls. Langfuse provides a decorator that automatically captures inputs, outputs, and metadata. You can also create spans for each tool call.
from langfuse import Langfuse
from langfuse.decorators import observe
langfuse = Langfuse(
public_key="pk-...",
secret_key="sk-...",
host="https://cloud.langfuse.com"
)
@observe()
def run_agent_with_observability(user_input):
# your agent logic here
return result
- Use environment variables for API keys, never hardcode them.
- Langfuse automatically creates a trace for each invocation and spans for nested functions.
- You can add custom metadata like user ID or session ID.
Step 3: Log every tool call
Tool calls are where agents often go wrong. Maybe the tool returns an error, or the agent misuses the arguments. You need to log the exact input and output of every tool invocation. Here is an example of wrapping a tool function to capture that.
import functools
import json
import time
def traced_tool(name):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
try:
result = func(*args, **kwargs)
status = "success"
except Exception as e:
result = str(e)
status = "error"
duration = time.time() - start
print(json.dumps({
"event": "tool_call",
"tool": name,
"args": args,
"kwargs": kwargs,
"result": result,
"status": status,
"duration_s": round(duration, 3),
}))
return result
return wrapper
return decorator
@traced_tool("get_weather")
def get_weather(city: str):
# actual implementation
return {"temp": 20, "unit": "C"}
- Log the raw arguments and result, not just a summary.
- Include status (success or error) and duration.
- In production, send these to the same tracing backend using a span.
Step 4: Measure cost and latency
Cost and latency are critical for production agents. You need to know how much each run costs and where time is spent. Most LLM providers return usage data. Here is a simple script to compute cost from token counts.
def compute_cost(model, prompt_tokens, completion_tokens):
# Pricing as of 2025-06-01 for gpt-4o-mini
pricing = {
"gpt-4o-mini": {"input": 0.00015, "output": 0.0006},
"gpt-4o": {"input": 0.005, "output": 0.015},
}
if model not in pricing:
return None
p = pricing[model]
return (prompt_tokens / 1000) * p["input"] + (completion_tokens / 1000) * p["output"]
# Example usage
cost = compute_cost("gpt-4o-mini", 1500, 200)
print(f"Cost: ${cost:.4f}")
- Keep pricing in a config file or environment variable, as it changes.
- Log cost with each trace so you can aggregate per user or per session.
- Set alerts when cost per run exceeds a threshold.
Step 5: Add tracing to a simple agent
Now let's put it all together. Here is a minimal agent that uses a weather tool and sends traces to Langfuse. This is a complete, runnable example you can adapt.
import json
from openai import OpenAI
from langfuse.decorators import observe
client = OpenAI()
tools_schema = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current temperature for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
}
]
def get_weather(city: str):
# Mock implementation
return {"city": city, "temperature": 22, "unit": "C"}
@observe()
def run_agent(user_input: str):
messages = [{"role": "user", "content": user_input}]
for _ in range(5):
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools_schema,
)
message = response.choices[0].message
messages.append(message)
if message.tool_calls:
for tc in message.tool_calls:
args = json.loads(tc.function.arguments)
result = get_weather(**args)
messages.append({
"role": "tool",
"tool_call_id": tc.id,
"content": json.dumps(result)
})
else:
return message.content
return "Max steps reached"
if __name__ == "__main__":
print(run_agent("What's the weather in Berlin?"))
- The @observe() decorator captures the entire function call as a trace.
- Tool calls are automatically logged as spans if you also decorate them.
- Run this script and check the Langfuse dashboard to see the trace.
Verify it worked
After running the script, go to your Langfuse project and open the latest trace. You should see a timeline with the model call, the tool call, and the final response. Each span shows duration, token usage, and cost if configured.
If you don't see the trace, check that your public and secret keys are correct and that the host is reachable. Also ensure you have network access to Langfuse cloud or your self-hosted instance.
Troubleshooting common issues
Answers to the questions that come up most often on this topic.
- No traces appearing: verify your Langfuse credentials and that the decorator is on the function that actually runs.
- Missing tool call details: make sure you log the tool call arguments and results as shown in Step 3.
- Cost shows zero: ensure you set the pricing for the model you use, or use Langfuse's built-in pricing if available.
- Traces are too large: consider redacting sensitive data or truncating long prompts and completions.
- Latency spikes: check the duration of each span to find slow tool calls or model calls.
What I would do: a recommended setup
For a production agent, I would set up the following stack: Langfuse for tracing, structured JSON logs to stdout for development, and a simple metrics endpoint to track cost and latency over time. Here is a copy-paste starter for the logging part.
#!/bin/bash
export LANGFUSE_PUBLIC_KEY=your_public_key
export LANGFUSE_SECRET_KEY=your_secret_key
export LANGFUSE_HOST=https://cloud.langfuse.com
python your_agent.py > agent_logs.jsonl- Use environment variables for all secrets.
- Log in JSON Lines format so you can parse with jq or load into a log aggregator.
- Set up alerts for cost per run exceeding $0.10 or latency above 10 seconds.
FAQ
Answers to the questions that come up most often on this topic.
- Q: Can I use OpenTelemetry for agent tracing? A: Yes, OpenTelemetry is the standard for distributed tracing. Langfuse and Phoenix support OTLP, so you can export traces to your existing OTel collector.
- Q: What if I use a framework like LangChain or LlamaIndex? A: These frameworks have built-in callbacks for popular tracing tools. You can enable Langfuse or Phoenix with a single line of code.
- Q: How do I trace agents that use multiple models? A: Log the model name in each span. Then you can filter and compare performance per model.
- Q: Is tracing expensive? A: The overhead is minimal, usually a few milliseconds per event. The cost of storing traces is far less than the cost of debugging blind.
- Q: Do I need to trace every run? A: In production, sample traces (e.g., 10%) to reduce overhead, but always trace errors and high-cost runs.
Next step: run a trace today
The fastest way to start is to add a simple print statement to your agent loop, as shown in Step 1. Then, when you hit a failure, you can inspect the trace and see exactly what went wrong. Once you are comfortable, integrate a tracing backend for long-term visibility.
Create a new file called trace_demo.py with the minimal loop from Step 1, run it with a prompt that triggers a tool call, and inspect the JSON output. That is your first observability win.
Key takeaways
- Apply one concrete change from this post before collecting more reading.
- Prefer browser-side tools when the work involves secrets, tokens, or PII.
- Document the why next to the how so the next reviewer inherits context.
FAQ
- Who is this guide on ai-agents for?
- Working developers who need a practical take on why ai agents need observability — not a marketing overview. Skim the sections, apply one tip, then come back when you hit an edge case.
- Do I need an account to use the related tools?
- No. code.live tools run in your browser with no signup. Nothing you paste is uploaded to a server for the client-side utilities linked from this post.
- How often is this article updated?
- This post was published November 26, 2026. Fundamentals stay stable; check linked tool pages and official docs when version-specific behavior matters.