Skip to Content
Recodocs

Evaluation

The layer that defines suites, runs them against an agent, grades the evidence, records results and gates changes on fresh receipts.

10 min read

Suppose an assistant's new prompt fixes one wrong invoice answer but breaks a calculation that worked yesterday. The evaluation layer makes both outcomes visible. Declare cases and expected behaviour, run the agent as a target, grade the results and keep them in an append-only journal. A gate checks whether changed files have fresh, sufficient evidence before a change can pass. See self-improving agents for why independent evaluation matters.

The core owner is recohut_kit.evals. It is framework neutral: the agent keeps its own reasoning loop, and the kit only observes tool calls and the final output. Missing evidence is reported as unverified, never as a pass. The layer does not run the agent in production (see Serving) and does not record live traces (see Observability).

Owners

recohut_kit.evals is large. A new build needs about eight entry points; the rest is catalog.

#NeedModule and namesWhat it does
1Cases and suitesevals.suites: Case, Suite, TurnExpectation, load_suiteDeclare inputs, required and forbidden tools, argument and scope checks, cited ids, abstention, severity and holdout. Suite.digest binds results to the exact suite. load_suite reads JSON or YAML
2Target and trajectoryevals.contracts: AgentTarget, Trajectory, Turn, RunContext, ReportThe thing under test returns tool observations and a final output
3Deterministic gradersevals.graders: TrajectoryGrader, EvidenceIntegrityGrader; evals.retrieval.RetrievalGraderChecks on tools, outcome, citations, abstention and recall
4LLM judgeevals.judge: LLMGrader, CalibrationA judge over any text client, fingerprinted by rubric, model and settings. Calibration at this level is a smoke check
5Run and journalevals.system.EvaluationSystem, evals.runner.Runner, evals.journal.JournalRuns a suite, repeats it, appends evidence to SQLite
6Gateevals.gate: gate, GatePolicy, ChangeRule, build_receipt, load_receiptsCI rule: changed prompt, tool-schema or model-route files need a fresh receipt. No model call
7Ledgerevals.ledger.RunLedgerTrend and delta across runs in one SQLite file the application owns
8Phoenix bridgeevals.phoenix, evals.phoenix_runtimeWrites completed evaluation results to a Phoenix server. The journal stays authoritative

Supported and catalog packages around the owner:

PackageImport pathTierWhat it is for
PydanticAI targetsrecohut_kit_pydantic_ai.evals.targets, recohut_kit_pydantic_ai.evals.harnesssupportedPydanticAITarget and HarnessTarget wrap a native PydanticAI agent as an AgentTarget
Strands targetrecohut_kit_strands.evals.targetssupportedStrandsTarget, an AgentTarget adapter for Strands
OpenAI Agents targetrecohut_kit_openai_agents.evals.targetssupportedOpenAIAgentsTarget, an AgentTarget adapter for the OpenAI Agents SDK
Learning looprecohut_kit.learningsupportedGoverned loop for agent prompts and skills that consumes evaluation evidence and produces reviewed regression cases
Red teamrecohut_kit.redteamcatalogVersioned attack cases paired with benign controls, compiled to trajectory expectations and graded from evidence
Scenariosrecohut_kit.scenarioscatalogNeutral scenario files (personas, steps, attack cases, lanes, proof labels) compiled to a Suite
Simulatorsrecohut_kit.simulatorscatalogPersona user simulators, scripted or model-driven, with deterministic goal and refusal sensors
Decision judgerecohut_kit.decision_judgecatalogTyped questions over Phoenix spans, published as span annotations
Verificationrecohut_kit.verificationcatalogTest-design records, behavioural contracts, call and token budgets
Visualrecohut_kit.visualcatalogPlaywright inspector that measures rendered geometry against declared values
Walkthroughrecohut_kit.walkthroughcatalogTechnical walkthrough packs built from executed evidence
Chat and MCP targetsrecohut_kit.agents.targetscatalogChat-endpoint, MCP-tools, recorded and scripted targets for black-box agents
pytest plugin and LangChain wrappersrecohut_kit.integrations.pytest_plugin, recohut_kit.integrations.langchain_evalscatalogRun suites under pytest; wrap LangSmith and LangChain evaluators

Inside evals there are further sub-areas that are catalog unless you need them: evals.measurement (oracle integrity, judge admission, reliability, release decisions), evals.schedule (scheduled runs and triage), evals.adapters (import and export to DeepEval, Inspect, Langfuse and Promptfoo formats), and the RAG metric modules (evals.rag_metrics, evals.ragas).

Older flat module names such as eval_gate, eval_ledger and evals_langchain are re-export shims for the evals.* sub-packages. Use the evals.* paths.

How the pieces fit

Separate the case, the target being compared, and the grader. Otherwise a changed target could change its own pass conditions, making comparisons unreliable.

A run has an ExecutionIdentity: the source digest, suite digest, grader fingerprint, calibration digest, model route, repetitions and harness digest. Any change to one of them is a different run, so results from different configurations are never merged.

Deterministic review results

The review_gates module builds a verdict from typed checks and an exact input fingerprint. A verdict can be verified, blocked, or escalated for human review when required evidence is missing or conflicts. The calling application owns its authorization decision and any explanation presented to users.

Worked examples

Define and run a small suite

A Case declares what must happen. A target is any object with an async run method that returns a Trajectory, and an unwrap method. In real use the target wraps your agent; here a stand-in produces the tool calls so the example runs offline.

run_suite.py
import asyncio
import tempfile
from pathlib import Path

from recohut_kit.evals import (
    Case, EvaluationSystem, Journal, RunContext, Suite, Trajectory, TrajectoryGrader, Turn,
)
from recohut_kit.integrations.contracts import ToolObservation


class LeaveBot:
    """Stand-in for the system under test."""

    async def run(self, case_input, history, context: RunContext):
        tools = ()
        if "leave" in case_input:
            tools = (
                ToolObservation("call", "policy_lookup", "c1", {"topic": "leave"}),
                ToolObservation("return", "policy_lookup", "c1", None, {"days": 24}),
            )
        output = "24 days" if tools else "Hello!"
        return Trajectory(
            turns=(Turn(1, case_input, output, tools=tools),),
            final_output=output,
            history_complete=True,
        )

    def unwrap(self):
        return self


suite = Suite(
    "leave-smoke",
    (
        Case(
            "lookup",
            ("How much leave do I get?",),
            expected_outcome="24 days",
            required_tools=("policy_lookup",),
            forbidden_tools=("send_email",),
            severity="critical",
        ),
        Case("smalltalk", ("Hi there",), no_tool=True),
    ),
)

journal = Journal.local(Path(tempfile.mkdtemp()))
system = EvaluationSystem(
    lambda context: LeaveBot(),
    (TrajectoryGrader(),),
    journal,
    source_digest=lambda: "src-1",
    model_route="scripted",
    harness_digest=lambda: "h-1",
)
report = asyncio.run(system.run(suite, repetitions=2))

for trial in report.trials:
    print(trial.case_id, trial.repetition, trial.verdict, [c.name for c in trial.checks])
# lookup 1 pass ['completion', 'required_tools', 'forbidden_tools', 'outcome']
# smalltalk 1 pass ['completion', 'required_tools', 'forbidden_tools', 'no_tool']
# ... one line per trial, four trials in all

EvaluationSystem takes engine="kit" by default, or engine="pydantic" to run through PydanticAI's native dataset integration. concurrency sets how many trials run at once.

See a failure

A target that calls a forbidden tool fails the case, and the failing checks name the rule that broke.

failing_target.py
class BadBot(LeaveBot):
    async def run(self, case_input, history, context):
        calls = (ToolObservation("call", "send_email", "c9", {"to": "all"}),)
        return Trajectory(
            turns=(Turn(1, case_input, "done", tools=calls),),
            final_output="done",
            history_complete=True,
        )


bad = EvaluationSystem(
    lambda context: BadBot(), (TrajectoryGrader(),), journal,
    source_digest=lambda: "src-2", model_route="scripted", harness_digest=lambda: "h-2",
)
for trial in asyncio.run(bad.run(suite)).trials:
    print(trial.case_id, trial.verdict, [c.name for c in trial.checks if c.verdict != "pass"])
# lookup fail ['required_tools', 'forbidden_tools', 'outcome']
# smalltalk fail ['no_tool']

A trial passes only when every included check passes. An error in the trajectory, or any failed check, makes the trial fail. A trial with no checks, an incomplete run or any unverified check is unverified.

Turn a report into a receipt and gate a change

A receipt summarises a report: pass counts and a Wilson confidence interval on the pass rate. The gate reads receipts and a list of changed paths. A rule maps a family of files (prompt, tool schema, model route) to the suites that must have run.

gate_change.py
from pathlib import Path

from recohut_kit.evals.gate import ChangeRule, GatePolicy, build_receipt, gate

receipt = build_receipt(report, lane="scripted", source_digest="src-1")
print(receipt.total, receipt.passes, round(receipt.wilson_lower, 2), receipt.proof_label)
# 2 2 0.34 deterministic_harness

rules = (ChangeRule("prompt", "**/prompts/*@*.md", ("leave-smoke",), "prompt files"),)
tree = Path("my-agent")   # the source tree that holds prompts/system@2.md

# No changed governed files: nothing is required.
print(gate([], [], tree, rules=rules).decision)                 # PASS

# A changed prompt with no receipt: blocked.
decision = gate(["prompts/system@2.md"], [], tree, rules=rules, policy=GatePolicy(min_cases=2))
print(decision.decision, decision.exit_code)                    # BLOCK 1
print(decision.render())
# eval gate: BLOCK
# requires leave-smoke for prompt prompts/system@2.md
# [missing_receipt] leave-smoke: no eval receipt supplied for this suite

