- Resources
Cookbooks
Build an evaluation dataset and run a first evaluation
Build an evaluation dataset and run a first evaluation
Build a Studio dataset from hand-written records, a JSONL file, and production spans, then curate it and use it to drive an offline evaluation.
Public Preview. Datasets are part of Observability, available to Enterprise-tier organizations only. The API can change during the preview.
A dataset is a named collection of records stored in Studio. Each record has:
- a payload: a JSON object holding the test case. You choose its keys, for example question and expected_answer. When you run an offline evaluation on the dataset, each payload becomes one input record of the run.
- properties (optional): metadata about the record, such as its origin or a review status. Properties aren't passed to the evaluation.
- a source, set by Studio, recording how the record was created: DIRECT_INPUT, UPLOADED_FILE, TELEMETRY_SPAN, PLAYGROUND, or EXPLORER.
In this cookbook, you build a dataset of customer-support questions, fill it from three sources, curate it, and run an offline evaluation on it.
Prerequisites
To complete this cookbook, you will need:
- Python 3.12 or later
- A Mistral account on the Enterprise tier and an API key
- The Workspace Admin or Observability Viewer role, to import records from production spans
Environment setup
This section installs the SDKs and configures your API key.
Install
Install the Mistral Python SDK, the Mistral OpenTelemetry SDK, and the Evaluation SDK:
%pip install -qU "mistralai>=3.7.0" "mistralai-otel-observability[mistral]" "mistralai-evaluations>=0.9.0"
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:
from mistralai.client import Mistral
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
datasets = client.beta.observability.datasets
1. Create a dataset
Give the dataset a name that says what it tests and which version it is. Studio derives a unique slug from the name, which you can use later to select the dataset in an evaluation.
dataset = datasets.create(
name="Support questions golden set",
description="Customer-support questions with reference answers, for the support assistant.",
)
print(f"Created {dataset.slug}: https://console.mistral.ai/observability/datasets/{dataset.id}")
2. Add records one by one
create_record is the simplest way to add a few hand-written test cases. Every record in this dataset uses the same payload keys, question and expected_answer, so a single evaluation task can read any of them. Use properties for metadata that the evaluation doesn't need.
record = datasets.create_record(
dataset_id=dataset.id,
payload={
"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.",
},
properties={"topic": "sharing", "author": "support-team"},
)
print(record.id, record.source)
3. Import records from a JSONL file
For more than a handful of records, upload a JSONL file and import it in one task. With the dataset_records file purpose, each line wraps one record as {"payload": {...}, "properties": {...}}. payload is required, properties is optional, and no other key is accepted.
This cell writes a small file. In practice, you'd export it from your own test cases or labeling tool.
import json
records = [
{
"payload": {
"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.",
},
"properties": {"topic": "recovery"},
},
{
"payload": {
"question": "What's the maximum file size I can upload?",
"expected_answer": "50 GB per file on every plan.",
},
"properties": {"topic": "limits"},
},
{
"payload": {
"question": "My sync client says 'quota exceeded'. What should I do?",
"expected_answer": "Free up space by emptying the Trash or deleting files, or upgrade your plan.",
},
"properties": {"topic": "limits"},
},
]
with open("support-questions.jsonl", "w") as f:
for line in records:
f.write(json.dumps(line) + "\n")
Upload the file with the dataset_records purpose, then start the import. Imports run in the background and return a task.
with open("support-questions.jsonl", "rb") as f:
uploaded = client.files.upload(
file={"file_name": "support-questions.jsonl", "content": f},
purpose="dataset_records",
)
import_task = datasets.import_from_file(dataset_id=dataset.id, file_id=uploaded.id)
print(f"Import task {import_task.id}: {import_task.status}")
Poll the task until it leaves the RUNNING status. When the import fails, for example on an invalid line, the task's message lists the failing lines and why they failed.
import time
def wait_for_task(task_id: str, timeout_s: int = 300):
deadline = time.monotonic() + timeout_s
while True:
task = datasets.fetch_task(dataset_id=dataset.id, task_id=task_id)
if task.status != "RUNNING" or time.monotonic() > deadline:
return task
time.sleep(3)
task = wait_for_task(import_task.id)
print(task.status, task.message or "")
if task.result:
print(f"Imported {task.result.imported_record_count}/{task.result.requested_record_count} record(s)")
4. Import records from production spans
Production traffic is the best source of realistic test cases. If your application sends traces to Mistral Observability, you can turn any span into a dataset record. This step first sends one traced chat call, then imports its span.
The span records the user question as a custom attribute, app.question. Creating the operation with include_content=True also records the full conversation as gen_ai.input.messages and gen_ai.output.messages.
from mistralai.observability.otel import observability
from mistralai.observability.otel import semconv_constants as genai
observability.configure_mistral(service_name="datasets-cookbook") # reads MISTRAL_API_KEY
question = "Can I recover a previous version of a document?"
messages = [{"role": "user", "content": question}]
with observability.operation(
genai.OPERATION_NAME_CHAT,
model="mistral-small-latest",
provider=genai.PROVIDER_NAME_MISTRAL_AI,
include_content=True,
attributes={"app.question": question},
) as chat:
response = client.chat.complete(model="mistral-small-latest", messages=messages)
chat.mistral_completion(response, messages=messages)
observability.flush()
span_reference = {"trace_id": chat.trace_id, "span_id": chat.span_id}
print(span_reference)
In a real project, you'd find the spans to import with the trace explorer or with client.beta.observability.spans.search_spans, for example spans that a live eval scored low. See the online evaluation cookbook.
import_from_spans takes span references and a mapping contract. Each mapping copies one span attribute (span_attributes) or resource attribute (resource_attributes) into a top-level payload key. Attribute keys are literal: the dots in gen_ai.input.messages don't denote a nested path. JSON strings, such as message lists, are parsed into structured values.
This mapping fills question the same way as the other records and keeps the production conversation for reference. The production span has no reference answer: add it during review, in the next step.
mapping_contract = {
"version": 1,
"mappings": [
{"target_field": "question", "source_field": {"namespace": "span_attributes", "key": "app.question"}},
{
"target_field": "production_conversation",
"source_field": {"namespace": "span_attributes", "key": "gen_ai.output.messages"},
},
],
}
Spans become available to the import a few seconds after ingestion. A span that isn't found yet, or that has none of the mapped attributes, is skipped rather than failing the import. Since the span was sent a moment ago, the cell retries the import until the span is found:
for attempt in range(12):
span_import = datasets.import_from_spans(
dataset_id=dataset.id,
span_references=[span_reference],
mapping_contract=mapping_contract,
)
task = wait_for_task(span_import.id)
if task.result and task.result.imported_record_count:
break
time.sleep(10)
print(task.status, task.result)
Records imported from spans get the TELEMETRY_SPAN source, and their properties hold the trace_id and span_id they came from.
To pick spans by hand instead, select them in the Studio trace explorer and choose Add to dataset. See Add spans to a dataset.
5. List and curate records
list_records is paginated with page and page_size. This helper reads every page:
def list_all_records(dataset_id: str) -> list:
all_records, page = [], 1
while True:
response = datasets.list_records(dataset_id=dataset_id, page=page, page_size=50)
all_records.extend(response.records.results or [])
if not response.records.next:
return all_records
page += 1
all_records = list_all_records(dataset.id)
for r in all_records:
print(f"{r.source:<14} {r.payload['question']}")
Review the records before you use them. Fix a record's payload with records.update_payload, which replaces the whole payload. Here, the reviewer adds the missing reference answer to the record imported from production, and marks it as reviewed with records.update_properties:
from_span = next(r for r in all_records if r.source == "TELEMETRY_SPAN")
datasets.records.update_payload(
dataset_record_id=from_span.id,
payload={
**from_span.payload,
"expected_answer": "Yes. Open the document's menu, choose Version history, and restore any version from the last 30 days.",
},
)
datasets.records.update_properties(
dataset_record_id=from_span.id,
properties={**from_span.properties, "reviewed": True},
)
Delete records that don't belong in the dataset with records.delete, or several at once with records.bulk_delete. This cell removes the hand-written record from step 2:
datasets.records.delete(dataset_record_id=record.id)
print(f"{len(list_all_records(dataset.id))} record(s) left")
Datasets aren't snapshots. Each evaluation run reads the records that exist when it starts. To compare runs over time, freeze the dataset, or create a new one, for example Support questions golden set v2, before you change it.
6. Export the dataset
export_to_jsonl writes every record to a JSONL file and returns a temporary download URL. Each line uses the same {"payload": ..., "properties": ...} format as the import, so you can version the file in Git or import it into another dataset.
export = datasets.export_to_jsonl(dataset_id=dataset.id)
print(export.file_url)
7. Run an offline evaluation on the dataset
The Evaluation SDK can read a Studio dataset directly: pass Dataset(slug=...) or Dataset(id=...) to evaluation.run(). Each record's payload becomes ctx.input_record.
The task calls the assistant, and an LLM judge compares its answer to expected_answer:
from mistralai.evaluations import Dataset, Evaluation, Evaluator, Mistral as EvaluationClient, Project, ScorerContext, TaskContext
eval_client = EvaluationClient(api_key=os.environ["MISTRAL_API_KEY"])
SYSTEM_PROMPT = "You are the support assistant for Acme Cloud Storage. Answer in at most three sentences."
async def task(ctx: TaskContext) -> str:
response = await eval_client.chat.complete_async(
model="mistral-small-latest",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": ctx.input_record["question"]},
],
)
return str(response.choices[0].message.content)
async def matches_reference(ctx: ScorerContext) -> int:
response = await eval_client.chat.complete_async(
model="mistral-small-latest",
messages=[
{
"role": "user",
"content": (
"Does the answer convey the same facts as the reference? Reply with only 1 or 0.\n\n"
f"Reference: {ctx.input_record['expected_answer']}\n\nAnswer: {ctx.output}"
),
}
],
temperature=0,
)
return 1 if str(response.choices[0].message.content).strip().startswith("1") else 0
run = await eval_client.evaluation.run(
project=Project(name="Support assistant"),
evaluation=Evaluation(name="Golden set"),
dataset=Dataset(slug=dataset.slug),
task=task,
evaluators=[Evaluator(name="matches_reference", scorer=matches_reference)],
)
run.show()
The run and its per-record results are in Studio under Evaluate → Evaluations, linked to the dataset they ran on. To build richer judges, compare runs, and optimize the prompt, see the offline evaluation and optimization cookbook.
Clean up
Delete the dataset and the local file. Deleting a dataset also deletes its records.
datasets.delete(dataset_id=dataset.id)
os.remove("support-questions.jsonl")
observability.shutdown()
Summary
This cookbook built a Studio dataset from three sources, curated it, and used it to drive an offline evaluation.
What you built
- A dataset of support questions with reference answers
- Records added one by one, imported from a JSONL file, and imported from a production span with a mapping contract
- A review pass that fixed a payload, tagged a record, and removed another
- A JSONL export and an offline evaluation run on the dataset
Mistral features used
- Observability datasets API
- Files API
- Mistral OpenTelemetry SDK (mistralai-otel-observability)
- Evaluation SDK (mistralai-evaluations)
- Chat Completions API
View your datasets in Studio, and read the datasets documentation.