mistralM

Docs

API reference

Reference for the Evaluation SDK's core types and the evaluation.run() entry point.

Reference for the Evaluation SDK's core types and the main evaluation.run() entry point. For the method-level reference of the advanced operations, see Retry failed records, Rescore persisted runs, and Optimize prompts and parameters. For size limits and API errors, see Limits.

evaluation.run()

The main entry point for running evaluations.

run = await client.evaluation.run(
    dataset=...,
    task=...,
    evaluators=...,
    # optional parameters below
)

Parameter

Type

Default

Description

datasetSequence[Mapping[str, Any]] | DatasetrequiredInline input records, or a Studio dataset (max 10,000 records per run).
taskTaskFunctionrequiredAsync or sync function (ctx: TaskContext) -> output.
evaluatorslist[Evaluator | EvaluatorGroup]requiredPer-record evaluators, and groups of evaluators scored by one scorer call.
run_evaluatorslist[RunEvaluator][]Run-level evaluators (executed after all records).
projectProjectNoneProject to save to (created if it doesn't exist and is selected by name). A run with an evaluation but no project is saved under a project named "Default project".
evaluationEvaluationNoneEvaluation to save to (created if it doesn't exist and is selected by name). Without it, the run stays local and isn't saved.
namestrNoneRun name.
descriptionstrNoneRun description.
metadatadict | RunMetadataFunctionNoneStatic key-value metadata, or a callback that receives a RunMetadataContext after the run and returns a dict to merge.
record_metadataRecordMetadataFunctionNoneCallback run once per record, after its task and scorers. It receives a RecordMetadataContext, and its returned dict is stored on the record's metadata.
tagslist[str][]Tags for filtering in Studio.
num_generationsint1Number of task executions per input record.
localboolFalseIf True, skip upload to Studio.
systemSystemNoneSystem config passed to the task and scorers via context objects.
upload_batch_sizeint10Number of records to buffer before each streaming upload (at least 1). A single upload request never carries more than 500 records: the SDK splits larger buffers.
max_concurrencyint10Maximum concurrent record processing.

It returns an EvaluationRun:

Field

Type

Description

output_recordslist[EvaluationRunRecord]All processed records, with their generations and scores.
failed_record_countintRecords whose task or a score failed, out of len(output_records) (0.10.0+). What failed is not in statistics; retry_failed_records() runs these records again.
statisticsdict[str, EvaluatorStatistics]Per-evaluator aggregate statistics, without failed generations and scores.
run_scoresdict[str, Score]Run-level evaluator results, keyed by run evaluator name. Each entry is a Score (value, rationale, metadata) with two more fields: status ("success" or "error") and error.
run_idstr | NoneID of the run in Studio. None for a local run.
run_urlstr | NoneLink to the run in Studio. None for a local run.
statusstr | NoneRun lifecycle status: "pending", "running", "completed", "failed", or "cancelled".

run() marks the run "running" while it executes, then "completed". If the run raises, it's marked "failed"; if it's interrupted, "cancelled". While the run executes, the SDK sends a heartbeat to Studio, so a run whose process dies is marked "cancelled" instead of staying in progress.

Method

Description

run.show(mode, level)Print results (returns nothing). mode: "text" (default), "json". level: "run" (default), "records", "generations", "scores".

Project

A project groups related evaluations together. Think of it as a folder — for example, "Chatbot QA" or "RAG Pipeline".

Project(name="My Project")       # create or get by name
Project(slug="my-project")       # get by slug

At least one of name or slug must be provided. A project selected by name is created if it doesn't exist; a project selected by slug must already exist.

Dataset

Selects a Studio dataset by slug or UUID. The SDK fetches its records before the run starts. See Use a Studio dataset.

from mistralai.evaluations import Dataset

Dataset(slug="customer-support-golden-set")
Dataset(id="018f879d-20cd-7e9f-a1bc-2f4f08b6f170")

Exactly one of id and slug must be provided, and id must be a valid UUID. The dataset must already exist: selecting it by slug never creates it.

evaluation.add_dataset_records()

Adds records to an existing Studio dataset. Each record is the record's payload: the JSON object a run reads as its input record. See Add records to a Studio dataset.

ids = await client.evaluation.add_dataset_records(
    dataset=Dataset(slug="customer-support-golden-set"),
    records=[
        {"input": "How do I reset my password?", "expected": "Settings > Security"},
        {"input": "Can I get a refund after 30 days?", "expected": "No"},
    ],
)

Parameter

Type

Description

datasetDatasetThe dataset to add to, by id or slug.
recordsSequence[Mapping[str, Any]]The payloads of the new records.

It returns the IDs of the new records, in order. Requires SDK 0.11.0+.

Evaluation

An evaluation is a named test you run repeatedly over time — for example, "Accuracy on French prompts". Each call to evaluation.run() creates a new run under it, so you can track how scores evolve across runs.

Evaluation(name="My Eval")       # create or get by name
Evaluation(slug="my-eval")       # get by slug

At least one of name or slug must be provided. An evaluation selected by name is created under the given project if it doesn't exist; an evaluation selected by slug must already exist.

Evaluator

An evaluator defines how to score each individual record. It pairs a name with a scorer function that receives a ScorerContext and returns a score.

Evaluator(
    name="accuracy",
    scorer=my_scorer,
    description="Optional description",
    tags=["tag1"],
    num_scores=1,
    goal=Goal.gte(0.8),
)

Parameter

Type

Default

Description

namestrrequiredUnique evaluator name.
scorerScoreFunctionrequired outside a group(ctx: ScorerContext) -> value or Score. Leave it out for an evaluator of an EvaluatorGroup.
descriptionstrNoneDescription shown in Studio on hover.
tagslist[str][]Tags.
num_scoresint1Number of scoring passes per generation (results averaged — useful for noisy LLM judges).
goalGoalSpecNonePer-generation pass/fail goal (for example, Goal.gte(0.8)).
direction"maximize" | "minimize"NoneWhich way is better. Inferred from the goal when unset.
min_value / max_valuefloatNoneMin-max normalization window (set both or neither).
weightfloat1.0Optimization pressure; 0 makes the metric a pure constraint.
statisticslist[StatisticSpec]NoneWhich run-level statistics to expose. See Configure statistics.
displayDisplayNoneHow Studio renders the evaluator's values (0.11.0+). See Display.
aggregate_goalGoalSpecNoneDeprecated — prefer a statistic-level goal. Run-level goal evaluated against the average score.

A scorer can return:

  • int or float — numeric score (statistics: avg, min, max, std, count).
  • str or bool — categorical score (statistics: frequencies and mode, when statistics is omitted).
  • Score(value=..., rationale=..., metadata=...) — rich score with an explanation and extra data.

EvaluatorGroup

Several evaluators scored by one scorer call, for example an LLM judge grading several criteria at once. Pass it in evaluators next to plain evaluators (run, rescore, retry_failed_records, optimize). Each evaluator of the group is a regular evaluator in Studio: only the scoring call is shared. Requires SDK 0.11.0+. See Several criteria in one judge call.

from mistralai.evaluations import Evaluator, EvaluatorGroup, Goal

EvaluatorGroup(
    name="quality_judge",
    scorer=quality_judge,  # (ctx: ScorerContext) -> {"correctness": Score(...), "completeness": 3}
    evaluators=[
        Evaluator(name="correctness", goal=Goal.gte(4), min_value=0, max_value=5),
        Evaluator(name="completeness", min_value=0, max_value=5),
    ],
    num_scores=1,
)

Parameter

Type

Default

Description

namestrrequiredNames the group in logs and errors (not shown in Studio). Unique per run.
scorerGroupScoreFunctionrequired(ctx: ScorerContext) -> dict[str, value or Score], keyed by evaluator name.
evaluatorslist[Evaluator]requiredAt least one. Evaluators without a scorer and with the default num_scores. Every other parameter works as usual.
descriptionstrNoneDescription of the group.
num_scoresint1Scorer calls per generation. Each call scores every evaluator of the group.

The scorer's result: a missing key gives that evaluator an error score. A key that matches no evaluator is ignored, with a warning. An exception, or a result that isn't a dict, gives every evaluator of the group an error score.

RunEvaluator

A run evaluator operates on the full set of results after all records have been processed. Use it for aggregate metrics that can't be expressed per-record — like F1 score, global pass/fail gates, or cross-record analysis.

RunEvaluator(
    name="accuracy_gate",
    scorer=my_run_scorer,
)

Parameter

Type

Default

Description

namestrrequiredUnique name.
scorerRunEvaluatorFunctionrequired(ctx: RunEvaluatorContext) -> value or Score.
descriptionstrNoneDescription.
tagslist[str][]Tags.
goalGoalSpec | list[GoalSpec]NonePass/fail goals for the run-level score (for example, Goal.gte(0.85)). With a list, all must pass. metric= targets one of the score's metrics.
direction"maximize" | "minimize" | Direction | listNoneWhich way is better for the value. Inferred from the goal when unset. A list with Direction entries sets a direction per metric.
displayDisplay | list[Display]NoneHow Studio renders the value and the metrics (0.11.0+). See Display.
min_value / max_valuefloatNoneDisplay and normalization window. Set both or neither.

The scorer receives a RunEvaluatorContext with access to all records, their scores, aggregate statistics, and system config. See the run evaluators guide for examples.

Score

The rich return type of a scorer.

from mistralai.evaluations import Score

Score(value=0.8, rationale="Covers 4 of the 5 expected facts.", metadata={"facts": 5})
Score(value=0.63, metrics={"lower": 0.47, "upper": 0.82})  # run evaluator only

Field

Type

Description

valueJsonValue | NoneThe main result.
rationalestr | NoneOptional explanation, shown in Studio.
metadatadict[str, JsonValue]Context about the result (sample size, method), shown on hover.
metricsdict[str, float]RunEvaluator scores only (0.11.0+): named numbers shown next to value in the order returned, which a goal, a Display, and a Direction can target. Finite numbers (not booleans), at most 100, with names of 1 to 100 characters other than "value". A per-record Evaluator score with metrics is recorded as an error.

Goal

Factory for creating goal specifications. See Set goals for the full guide.

from mistralai.evaluations import Goal

Goal.gte(0.8)             # gate: score >= 0.8
Goal.lte(0.1)             # gate: score <= 0.1
Goal.between(0.2, 0.8)    # gate: 0.2 <= score <= 0.8

A Goal is only a gate. To declare which way is better, set direction="maximize" / "minimize" on the evaluator (it is also inferred from a gte/lte goal).

Each method takes an optional metric. On an Evaluator, it's the statistic to target ("avg", "min", "max", or "std"). On a RunEvaluator, it's the name of a score metric, and None targets the score's value.

Display

Sets how Studio renders an evaluator's numeric values. Pass it as Evaluator.display or RunEvaluator.display. Requires SDK 0.11.0+. See Display format.

from mistralai.evaluations import Display

Display(format="percent")                       # 0.6341 reads 63.4%
Display(format="integer", unit="chars")         # 41.6 reads 42 chars
Display(format="number", unit="s", decimals=2)  # 1.721 reads 1.72 s

Field

Type

Description

format"number" | "percent" | "integer" | NoneHow the value reads. None keeps the default rendering.
unitstr | NoneSuffix after the value (1 to 20 characters). Not allowed with "percent".
decimalsint | NoneDecimals for number and percent (0 to 10, percent defaults to 1). No effect without format.
metricstr | NoneRunEvaluator only: the score metric this format applies to. Without it, the format applies to the value and is the default of every metric.

RunEvaluator.display takes one Display or a list, with at most one Display without metric and one per metric name. Display only: stored values, statistics, and goals are unchanged.

Direction

Says which way a number of a RunEvaluator improves, so Studio colors the change between runs. Pass it in RunEvaluator.direction, alone or in a list next to "maximize" or "minimize" (the value's direction). Requires SDK 0.11.0+.

from mistralai.evaluations import Direction, RunEvaluator

RunEvaluator(
    name="action_coverage",
    scorer=action_coverage,
    direction=[Direction.maximize(), Direction.minimize(metric="missing_tool")],
)

Field

Type

Description

direction"maximize" | "minimize"Which way is better.
metricstr | NoneThe score metric it applies to. None for the value.

At most one direction per target. A metric's direction is never inferred from its goals: without one, its change reads without color.

System

A system captures the configuration that drives your task — model name, temperature, system prompt, and so on. Storing these as params (instead of hardcoding them) makes them visible in Studio so you can compare runs across different configs. See Configure system params for details.

from mistralai.evaluations import System

system = System(name="small-t0", params={"model": "mistral-small-latest", "temperature": 0})

When system is provided, it is available via ctx.system in tasks and scorers:

async def task(ctx: TaskContext) -> str:
    response = await client.chat.complete_async(
        model=str(ctx.system.params["model"]),
        temperature=float(ctx.system.params["temperature"]),
        messages=[{"role": "user", "content": ctx.input_record["prompt"]}],
    )
    return str(response.choices[0].message.content)

Parameter

Type

Default

Description

namestrrequiredSystem name (shown in Studio).
paramsdict[str, str | int | float | bool]requiredFlat key-value config passed to the task. Lists and dicts are rejected: serialize structured config, such as tool definitions, to a JSON string.

See Use context objects for the full context reference.

Manage projects, evaluations, and runs

Fetch and update projects, and delete runs, evaluations, and projects, from the SDK. Requires SDK 0.11.0+.

# Fetch a project by slug
project = await client.project.beta.get(project_slug="my-project")

# Update a project. Only the fields you pass change: description=None clears it.
await client.project.beta.update(project_slug="my-project", description="Document extraction evals")

# Delete a run, an evaluation, or a project
await client.evaluation.beta.delete_run(run_id=run.run_id)
await client.evaluation.beta.delete(evaluation_slug="my-eval")
await client.project.beta.delete(project_slug="my-project")
exclamationMark

Deletes are permanent and cascade: a project takes its evaluations with it, an evaluation its runs, and a run its records, scores, and statistics. Studio datasets are never deleted with them.

Manage Studio datasets with the mistralai client:

await client.beta.observability.datasets.update_async(dataset_id=dataset_id, name="Invoices v2")
await client.beta.observability.datasets.delete_async(dataset_id=dataset_id)