- Studio
- Observability
- Offline evaluations
Evaluators
Evaluators
An evaluator scores each record of a run. It pairs a name with a scorer — a function that receives a ScorerContext and returns a score — plus an optional description and goal.
from mistralai.evaluations import Evaluator, Goal
Evaluator(
name="accuracy",
description="1 if the expected answer appears in the output.",
scorer=accuracy_scorer,
goal=Goal.gte(0.8),
)
A scorer can be one of two kinds:
- Rule-based — a plain function that computes a score from the output. Deterministic, fast, and free.
- LLM-as-judge — a function that calls a model to grade the output. Use it for criteria that are hard to express in code, such as helpfulness, factual accuracy, or tone.
Both are just functions, so a single run can hold any mix of them. See Multiple evaluators to run several at once.
Rule-based scorers
A rule-based scorer returns a number (or a str/bool for categorical scores) computed directly from the record and output:
from mistralai.evaluations import ScorerContext
def contains_expected(ctx: ScorerContext) -> int:
return 1 if ctx.input_record["expected"].lower() in str(ctx.output).lower() else 0
Numeric scores produce numeric statistics (avg, min, max, std, count); str/bool scores produce frequency distributions and a mode when statistics is omitted. See Configure statistics.
LLM-as-judge scorers
To use a model as a judge, call the Mistral API inside your scorer and return a numeric score:
import os
from mistralai.evaluations import Mistral, ScorerContext
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
JUDGE_PROMPT = """You are a strict grader. Given a user prompt and a model answer,
respond with a single integer between 0 and 5 (higher is better) measuring how helpful and on-topic
the answer is. Respond with only the integer, no other text.
User prompt: {prompt}
Model answer: {answer}
"""
def llm_judge(ctx: ScorerContext) -> int:
response = client.chat.complete(
model="mistral-large-latest",
messages=[
{
"role": "user",
"content": JUDGE_PROMPT.format(
prompt=ctx.input_record["prompt"], answer=ctx.output
),
}
],
temperature=0,
)
raw = str(response.choices[0].message.content).strip()
try:
return int(raw[0])
except (ValueError, IndexError):
return 0
Use it in an evaluator like any other scorer:
from mistralai.evaluations import Evaluator, Goal
Evaluator(
name="helpfulness",
description="LLM judge: helpfulness score from 0 to 5.",
scorer=llm_judge,
goal=Goal.gte(3.5),
min_value=0, # the judge scores on a 0-5 scale: declare it so the goal
max_value=5, # sits inside the normalization window
)
Structured output with Score
For richer feedback, return a Score object with a value and a rationale. The rationale is stored alongside the score in Studio:
from pydantic import BaseModel
from mistralai.evaluations import ScorerContext, Score
class RecallJudgment(BaseModel):
score: float
comment: str
async def recall_scorer(ctx: ScorerContext) -> Score:
completion = await client.chat.parse_async(
model="mistral-large-latest",
messages=[
{
"role": "user",
"content": (
f"Evaluate recall between 0.0 and 1.0.\n\n"
f"Expected: {ctx.input_record['expected']}\n"
f"Got: {ctx.output}\n\n"
f"Provide a score and a short comment."
),
}
],
response_format=RecallJudgment,
)
judgment = completion.choices[0].message.parsed
return Score(value=judgment.score, rationale=judgment.comment)
Reduce judge variance
LLM judges can be noisy. Set num_scores on the evaluator to score each generation multiple times and average the results:
Evaluator(
name="recall",
description="LLM judge: recall score (0.0 to 1.0).",
scorer=recall_scorer,
num_scores=3, # scored 3 times per generation, results are averaged
)
Several criteria in one judge call
A judge often grades several criteria in one answer. With an EvaluatorGroup, one scorer call scores several evaluators: the judge runs once per generation, and each criterion is still a regular evaluator in Studio, with its own column, statistics, goal, and compare row.
The group's scorer returns a dict keyed by evaluator name. The evaluators of the group have no scorer of their own:
import os
from pydantic import BaseModel
from mistralai.evaluations import Evaluator, EvaluatorGroup, Goal, Mistral, Score, ScorerContext
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
class Judgment(BaseModel):
correctness: int # 0-5
completeness: int # 0-5
hallucination: bool
comment: str
async def quality_judge(ctx: ScorerContext) -> dict[str, Score | bool]:
completion = await client.chat.parse_async(
model="mistral-medium-latest",
messages=[
{
"role": "user",
"content": (
"Grade the answer. correctness and completeness are integers from 0 to 5.\n"
f"Question: {ctx.input_record['question']}\n"
f"Expected: {ctx.input_record['expected']}\n"
f"Answer: {ctx.output}"
),
}
],
response_format=Judgment,
temperature=0,
)
j = completion.choices[0].message.parsed
return {
"correctness": Score(value=j.correctness, rationale=j.comment),
"completeness": Score(value=j.completeness, rationale=j.comment),
"hallucination": j.hallucination, # a plain value works, as for a single scorer
}
evaluators = [
EvaluatorGroup(
name="quality_judge",
scorer=quality_judge,
evaluators=[
Evaluator(name="correctness", goal=Goal.gte(4), min_value=0, max_value=5),
Evaluator(name="completeness", min_value=0, max_value=5),
Evaluator(name="hallucination", description="True if the answer invents facts."),
],
),
Evaluator(name="exact_match", scorer=exact_match),
]
- Errors: if the scorer raises or doesn't return a dict, every evaluator of the group gets an error score. A missing key gives an error score to that evaluator. A key that matches no evaluator of the group is ignored, with a warning.
- num_scores is set on the group: num_scores=3 calls the judge three times per generation, and each call scores every evaluator of the group.
- Rescoring: pass the whole group to rescore(evaluators=[...]). An evaluator of a group has no scorer, so it can't be rescored alone.
- Independence: grading several criteria in one prompt can make them less independent than one call per criterion. A group cuts the cost. Keep a dedicated judge for the criterion that matters most.
EvaluatorGroup requires SDK 0.11.0+. Outside a group, Evaluator.scorer is still required: run(), rescore(), retry_failed_records(), and optimize() raise a ValueError for an evaluator without a scorer.
Write good judge instructions
Craft your judge prompts with care:
- Be specific. Avoid vague criteria: describe exactly what a good response looks like for your use case.
- Don't assume the judge knows your context. Spell out what "good" means explicitly.
- Use boundary examples: "A score of 3 means the response partially answers the question but omits a key detail."
- Keep temperature low (for example, temperature=0) for more deterministic judgments.
- Test on a small sample before using a judge in a large evaluation run. Spot inconsistencies early.
FAQ
Use rule-based scoring whenever possible: it's deterministic, fast, and cheap. Use an LLM judge when the quality criterion can't be captured with code, such as tone, coherence, or nuanced factual accuracy.
The prompt is probably too vague. Add explicit criteria and concrete boundary examples. Try a stronger model. Run the same input multiple times and set num_scores to average out noise.
Use structured output (response_format) with a Pydantic model to force valid output. Add a try/except around the parsing logic to return a fallback score rather than crashing.
No. Declare the criteria in an EvaluatorGroup: the judge runs once per generation, and each criterion is still its own evaluator in Studio.
Yes. An evaluator is a function paired with a name. Reuse it across any number of runs. If you change a judge prompt between runs, scores won't be directly comparable.