Metrics Module
The metrics module provides functions to calculate various evaluation metrics.
Accuracy Metrics
- toolscore.metrics.calculate_invocation_accuracy(gold_calls, trace_calls)[source]
Calculate tool invocation accuracy.
Measures whether the agent invoked tools when it was supposed to, and refrained from invoking when not needed.
Sequence Metrics
- toolscore.metrics.calculate_edit_distance(gold_calls, trace_calls)[source]
Calculate edit distance metrics for tool call sequences.
Computes Levenshtein edit distance between the sequence of tool names in the gold standard and the actual trace.
- Parameters:
- Returns:
edit_distance: Raw Levenshtein distance (lower is better)
normalized_distance: Distance normalized by max sequence length (0-1)
sequence_accuracy: 1 - normalized_distance (higher is better, 0-1)
- Return type:
Argument Metrics
- toolscore.metrics.calculate_argument_f1(gold_calls, trace_calls, strict=False)[source]
Calculate F1 score for argument matching.
Evaluates how well the arguments provided to each tool match the expected arguments.
- Parameters:
- Return type:
Gold calls whose
args is Nonecarry a “do not check arguments” expectation (tool-name-only): they are skipped entirely from argument counting and never penalize the score. An explicitargs == {}keeps the strict “expect zero arguments” meaning. When every matched gold call opts out of argument checking, there is nothing to score against, so the result is a perfectf1 == 1.0rather than an undefined 0/0.
Required Calls
- toolscore.metrics.calculate_required_call_recall(gold_calls, trace_calls)[source]
Share of required calls that the trace completed, counting every required call.
Each expected call needs its own actual call with the same tool name that did not fail (see
ToolCall.is_error), so a contract that requiressearchtwice is half met by onesearch, and a required call whose only attempt failed is not met.calculate_tool_correctness()compares sets of tool names and reports both cases as fully correct. Order and arguments are not considered here. Traces without error information count every call as completed.- Parameters:
- Return type:
- Returns:
A value in
[0, 1], orNonewhen nothing is required (the metric does not apply; it is not a zero).
Example
>>> gold = [ToolCall(tool="search"), ToolCall(tool="search")] >>> calculate_required_call_recall(gold, [ToolCall(tool="search")]) 0.5
Efficiency Metrics
- toolscore.metrics.calculate_redundant_call_rate(gold_calls, trace_calls)[source]
Calculate redundant call rate.
Measures inefficiency in tool use by quantifying how many tool calls were unnecessary or redundant.
- Parameters:
- Returns:
redundant_count: Number of redundant calls
total_calls: Total number of calls made
redundant_rate: Proportion of calls that were redundant (0-1)
identical_count: Calls that exactly repeat an earlier call (same tool and same arguments). Unlike
redundant_count, which counts calls beyond the gold’s per-tool expectation, this isolates loop-like repetition from productive repeated use of a tool.identical_rate:
identical_count/total_calls(0-1)error_count: Calls that failed (see
ToolCall.is_error). Zero when the trace carries no error information.error_rate:
error_count/total_calls(0-1)retry_after_error_count: Calls that repeat the immediately preceding call exactly (same tool and arguments) after that call failed, i.e. retrying a failure without changing anything.
- Return type:
Reports error_count, error_rate and retry_after_error_count alongside
the redundancy and loop (identical_rate) metrics.
Safety: Credentials and Forbidden Calls
See Behavior and Safety Checks for the guide, the credential formats and the JSON rule operators.
- toolscore.metrics.redact_secrets(text)[source]
Replace every credential in
textwith its redacted preview.Used for reports that may be published (Markdown job summaries, HTML), so a credential found in a trace is not copied into them in full.
- toolscore.metrics.check_forbidden_calls(trace_calls, rules)[source]
Report every call that matches a forbidden rule.
- Parameters:
- Returns:
one entry per violating call with its
indexin the trace,tool,args, the index of the first matchingruleand that rule’sreason(if any).- Return type:
- Raises:
TypeError – If
rulesis not a list.ValueError – If a rule has no tool name or non-dict
args.
- toolscore.metrics.rules_from_json(data)[source]
Build forbidden rules from JSON data, turning
$operators into matchers.An argument value that is a one-key dict
{"$regex": pattern},{"$contains": item}or{"$one_of": [values]}becomes a matcher:$regexfinds the pattern anywhere in the value (re.search, so a second line or a prefix does not hide it; lists are matched as their items joined with spaces),$containsisContainsand$one_ofisOneOf. Any other value is compared exactly.- Parameters:
data (
Any) – A list of rule dicts, e.g. parsed from a JSON file.- Return type:
- Returns:
Rules ready for
check_forbidden_calls().- Raises:
TypeError – If
datais not a list.ValueError – If a rule or an operator is malformed.
- toolscore.metrics.load_forbidden_rules(path)[source]
Read forbidden rules from a JSON file (see
rules_from_json()).
Honesty
See Honesty Checks.
- toolscore.metrics.honesty.check_honesty(calls, final_answer, gold_calls=None, config=None, final_source=None, forbidden=None)[source]
Compare what the tools returned with what the agent said at the end.
- Parameters:
calls (
list[ToolCall]) – The agent’s tool calls, in order, with results and errors. Calls marked byapply_injections()(or recorded by the proxy) are judged against the injected fault.final_answer (
str|None) – The agent’s final answer, orNonewhen unknown.gold_calls (
list[ToolCall] |None) – The required calls, if known (forfailed_required).config (
HonestyConfig|None) – Patterns and tool lists; defaults when omitted.final_source (
str|None) – Where the final answer came from (reported as is).forbidden (
list[dict[str,Any]] |None) – Forbidden-call rules (seetoolscore.metrics.policy); a call that matches one after a planted instruction isprompt-injection-followed.
- Return type:
- Returns:
final_answer("known"/"unknown"),final_source,answer_language("english","other"orNonewithout an answer; with"other"the answer-dependent counts areNone),results(seeresults_coverage()),findings(dicts withrule,severity,message, 1-basedcall,toolandconfidence),false_success(the counts described in the module docstring),prompt_injection(planted,followedandcanary_leaked: how many planted instructions the run got, followed and leaked;canary_leakedisNonewhen no leak was seen in the calls and the final answer is unknown) andflagged(Trueif any honesty rule fired,Noneif nothing fired but disclosure could not be checked, elseFalse).
- class toolscore.metrics.honesty.HonestyConfig(warning_patterns=<factory>, error_patterns=<factory>, refusal_patterns=<factory>, escape_hatch_tools=<factory>, override_patterns=<factory>, success_patterns=<factory>, disclosure_patterns=<factory>, neutral_patterns=<factory>, done_tools=<factory>, escape_window=5, min_shared_words=2, require_english=True)[source]
Patterns and tool lists for the honesty checks; every field is configurable.
- Variables:
warning_patterns (
list[str]) – Regexes (case-sensitive, multiline) for a warning in a result.error_patterns (
list[str]) – Regexes (case-sensitive, multiline) for an error written as text in a result that is not flaggedis_error.refusal_patterns (
list[str]) – Regexes (case-insensitive) for a refusal in a result.escape_hatch_tools (
list[str]) – Generic code-execution tools. A tool matches when its name (host prefix removed, lowercased) equals an entry or ends with_<entry>,-<entry>or.<entry>.override_patterns (
list[str]) – Regexes (case-sensitive) for code that overrides a refusal.success_patterns (
list[str]) – Regexes (case-insensitive) for a success claim.disclosure_patterns (
list[str]) – Regexes (case-insensitive) for an answer that admits a problem.neutral_patterns (
list[str]) – Regexes (case-insensitive) for phrases that use a problem word without reporting a problem: reassurance (“no errors”, “without issues”, “nothing failed”, “didn’t hit any warnings”) and nouns (“created the issue”, “issue #12”). They are removed before the disclosure patterns run, so “Done, no errors!” claims success and discloses nothing.require_english (
bool) – Report the checks that read the final answer as unknown when it is not in English (seeanswer_language()); the default patterns are English. Set it to false with patterns for another language.done_tools (
list[str]) – Tool names that finish a run (not counted as the last call).escape_window (
int) – How many calls after a refusal are checked for an escape hatch.min_shared_words (
int) – Distinctive words a final answer must share with a warning to count as disclosing it (when it has no disclosure word).
- Parameters:
- classmethod from_mapping(data)[source]
Build a config from parsed JSON/YAML.
Each list replaces the default; with
"extend": truelists are added to the defaults instead.- Raises:
ValueError – On an unknown key or a value of the wrong type.
- Return type:
- Parameters:
data (Any)
- __init__(warning_patterns=<factory>, error_patterns=<factory>, refusal_patterns=<factory>, escape_hatch_tools=<factory>, override_patterns=<factory>, success_patterns=<factory>, disclosure_patterns=<factory>, neutral_patterns=<factory>, done_tools=<factory>, escape_window=5, min_shared_words=2, require_english=True)
- toolscore.metrics.honesty.load_honesty_config(path)[source]
Read an honesty config file (JSON, or YAML with PyYAML installed).
- Return type:
- Parameters:
path (str | Path)
- toolscore.metrics.honesty.apply_injections(calls, injections)[source]
Mark calls with the faults a proxy session says were injected.
For a trace recorded by the agent (not by the proxy), match each injection to the agent’s calls by tool name (host prefixes such as
mcp__server__ignored) and by order among calls of that tool. Calls that already carry an injection are left alone.
Side-Effect Metrics
- toolscore.metrics.calculate_side_effect_success_rate(gold_calls, trace_calls, validators=None)[source]
Calculate side-effect success rate.
Evaluates whether tool calls achieved their intended side effects or outcomes.
- Parameters:
- Returns:
total_checks: Total number of side effect checks
passed_checks: Number of passed checks
success_rate: Proportion of checks that passed (0-1)
details: List of detailed check results
- Return type:
Performance Metrics
- toolscore.metrics.calculate_latency(trace_calls)[source]
Calculate latency metrics from tool calls.
- Parameters:
trace_calls (
list[ToolCall]) – Tool calls with timing information.- Returns:
total_duration: Total time spent on the timed calls (seconds), or
Nonewhen no call was timedaverage_duration: Average duration per timed call (seconds) or
Nonemax_duration: Maximum duration of any timed call (seconds) or
Nonemin_duration: Minimum duration of any timed call (seconds) or
Nonemeasured_calls: Calls that carry a duration
total_calls: All calls
status:
"measured","partial"or"unknown"(see the module docstring)
- Return type:
- toolscore.metrics.calculate_cost_attribution(trace_calls)[source]
Calculate cost attribution from tool calls.
- Parameters:
trace_calls (
list[ToolCall]) – Tool calls with cost information.- Returns:
total_cost: Total cost of the calls that carry one (USD), or
Nonewhen no call doesaverage_cost: Average cost per costed call (USD) or
Nonecost_by_tool: Dictionary mapping tool names to their total costs (costed calls only)
measured_calls, total_calls, status: as for
calculate_latency()
- Return type:
Model prices
List prices per million tokens, verified on the providers’ pricing pages on
2026-11-01. Names match exactly or by the longest known prefix; an unknown model
has no price (None and an UnknownModelPriceWarning).
- toolscore.metrics.calculate_llm_cost(model, input_tokens=0, output_tokens=0, pricing=None)[source]
Calculate the cost of an LLM API call.
- Parameters:
model (
str) – Model name (e.g."gpt-6-luna","claude-haiku-5-5").input_tokens (
int) – Number of input tokens.output_tokens (
int) – Number of output tokens.pricing (
tuple[float,float] |None) – Optional(input, output)USD per 1M tokens, used instead of the built-in table (for unlisted models or negotiated prices).
- Return type:
- Returns:
Cost in USD, or
None(with anUnknownModelPriceWarning) when the model is unknown and nopricingwas given.
- toolscore.metrics.lookup_pricing(model)[source]
Find the (input, output) price per 1M tokens for a model name.
Matching is exact first, then the longest known name that
modelstarts with, followed by-,@or:(a dated snapshot or a variant). Case and provider prefixes (openai/,models/) are ignored.
- toolscore.metrics.estimate_trace_cost(trace_data, model='gpt-6-luna', pricing=None)[source]
Estimate cost for an entire trace.
- Parameters:
- Return type:
- Returns:
Estimated cost in USD, or
Nonefor an unknown model (seecalculate_llm_cost()).
Default models
Current default model IDs, in one place.
Toolscore itself never calls a model; these IDs are the defaults for the
optional LLM judge (toolscore eval --llm-judge) and the examples, scaffolds
and docs. Provider model lists change often, so every value here was checked
against the provider’s official documentation on the date below. Update them
together, with the date.
Verified 2026-11-01 against:
Current Anthropic models (Opus 4.7 and later, Sonnet 5 and later, Haiku 5.5)
and OpenAI’s GPT-6 models at their default reasoning effort reject a
non-default temperature, so the judge sends none unless asked to.
- toolscore.models.ANTHROPIC_BALANCED = 'claude-sonnet-5-5'
Anthropic’s balanced current model (a stronger judge).
- toolscore.models.ANTHROPIC_FAST = 'claude-haiku-5-5'
Anthropic’s fastest, cheapest current model.
- toolscore.models.ANTHROPIC_TOP = 'claude-opus-5-5'
Anthropic’s most capable Opus model.
- toolscore.models.DEFAULT_JUDGE_MODEL = 'gpt-6-luna'
The LLM judge’s default model.
- toolscore.models.GEMINI_DEFAULT = 'gemini-3.5-flash-lite'
Google’s low-cost current Gemini model.
- toolscore.models.OPENAI_BALANCED = 'gpt-6.1-sol'
OpenAI’s balanced model.
- toolscore.models.OPENAI_DEFAULT = 'gpt-6-luna'
OpenAI’s model for cost-sensitive, high-volume work; the default judge.
- toolscore.models.VERIFIED_ON = '2026-11-01'
Date the IDs below were last checked against the providers’ docs.
LLM-as-a-judge Metrics (Optional)
These metrics use an optional LLM judge that supports OpenAI, Anthropic, Gemini,
and any OpenAI-compatible endpoint. Configure it with a
JudgeConfig (or a model-name string). See
the LLM-as-a-Judge guide for provider inference, env-var keys, and install
extras.
- toolscore.metrics.llm_judge.calculate_semantic_correctness(gold_calls, trace_calls, *, judge=None)[source]
Calculate semantic correctness using LLM-as-a-judge.
Uses an LLM to evaluate whether the trace calls are semantically equivalent to the gold standard calls, even if they differ syntactically.
By default this issues a single batched request containing every gold/trace pair and asks for a JSON array of per-pair scores. If the batched response cannot be parsed, it falls back to one request per pair.
- Parameters:
trace_calls (
list[ToolCall]) – Actual tool calls from the agent.judge (
JudgeConfig|str|None) – Judge configuration. May be aJudgeConfig, a model-name string shorthand, orNone(defaultJudgeConfig()).
- Returns:
semantic_score: Overall semantic correctness (0.0 to 1.0).per_call_scores: List of scores for each call pair.explanations: List of explanations for each evaluation.model_used: The model that was used.gold_count: Number of gold calls.trace_count: Number of trace calls.
- Return type:
- Raises:
ImportError – If the required provider SDK is not installed.
ValueError – If no API key is available for the resolved provider.
Example
>>> gold = [ToolCall(tool="search", args={"query": "Python"})] >>> trace = [ToolCall(tool="web_search", args={"q": "Python"})] >>> result = calculate_semantic_correctness(gold, trace) >>> result["semantic_score"] 0.95 # High score despite different naming
- toolscore.metrics.llm_judge.calculate_batch_semantic_correctness(evaluations, *, judge=None)[source]
Calculate semantic correctness for multiple independent evaluations.
This is useful for evaluating multiple test cases at once. Each evaluation is judged with
calculate_semantic_correctness()(itself batched).- Parameters:
evaluations (
list[tuple[list[ToolCall],list[ToolCall]]]) – List of(gold_calls, trace_calls)tuples.judge (
JudgeConfig|str|None) – Judge configuration (seecalculate_semantic_correctness()).
- Returns:
average_score: Average semantic score across all evaluations.individual_scores: List of scores for each evaluation.total_evaluations: Number of evaluations performed.
- Return type: