A Practical Three-Layer Evaluation Framework for AI Agents: Contracts, Trace Replay, and Sampled LLM Judging

    AI agents are nondeterministic, so keyword matching alone is not enough to prove that an answer is usable. This article presents a layered, repeatable, regression-ready evaluation approach that combines versioned contracts, live agent runs, trace replay, and sampled LLM judging. It explains how to verify tool use, search behavior, output structure, constraints, and citation traceability; how to replay historical traces without calling models; and how to apply a rubric-based judge to semantic quality such as relevance, authority, freshness, completeness, traceability, and constraint compliance. The article also covers configuration examples, pseudocode, local observability setup, implementation steps, security considerations, and common pitfalls.

    A Practical Three-Layer Evaluation Framework for AI Agents: Contracts, Trace Replay, and Sampled LLM Judging

    1. Background: Keyword Matching Is Not Enough

    The central challenge in agent evaluation is nondeterminism. Traditional unit tests expect the same output on every execution. An agent, however, may call different tools, choose different search terms, generate different wording, or even produce answers of noticeably different quality for the same prompt. Evaluation therefore cannot be limited to checking whether the final text contains certain keywords. It must check whether agent behavior is as expected: whether the right tools were called, whether constraints on quantity, source, and freshness were respected, and whether the answer is genuinely useful and traceable.

    A typical misclassification case is useful here. An agent is asked, “What are today’s top financial-market headlines?” It searches the web and returns five items with links. Two of the items are not headline news. More importantly, every link points to a home page or a section page rather than to a specific news article. Because the answer contains the required keywords, the keyword check still passes. A sampled LLM judge, however, gives the answer a score of 0.45, below the threshold, and classifies it as failing. This shows that keyword matching alone misses problems related to result granularity, source authority, content relevance, and link traceability.

    A single form of evaluation is also insufficient for checking agent behavior. We need a layered, repeatable, regression-ready evaluation system that can quickly check contracts during development, run the agent multiple times to observe behavior, replay historical traces without calling models, and finally use a sampled LLM judge to cover semantic quality.

    2. Overall Design of the Evaluation Framework

    This article uses a framework centered on three evaluation layers, supplemented by sampled judging:

    1. Versioned contract layer: Centrally manage prompts, model policies, tool allowlists, evaluation rules, thresholds, and sampling rates, and keep them under version control.
    2. Live run test layer: Run the agent multiple times and inspect tool calls, parameters, constraint compliance, and output structure.
    3. Trace replay layer: Re-check historical runs based on recorded traces without calling the model, making it suitable for fast regression testing and incident review.
    4. Sampled LLM judge: Score recorded answers on a sampled basis to supplement semantic judgments such as relevance, authority, freshness, completeness, and traceability.

    Each layer has clear boundaries. The contract layer ensures that “rules are explicit and versioned.” The live run layer reveals “behavioral deviations during real execution.” The trace replay layer ensures that “historical issues can be reproduced and regressed.” The sampled judge addresses “semantic quality that rules cannot easily cover.” Together, these components form an evaluation loop from development to release.

    3. Layer 1: Versioned Contracts

    The contract is the starting point for the entire evaluation workflow. It should not be scattered across test code, prompt files, and human-readable documentation. Instead, it should be a centralized, version-controlled configuration object. A contract should contain at least the following fields:

    • agent_id: The agent identifier.
    • prompt_version: The prompt version.
    • model_policy: The model policy, including temperature, maximum tool calls, timeout, and retry policy.
    • tools: The allowlist of tools the agent may call.
    • evals: The list of evaluation rules.
    • thresholds: The pass thresholds.
    • sample_rate: The sampling rate for LLM judging.

    An example configuration is shown below:

    1. {
    2. "agent_id": "financial_market_headlines",
    3. "prompt_version": "v3",
    4. "model_policy": {
    5. "name": "generic conversational model placeholder",
    6. "temperature": 0.2,
    7. "max_tool_calls": 5,
    8. "timeout_seconds": 30
    9. },
    10. "tools": ["web_search"],
    11. "evals": [
    12. {"name": "must_call_search", "type": "tool_call"},
    13. {"name": "link_is_article_level", "type": "rule"},
    14. {"name": "source_is_authoritative", "type": "rule"},
    15. {"name": "answer_relevance", "type": "llm_judge", "sample_rate": 0.2}
    16. ],
    17. "thresholds": {
    18. "pass_score": 0.7,
    19. "max_tool_calls": 5
    20. }
    21. }

    Once the contract is under version control, every change to prompts, model parameters, or evaluation rules should be reviewed and recorded. When evaluation results change, the team can then determine whether the change came from model behavior, tool results, or the evaluation rules themselves. The contract should also define fail-blocking rules explicitly. For example, the agent must call the search tool, links must point to specific content pages, sources must belong to an authoritative category, and the number of returned answers must fall within the required range. For questions such as financial-market headlines, keyword rules should be treated only as a minimum gate, not as a sufficient pass criterion.

    4. Layer 2: Live Agent Tests

    Live agent tests require running the agent multiple times against the same contract and recording trace data for each run. The number of runs should not be too small, or fluctuations will be difficult to observe. It should not be too large either, to avoid excessive cost and latency. In practice, three to five baseline runs can be used, with additional runs for critical scenarios. Each run should check:

    • Whether only allowed tools were called.
    • Whether the number of tool calls exceeded the limit.
    • Whether the search terms were relevant to the question.
    • Whether the returned results met requirements for quantity, freshness, source category, and link granularity.
    • Whether the final answer had a complete structure and traceable citations.
    • Whether duplicate links, home-page links, or section-page links appeared.

    Pseudocode:

    1. def run_live_eval(contract, runs=5):
    2. traces = []
    3. for i in range(runs):
    4. trace = agent.run(contract.prompt, tools=contract.tools)
    5. rule_result = rule_engine.check(trace, contract.evals)
    6. traces.append({
    7. "trace": trace,
    8. "rule_result": rule_result
    9. })
    10. return summarize(traces, contract.thresholds)

    The value of live testing is that it exposes deviations between actual behavior and contract expectations. For example, the agent may call the search tool but search only with broad terms, resulting in section pages. It may also return enough links, but some of them are not headline content. These issues cannot be found through final-text keyword checks alone. The evaluation must inspect trace data and verify the correspondence between tool inputs, tool outputs, and answer citations.

    5. Layer 3: Trace Replay Evaluation

    Trace replay evaluation does not call the model. Instead, it re-runs rule checks against recorded trace data. It is useful for quickly validating changes to evaluation rules, fixes to the rule engine, or reviews of production incidents. Because it does not call the model or search APIs, it is inexpensive, fast, and stable, which makes it well suited for continuous integration.

    Pseudocode:

    1. def replay_trace(trace, contract):
    2. step_results = []
    3. for step in trace.steps:
    4. result = rule_engine.check_step(step, contract.evals)
    5. step_results.append(result)
    6. return aggregate(step_results, contract.thresholds)

    The key requirement for trace replay is that trace data must be complete enough. Tool call names, parameters, returned results, timestamps, model inputs and outputs, final answers, and citation relationships should all be recorded. Trace records can be exported to a standard telemetry backend and archived in object storage-compatible storage. This allows the team to reproduce historical issues such as “keyword checks pass but link granularity fails” without re-running the agent, and to verify whether new rules correctly block those issues.

    6. Sampled LLM Judge

    Rule-based evaluation cannot cover every aspect of semantic quality. A sampled LLM judge can score recorded answers on a proportional basis. The scoring dimensions include relevance, authority, freshness, completeness, traceability, and constraint compliance. The judge should use an explicit rubric rather than being asked vaguely whether an answer is “good.” For example:

    • Relevance: Does the answer directly address the question?
    • Authority: Does the source belong to an authoritative category?
    • Freshness: Does the information meet the time requirement?
    • Traceability: Do the links point to specific content rather than home pages or section pages?
    • Completeness: Does the answer cover the required quantity without obvious omissions?
    • Constraint compliance: Does the answer follow quantity, format, and tool-call limits?

    Pseudocode:

    1. def sample_judge(traces, rate, judge_model, rubric):
    2. sampled = sample(traces, rate)
    3. scores = []
    4. for item in sampled:
    5. score = judge_model.score(
    6. question=item.question,
    7. answer=item.answer,
    8. evidence=item.tool_results,
    9. rubric=rubric
    10. )
    11. scores.append(score)
    12. return aggregate_scores(scores)

    In the earlier example, the judge gives the answer 0.45, which is below the 0.7 threshold, so the answer fails. This result matches human judgment: although the answer contains the keywords, its links point to home pages or section pages, the content is not headline news, and both traceability and relevance are insufficient. The sampled judge should not replace rule-based evaluation. It should supplement it by identifying semantic issues that are difficult to express as rules.

    7. Technology Stack and Local Environment

    To reduce the cost of building an evaluation environment, observability components can run in local containers. Use a standard telemetry protocol to export trace data to a trace backend. Archive trace records in object storage-compatible storage. Metrics, logs, and dashboards can be handled by common monitoring components. The agent and evaluation logic run as independent services. Model calls and web search still require external paid APIs, while the remaining components can run in a local container environment.

    A local development environment requires particular attention. Default login credentials are for local debugging only. Production must replace them with secret management, access control, transport encryption, and least-privilege policies. Object storage should have lifecycle and archival policies. Trace data may contain user inputs and tool-returned content, so data redaction and retention limits must be managed. For enterprise deployments, general services such as Baidu AI Cloud object storage, logging, and monitoring and alerting can support trace archiving, log aggregation, and alerting. Specific APIs and configurations should follow the actual environment.

    8. Implementation Steps and Best Practices

    Implementation can follow these steps:

    1. Define the contract: Centrally configure the prompt, model policy, tool allowlist, evaluation rules, and thresholds, and place them under version control.
    2. Integrate tracing: Record complete traces for agent runs, including tool calls, parameters, returned results, and final answers.
    3. Run live tests: Execute the agent multiple times and check tool-call and output rules.
    4. Build trace replay regression: Archive historical traces and support rule replay without calling models.
    5. Introduce sampled judging: Define a rubric and sampling rate for semantic quality, and keep costs under control.
    6. Set thresholds and alerts: Block releases or trigger alerts when results fall below thresholds.
    7. Calibrate continuously: Regularly review judge results manually and adjust rules and rubrics.

    Common pitfalls include checking only keywords; running the agent once and declaring success; separating the contract from test code; recording traces without tool results; using vague judge scoring criteria; and using default local credentials directly in production. Avoiding these pitfalls is essential if evaluation is to become real infrastructure for agent quality assurance.

    9. Conclusion

    Agent evaluation is not a single test. It is a repeatable, regression-ready, and evolvable closed loop. Versioned contracts keep rules explicit. Live tests observe real behavior. Trace replay re-checks historical runs without calling models. A sampled LLM judge supplements semantic quality. The combination of three evaluation layers and sampled judging can reveal subtle issues such as “keywords pass but link granularity does not” and “tool calls are correct but results are unusable.” This helps teams keep quality under control while agents iterate rapidly.