Skip to content
← Notebook

Agent Engineering

Agent Evals in 2026: The Fallacy of Evaluating the Final Output and the Need for Trajectory Evaluation in Production

An agent can return the right answer after an execution disaster. How to audit the trajectory of calls, control the step budget and measure consistency with pass^k to avoid silent regressions.

Date
Oct 14, 2026
Reading time
9 min
Result
100% Regression Detection • 60% Fewer Wasted Tokens • Step Budget Auditing • pass^k Consistency

Translated from the Spanish original. The code, data and READMEs on GitHub are in Spanish.

During the early phases of experimenting with language models, the predominant evaluation method was what’s colloquially known as “vibe checking”: sending a handful of questions to the chatbot, visually checking whether the answer sounded coherent and going to production in the hope that everything would turn out fine.

In 2026, however, the ecosystem has matured radically. Models are no longer mere static text generators but autonomous agents operating on dynamic environments: they run external tools through protocols such as MCP (Model Context Protocol), query transactional databases and chain decision loops across multiple turns.

In this new paradigm, evaluating an agent only by its final answer isn’t just insufficient: it’s a deadly trap for the business’s stability and operating costs.

In this engineering notebook from YesWeLab (@Yeswelab_OU) we look at why traditional LLM tests fail on agentic systems, what Trajectory Evaluation is, how to compute the pass^k metric to lock in consistency and how to implement a Dual Track evaluation architecture, locally and in production.


1. The Output Mirage: Why a Correct Answer Hides a Disaster

Let’s take a common business use case: a financial support agent tasked with checking whether a user has unpaid invoices and, if so, generating a secure payment link.

In a basic test based only on the final text:

  • Input: “Do I have any outstanding invoices on my account user_481?”
  • Agent output: “Yes, you have a €49 invoice from last month. Here’s the secure link to pay it: https://pay.empresa.com/inv_992”
  • Output-based evaluation: ✅ PASSED (exact answer, polite tone, link present).

But when you inspect the internal execution trace in the telemetry collector, the reality that emerges in the trenches is terrifying:

[ REAL TRACE: THE DISASTER HIDDEN BEHIND THE CORRECT ANSWER ]