A receipt passes the gate when it is fresh (it binds the current digest of each changed artifact), covers enough cases (min_cases), clears the Wilson lower-bound floor (min_lower), has no unverified critical failures and comes from an accepted lane. With only two cases the lower bound is 0.34, which is below the default floor of 0.5, so a small suite needs GatePolicy values you choose deliberately. receipt.write(directory) saves a receipt as JSON and load_receipts(directory) reads them back with any parse errors.

In CI, run the same gate as a command. It exits 0 on PASS, 1 on BLOCK and 2 on a usage error.

ci_gate.sh
python -m recohut_kit.evals.gate \
  --source-tree . \
  --base origin/main \
  --receipts eval-receipts \
  --rules change-rules.json \
  --summary "$GITHUB_STEP_SUMMARY"

Use --changed-paths FILE instead of --base to supply the paths yourself, --policy for a JSON GatePolicy, --baseline to enforce max_drop against earlier receipts, and --report-mode to print BLOCK but exit 0 in reporting jobs. The default change rules name the kit's own built-in suite ids, so pass --rules with your suite names.

Start from a neutral starter suite

evals.gate.starter_suite holds four generic cases: a grounded answer that cites its source, an answer that abstains when no source supports it, a refusal to reveal a secret, and a plain exchange that must not call tools. Copy it, replace the inputs and cited ids, and register it under your own suite name.

starter.py
from recohut_kit.evals.gate.starter_suite import starter_graders, starter_suite, suite_by_name

suite = suite_by_name("starter")
print([case.id for case in suite.cases])
# ['starter-grounded-answer', 'starter-unsupported-abstains',
#  'starter-refusal-of-secret', 'starter-plain-exchange']

Grade retrieval recall

RetrievalGrader scores recall at k against reviewed reference sources, using retrieval evidence that your code projects out of the trajectory. It makes no semantic judgement of passages.

retrieval_grader.py
from recohut_kit.evals import RetrievalGrader, RetrievalObservation, RetrievalReference

grader = RetrievalGrader(
    references={"lookup": RetrievalReference(source_ids=("hr/leave.txt",))},
    observe=my_projection,        # (Case, Trajectory) -> RetrievalObservation | None
    projection_version="v1",
    k=5,
    threshold=0.8,
)

my_projection is your function. The grader refuses an empty projection version, a non-positive k and a threshold outside 0 to 1.

Choosing between owners

You need toUse
Check tool use, outcome, citations and abstention deterministicallyTrajectoryGrader
Check that runtime text has no forbidden literalsEvidenceIntegrityGrader
Check retrieval recall against reviewed sourcesRetrievalGrader with retrieval.recall_at_k
Judge open-ended qualityLLMGrader with a rubric, then admit the judge through evals.measurement before you rely on it for release
Evaluate a PydanticAI agentrecohut_kit_pydantic_ai.evals.targets.PydanticAITarget
Evaluate a black-box chat endpoint or MCP serveragents.targets
Probe with attacks plus benign controlsredteam, compiled into the same Suite
Drive multi-turn runs with a simulated usersimulators, with deterministic goal sensors
Block merges that change prompts, tools or routesevals.gate in CI
Track pass rate, cost and latency over timeevals.ledger.RunLedger
Turn failures into reviewed regression caseslearning

Failure behaviour, limits and gotchas

  • Unverified is not pass. If the trajectory does not declare history_complete=True, a check on required or forbidden tools is unverified when the evidence cannot show absence. Set history_complete only when the trajectory is the full tool history.
  • Empty inputs are refused. Runner refuses an empty grader tuple. Suite rejects duplicate case ids and an empty case list. A Case with contradictory tool expectations (a tool both required and forbidden) raises ValueError.
  • The suite digest changes with the cases. Edit a case and its receipts no longer match. Bump Suite.version when you change meaning without changing structure.
  • Judge calibration is a smoke check. LLMGrader calibration reports an admission tier of smoke. Release-grade judge admission is in evals.measurement, a separate step.
  • The gate is not a signature check. A receipt is unsigned JSON. The gate verifies that it matches the tree and the policy, not who wrote it.
  • Small suites give wide intervals. The Wilson lower bound for a clean pass over six cases is about 0.61, and one failure drops it to about 0.44. The default floor of 0.5 therefore means no failures on a six-case suite. Set the floor for your suite size.
  • The default change rules use built-in suite names. Supply your own ChangeRule list for your suite ids.
  • HarnessTarget lives in another distribution. It is part of the optional PydanticAI package, not the core recohut_kit.evals module. Import it from recohut_kit_pydantic_ai.evals.harness.
  • Phoenix delivery never changes a verdict. If delivery to Phoenix fails, the journal result stands.
  • Import weight. import recohut_kit.evals loads no evaluation SDK. Bridges to DeepEval, Ragas, Phoenix, MLflow and Inspect load lazily when you use them.
  • Stand-in receipts are not usage evidence. Simulator stand-ins and scripted targets produce results labelled as such; the receipt's proof_label and lane record how the evidence was produced.

How is this page?

Last updated on