# AI Agent Evaluation: Test Cases, Traces, Metrics, and Improvement

**Harness Engineering · Module 9 of 16**

> **Start here:** basic Python for the optional metric check. No tracing account required.
>
> **Your goal:** explain whether a change improved the task and which stage caused a failure.

The new prompt produces friendlier answers. Exception handling drops from four correct cases to two. A style review would call this progress; a task evaluation should not.

Write success criteria before inspecting model output. Keep answer quality, execution behavior, user feedback, latency, and cost separate long enough to understand them. A single blended score can hide a dangerous regression.

![Reference cases and traced runs feed separate code, human, and model-assisted checks before a reviewed release decision.](https://cdn.hashnode.com/uploads/covers/5fb3b801b589f1618af9d143/8017ae56-786a-4def-8ed0-c36776a8c84e.png)

*Evaluation asks whether behavior is acceptable. Observability helps explain why that behavior occurred.*

## 1. Build cases with reference evidence

For the fictional shop, include an ordinary return, opened coffee, a missing receipt, an absent store-credit rule, an ambiguous date boundary, and a dispatch-versus-delivery question. Add forbidden-tool and repeated-call cases.

Each record needs input, expected outcome, supporting source IDs, relevant slice, and an understandable scoring rule. Keep some cases held out from prompt tuning. Otherwise, improvement may mean familiarity with the development set.

| Dimension | Concrete criterion |
|---|---|
| Correctness | Applies the opened-consumables exception |
| Grounding | Sources support the actual claim |
| Uncertainty | Missing store-credit authority remains unknown |
| Execution | No refund or customer message occurs |
| Efficiency | Finishes within the configured budget |

Record model, prompt, tools, retrieval index, source versions, and evaluator version with each experiment. Change one major component at a time when trying to attribute an improvement.

## 2. Combine three evaluation methods

**Code checks** work for exact requirements: valid fields, allowed values, calculations, source-ID membership, and forbidden tool use. **Human review** judges context-sensitive correctness and usefulness. **Model-assisted judging** can help scale rubric application, but it needs calibration against reviewed examples and examination of disagreements.

Do not ask a judge only “is this good?” Give it the task, evidence, rubric, and definitions. Blind variant labels where practical. Pairwise comparison can reveal preferences between two drafts; it does not by itself establish that either is correct.

Calibrate reviewers on shared examples. Record disagreement rather than forcing every ambiguous case into an artificial consensus. High-risk failures may warrant a separate gate even when the overall average rises.

## 3. Understand the denominator

Suppose the positive label is “requires human escalation.” In this synthetic evaluation, the reference labels and predictions are:

```python
truth = [True, True, False, False, True]
pred =  [True, False, True, False, True]
tp = sum(t and p for t, p in zip(truth, pred))
fp = sum(not t and p for t, p in zip(truth, pred))
fn = sum(t and not p for t, p in zip(truth, pred))
accuracy = sum(t == p for t, p in zip(truth, pred)) / len(truth)
precision = tp / (tp + fp)
recall = tp / (tp + fn)
assert (tp, fp, fn) == (2, 1, 1)
assert accuracy == 0.6
assert precision == recall == 2 / 3
print(accuracy, precision, recall)
```

This block was run locally. Accuracy is 60%; precision and recall are each about 66.7%. These numbers describe five invented cases, not a deployed system. In a reusable evaluator, define what happens when a metric's denominator is zero.

Inspect slices. A classifier that misses every rare escalation can still have high overall accuracy when most tasks are routine. Decide whether a false negative or false positive carries the greater cost for your actual workflow.

## 4. Trace the route, not just the final text

A trace groups one task and its child operations: model call, retrieval, tool execution, draft, validation. Threads can group related conversational runs. Preserve parent-child IDs and tool call/result association.

An illustrative trace might contain:

```text
R1  policy-answer run
  R1.1  retrieve  sources=P1,P2  status=ok
  R1.2  draft     status=ok
  R1.3  validate  error=missing_exception
```

This trace is synthetic. It nevertheless shows where to investigate: P2 was retrieved, so inspect generation and validation before rebuilding the index. If P2 were absent, retrieval would be the earlier broken stage.

Do not log credentials or unnecessary private content. Tracing sends data to a destination with its own access and retention controls. Sanitization and sampling are part of the observability design.

## 5. Keep monitoring dimensions separate

| Signal | Useful question | Misinterpretation to avoid |
|---|---|---|
| Volume | Are intended users adopting the workflow? | Usage proves value |
| User feedback | What caused frustration? | A liked answer must be correct |
| Quality slices | Which tasks regress? | Average score describes every task |
| Latency distribution | Who experiences slow requests? | Mean latency describes the tail |
| Token and tool usage | What consumes resources? | Token count alone equals billed cost |
| Review backlog | Can oversight keep pace? | A draft is finished when generated |

For durations `[100, 110, 120, 130, 2000]` milliseconds, the mean is 492 ms. The nearest-rank 95th percentile is 2000 ms. Specify the percentile convention and sample size; five synthetic values are not a stable capacity estimate.

Online evaluation examines sampled live behavior. Offline evaluation compares controlled datasets. Use random sampling for general patterns and targeted review for rare or severe failures. Annotation queues need an owner and a resolution process.

## 6. Improve through a reviewed loop

Keep a baseline, propose a focused change, run development cases, inspect held-out results, review regressions, and decide whether to release. An Engine-style improvement workflow can automate proposals and measurements while retaining release authority.

For A/B testing, define the assignment unit, duration, success metric, and guardrails in advance. Avoid changing multiple uncontrolled components. Preserve versions and rollback instructions so a good-looking experiment can be reversed if operating behavior worsens.

## 7. Follow along

Create ten synthetic traces with duration, status, usage, sources, and quality labels. Identify the two most important failures and name the responsible stage. Design three alerts, each with condition, owner, response, and recovery definition.

**Expected result:** a candidate prompt that improves style but harms exceptions is rejected or revised. Quality claims name the dataset and denominator. No fixture measurement becomes a production benchmark.

## Further reading

- [LangSmith evaluation](https://docs.langchain.com/langsmith/evaluation) — experiments and evaluator workflows.
- [LangSmith observability](https://docs.langchain.com/langsmith/observability) — tracing concepts.
- [Production monitoring course](https://academy.langchain.com/courses/production-monitoring) — monitoring practice.

## Next module

**Deploy and operate the assistant:** carry identity, state, limits, and recovery into the service boundary.

