AI Agent Failures: Production Observability Guide
In this article
This guide explains how to make AI agent failures visible in production by implementing structured logging, tracing, and evaluation pipelines. You'll learn concrete steps to detect, diagnose, and alert on agent missteps—from tool-call errors to hallucinated outputs—so your team can respond before users notice.
What You'll Need
- A deployed AI agent (e.g., built with LangChain, LlamaIndex, or a custom framework) that you can modify and redeploy.
- Access to your application's logging infrastructure (e.g., stdout, a log aggregator like ELK or Datadog, or a cloud logging service).
- Basic familiarity with JSON and your programming language of choice (Python, TypeScript, etc.).
- Optional: A vector database or evaluation framework for offline testing (e.g., LangSmith, Ragas, or custom scripts).
Step-by-Step
- Define what a failure looks like for your agent. Start by listing concrete failure modes: tool call errors (e.g., API timeout, invalid arguments), invalid final answers (e.g., hallucinated facts, off-topic responses), loop detection (agent repeating the same action), and user-reported dissatisfaction. For each, define a machine-checkable condition—for instance, a tool call that returns an HTTP 500, or a final answer that contains a specific placeholder.
- Add structured logging at every step. Modify your agent's code to emit a JSON log line for each event: user input, each tool call (with input and output), each LLM call (with prompt and response), and the final answer. Include a unique request ID, timestamp, and step number. Example: . Log to stdout or a dedicated file.
- Instrument the LLM calls themselves. Wrap your LLM API calls to capture latency, token usage, and the raw response. Log the model name, prompt, and completion. This helps distinguish between a model that returned a bad answer and a tool that failed.
- Add a tracing layer for multi-step reasoning. If your agent uses a framework like LangChain, enable built-in tracing (e.g., LangSmith or OpenTelemetry). For custom agents, create a simple span-based tracer that records each step's duration and parent-child relationships. This allows you to visualize the entire reasoning path in a trace viewer.
- Implement automatic failure detection. Write a small service or script that consumes your logs and flags events that match your failure definitions. For example, a regex that matches
"status": 5in tool outputs, or a check that the final answer contains"error". Use a rules engine or a simple Python script that reads logs from a queue. - Set up alerts for critical failures. Configure your monitoring system (e.g., Prometheus + Alertmanager, or cloud alerts) to notify your team when the failure rate exceeds a threshold (e.g., >5% of requests in 5 minutes). Include the request ID in the alert payload so you can jump to the trace.
- Build a dashboard for real-time visibility. Create a dashboard that shows key metrics: number of requests, success rate, average latency, token usage, and counts of each failure type. Use your log aggregator's query language to filter by event type. This gives you a live view of agent health.
- Add offline evaluation as a safety net. Periodically run a batch of test prompts against your agent and compare outputs against expected answers. Use a simple script that checks for exact matches or use an LLM-as-a-judge to score relevance. Log failures to a separate dataset for analysis.
- Create a runbook for common failures. Document the most frequent failure modes you observe—e.g., a specific API returning 429, or the model repeating a tool call. For each, write the likely cause and the first remediation step (e.g., increase timeout, add retry logic, adjust prompt). Store this runbook in your team's wiki.
- Iterate based on observed patterns. Review your dashboards and logs weekly. Identify the top failure causes and fix them—for instance, by adding better error handling in tool calls, or by adding a validation step that catches hallucinations before returning to the user.
Common Mistakes
- Logging only the final answer. Without intermediate steps, you can't diagnose where the failure occurred. Always log tool calls and LLM calls.
- Ignoring the prompt/context. A failed output might be due to a bad prompt. Log the full prompt (including system messages) to reproduce the issue.
- Using unstructured logs. Free-text logs are hard to query. Use JSON with consistent field names.
- Not setting a request ID. Without a unique ID, you can't correlate logs across steps. Generate one at the start of each request.
- Alerting on every error. This causes alert fatigue. Aggregate and threshold your alerts.
- Forgetting about token usage. High token consumption can indicate loops or inefficiency. Track it as a metric.
Tips
- Use a log sampling strategy for high-traffic agents—log 100% of failures but only 10% of successes to reduce volume.
- Add a
step_typefield to every log line to make filtering easier. - Include a
duration_msfield for each step to spot slow tool calls. - For hallucination detection, consider using a separate LLM call to verify the final answer against the context—but only for high-risk outputs to save cost.
- Store logs in a centralized system that supports full-text search and time-based queries.
- Set up a weekly review meeting to go through the top failure patterns and decide on fixes.
Troubleshooting
Logs are missing or incomplete. Check that your logging code is actually executed—add a test that triggers a tool call and verifies the log appears. Ensure your log aggregator is configured to receive from your application's stdout or file.
Alerts fire too often. Adjust the threshold and the time window. Also, filter out known benign errors (e.g., a tool that returns 404 for a valid query).
Trace visualization doesn't show full paths. If you're using a custom tracer, ensure you propagate the trace ID across async calls. If using a framework, read the docs to enable distributed tracing.
Offline evaluation gives false negatives. Your test prompts may not cover real-world cases. Use a small set of production logs to seed your evaluation set.
Can't correlate a user complaint with logs. Make sure you log the user session ID or conversation ID at the start of each request, and include it in all subsequent logs.
Frequently Asked Questions
Q: Do I need a special framework to add observability? A: No. You can add JSON logging manually in any agent code. Frameworks like LangChain have built-in tools, but they're optional.
Q: How do I detect a hallucination automatically? A: A simple heuristic is to check if the final answer contains entities not present in the context. More robustly, use an LLM judge to score faithfulness, but this adds cost.
Q: What if my agent is a single LLM call without tools? A: Then focus on logging the prompt and response, and use output validation (e.g., schema checks) to catch malformed responses.
Q: How often should I run offline evaluations? A: Start with every deployment. If your agent changes frequently, run them in CI on each commit; otherwise, weekly is fine.
Q: Can I use OpenTelemetry for tracing? A: Yes, OpenTelemetry supports custom spans. You can instrument your agent's steps manually and export to any compatible backend.
Q: What's the minimum I should implement first? A: Start with structured logging of tool calls and final answers, plus a simple alert on tool errors. That covers the most common failures.