Your Agent Gave the Right Answer for the Wrong Reason — and You Have No Idea
From the publisher’s feed, collected in the ZeroLabs newsroom.
A practical framework for observability and evaluation of agentic AI systems — built to work on any use caseimage 1.1“LLMs are non-deterministic. You can’t really test them.”I heard this in a production review meeting after a multi-agent pipeline we built started returning confident, plausible, and occasionally incorrect answers. Nobody had caught it because nobody was looking at the steps — only the final output.That statement is one of the most dangerous half-truths in AI engineering today.You can’t test LLMs the way you test a sort function. But you absolutely can — and must — instrument, observe, and evaluate every step an agent takes to reach its answer. The failure to do so is not a technical limitation. It is a choice. And in production, it is an expensive one.TL;DR: Agents fail silently — the final answer can look fine while every intermediate step is wrong. Observability means capturing what the agent did; evaluation means judging whether those steps were good. This article walks through a practical custom framework to do both, for any agentic use case.The problem nobody talks about until it bites themMost teams evaluate their agents the way a restaurant critic reviews a meal by only reading the menu.You run the agent. You check the output. If it looks right, you ship. If it looks wrong, you tweak the prompt. You repeat this until the demo is clean, then you call it production-ready.This works until it doesn’t. And when it doesn’t, it usually fails in one of three ways:The right answer, wrong path. The agent returns the correct result but retrieved the wrong context, skipped a required tool call, and hallucinated the middle two reasoning steps. It passed your eval. It will fail on the next variant.The confident failure. The agent hits an error in step 3 of 7, silently falls back to its parametric knowledge, and confidently synthesises a response that has no grounding in your data. No error is thrown. Your eval passes. Your user is misled.The latency cliff. Everything works in testing. Under load at 2AM, the agent enters a retry loop, burns 80% of the context window on re-fetched tool outputs, and times out. You find out from a user complaint, not a dashboard.I have hit all three. The pipeline I mentioned earlier had the second failure mode running in production for three days before a domain expert noticed the pattern. We had excellent final-answer accuracy metrics. We had no trace visibility into what the agent was actually doing.That is what gap between observability and evaluation looks like in practice.Two concepts that must be separatedBefore building anything, get these definitions sharp. They are often conflated, and conflating them causes you to build the wrong thing.Observability is the infrastructure question: What did the agent do? It means capturing every step — every tool call, every retrieval, every model invocation, every intermediate output, every latency measurement — in a structured, queryable form. Observability is passive. It records. It does not judge.Evaluation is the quality question: Were those steps good? It means taking the traces you captured and applying judgement — heuristic, metric-based, or LLM-as-judge — to decide whether the agent behaved correctly, efficiently, and safely. Evaluation is active. It judges.You cannot evaluate what you cannot observe. And raw observation without evaluation is just a very large log file.Build them separately. Instrument first. Score second.Part 1: Observability — capturing every step the agent takesThe unit of observation is the span, not the responseStop thinking about your agent as a black box that produces outputs. Think about it as a tree of operations — a root span that represents the full agent run, with child spans for every action taken inside it.This is the mental model that OpenTelemetry and tracing frameworks like LangSmith, Arize Phoenix, and Helicone are built on. You do not need any of them to apply the model. You can implement it yourself in under 200 lines of Python.Here is the core data structure to capture for every span:from dataclasses import dataclass, fieldfrom typing import Any, Optionalimport time, uuid@dataclassclass AgentSpan: span_id: str = field(default_factory=lambda: str(uuid.uuid4())) parent_span_id: Optional[str] = None trace_id: str = "" # ties all spans in one run together span_type: str = "" # "llm_call" | "tool_call" | "retrieval" | "agent_step" name: str = "" # e.g. "search_knowledge_base", "generate_response" input: Any = None # what went in output: Any = None # what came out start_time: float = field(default_factory=time.time) end_time: Optional[float] = None latency_ms: Optional[float] = None token_usage: Optional[dict] = None # {"prompt": int, "completion": int} metadata: dict = field(default_factory=dict) # model name, temperature, tool name, etc. error: Optional[str] = None def close(self, output: Any = None, error: str = None): self.end_time = time.time() self.latency_ms = (self.end_time - self.start_time) * 1000 if output is not None: self.output = output if error is not None: self.error = errorWrap this around every meaningful operation in your agent. A LangGraph node becomes a span. A tool call becomes a span. A retrieval step becomes a span. An LLM invocation becomes a span.A minimal tracer that works with any frameworkThis TracerContext class can be dropped into a LangGraph workflow, a CrewAI agent, an AutoGen conversation, or a raw function-calling loop — without modifying your agent architecture:import jsonfrom contextlib import contextmanagerfrom typing import Listclass AgentTracer: def __init__(self, trace_id: str = None): self.trace_id = trace_id or str(uuid.uuid4()) self.spans: List[AgentSpan] = [] self._active_stack: List[str] = [] # stack of active span_ids @contextmanager def span(self, span_type: str, name: str, input: Any = None, metadata: dict = None): parent_id = self._active_stack[-1] if self._active_stack else None s = AgentSpan( trace_id=self.trace_id, parent_span_id=parent_id, span_type=span_type, name=name, input=input, metadata=metadata or {} ) self._active_stack.append(s.span_id) try: yield s s.close() except Exception as e: s.close(error=str(e)) raise finally: self._active_stack.pop() self.spans.append(s) def to_dict(self) -> dict: return { "trace_id": self.trace_id, "spans": [vars(s) for s in self.spans] } def save(self, path: str): with open(path, "w") as f: json.dump(self.to_dict(), f, indent=2)Usage inside a LangGraph node looks like this:def research_node(state: AgentState, tracer: AgentTracer): with tracer.span("tool_call", "web_search", input=state["query"]) as span: results = web_search_tool(state["query"]) span.metadata["num_results"] = len(results) return {"search_results": results}Two things happen here that matter. First, the span captures the input and output of the tool call. Second, the metadata field carries contextual signals — number of results, tool name, any parameter that might explain a failure downstream.What to capture at each layerDifferent span types need different metadata:Span type Essential fields to capture llm_call model name, temperature, prompt tokens, completion tokens, finish reason (stop vs. length vs. tool_calls) tool_call tool name, arguments, return value, status code if HTTP retrieval query, top-k, chunk IDs returned, similarity scores agent_step step number, action chosen, reasoning trace (if chain-of-thought is exposed) agent_run (root) total latency, total tokens, number of steps, final answerThe finish_reason from an LLM call is a cheap signal that teams routinely ignore. If it is length, the model hit the token limit and truncated its output. You should know about that. Capture it.Part 2: Evaluation — scoring what you observedThe three dimensions of agent qualityOnce you have traces, you need to decide what “good” means. After two years of building production agentic systems, I have converged on three dimensions that matter across every use case:1. Faithfulness — Does the final response stay grounded in the retrieved or provided context? Did the agent fabricate information not present in its sources?2. Step correctness — Did the agent take the right steps? Did it call the tools it was supposed to call, in a reasonable order, with reasonable arguments?3. Efficiency — Did the agent reach the answer without unnecessary steps, retry loops, or token waste?These map directly to the three failure modes I described earlier. Faithfulness catches the confident failure. Step correctness catches the right-answer-wrong-path problem. Efficiency catches the latency cliff before it manifests under load.Heuristic evaluators — fast and cheapSome signals don’t need an LLM to compute. Build these as deterministic functions that run on every trace:class HeuristicEvaluator:@staticmethod def step_count_score(spans: list, expected_max_steps: int = 8) -> dict: agent_steps = [s for s in spans if s["span_type"] == "agent_step"] count = len(agent_steps) score = max(0.0, 1.0 - max(0, count - expected_max_steps) * 0.1) return {"step_count": count, "step_efficiency_score": round(score, 2)} @staticmethod def tool_error_rate(spans: list) -> dict: tool_spans = [s for s in spans if s["span_type"] == "tool_call"] if not tool_spans: return {"tool_error_rate": 0.0} errors = [s for s in tool_spans if s.get("error")] return {"tool_error_rate": round(len(errors) / len(tool_spans), 3)} @staticmethod def context_truncation_flag(spans: list) -> dict: llm_spans = [s for s in spans if s["span_type"] == "llm_call"] truncated = [ s for s in llm_spans if s.get("metadata", {}).get("finish_reason") == "length" ] return {"context_truncation_detected": len(truncated) > 0, "truncated_calls": len(truncated)} @staticmethod def token_efficiency(spans: list) -> dict: llm_spans = [s for s in spans if s["span_type"] == "llm_call"] total_prompt = sum(s.get("token_usage", {}).get("prompt", 0) for s in llm_spans) total_completion = sum(s.get("token_usage", {}).get("completion", 0) for s in llm_spans) return {"total_prompt_tokens": total_prompt, "total_completion_tokens": total_completion}These run in microseconds. Run them on every trace automatically. Feed them to a dashboard. Set alerts when tool_error_rate crosses 0.1 or context_truncation_detected is true.LLM-as-judge — for the judgements that need languageSome evaluations require semantic understanding. Faithfulness, answer relevance, and step reasoning quality cannot be reliably scored with string matching or keyword heuristics. This is where LLM-as-judge earns its place.The key principle: the judge needs both the answer and the evidence. Never ask the judge to score an answer in isolation.import anthropicdef faithfulness_judge( question: str, retrieved_context: str, agent_answer: str, model: str = "claude-sonnet-4-20250514") -> dict: client = anthropic.Anthropic() prompt = f"""You are an evaluation judge assessing faithfulness of an AI agent's answer.QUESTION: {question}RETRIEVED CONTEXT (what the agent had access to):{retrieved_context}AGENT ANSWER: {agent_answer}Score the answer on FAITHFULNESS: Does every claim in the answer have support in the retrieved context?Respond in this exact JSON format:{{ "faithfulness_score": , "unsupported_claims": [], "reasoning": ""}}Return ONLY the JSON. No preamble.""" response = client.messages.create( model=model, max_tokens=500, messages=[{"role": "user", "content": prompt}] ) import json return json.loads(response.content[0].text)A few implementation notes from production experience:First, use a cheaper model for step-level evaluation and a stronger model for final-answer evaluation. Scoring every intermediate LLM call with your best model is expensive and usually unnecessary.Second, always ask the judge for reasoning alongside the score. A faithfulness_score of 0.4 with no explanation is not actionable. The unsupported_claims list tells you exactly where to look.Third, run the faithfulness judge against retrieved_context, not the full conversation history. This distinction matters: you want to know if the answer is grounded in what was retrieved, not whether it is internally consistent.Step-sequence evaluation — did the agent do the right things?For structured agentic workflows where the expected tool call sequence is known, you can evaluate the agent’s actual trace against an expected trace:from difflib import SequenceMatcherdef step_sequence_score( actual_tool_calls: list, # list of tool names in order called expected_tool_calls: list # list of tool names in expected order) -> dict: matcher = SequenceMatcher(None, actual_tool_calls, expected_tool_calls) similarity = matcher.ratio() missing = set(expected_tool_calls) - set(actual_tool_calls) extra = set(actual_tool_calls) - set(expected_tool_calls) return { "sequence_similarity": round(similarity, 3), "missing_tool_calls": list(missing), "unexpected_tool_calls": list(extra) }This is especially useful for agents with compliance or safety requirements — healthcare billing, legal document processing — where the sequence of steps is as important as the final answer.Part 3: Putting it together — the evaluation pipelineRun this on every trace, automatically:def evaluate_trace(trace: dict, question: str, expected_tools: list = None) -> dict: spans = trace["spans"] results = {} # Layer 1: Heuristics (always run, zero cost) results["heuristics"] = { **HeuristicEvaluator.step_count_score(spans), **HeuristicEvaluator.tool_error_rate(spans), **HeuristicEvaluator.context_truncation_flag(spans), **HeuristicEvaluator.token_efficiency(spans), } # Layer 2: Step sequence (if expected sequence is defined) if expected_tools: actual_tools = [ s["name"] for s in spans if s["span_type"] == "tool_call" and not s.get("error") ] results["step_sequence"] = step_sequence_score(actual_tools, expected_tools) # Layer 3: LLM judge (run on final answer only) final_answer_span = next( (s for s in reversed(spans) if s["span_type"] == "llm_call" and not s.get("error")), None ) retrieval_spans = [s for s in spans if s["span_type"] == "retrieval"] if final_answer_span and retrieval_spans: context = "\n\n".join( str(s.get("output", "")) for s in retrieval_spans ) results["faithfulness"] = faithfulness_judge( question=question, retrieved_context=context, agent_answer=str(final_answer_span.get("output", "")) ) return resultsThis three-layer approach is deliberate. Heuristics run on everything. Step sequence runs when you have a defined expected path. The LLM judge runs only on final answers, where the cost is justified.The metrics that actually matterAfter running this framework across multiple production deployments, these are the five numbers I put on every agent dashboard:Metric What it catches Alert threshold faithfulness_score Hallucination and unsupported claims 0.05 step_efficiency_score Retry loops, redundant calls 0.01 p95_latency_ms Production performance under load Depends on SLAThe most underrated one is context_truncation_rate. In six months of production monitoring, it has been my earliest warning signal for two different failure modes: prompts growing too large after tool output injection, and agents entering retry loops that inflate the context. Both show up here before they show up anywhere else.Where this approach breaks downThis framework assumes your agent returns some form of final answer and uses tool calls or retrieval as intermediate steps. That covers most agentic patterns today — ReAct agents, LangGraph workflows, CrewAI crews, function-calling loops.It is less useful for:Purely streaming or conversational agents where there is no discrete “final answer” span. You will need to define checkpoints manually and instrument them as root spans.Agents with human-in-the-loop steps where the trace is split across sessions. The trace_id needs to persist across sessions in this case — not just within a single run. Store it in your session state, not in memory.Very long-horizon agents (50+ steps) where the expected_tools approach for step sequence evaluation becomes impractical. At that scale, cluster-based analysis of trace patterns works better than sequence comparison.For all three, the observability layer stays the same. Only the evaluation layer needs adjustment.Start hereIf you have a working agent and no observability layer, here is the fastest path to value:In the next 30 minutes: Add the AgentSpan dataclass and AgentTracer context manager. Wrap your most important tool call. Run one trace. Look at the JSON. You will immediately see something you did not know was happening.This week: Add the four heuristic evaluators. Set up a simple CSV log that writes one row per trace with the key metrics. After 50 runs, you will have your first real data on where your agent spends tokens and where it fails.This month: Add the faithfulness judge on final answers. Compare faithfulness scores on passing runs versus failing runs. You will almost certainly find that the score distribution is bimodal — a clean pass cluster and a failure cluster with a visible gap between them. That gap is where your prompt engineering effort should go.The agents that fail silently in production are the ones where nobody looked at the steps. Looking is not hard. It just requires building the infrastructure to do it.ResourcesOpenTelemetry Python SDK — the open standard for distributed tracing, adaptable to LLM spansArize Phoenix — open-source LLM observability with LangGraph integrationLangSmith — tracing and evaluation for LangChain/LangGraph-based agentsRAGAS — evaluation framework with faithfulness, answer relevance, and context precision metricsAnthropic Claude API — used here as the LLM judge backendLangGraph documentation — for building the agentic workflows this framework instrumentsRibeiro et al. (2020), Beyond Accuracy: Behavioral Testing of NLP Models with CheckList — foundational thinking on behavioural evaluation [1]Zheng et al. (2023), Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena — the academic basis for LLM-as-judge evaluation [2]References[1] Ribeiro, M. T., Wu, T., Guestrin, C., & Singh, S. (2020). Beyond Accuracy: Behavioral Testing of NLP Models with CheckList. ACL 2020. https://arxiv.org/abs/2005.04118[2] Zheng, L., Chiang, W. L., Sheng, Y., et al. (2023). Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena. NeurIPS 2023. https://arxiv.org/abs/2306.05685Follow me on Medium for more articles on production agentic AI — I write about LangGraph, RAG systems, and building AI that actually works outside the demo.Your Agent Gave the Right Answer for the Wrong Reason — and You Have No Idea was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.