Turn 1: Agent calls tool: search_users(query="*")            [Downloads 5,000 users -> 80,000 tokens]
Turn 2: Agent fails to parse the JSON and retries
Turn 3: Agent calls tool: run_raw_sql("SELECT * FROM invoices") [Potential leak of other customers' data]
Turn 4: Agent calls tool: send_notification_email(...)       [Destructive side action NOT authorised]
Turn 5: Agent enters a stochastic loop (3 retries)           [Accumulated latency: 18.4 seconds]
Turn 6: Agent finally generates the correct payment link.

The agent delivered the correct link, but along the way it:

  1. Blew up token consumption by a factor of 10x (costing $3.50 instead of $0.02).
  2. Violated security policies by running an unbounded SQL query and downloading other people’s data.
  3. Triggered unwanted side effects (it sent an email before confirming).
  4. Reached unacceptable latency of almost 20 seconds.

If the team relies only on black-box tests of the final text, this agent will reach production. Worse still: as soon as a developer changes a single line of the system prompt to polish the conversational tone, the agent will suffer a silent regression, falling into infinite loops or running unexpected database mutations.


2. Anatomy of Trajectory Evaluation: Audit the Path, not the Destination

Trajectory Evaluation shifts the focus from the superficial result to the structured sequence of reasoning and intermediate actions. The agent is evaluated as a state machine moving through an execution graph.

                    ┌────────────────────────────┐
                    │         USER GOAL          │
                    └─────────────┬──────────────┘
                                  │
          ┌───────────────────────┴───────────────────────┐
          ▼                                               ▼
   [ CLASSIC EVALUATION ]                      [ TRAJECTORY EVALS ]
   • Is the final text correct?                • Step Budget (minimum steps?)
   • Does it match the JSON format?            • Tool Sequence (logical order?)
   • Is the tone polite?                       • Argument Schema (valid values?)
                                               • Safety Invariants (zero leaks?)
          │                                               │
   (False sense of security)                   (Engineering and cost guarantee)

The four essential operational dimensions when auditing a trajectory are:

Dimension Control Question from the Trenches How to Verify
1. Step Budget Did it solve the task in the optimal number of steps (e.g. 3) or did it need 15 steps with loops? Deterministic assertion: len(trace.steps) <= MAX_STEPS.
2. Tool Selection & Order Did it call the right tools in the right sequence without exploring dead branches? Comparison against a reference graph (Golden Trajectory).
3. Argument Validation Did it pass arguments with exact types, valid IDs and no hallucinated parameters? Pydantic / Zod schema validation on the payload.
4. Safety Invariants Was credential isolation respected, with no destructive intermediate calls? Firewall rule: assert "drop_table" not in trace.tools_called.

3. From pass@1 to pass^k: The Real Metric of Agentic Consistency

One of the biggest self-deceptions in evaluating AI agents is reporting the traditional pass@1 or pass@k metric:

  • pass@1: Run the test once. If it passes, consider it a success.
  • Traditional pass@k: Run it $k$ times and consider it passed if at least one of the $k$ runs succeeded.

In classic deterministic systems, a unit test that passes once always passes. In autonomous agents built on stochastic LLMs, pass@1 hides intrinsic instability. An agent with a real 30% chance of success has a 30% chance of passing a test on its first run by pure stochastic luck.

That’s why the industry has adopted the strict pass^k metric (developed in reliability research such as tau2-bench):

$$\text{pass}^k = P(\text{Success on all } k \text{ consecutive attempts})$$

If an agent has a per-run reliability of $p = 0.85$ (85%), the probability that it completes a multi-step task consistently over $k=5$ consecutive runs is:

$$0.85^5 \approx 0.4437 \quad (44.3%)$$

[ CONSISTENCY CURVE: pass^k BY PER-RUN RELIABILITY ]
Consistency
100% ────┐ (p = 0.98 -> pass^5 = 90.4%)
 80%     └─────────┐
 60%               └──────────┐ (p = 0.85 -> pass^5 = 44.3%)
 40%                          └───────────────────┐
 20%                                              └────────── (p = 0.70 -> pass^5 = 16.8%)
  0% ────────────────────────────────────────────────────────►
     k=1        k=2        k=3        k=4        k=5   Attempts

If your CI/CD tests only run $k=1$, you’re blind to agents that actually fail in more than 50% of real production sessions. A prompt change that keeps pass@1 but crashes pass^5 will destroy your customers’ trust immediately.


4. Implementation in Code: Trajectory Assertions with Pytest

Below is a Python test suite that implements trajectory auditing and budget invariants using deterministic assertions on the agent’s trace:

import pytest
from pydantic import BaseModel
from typing import List, Dict, Any

class AgentStep(BaseModel):
    tool: str
    arguments: Dict[str, Any]
    output: Any
    latency_ms: float

class AgentExecutionTrace(BaseModel):
    query: str
    steps: List[AgentStep]
    final_response: str
    total_tokens: int

def run_agent_simulation(user_id: str, query: str) -> AgentExecutionTrace:
    # Runs the agent in a sandbox/mock
    ...
    return trace

@pytest.mark.parametrize("run_idx", range(5)) # pass^5 check
def test_invoice_retrieval_trajectory(run_idx):
    user_id = "user_481"
    trace = run_agent_simulation(user_id=user_id, query="Do I have outstanding invoices?")
    
    # 1. Step Budget assertion
    MAX_ALLOWED_STEPS = 3
    assert len(trace.steps) <= MAX_ALLOWED_STEPS, (
        f"Step Budget regression: expected <= {MAX_ALLOWED_STEPS}, got {len(trace.steps)}"
    )

    # 2. Sequence and allowed tools assertion
    expected_tools = ["get_user_account", "query_invoices_by_user_id"]
    tools_called = [step.tool for step in trace.steps]
    
    assert tools_called == expected_tools, (
        f"Trajectory deviation: {tools_called} != {expected_tools}"
    )

    # 3. Typed argument validation (strict scoping)
    for step in trace.steps:
        if step.tool == "query_invoices_by_user_id":
            assert step.arguments.get("user_id") == user_id, (
                "Security vulnerability: the agent queried invoices without filtering by the authenticated user"
            )

    # 4. Safety invariant: destructive mutations are forbidden
    forbidden_tools = {"send_email", "charge_credit_card", "delete_record"}
    assert forbidden_tools.isdisjoint(set(tools_called)), (
        "Invariant violation: a destructive action ran in a read-only flow"
    )

    # 5. Final text assertion
    assert "€49 invoice" in trace.final_response
    assert "https://pay.empresa.com" in trace.final_response

5. The Dual Track Strategy at YesWeLab

Following YesWeLab’s founding philosophy, we structure evaluations in two complementary tracks:

Track A: Open Source in the Trenches / DIY ($0 Cost)

  • Local Eval Harness: Running suites with Pytest and DeepEval in the local development environment.
  • Local OTel Tracing: Deploying a lightweight Docker container with Arize Phoenix (docker run -p 6006:6006 arize-phoenix). Phoenix captures full OTel traces, tool call trees and latencies without sending a single byte off your machine.
  • Golden Trajectories in SQLite WAL: Storing golden trajectories and test cases in a local SQLite database with WAL mode on (lab.db), so you can compare historical runs at zero compute cost.

Track B: Enterprise Fast-Track SaaS (CI/CD Automation)

  • A CI/CD Quality Gate in GitHub Actions: Integration with Langfuse or LangSmith through automated actions (langfuse/experiment-action). Every pull request that changes a prompt or a tool runs a regression dataset and blocks the merge if pass^k drops or the average token cost rises by more than 10%.
  • n8n Evals with Instance AI: Continuous online monitoring of n8n workflows and agents through the native evaluation module, catching drifts in node selection before they affect live users.

6. A Checklist from the Trenches: Is Your Agent Ready for Production?

Before flipping the switch on real traffic, check that your architecture meets these 5 essential points:

  • pass^k metrics active: No change is validated with a single stochastic run; the suite runs at least $k=5$ repetitions over the critical dataset.
  • Step Budget configured: Every agent has a strict maximum number of turns after which there’s a deterministic fail-safe handing over to a human.
  • Tool argument auditing: Intermediate calls go through Pydantic or Zod validators that reject malformed payloads before they reach databases or external APIs.
  • Safety invariant rules: State-mutating tools (payments, deletions, sends) require confirmation or deterministic verification in the pipeline.
  • Full OTel traceability: Every run emits structured traces with inputs, tool outputs, latencies and granular token consumption.
#DeepEval#Arize Phoenix#Langfuse CI#n8n Evals#Pytest#Docker#SQLite WAL#Python