X

Build a 2-Layer AI Agent Evaluation Suite in Python: Deterministic Guardrails + LLM-as-a-Judge

# Build a 2-Layer AI Agent Evaluation Suite in Python: Deterministic Guardrails + LLM-as-a-Judge

Every team that builds an AI agent eventually runs into the same silent failure mode: you tweak two sentences in a system prompt to fix one edge case, eyeball three manual test chats, and deploy—only to find out later that thirty percent of your refund or search flows quietly broke.

Standard `assert output == expected` unit tests do not work on natural-language replies, and relying purely on an LLM judge for everything is slow, expensive, and non-deterministic.

In this tutorial, we build a practical 2-layer AI Agent Evaluation Suite in plain Python and SQLite that acts as a real CI deployment gate. Our working use case evaluates a customer-support agent across policy lookup, order queries, and refund execution:

1. Layer 1 (Deterministic Guardrails): Fast, zero-cost Python assertions checking JSON schema validity, expected tool selection, latency budgets, required facts, and secret-leak prevention.

2. Layer 2 (Rubric Judge + SQLite Gate): Scores completeness and faithfulness on a 1–5 scale, persists every run in SQLite WAL, and blocks deployment (`BLOCKED`) whenever a prompt regression drops below the pass bar.

This eval suite pairs directly with our Production-Style AI Agent Harness in Python and Hybrid RAG Engine in Python.

—

Why Deterministic Checks Must Run Before Any LLM Judge

Calling an LLM judge on every output without deterministic filters wastes tokens and hides obvious bugs. If an agent picked `query_order` instead of `create_refund`, exceeded its 800 ms latency budget, or leaked an API key (`sk-…`), you do not need another model to tell you it failed.

Running cheap Python assertions first catches hard failures in microseconds and keeps your judge focused strictly on answer quality:

import re
from dataclasses import dataclass

SECRET_PATTERN = re.compile(r"(sk-[A-Za-z0-9_-]{8,}|Bearer\s+[A-Za-z0-9._-]+)")


@dataclass
class EvalCase:
    case_id: str
    prompt: str
    expected_tool: str
    max_latency_ms: float
    must_contain: str


@dataclass
class AgentOutput:
    tool_called: str
    answer_text: str
    latency_ms: float
    structured_ok: bool


def deterministic_checks(case: EvalCase, out: AgentOutput) -> tuple[bool, list[str]]:
    """Fast, zero-cost assertions that never rely on an LLM opinion."""
    failures: list[str] = []
    if not out.structured_ok:
        failures.append("invalid_json_schema")
    if out.tool_called != case.expected_tool:
        failures.append(f"wrong_tool:{out.tool_called}!={case.expected_tool}")
    if out.latency_ms > case.max_latency_ms:
        failures.append(f"latency_exceeded:{out.latency_ms}ms>{case.max_latency_ms}ms")
    if case.must_contain.lower() not in out.answer_text.lower():
        failures.append(f"missing_fact:{case.must_contain}")
    if SECRET_PATTERN.search(out.answer_text):
        failures.append("secret_leak_detected")
    return len(failures) == 0, failures

—

Step 1: Persisting Prompt Regressions in SQLite WAL

Evaluating a prompt once is not enough—you need to compare `prompt-v1` against `prompt-v2` over time. Storing `eval_runs` and `eval_results` in a local SQLite WAL database gives you an instant audit log of every CI run:

import sqlite3


def init_eval_db(db_path: str) -> sqlite3.Connection:
    conn = sqlite3.connect(db_path, timeout=10.0)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA journal_mode=WAL;")
    conn.execute("PRAGMA synchronous=NORMAL;")
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS eval_runs (
            run_id TEXT PRIMARY KEY,
            prompt_version TEXT NOT NULL,
            total_cases INTEGER NOT NULL,
            passed_cases INTEGER NOT NULL,
            avg_score REAL NOT NULL,
            gate_status TEXT NOT NULL,
            created_at REAL NOT NULL
        );
        CREATE TABLE IF NOT EXISTS eval_results (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            run_id TEXT NOT NULL,
            case_id TEXT NOT NULL,
            det_passed INTEGER NOT NULL,
            judge_score INTEGER NOT NULL,
            verdict TEXT NOT NULL,
            failures_json TEXT NOT NULL,
            latency_ms REAL NOT NULL
        );
        """
    )
    conn.commit()
    return conn

—

Step 2: Enforcing the CI Release Gate

Each run executes every `EvalCase`, runs `deterministic_checks`, scores the output against the rubric, and computes `gate_status`:

def compute_gate_status(passed_cases: int, total_cases: int, avg_score: float, min_avg_score: float = 4.2) -> str:
    if passed_cases == total_cases and avg_score >= min_avg_score:
        return "PASS"
    return "BLOCKED"

Notice the strict rule: both conditions must hold. Even if `avg_score` is high, a single failed deterministic guardrail (such as a secret leak or wrong tool call) flips `gate_status` to `BLOCKED`.

—

Step 3: Verified Pytest Output & Recorded Regression Comparison

Running `pytest` in `demos/agent_eval_suite/` tests both a clean `prompt-v1` release and a regressed `prompt-v2` build where case `C03_refund` calls the wrong tool and leaks a secret string:

test_evals.py::test_v1_passes_ci_gate PASSED                             [ 50%]
test_evals.py::test_v2_regression_blocks_deploy PASSED                   [100%]

============================== 2 passed in 0.03s ===============================

Recorded comparison from `recorded_eval_run.json`:

| Run | Prompt Version | Passed Cases | Avg Score | Gate Status |

| :— | :— | :-: | :-: | :-: |

| `run-v1` | `prompt-v1` | 3 / 3 | `5.0` | `PASS` |

| `run-v2` | `prompt-v2` | 2 / 3 | `3.67` | `BLOCKED` |

—

Limitations and Next Steps

1. Remember an LLM judge is still a model opinion: Always anchor your suite with deterministic checks for schemas, tool calls, latency, and secret redaction.

2. Grow your golden dataset from production bugs: Every time a real trace fails in production, export the failing input and add it as a permanent `EvalCase`.

—

Frequently Asked Questions

How many eval cases do I need to start?

Start with 10 to 20 golden cases covering your happy paths, edge cases, and known past bugs. Even a small suite catches silent regressions before users hit them.

Should I run LLM judges on every local save?

No. Run deterministic checks on every local save, and run the full LLM-as-a-Judge suite in CI before merging prompt or model changes.

Jamaley Hussain: Senior Data Scientist (AI/ML) & AI Architect specializing in Generative AI, Large Language Models, Autonomous AI Agents, and scalable Knowledge Retrieval (RAG) systems. Alumnus of Staffordshire University and founder of TechJunkGigs. <a href="https://www.linkedin.com/in/jamaley-hussain/" target="_blank" rel="noopener"><strong>LinkedIn</strong></a> • <a href="https://twitter.com/JamaleyHussain" target="_blank" rel="noopener"><strong>X (Twitter)</strong></a> • <a href="https://www.techjunkgigs.com/start-here/"><strong>Production AI Roadmap</strong></a>
Related Post