- Studio
- Observability
- Offline evaluations
- Advanced guides
Use run-level evaluators
Use run-level evaluators
While regular evaluators score each record individually, run evaluators operate on the full set of results after all records have been processed. Use them for global assertions, aggregate metrics like F1, or cross-record analysis.
Basic run evaluator
A run evaluator receives a RunEvaluatorContext with all records, statistics, and metadata:
import asyncio
import os
from mistralai.evaluations import (
Evaluation, Evaluator, Mistral, RunEvaluator, RunEvaluatorContext,
ScorerContext, System, TaskContext,
)
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
dataset = [
{"prompt": "What is the capital of France?", "expected": "Paris"},
{"prompt": "Which planet is known as the Red Planet?", "expected": "Mars"},
]
def accuracy_scorer(ctx: ScorerContext) -> int:
return 1 if ctx.input_record["expected"].lower() in str(ctx.output).lower() else 0
def accuracy_gate(ctx: RunEvaluatorContext):
return ctx.statistics["accuracy"].avg > 0.8
async def task(ctx: TaskContext) -> str:
r = await client.chat.complete_async(
model="mistral-small-latest",
messages=[{"role": "user", "content": ctx.input_record["prompt"]}],
)
return str(r.choices[0].message.content)
async def main():
run = await client.evaluation.run(
evaluation=Evaluation(name="Gated Eval"),
dataset=dataset,
task=task,
evaluators=[Evaluator(name="accuracy", description="1 if the expected answer appears in the output.", scorer=accuracy_scorer)],
run_evaluators=[
RunEvaluator(
name="accuracy_above_80pct",
description="True if average accuracy exceeds 80%.",
scorer=accuracy_gate,
),
],
)
print(run.run_scores["accuracy_above_80pct"].value) # True
asyncio.run(main())
Computing F1 with get_score
The get_score() helper extracts individual evaluator scores from run evaluator records:
from mistralai.evaluations import RunEvaluator, RunEvaluatorContext, Score, get_score
def f1_scorer(ctx: RunEvaluatorContext) -> Score:
tp = fp = fn = 0
for record in ctx.records:
# Failed records are passed too: skip any record whose generation or scoring failed.
if any(
g.status != "success" or any(s.status != "success" for scores in g.scores.values() for s in scores)
for g in record.output.generations
):
continue
predicted = get_score(record, "predicted_label").value
expected = get_score(record, "expected_label").value
if predicted == 1 and expected == 1:
tp += 1
elif predicted == 1 and expected == 0:
fp += 1
elif predicted == 0 and expected == 1:
fn += 1
precision = tp / (tp + fp) if (tp + fp) > 0 else 0
recall = tp / (tp + fn) if (tp + fn) > 0 else 0
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0
return Score(
value=f1,
metrics={"precision": precision, "recall": recall, "tp": tp, "fp": fp, "fn": fn},
)
run = await client.evaluation.run(
# ...
run_evaluators=[RunEvaluator(name="f1", description="Harmonic mean of precision and recall across all records.", scorer=f1_scorer)],
)
RunEvaluatorContext reference
Field | Type | Description |
|---|---|---|
| records | list[RunEvaluatorRecord] | All processed records with their scores |
| statistics | dict[str, EvaluatorStatistics] | Per-evaluator aggregate statistics |
| metadata | dict[str, JsonValue] | Run metadata |
| system | System | None | System config from evaluation.run(system=...) |
Adding goals
Run evaluators support pass/fail goals the same way regular evaluators do:
from mistralai.evaluations import Goal
RunEvaluator(
name="f1",
description="Harmonic mean of precision and recall.",
scorer=f1_scorer,
goal=Goal.gte(0.85),
)
See Goals for the full guide.
Several metrics in one run evaluator
A run evaluator often computes more than one useful number at once: an accuracy and its confidence interval, a p50 latency with its p95 and p99, an F1 with its precision and recall, or counts. Return the main result in value and the other numbers in metrics. Studio shows them on the score card, in its hover card, and in the compare view, and you can put a goal on each of them.
from scipy.stats import binomtest
from mistralai.evaluations import Display, Goal, RunEvaluator, RunEvaluatorContext, Score, get_score
def accuracy_with_ci(ctx: RunEvaluatorContext) -> Score:
k = sum(get_score(r, "field_match").value for r in ctx.records)
n = len(ctx.records)
ci = binomtest(k, n).proportion_ci(confidence_level=0.95, method="wilson")
return Score(
value=k / n,
metrics={"lower": ci.low, "upper": ci.high},
metadata={"n_docs": n, "method": "wilson 95%"},
)
RunEvaluator(
name="accuracy",
description="Share of documents fully extracted, with its 95% confidence interval.",
scorer=accuracy_with_ci,
goal=Goal.gte(0.45, metric="lower"),
display=Display(format="percent"), # the value and, by default, lower and upper
)
Field | What it is | Where it shows | Goal |
|---|---|---|---|
| value | The main result | Large on the card and in compare | Goal.gte(x) |
| metrics | Other numbers from the same computation | On the card, under the value. In compare, by expanding the row. | Goal.gte(x, metric="name") |
| metadata | Context (sample size, method, parameters) | In the card's hover | No |
Put a result you want to read or gate in metrics. Put what helps understand the result in metadata. Metrics show in the order the scorer returns them, and value can be None when only the metrics matter.
Run evaluator metrics require SDK 0.11.0+ and a recent Studio backend. Against an older backend, a run evaluator with several goals or a goal on a metric fails when the run is created, and uploading a score with metrics raises RuntimeError (the score is saved without its metrics).
Goals on metrics
goal takes one goal or a list. metric= picks the number checked: the value by default, or the name of a metric. The run evaluator passes when all its goals pass, and each goal shows on its own:
RunEvaluator(
name="f1",
scorer=f1_scorer,
goal=[
Goal.gte(0.80), # the value (F1)
Goal.gte(0.75, metric="recall"), # recall must not drop below 75%
],
)
A goal on a metric the score doesn't return fails, with the message run evaluator 'f1' has a goal on metric 'recall' but its scorer did not return it. It's never skipped.
Formats and directions per metric
display and direction also take a list, with the same metric= targeting:
- A Display without metric formats the value and is the default format of every metric. Display(metric=...) overrides it for one metric. See Display format.
- "maximize" or "minimize" is the value's direction. Direction.maximize(metric=...) or Direction.minimize(metric=...) sets a metric's direction, which Studio uses to color the change between runs.
from mistralai.evaluations import Direction, Display, Goal, RunEvaluator
RunEvaluator(
name="extraction_cells",
scorer=cells_accuracy, # Score(value=412 / 475, metrics={"correct": 412, "total": 475, "missing": 9})
goal=Goal.lte(10, metric="missing"),
display=[
Display(format="percent"), # 86.7%, and the default for the metrics
Display(metric="correct", format="integer"), # 412, not 41200%
Display(metric="total", format="integer"),
Display(metric="missing", format="integer"),
],
direction=[Direction.maximize(), Direction.minimize(metric="missing")],
)
A metric's direction is never inferred from its goals: without one, its change reads without color.
Rules
Situation | Result |
|---|---|
| A metric that isn't a number, or is a boolean, nan, or inf | ValueError when building the Score |
| A metric name that is empty, longer than 100 characters, or "value" | ValueError when building the Score |
| More than 100 metrics | ValueError when building the Score |
| metrics on the score of a per-record Evaluator | The score is recorded as an error: metrics are for run evaluators |
| A goal on a metric missing from the score | The goal fails, with a message |
| Two goals, two Display, or two directions on the same target | ValueError when building the RunEvaluator |
| A Display or a Direction on a metric missing from the score | No error |
| Goal.gte(x, metric="avg") on a run evaluator | Targets a metric named avg (a run evaluator has no statistics), with a warning |
run.show() prints the metrics after the value, formatted with their Display, with ✓ or ✗ on the ones a goal targets:
accuracy: 63.4% (expect >= 0.6) → PASS lower 47.0% ✓ upper 82.3%
Metrics and their goals, like the rest of a run evaluator, aren't part of the optimization objective or constraints.
After all records have been processed and scored. All records are passed in ctx.records, including the ones whose generation or scoring failed. Those records have no successful scores, so get_score() raises ValueError for them: skip them (check generation.status and each score's status) or the run evaluator ends with an error status.
In metrics: Score(value=f1, metrics={"precision": precision, "recall": recall}). Studio shows them next to the value, and you can put a goal, a format, and a direction on each. Keep metadata for context, such as the sample size or the method.
Yes. Use get_score(record, "evaluator_name") to retrieve a specific evaluator's score for any record in ctx.records.