MODULE 01.3 · PUBLISHED · ~1-2h

Early Golden-Set Evals & Cost/Latency Budgets

Deterministic golden-set evaluation suites with pass-rate scoring, per-request and batch cost accounting, and latency budget checks verified with pytest and GitHub Actions.

Changing a prompt, tightening a schema, or swapping models can quietly improve one test case while breaking three others or doubling token spend. Forward Deployed AI Engineers catch regressions early by pairing a small golden evaluation set with explicit cost and latency budgets.

In this module, you will model golden-set test cases and evaluation results, compute pass rates, estimated token costs, and nearest-rank P95 latency in Python, check budget compliance in the practice assignment, and verify everything with pytest and GitHub Actions.

What You Will Build

  • Golden-set evaluation runner: Score candidate outputs against expected categories and escalation flags across a deterministic golden dataset.
  • Token cost and P95 latency reporter: Calculate total input/output tokens, estimated USD cost, mean latency, and nearest-rank P95 latency across evaluation items.
  • Budget gate assignment: Implement evaluate_budget_compliance in the practice assignment to check cost and latency thresholds and utilization ratios.
  • Tests and CI: Verify golden-set scoring, estimated cost math, P95 latency, and budget checks with pytest and GitHub Actions.

1. Early Golden-Set Evals and Cost/Latency Budgets

  • Golden sets as regression guardrails: A golden set is a curated, version-controlled collection of representative inputs and expected outputs or assertions. Running it after prompt or model edits shows whether quality improved, stayed flat, or regressed before you ship.
  • Discrete field assertions: Asserting exact matches on structured fields (such as category and needs_escalation) gives clear, repeatable pass/fail signals without brittle free-text comparisons.
  • Cost budgets and estimated token economics: Estimated request cost is calculated from input and output token counts multiplied by configured per-million-token rates. These figures are estimates based on configured model rates and are not necessarily the final provider invoice; actual billing can vary with model pricing updates, cached tokens, and other provider-specific factors. Adding long system instructions or extra examples still increases input token volume across every call.
  • Latency budgets and tail percentiles: Mean latency alone hides slow outliers. Tracking P95 latency alongside average latency helps ensure user-facing and workflow SLAs hold even when a subset of requests takes longer.

