- Resources
Cookbooks
Evaluate and optimize a prompt with the Evaluation SDK
Evaluate and optimize a prompt with the Evaluation SDK
Measure a support assistant against a dataset with a code scorer and an LLM judge, compare configurations, and let the SDK search for a better system prompt.
Public Preview. Offline evaluations are part of Observability, available to Enterprise-tier organizations only. The API can change during the preview.
An offline evaluation runs your application on a fixed set of test cases and scores every answer. The Evaluation SDK (mistralai-evaluations) follows one model:
- a dataset: the test cases, as a list of dicts or a Studio dataset
- a task: the code under test, a function that turns one record into an output
- evaluators: functions that score each output, in code or with an LLM judge
- results: statistics and pass or fail verdicts, in your notebook and in Studio
This cookbook uses the same support assistant for Acme Cloud Storage as the online evaluation and evaluation datasets cookbooks. Live evals flagged long answers and off-topic replies, and you collected the questions into a dataset. You now measure the assistant, check whether a bigger model fixes it, and let the SDK optimize its system prompt.
Prerequisites
To complete this cookbook, you will need:
- Python 3.12 or later
- A Mistral account on the Enterprise tier and an API key
Environment setup
This section installs the SDKs and configures your API key.
Install
Install the Mistral Python SDK and the Evaluation SDK:
%pip install -qU "mistralai>=3.8.0" "mistralai-evaluations>=0.11.1"
Required environment variables
To complete this cookbook, you'll need a Mistral API key. In Studio, navigate to the API keys section and create a new API key.
Either set MISTRAL_API_KEY as an environment variable before starting the notebook, or leave it unset and enter the key when the next cell prompts you for it.
import getpass
import os
if not os.environ.get("MISTRAL_API_KEY"):
os.environ["MISTRAL_API_KEY"] = getpass.getpass("Mistral API key: ")
Initialize the client. The Evaluation SDK's Mistral client is the regular Mistral client plus the evaluation and project namespaces, so the same object calls the models and runs the evaluations. The SDK logs every record it processes at debug level: the cell keeps info messages and above.
import logging
import structlog
from mistralai.evaluations import Mistral
structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(logging.INFO))
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
1. Define the task
The task is the code you evaluate. Here, it's the support assistant: a system prompt, a small knowledge base, and one chat call per question.
The task reads the model and the system prompt from ctx.system.params, not from constants. Each run records these params, so Studio shows which settings produced which scores, and you can compare or optimize them without touching the task.
from mistralai.evaluations import TaskContext
KNOWLEDGE_BASE = """\
- Sharing: right-click a file or folder, choose Share, and enter the teammate's email address. Viewers can't edit.
- Trash: deleted files stay in the Trash for 30 days. Open Trash and choose Restore.
- Version history: open the file menu and choose Version history. Versions are kept for 30 days on Free, 180 days on Pro.
- File size: 50 GB per file on every plan.
- Storage: Free has 5 GB, Pro has 2 TB, Business has 5 TB per user.
- Quota exceeded: empty the Trash or delete files, or upgrade the plan.
- Offline access: in the desktop app, right-click a folder and choose Make available offline.
- Two-factor authentication: Settings > Security > Two-factor authentication.
- Refunds: annual plans are refundable within 14 days of purchase. Monthly plans aren't refundable.
- Support hours: chat support is open Monday to Friday, 9:00 to 18:00 CET.
"""
SEED_PROMPT = "You are a helpful assistant for Acme Cloud Storage."
async def task(ctx: TaskContext) -> str:
params = ctx.system.params
response = await client.chat.complete_async(
model=str(params["model"]),
messages=[
{"role": "system", "content": f"{params['system_prompt']}\n\nKnowledge base:\n{KNOWLEDGE_BASE}"},
{"role": "user", "content": ctx.input_record["question"]},
],
temperature=0,
)
return str(response.choices[0].message.content)
2. Write the evaluators
An evaluator pairs a name with a scorer, a function that receives a ScorerContext and returns a score. ctx.input_record is the dataset record and ctx.output is what the task returned. Return a Score to store a rationale next to the value: Studio shows it on every record.
The first scorer is plain code. Support answers should be short, so it returns 1 when the answer has at most 50 words:
from mistralai.evaluations import Score, ScorerContext
def concise(ctx: ScorerContext) -> Score:
words = len(str(ctx.output).split())
return Score(value=1 if words <= 50 else 0, rationale=f"{words} words")
Correctness is hard to check in code, so the second scorer is an LLM judge. It compares the answer to the record's expected_answer and returns a structured verdict through chat.parse_async, so the judge's output always parses. The judge uses a larger model than the assistant and temperature=0, to keep its verdicts stable.
from pydantic import BaseModel
JUDGE_PROMPT = """You grade a customer-support answer against a reference.
The answer is correct if it states the same facts as the reference and adds no claim that contradicts it
or that the reference doesn't support. Ignore style and length.
Question: {question}
Reference: {reference}
Answer: {answer}"""
class Judgment(BaseModel):
correct: bool
reason: str
async def correct(ctx: ScorerContext) -> Score:
completion = await client.chat.parse_async(
model="mistral-medium-latest",
messages=[
{
"role": "user",
"content": JUDGE_PROMPT.format(
question=ctx.input_record["question"],
reference=ctx.input_record["expected_answer"],
answer=ctx.output,
),
}
],
response_format=Judgment,
temperature=0,
)
judgment = completion.choices[0].message.parsed
return Score(value=1 if judgment.correct else 0, rationale=judgment.reason)
3. Set goals and statistics
A goal turns a score into a pass or fail verdict. A statistic is a run-level value computed from the scores, such as an average. Since both scorers return 0 or 1, their average is the share of answers that pass: the goals below require 90% of answers to be correct and 90% to be concise.
from mistralai.evaluations import Evaluator, Goal, Statistic
EVALUATORS = [
Evaluator(
name="correct",
description="LLM judge: 1 if the answer matches the reference answer, 0 otherwise.",
scorer=correct,
statistics=[Statistic.avg(goal=Goal.gte(0.9))],
),
Evaluator(
name="concise",
description="1 if the answer has at most 50 words, 0 otherwise.",
scorer=concise,
statistics=[Statistic.avg(goal=Goal.gte(0.9))],
),
]
A goal set on the evaluator itself, goal=Goal.gte(...), applies to every single score instead. See Set goals and Configure statistics for the other statistics, such as sums, percentiles, and classification metrics.
4. Iterate locally
Start with the test cases as a plain list. Each record holds a question and the answer a support agent would give. Two questions are off-topic, and one asks something the knowledge base doesn't cover: the assistant should decline them rather than invent an answer.
TEST_CASES = [
{"question": "How do I share a folder with a teammate?", "expected_answer": "Right-click the folder, choose Share, and enter the teammate's email address."},
{"question": "I deleted a file yesterday. Can I get it back?", "expected_answer": "Yes: deleted files stay in the Trash for 30 days; open Trash and choose Restore."},
{"question": "What's the maximum file size I can upload?", "expected_answer": "50 GB per file, on every plan."},
{"question": "My sync client says 'quota exceeded'. What should I do?", "expected_answer": "Empty the Trash or delete files, or upgrade the plan."},
{"question": "How far back can I restore an older version of a document on the Pro plan?", "expected_answer": "180 days on Pro."},
{"question": "How much storage do I get on the Free plan?", "expected_answer": "5 GB."},
{"question": "How much storage does a Business user get?", "expected_answer": "5 TB per user."},
{"question": "Can I get a refund on my monthly subscription?", "expected_answer": "No, monthly plans aren't refundable (only annual plans, within 14 days)."},
{"question": "I bought the annual plan 5 days ago. Can I get my money back?", "expected_answer": "Yes, annual plans are refundable within 14 days of purchase."},
{"question": "How do I turn on two-factor authentication?", "expected_answer": "Go to Settings > Security > Two-factor authentication."},
{"question": "Can I work on my files on a plane without internet?", "expected_answer": "Yes: in the desktop app, right-click a folder and choose Make available offline."},
{"question": "Is chat support available on Saturday?", "expected_answer": "No, chat support is open Monday to Friday, 9:00 to 18:00 CET."},
{"question": "Can a viewer edit the files I share with them?", "expected_answer": "No, viewers can't edit."},
{"question": "Can you recommend a good pizza place in Lyon?", "expected_answer": "Declines: it only answers questions about Acme Cloud Storage."},
{"question": "Write me a poem about the ocean.", "expected_answer": "Declines: it only answers questions about Acme Cloud Storage."},
{"question": "Does Acme Cloud Storage integrate with Salesforce?", "expected_answer": "Says it doesn't have that information and points to support, without inventing an answer."},
]
Run the evaluation with local=True: the SDK runs the task and the scorers on every record and prints the results, without saving anything in Studio. Use this mode while you adjust the task and the scorers.
System holds the params the task reads: the model and the seed system prompt.
from mistralai.evaluations import System
baseline_system = System(
name="small-seed-prompt",
params={"model": "mistral-small-latest", "system_prompt": SEED_PROMPT},
)
local_run = await client.evaluation.run(
dataset=TEST_CASES,
task=task,
evaluators=EVALUATORS,
system=baseline_system,
local=True,
)
local_run.show(level="run")
Both goals fail. List the records that scored 0 to see why, with the scorer's rationale:
def show_failures(run) -> None:
for record in run.output_records:
generation = record.generations[0]
for name, scores in generation.scores.items():
if scores and scores[0].value == 0:
answer = str(generation.output).replace("\n", " ")[:120]
print(f"[{name}] {record.input_record['question']}\n {answer}...\n -> {scores[0].rationale}\n")
show_failures(local_run)
The assistant writes long answers, and it doesn't always stay within the knowledge base: the system prompt never asks it to.
5. Store the test cases in a Studio dataset
To track results over time, keep the test cases in a Studio dataset rather than in the notebook. Create the dataset, then add the records with add_dataset_records, which sends them in batches. If you followed the evaluation datasets cookbook, you already have a dataset built from production traffic: use its slug instead.
from mistralai.evaluations import Dataset
dataset = client.beta.observability.datasets.create(
name="Acme support golden set (cookbook)",
description="Support questions with reference answers, for the offline evaluation cookbook.",
)
DATASET = Dataset(slug=dataset.slug)
record_ids = await client.evaluation.add_dataset_records(DATASET, TEST_CASES)
print(f"Added {len(record_ids)} records to {dataset.slug}")
6. Compare two models in Studio
Runs are saved in Studio under a project and an evaluation. The project groups the evaluations of one application; an evaluation collects the runs you want to compare. Both are created on first use. This cell creates the project and keeps its slug for the clean-up step:
from mistralai.evaluations import Evaluation, Project
project = await client.project.beta.get_or_create(name="Acme support assistant (cookbook)")
PROJECT = Project(slug=project.slug)
GOLDEN_SET = Evaluation(name="Golden set")
A bigger model might write better answers. Run the same evaluation twice on the Studio dataset, changing only the model in System. Tags label the runs so you can filter them in Studio.
baseline = await client.evaluation.run(
project=PROJECT,
evaluation=GOLDEN_SET,
dataset=DATASET,
task=task,
evaluators=EVALUATORS,
system=baseline_system,
tags=["model:small", "prompt:seed"],
)
baseline.show(level="run")
medium = await client.evaluation.run(
project=PROJECT,
evaluation=GOLDEN_SET,
dataset=DATASET,
task=task,
evaluators=EVALUATORS,
system=System(
name="medium-seed-prompt",
params={"model": "mistral-medium-latest", "system_prompt": SEED_PROMPT},
),
tags=["model:medium", "prompt:seed"],
)
medium.show(level="run")
The larger model doesn't pass the goals either, and its answers aren't shorter: the problem is the prompt, not the model.
Open the Golden set evaluation in Studio, under Evaluate → Evaluations → Offline, to see both runs with their system params. Select them and choose Compare runs to see the scores side by side, record by record.
7. Optimize the system prompt
Instead of rewriting the prompt by hand, let the SDK search for a better one. evaluation.optimize() takes the same dataset, task, and evaluators as evaluation.run(), plus:
- a TunableSystem: the system params, where Tunable(...) marks the values the optimizer may change. The model stays fixed, and the system prompt starts from the seed.
- an optimizer. SimpleOptimizer reflects on the worst records of the current best prompt, proposes a rewrite, and keeps it only if it scores better on the whole dataset.
- steer (optional): the problem you want fixed, in plain words. It guides the rewrites, but the scores still come from your evaluators.
The goals you set act as gates: a candidate wins only if it passes every goal. Each candidate is a regular run in Studio.
from mistralai.evaluations import SimpleOptimizer, Tunable, TunableSystem
result = await client.evaluation.optimize(
project=PROJECT,
evaluation=Evaluation(name="Prompt optimization"),
dataset=DATASET,
task=task,
evaluators=EVALUATORS,
system=TunableSystem(
name="optimized-prompt",
params={"model": "mistral-small-latest", "system_prompt": Tunable(SEED_PROMPT)},
),
algo=SimpleOptimizer(iterations=3, reflection_model="mistral-medium-latest"),
steer="Answers are too long, and some go beyond the knowledge base.",
)
result.show()
result.show() prints the baseline, the winner, and every candidate tried, with the hypothesis behind each rewrite. The search takes a few minutes. A run of this cell printed a result like this one; the prompts and scores vary from run to run:
=== Optimization result (SimpleOptimizer) ===
0.69 → 1.00 (+0.31, +45%, success)
Trajectory (3 candidates) (✓/✗ = passes goal thresholds)
✗ gen0 score=0.688 correct=0.69 concise=0.69 (seed)
✓ gen1 score=0.969 correct=0.94 concise=1.00 ←gen0
✓ gen2 score=1.000 correct=1.00 concise=1.00 ←gen1
Read the result in code. verdict is success when a candidate beats the baseline and passes every goal: it's then in winner. When the best candidate beats the baseline but still fails a goal, the verdict is best_attempt and the candidate is in best_attempt.
best = result.winner or result.best_attempt
print(result.verdict, result.stop_reason)
if best is not None:
print(f"{result.baseline.score:.2f} -> {best.score:.2f}\n")
print(best.system["system_prompt"])
Read the winning prompt before you ship it. The optimizer learns from your scorers' rationales and can copy their wording, such as "the reference", which means nothing to the assistant. Edit the prompt if needed, then confirm it with a run.
SimpleOptimizer is a good first choice on a small dataset: it's fast, and its trajectory reads one step at a time. Because it validates on the same records it learns from, it can overfit. On a larger dataset, use GEPA instead: it keeps a separate validation set and an optional holdout, so the reported gain holds on records the optimizer never saw. See Optimize prompts and parameters.
8. Rerun the winner
Run the winning prompt as a normal run in the Golden set evaluation, next to the two earlier runs. This is the run you'd compare against the next change.
if best is None:
raise RuntimeError("No candidate beat the baseline: rerun the optimization with more iterations.")
optimized = await client.evaluation.run(
project=PROJECT,
evaluation=GOLDEN_SET,
dataset=DATASET,
task=task,
evaluators=EVALUATORS,
system=System(name="small-optimized-prompt", params=best.system),
tags=["model:small", "prompt:optimized"],
)
optimized.show(level="run")
Compare the three runs in Studio: the optimized prompt on the small model passes the goals that the seed prompt failed on both models. To ship it, copy the prompt into your application.
9. Rescore a past run
Scoring is separate from running the task. evaluation.rescore() runs new or changed evaluators on the outputs already saved in a run, without calling the task again. This is useful when the task is slow or costly, or when you iterate on a judge.
Support guidelines also ask the assistant not to apologize. Add a no_apology evaluator to the baseline run:
def no_apology(ctx: ScorerContext) -> int:
text = str(ctx.output).lower()
return 0 if "sorry" in text or "apolog" in text else 1
rescored = await client.evaluation.rescore(
run_id=baseline.run_id,
evaluators=[Evaluator(name="no_apology", scorer=no_apology)],
)
print(f"Scored {rescored.scored_generation_count} generations: {baseline.run_url}")
The baseline run now has a no_apology column in Studio. Rescoring has patch semantics: it adds or replaces only the evaluators you pass, and leaves the other scores unchanged. See Rescore persisted runs.
10. Run evaluations as workflows
This notebook runs evaluations in-process. For long or large evaluations, such as agent rollouts over hundreds of records, run them in Mistral Workflows with the Workflow evaluation plugin. The task, scorers, and optimizers are the same: the plugin runs each record as a durable activity, with retries and parallelism, and the results land in the same Studio views.
Clean up
Delete the project, which also deletes its evaluations and runs, then the dataset. Datasets aren't deleted with a project.
await client.project.beta.delete(project_slug=project.slug)
client.beta.observability.datasets.delete(dataset_id=dataset.id)
Summary
This cookbook measured a support assistant with an offline evaluation, showed that a bigger model didn't fix its failures, and used the Evaluation SDK to find a system prompt that passes its goals.
What you built
- A task that reads its model and system prompt from System params
- A code scorer and an LLM judge with structured output, each with a goal on its average
- A Studio dataset filled from code, and runs compared across two models in Studio
- A prompt optimization with SimpleOptimizer, and a rerun of the winning prompt
- A new evaluator added to a past run with rescore, without rerunning the task
Mistral features used
- Evaluation SDK (mistralai-evaluations): evaluation.run, evaluation.optimize, evaluation.rescore
- Observability datasets API
- Chat Completions API, with structured outputs for the judge
View your evaluations in Studio, and read the offline evaluations documentation.