Contracts, Receipts, Evidence, Statistics and Export
Contracts
See Contracts v2.
- toolscore.contract.evaluate_contract(contract, actual, weights=None, strict=False, final_answer=None, honesty=None)[source]
Evaluate tool calls against a contract.
- Parameters:
contract (
Contract|dict[str,Any]) – AContractor a contract mapping.actual (
list[dict[str,Any]] |Any) – The calls (dicts, or any raw formattoolscore.evaluate()reads).weights (
dict[str,float] |None) – Score weights (default: the contract’s).strict (
bool) – Exact argument comparison.final_answer (
str|None) – The agent’s final answer, for the honesty checks.honesty (
HonestyConfig|None) – Honesty-check configuration.
- Return type:
- Returns:
The evaluation of the best combination of alternatives, with
metrics["contract_metrics"]:contract_version,alternatives(the option chosen per group and every combination’s score),optional_matched(the optional calls left out of the score) and the counts of required, optional and forbidden entries.trace_callsholds every call, optional ones included.
- toolscore.contract.load_contract(path)[source]
Read a contract file (JSON, or YAML with
tool-scorer[yaml]).
- toolscore.contract.contract_from_mapping(data)[source]
Validate and build a
Contractfrom parsed JSON (or a Python dict).- Raises:
ValueError – On a missing or unknown key, or a malformed call.
- Return type:
- Parameters:
data (Any)
- toolscore.contract.is_contract(data)[source]
Whether parsed JSON is a contract (it has
contract_version, orrequired/optional).
- toolscore.contract.matcher_from_json(value)[source]
Turn
$operators in a JSON value into matchers (see the module docstring).
- toolscore.contract.split_optional(actual, required, optional)[source]
Leave out optional calls that are not needed to fill a required call.
Walks the calls in order. A call matching an optional entry is dropped when the required calls of its tool are already filled by earlier calls (or the tool is not required at all); otherwise it is kept and fills one.
- class toolscore.contract.Contract(required=list(), optional=list(), forbidden=list(), weights=None, min_score=0.9)[source]
A parsed contract (see the module docstring).
- Variables:
- Parameters:
- property groups: list[AlternativeGroup]
The alternative groups, in order.
Receipts and regrade
See Receipts & Regrade.
- toolscore.receipts.build_receipt(result, inputs=None, settings=None, final_answer=None)[source]
Build the receipt of one evaluation.
- Parameters:
result (
EvaluationResult) – The evaluation.inputs (
dict[str,str|Path|None] |None) – Input files by role ("gold","trace","forbidden","honesty_config","injected"…);Noneentries are left out.settings (
dict[str,Any] |None) – Settings that changed the result (format,strict…). The normalized weights are always added.final_answer (
str|None) – A final answer given from outside the trace; only its hash is stored.
- Return type:
- Returns:
The receipt dict, with
receipt_sha256last.
- toolscore.receipts.write_receipt(path, receipt)[source]
Write a receipt as indented JSON and return its path.
- toolscore.receipts.verify_receipt(receipt, base=None)[source]
Check a receipt against itself and the files it names.
- Parameters:
- Return type:
- Returns:
Problems found, empty when the receipt and every input check out. A missing input is a problem; so is one whose bytes changed.
- toolscore.receipts.regrade(source, gold=None, weights=None, forbidden=None, format=None, honesty=None, final_answer=None, verify=True)[source]
Re-score a saved trace with a new gold file or contract, weights or rules.
Nothing is re-run.
sourceis a receipt (its trace, gold, format and weights are the defaults) or a trace file (thengoldis required).- Parameters:
gold (
str|Path|None) – The new gold file or contract (default: the receipt’s).weights (
dict[str,float] |None) – New score weights (default: the receipt’s).forbidden (
str|Path|None) – A forbidden-rules file (default: the receipt’s, if any).format (
str|None) – The trace format (default: the receipt’s, else"auto").honesty (
HonestyConfig|None) – Honesty-check configuration.final_answer (
str|None) – The final answer, when the trace does not hold one.verify (
bool) – Refuse a receipt whose inputs changed (raisesReceiptMismatchError);Falseregrades anyway and reports the problems.
- Return type:
- Returns:
The
Regrade.- Raises:
ValueError – If a trace is given without
gold.ReceiptMismatchError – If
verifyis on and the receipt’s inputs changed.
- class toolscore.receipts.Regrade(source, result, receipt, previous=None, problems=None)[source]
One regraded trace.
- Variables:
source (
str) – The receipt or trace that was regraded.result (
EvaluationResult) – The new evaluation.previous (
dict[str,Any] |None) – The previousresultblock (score,grade…) from the source receipt, orNonewhen regrading a bare trace.problems – What
verify_receipt()found (empty when it checked out or verification was off).
- Parameters:
- result: EvaluationResult
- exception toolscore.receipts.ReceiptMismatchError[source]
A receipt’s inputs changed since it was written, so a regrade would not be faithful.
- toolscore.receipts.canonical_json(value)[source]
valueas canonical JSON bytes: sorted keys, no whitespace, UTF-8.Non-JSON leaves (matchers, arbitrary objects) are written as their
repr.
- toolscore.receipts.json_sha256(value)[source]
The SHA-256 of
valueas canonical JSON (seecanonical_json()).
Evidence
Tri-state evidence: every check is pass, fail or unknown.
A check that lacks the data it needs does not pass. A trace that records only
the requests cannot show that a call succeeded; a trace without a final answer
cannot show that the agent disclosed a failure; a model without a known price
has no cost. Those checks are unknown, and evaluation_evidence()
counts them separately, so a report can say “4 pass, 0 fail, 3 unknown”
instead of a clean bill of health.
Checks of an evaluation (evaluation_evidence()):
Check |
Pass when |
Unknown when |
|---|---|---|
|
every required call was made and did not fail |
no calls were required; the calls’ outcomes were not captured |
|
no call failed |
no call has a result or error (and none failed) |
|
no call matched a forbidden rule (only with rules) |
never |
|
no credential in tool arguments |
never |
|
no success claim over a failure |
no final answer |
|
every warning and unrecovered error was disclosed (and every injected fault) |
no final answer, or no results captured |
|
no code-execution call got around a refusal |
no results captured |
|
every declared side effect validated (only when declared) |
never |
coverage reports how much of the trace holds the evidence: calls with an
outcome, a duration and a cost, and whether the final answer is known.
- toolscore.evidence.STATES: tuple[str, ...] = ('pass', 'fail', 'unknown')
The three states, in report order.
- class toolscore.evidence.Check(check, status, detail)[source]
One check’s verdict.
- Variables:
- Parameters:
- toolscore.evidence.tally(statuses)[source]
Count statuses:
{"pass": n, "fail": n, "unknown": n}(always all three keys).
- toolscore.evidence.evaluation_evidence(result)[source]
The tri-state checks and evidence coverage of one evaluation.
- Parameters:
result (
EvaluationResult) – The evaluation.- Return type:
- Returns:
checks(check,status,detaildicts),counts(pass/fail/unknown) andcoverage:calls,with_outcome,with_duration,with_cost(counts of calls) andfinal_answer("known"/"unknown").
Statistics and selection
See Comparing Runs.
- toolscore.stats.wilson_interval(successes, n, z=1.959963984540054)[source]
The Wilson score interval for a proportion.
- toolscore.stats.fisher_exact(a, b, c, d)[source]
Two-sided Fisher exact test p-value for the 2x2 table
[[a, b], [c, d]].Rows are variants, columns pass / not pass. The p-value sums the probabilities of every table with the same margins that is no more likely than the observed one.
- toolscore.stats.pass_hat_k(passes, n, k)[source]
Unbiased estimate of the probability that
kruns of a task all pass.C(passes, k) / C(n, k);Nonewhenn < k(not enough runs).
- toolscore.stats.compare_runs(runs, k=1, baseline=None, min_n=10, alpha=0.05)[source]
Compare variants over repeated runs (see the module docstring).
- Parameters:
- Return type:
- Returns:
The
Comparison.- Raises:
ValueError – If
baselineis not one of the variants.
- toolscore.stats.load_runs(paths, variant_key=None)[source]
Read runs from JSONL files (one JSON object per line; blank lines skipped).
- Raises:
ValueError – On a line that is not a JSON object, naming the file and line.
- Return type:
- Parameters:
- toolscore.stats.runs_from_traces(variant, directory, gold, min_score=0.9, task_pattern='^(?P<task>.+?)(?:[-_.]r?\\d+)?$')[source]
Score every
*.jsontrace in a directory against a gold file.A trace passes when its score is at least
min_scoreand it has no error-severity honesty finding; a trace that cannot be read is anerror(it stays in the population).- Parameters:
- Return type:
- Returns:
One run per trace file, sorted by file name.
- toolscore.stats.run_from_row(row, variant_key=None)[source]
Read a run from a JSONL row: a
toolscore agent runrow or an exported record.The variant is
row[variant_key], elsearm_id,variant,armormodel; the tasktask_idortask. The outcome isoutcome, else derived:status == "error"is an error,passedtrue/false is a pass/fail, anything else unknown. Cost iscost_usdorcost(a number, or{"usd": ...}); latencyduration_s,latencyorduration.
- toolscore.stats.select_variant(comparison, policy='lexicographic', objectives=None, weights=None)[source]
Pick a variant.
lexicographic: best on the first objective, ties broken by the next.weighted: each objective’s values are scaled to[0, 1]across the variants (1 is best; unknown is 0), and the weighted sum is highest.pareto: the Pareto front; when it has several variants, the first objective breaks the tie (then the next).
- Parameters:
comparison (
Comparison) – Fromcompare_runs().policy (
str) – The policy.objectives (
list[str] |None) –"metric:direction"strings (defaultDEFAULT_OBJECTIVES).weights (
dict[str,float] |None) – Weight per metric forweighted(default 1 each).
- Return type:
- Returns:
The
Selection.- Raises:
ValueError – On an unknown policy or metric.
- toolscore.stats.pareto_front(variants, objectives)[source]
Variants no other variant dominates (at least as good on every objective, better on one).
Unknown values count as the worst.
- Return type:
- Parameters:
variants (list[VariantStats])
objectives (list[Objective])
- toolscore.stats.evaluate_protocol(protocol, comparison)[source]
Evaluate decision rules declared before the runs.
Protocol keys:
protocol_version(1),title,baseline,candidate,alpha(0.05),min_runs(runs per variant before any rule can pass; default the comparison’smin_n) andrules. Each rule has anid, ametric(OBJECTIVE_METRICS) and one of:expect: candidate_better: the candidate is better than the baseline (forpass_rate: distinguishable by the Fisher test and the intervals; for other metrics: better by more thantolerance);expect: not_worse: the candidate is not worse by more thantolerance(default 0);min/max: bounds on the candidate’s value.
A rule whose metric is unknown, or whose variants have fewer than
min_runsruns, isunknown, never a pass.- Raises:
ValueError – On unknown keys, variants or metrics.
- Return type:
- Parameters:
comparison (Comparison)
- toolscore.stats.load_protocol(path)[source]
Read a protocol file (YAML with
pip install "tool-scorer[yaml]", or JSON).
- class toolscore.stats.Run(variant, task, outcome, cost=None, latency=None, run_id='')[source]
One run of one task under one variant.
- class toolscore.stats.VariantStats(variant, n, counts, pass_rate, interval, pass_hat_k, k, tasks, tasks_short, cost, cost_known, latency, latency_known)[source]
The summary of one variant (see the module docstring).
- Variables:
variant (
str) – The variant.n (
int) – Runs.interval (
tuple[float,float]) – 95% Wilson interval of the pass rate.pass_hat_k (
float|None) – Meanpass^kover tasks with at leastkruns, orNone.k (
int) – Thekused.tasks (
int) – Tasks seen.tasks_short (
int) – Tasks with fewer thankruns (left out ofpass^k).cost (
float|None) – Mean cost of the runs that have one, orNone.cost_known (
int) – Runs with a cost.latency (
float|None) – Mean latency of the runs that have one, orNone.latency_known (
int) – Runs with a latency.
- Parameters:
- __init__(variant, n, counts, pass_rate, interval, pass_hat_k, k, tasks, tasks_short, cost, cost_known, latency, latency_known)
- class toolscore.stats.Comparison(variants, pairs, k, min_n, alpha, notes=list())[source]
The result of
compare_runs().- Variables:
variants (
list[VariantStats]) – Per-variant statistics, in first-seen order.pairs (
list[PairComparison]) – Pairwise comparisons (each variant against the baseline, or all pairs).k (
int) – Thekofpass^k.min_n (
int) – Runs needed per variant before a difference can be called.alpha (
float) – Significance level.
- Parameters:
variants (list[VariantStats])
pairs (list[PairComparison])
k (int)
min_n (int)
alpha (float)
- variants: list[VariantStats]
- pairs: list[PairComparison]
- __init__(variants, pairs, k, min_n, alpha, notes=<factory>)
- Parameters:
variants (list[VariantStats])
pairs (list[PairComparison])
k (int)
min_n (int)
alpha (float)
- Return type:
None
- class toolscore.stats.PairComparison(a, b, difference, p_value, overlap, distinguishable, verdict)[source]
Two variants side by side.
- Variables:
a (
str) – The first variant.b (
str) – The second variant.difference (
float|None) –pass_rate(b) - pass_rate(a), orNone.p_value (
float) – Two-sided Fisher exact p-value.overlap (
bool) – Whether the 95% intervals overlap.distinguishable (
bool) – Whether the difference is distinguishable (see the module docstring).verdict (
str) – A sentence for reports.
- Parameters:
- class toolscore.stats.Selection(chosen, policy, objectives, ranking, pareto_front, scores, unknown, reason)[source]
The result of
select_variant().- Variables:
chosen (
str|None) – The selected variant, orNonewith no variants.policy (
str) –"lexicographic","weighted"or"pareto".objectives (
list[Objective]) – The objectives used.ranking (
list[str]) – Variants best first, under the policy.scores (
dict[str,float]) – Weighted scores (weightedpolicy only).unknown (
dict[str,list[str]]) – Per variant, the objectives whose value is unknown.reason (
str) – Why the chosen variant won.
- Parameters:
- class toolscore.stats.ProtocolResult(title, protocol_sha256, baseline, candidate, rules, decision)[source]
The result of
evaluate_protocol().- Variables:
title (
str) – The protocol’s title.protocol_sha256 (
str) – Hash of the protocol as declared (record it before the runs).baseline (
str) – The baseline variant.candidate (
str) – The candidate variant.rules (
list[RuleOutcome]) – Each rule’s outcome.decision (
str) –"adopt"(every rule passed),"reject"(a rule failed) or"undecided"(a rule is unknown and none failed).
- Parameters:
Export
- toolscore.export.export_records(inputs, gold=None, variant='', min_score=0.9)[source]
Run records for agent-run JSONL files, trace files and receipts.
- Parameters:
inputs (
Iterable[str|Path]) –.jsonlfiles fromtoolscore agent run, trace files (any supported format), or receipts fromtoolscore eval --receipt.gold (
str|Path|None) – A gold file or contract for traces (receipts carry their own).variant (
str) – The variant of traces and receipts.min_score (
float) – The passing score of traces and receipts.
- Return type:
- Returns:
The records, in input order.
- Raises:
ValueError – On an unreadable input.
- toolscore.export.write_export(path, records, inputs)[source]
Write records as JSONL and a manifest next to it.
- toolscore.export.validate_record(record)[source]
Check a record against the shipped JSON Schema (Toolscore’s conservative validator).
- toolscore.export.record_from_run(row, source)[source]
The run record of one
toolscore agent runrow.
- toolscore.export.SCHEMA_VERSION = '1'
The schema version of a run record.
Doctor
- toolscore.doctor.run_doctor(spec_path=None, contract_path=None, server=None, keys=None, allow_unknown_price=False, start_server=True)[source]
Run the preflight checks (see the module docstring).
- Parameters:
spec_path (
str|Path|None) – An agent spec to check (server, keys, packages, prices, budget).contract_path (
str|Path|None) – A contract or gold file to validate.server (
MCPServerSpec|None) – A server to start and list (when there is no spec).keys (
list[str] |None) – More environment variable names that must be set.allow_unknown_price (
bool) – As fortoolscore agent run.start_server (
bool) – Start the spec’s server (Falsechecks only the files).
- Return type:
- Returns:
The checks, in the order they ran.
- toolscore.doctor.check_server(spec, verify=None, timeout=30.0)[source]
Start a server, list its tools and check its build; nothing else is called.
- Return type:
- Parameters:
spec (MCPServerSpec)
timeout (float)
- toolscore.doctor.doctor_report(checks)[source]
A JSON-safe report: the checks, the counts and the worst status.
- Return type:
- Parameters:
checks (list[DoctorCheck])