2. Step-by-Step Build Walkthrough

  1. Set up the fde-01-3 repository and virtual environment: Create the package layout, configure .env.example, .gitignore, and pyproject.toml, and install editable dev dependencies.

    macOS / Linux:

    mkdir -p fde-01-3/src/fde_01_3 fde-01-3/tests
    cd fde-01-3
    python3 -m venv .venv
    source .venv/bin/activate
    python -m pip install --upgrade pip
    python -m pip install -e ".[dev]"
    cp .env.example .env

    Windows (PowerShell):

    mkdir fde-01-3
    cd fde-01-3
    py -m venv .venv
    .\.venv\Scripts\Activate.ps1
    py -m pip install --upgrade pip
    py -m pip install -e ".[dev]"
    Copy-Item .env.example .env

    Windows (CMD):

    mkdir fde-01-3
    cd fde-01-3
    py -m venv .venv
    .venv\Scripts\activate.bat
    python -m pip install --upgrade pip
    python -m pip install -e ".[dev]"
    copy .env.example .env
  2. Define golden-set case, pricing, outcome, and report models: Use Pydantic v2 models with strict validation so evaluation inputs, pricing rates, and summary reports stay typed and unambiguous.
    from typing import Literal
    from pydantic import BaseModel, ConfigDict, Field
    
    class GoldenCase(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        case_id: str = Field(min_length=1)
        prompt: str = Field(min_length=1)
        expected_category: Literal["billing", "auth", "infra", "general"]
        expected_escalation: bool
    
    class CaseEvaluation(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        case_id: str = Field(min_length=1)
        passed: bool
        actual_category: Literal["billing", "auth", "infra", "general"]
        actual_escalation: bool
        input_tokens: int = Field(ge=0)
        output_tokens: int = Field(ge=0)
        latency_ms: float = Field(ge=0.0)
        cost_usd: float = Field(ge=0.0)
    
    class PricingConfig(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        input_cost_per_million_usd: float = Field(ge=0.0)
        output_cost_per_million_usd: float = Field(ge=0.0)
    
    class EvalReport(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
        total_cases: int = Field(ge=0)
        passed_cases: int = Field(ge=0)
        pass_rate: float = Field(ge=0.0, le=1.0)
        total_input_tokens: int = Field(ge=0)
        total_output_tokens: int = Field(ge=0)
        total_cost_usd: float = Field(ge=0.0)
        avg_latency_ms: float = Field(ge=0.0)
        p95_latency_ms: float = Field(ge=0.0)
        results: list[CaseEvaluation]

    Example golden-set case:

    sample_case = GoldenCase(
        case_id="CASE-001",
        prompt="I cannot access my account after resetting my password.",
        expected_category="auth",
        expected_escalation=False,
    )
  3. Compute estimated per-case cost, evaluate golden cases, and aggregate report metrics: Calculate estimated cost from configured rates (noting that actual provider billing can vary with model pricing, cached tokens, and provider-specific factors), reject negative token counts or non-finite/negative latency values, compute nearest-rank P95 latency (ceil(0.95 * n) - 1 zero-based index), and return clean zeroed metrics when given an empty case list.
    import math
    from typing import Callable
    
    CandidateOutput = tuple[
        Literal["billing", "auth", "infra", "general"],
        bool,
        int,
        int,
        float,
    ]
    CandidateRunner = Callable[[GoldenCase], CandidateOutput]
    
    def compute_call_cost_usd(
        input_tokens: int,
        output_tokens: int,
        pricing: PricingConfig,
    ) -> float:
        if input_tokens < 0 or output_tokens < 0:
            raise ValueError("Token counts must be non-negative")
        input_cost = (input_tokens / 1_000_000.0) * pricing.input_cost_per_million_usd
        output_cost = (output_tokens / 1_000_000.0) * pricing.output_cost_per_million_usd
        return input_cost + output_cost
    
    def nearest_rank_p95(latencies_ms: list[float]) -> float:
        if not latencies_ms:
            return 0.0
        ordered = sorted(latencies_ms)
        idx = max(0, math.ceil(0.95 * len(ordered)) - 1)
        return float(ordered[idx])
    
    def run_golden_eval(
        cases: list[GoldenCase],
        runner: CandidateRunner,
        pricing: PricingConfig,
    ) -> EvalReport:
        if not cases:
            return EvalReport(
                total_cases=0,
                passed_cases=0,
                pass_rate=0.0,
                total_input_tokens=0,
                total_output_tokens=0,
                total_cost_usd=0.0,
                avg_latency_ms=0.0,
                p95_latency_ms=0.0,
                results=[],
            )
    
        evaluations: list[CaseEvaluation] = []
        for case in cases:
            actual_cat, actual_esc, in_tok, out_tok, lat_ms = runner(case)
            if (
                in_tok < 0
                or out_tok < 0
                or not math.isfinite(lat_ms)
                or lat_ms < 0.0
            ):
                raise ValueError("Runner returned invalid token count or latency")
            cost = compute_call_cost_usd(in_tok, out_tok, pricing)
            passed = (
                actual_cat == case.expected_category
                and actual_esc == case.expected_escalation
            )
            evaluations.append(
                CaseEvaluation(
                    case_id=case.case_id,
                    passed=passed,
                    actual_category=actual_cat,
                    actual_escalation=actual_esc,
                    input_tokens=in_tok,
                    output_tokens=out_tok,
                    latency_ms=lat_ms,
                    cost_usd=cost,
                )
            )
    
        total_cases = len(evaluations)
        passed_cases = sum(1 for item in evaluations if item.passed)
        pass_rate = passed_cases / total_cases
        total_in = sum(item.input_tokens for item in evaluations)
        total_out = sum(item.output_tokens for item in evaluations)
        total_cost = sum(item.cost_usd for item in evaluations)
        latencies = [item.latency_ms for item in evaluations]
        avg_lat = sum(latencies) / total_cases
        p95_lat = nearest_rank_p95(latencies)
    
        return EvalReport(
            total_cases=total_cases,
            passed_cases=passed_cases,
            pass_rate=pass_rate,
            total_input_tokens=total_in,
            total_output_tokens=total_out,
            total_cost_usd=total_cost,
            avg_latency_ms=avg_lat,
            p95_latency_ms=p95_lat,
            results=evaluations,
        )
  4. Run tests and commit to Git: Verify deterministic unit tests with pytest, add .github/workflows/pytest.yml, and commit to Git.
    python -m pytest -v
    git status
    git add .
    git commit -m "Complete FDE module 01.3"

3. Common Pitfalls and Operational Hygiene

  • Evaluating only on happy-path prompts: Include edge cases, ambiguous wording, and escalation boundaries in your golden set so blind spots show up early.
  • Treating estimated token cost as final billing or ignoring latency when chasing pass rate: Configured rate math gives an estimate (actual provider billing can vary with model pricing, cached tokens, and provider-specific factors), and a small pass-rate gain may not justify higher cost or slower P95 latency.
  • Relying on flaky live API calls inside unit test CI: Keep unit tests deterministic with stubbed runners and fixtures, and run live model benchmarks separately on a controlled schedule.

4. Practice Assignment

In fde-01-3, implement evaluate_budget_compliance(report: EvalReport, max_cost_usd: float, max_p95_latency_ms: float) -> dict[str, object] in src/fde_01_3/budgets.py that validates max_cost_usd > 0 and max_p95_latency_ms > 0 (raising ValueError otherwise) and returns:

  • within_cost_budget (bool)
  • within_latency_budget (bool)
  • cost_utilization (float)
  • latency_utilization (float)
  • passed (bool)

Add unit tests in tests/test_budgets.py covering compliant runs, cost or latency budget breaches, exact threshold boundaries, and invalid thresholds, then run python -m pytest -v and push fde-01-3 (including .github/workflows/pytest.yml) to GitHub.

5. Knowledge Check

  1. Why should teams keep a small, deterministic golden set in version control before scaling prompts, models, or retrieval pipelines?
  2. Why is tracking average latency or average cost per call insufficient when enforcing production SLAs and budgets?
  3. How do input tokens, output tokens, and model tier pricing interact when you tune prompts or add few-shot examples, and why is rate-based cost an estimate rather than a final invoice?
  4. What happens when a prompt change improves golden-set accuracy slightly while doubling token cost or pushing P95 latency past budget?
  5. Why should golden-set evaluation runs in CI stay deterministic rather than calling live external model APIs on every commit?
Self-Review Answers
  • 1. Early golden sets: A focused golden set gives a fast, repeatable baseline to catch regressions when changing prompts, schemas, or models before expensive production rollouts.
  • 2. Beyond averages: Averages hide tail latency spikes (such as P95/P99) and high-token outlier requests that can breach SLAs or daily spend caps.
  • 3. Token pricing and estimates: Longer prompts and few-shot examples raise input token volume on every request, while verbose outputs raise output token volume; rate-based calculations are estimates and actual provider invoices can vary with model pricing, cached tokens, and provider-specific factors.
  • 4. Quality vs. cost/latency trade-offs: A small accuracy gain may not justify higher unit cost or slower tail latency; explicit cost and P95 latency budgets force deliberate engineering trade-offs.
  • 5. Deterministic CI: Mocked or fixture-driven evaluations run fast, never fail due to external network flakes or rate limits, and provide repeatable regression checks on every pull request.

6. Completion Criteria

  • run_golden_eval computes pass rate, token totals, estimated cost, average latency, and nearest-rank P95 latency cleanly across empty and non-empty case lists while rejecting invalid token counts or non-finite/negative latencies.
  • evaluate_budget_compliance implemented and tested across passing, over-budget, boundary, and invalid-threshold inputs.
  • Golden-set evaluation, estimated cost vs. actual billing factors, P95 latency trade-offs, and deterministic CI practices explained clearly.
  • All pytest tests pass locally and in GitHub Actions, and the repository is committed to GitHub.
Practice assignment

Build this

In fde-01-3, implement evaluate_budget_compliance(report: EvalReport, max_cost_usd: float, max_p95_latency_ms: float) -> dict[str, object] in src/fde_01_3/budgets.py that validates positive budget thresholds (raising ValueError if max_cost_usd <= 0 or max_p95_latency_ms <= 0) and returns:

  • within_cost_budget (bool): report.total_cost_usd <= max_cost_usd
  • within_latency_budget (bool): report.p95_latency_ms <= max_p95_latency_ms
  • cost_utilization (float): report.total_cost_usd / max_cost_usd
  • latency_utilization (float): report.p95_latency_ms / max_p95_latency_ms
  • passed (bool): within_cost_budget and within_latency_budget

Add unit tests in tests/test_budgets.py covering passing budgets, cost or latency overruns, boundary equality, and invalid non-positive thresholds, then run python -m pytest -v and push fde-01-3 (including .github/workflows/pytest.yml) to GitHub.

View reference repository ↗

Knowledge check

Test your understanding

  1. Why should teams keep a small, deterministic golden set in version control before scaling prompts, models, or retrieval pipelines?
  2. Why is tracking average latency or average cost per call insufficient when enforcing production SLAs and budgets?
  3. How do input tokens, output tokens, and model tier pricing interact when you tune prompts or add few-shot examples?
  4. What happens when a prompt change improves golden-set accuracy slightly while doubling token cost or pushing P95 latency past budget?
  5. Why should golden-set evaluation runs in CI stay deterministic rather than calling live external model APIs on every commit?
Reveal self-review answers (attempt the questions first)
  1. Early golden sets: A focused golden set gives a fast, repeatable baseline to catch regressions when changing prompts, schemas, or models before expensive production rollouts.
  2. Beyond averages: Averages hide tail latency spikes (such as P95/P99) and high-token outlier requests that can breach SLAs or daily spend caps.
  3. Token and pricing trade-offs: Longer prompts and few-shot examples raise input token costs on every request, while verbose outputs raise output token costs (often priced higher per million tokens than input tokens).
  4. Quality vs. cost/latency trade-offs: A small accuracy gain may not justify higher unit cost or slower tail latency; explicit cost and P95 latency budgets force deliberate engineering trade-offs.
  5. Deterministic CI: Mocked or fixture-driven evaluations run fast, never fail due to external network flakes or rate limits, and provide repeatable regression checks on every pull request.
Not completed
Discussion & field notes

Questions or notes on this module?

Leave a note or question

Comments are held in a moderation queue and appear once approved. Your email will not be published.