[9' read]
Score production traffic with online evaluations
Attach LLM judges to your application's traces so every matching span gets scored automatically, then read the scores back to find and fix weak answers.
Public Preview. Online evaluations are part of Observability, available to Enterprise-tier organizations only. The API can change during the preview.
Online evaluation runs LLM judges on production traffic, with no code change on the request path. You configure two objects:
- A scorer is a reusable judge: a model, a prompt template, and an output type.
- A live eval selects which spans to score and attaches one or more scorers to them, each with its own sampling rate.
Your application sends OpenTelemetry spans to Mistral. Shortly after ingestion, each selected span is scored, and the score is written back as telemetry attached to the span. You can then search scores, aggregate them, and open the scored span from its trace.
In this cookbook, you build a small support assistant, attach a helpfulness judge and an apology detector to its traffic, and read back the results.
Prerequisites#
To complete this cookbook, you will need:
- Python 3.10 or later
- A Mistral account on the Enterprise tier and a user API key (service account keys can't create live evals)
- The Workspace Admin or Observability Viewer role in the workspace, to create live evals and read their results
Environment setup#
This section installs the SDKs and configures your API key.
Install#
Install the Mistral Python SDK and the Mistral OpenTelemetry SDK, which records your application's calls as spans:
%pip install -qU "mistralai>=3.8.0" "mistralai-otel-observability[mistral]"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. SERVICE_NAME tags every span this notebook sends, so the live eval only scores this notebook's traffic.
from datetime import datetime, timezone
from mistralai.client import Mistral
SERVICE_NAME = "online-eval-cookbook"
ASSISTANT_MODEL = "mistral-small-latest"
JUDGE_MODEL = "mistral-small-latest"
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
started_at = datetime.now(timezone.utc)1. Create the scorers#
A scorer defines how to judge, not what to judge. Its prompt is a Jinja2 template: every variable you don't define, such as {{ question }}, becomes a scorer variable that the live eval fills from the span being scored. Some names are always available without a mapping, including {{ transcript }}, the formatted input and output messages of the span.
Each scorer has one of three output types:
output_spec | Result field | Use it for |
|---|---|---|
{"type": "numeric", "min": 1, "max": 5} | score_value | Ratings you want to average or chart |
{"type": "categorical", "labels": ["good", "bad"]} | score_label | A fixed set of classes |
{"type": "boolean"} | score_label ("true" or "false") | Yes-or-no checks |
Creating a scorer isn't idempotent: posting the same definition twice creates two scorers. This helper looks the scorer up by name first and updates it if it exists. A changed config creates a new scorer version; an unchanged one doesn't.
scorers = client.beta.observability.evaluations.scorers
def upsert_scorer(name: str, description: str, config: dict):
"""Create the scorer, or update its config if a scorer with this name exists."""
existing = [s for s in scorers.list(q=name).scorers.results or [] if s.name == name]
if existing:
return scorers.update(scorer_slug=existing[0].slug, description=description, config=config)
return scorers.create(name=name, description=description, kind="llm_judge", config=config)The first scorer rates helpfulness from 1 to 5. A numeric output is the easiest to chart: you can average it directly. The prompt defines every score band, because the output schema forces the shape of the answer, not its meaning.
helpfulness = upsert_scorer(
name="Support helpfulness",
description="Rates from 1 to 5 how well the assistant resolved the customer's question.",
config={
"model": JUDGE_MODEL,
"prompt_template": """You grade answers from a customer-support assistant for {{ product }}.
Judge only whether the final assistant message resolves the customer's last question. Ignore tone and formatting.
- 5: fully resolves the question, with accurate and actionable steps.
- 4: resolves it, with minor gaps.
- 3: partially helpful; the customer still needs to ask again.
- 2: mostly unhelpful or vague.
- 1: wrong, off-topic, or a refusal.
Conversation:
{{ transcript }}""",
"output_spec": {"type": "numeric", "min": 1, "max": 5},
"params": {"temperature": 0},
},
)
print(helpfulness.slug, "variables:", helpfulness.latest_version.variables)The response lists the template variables the live eval has to fill. Here, product is a variable. transcript isn't one, because it's always available.
The second scorer is a boolean check that flags answers in which the assistant apologizes:
apology = upsert_scorer(
name="Apology detector",
description="Flags assistant answers that contain an apology.",
config={
"model": JUDGE_MODEL,
"prompt_template": """Does the final assistant message contain an explicit apology, such as "I'm sorry" or "I apologize"?
Answer true if it does, false otherwise.
Conversation:
{{ transcript }}""",
"output_spec": {"type": "boolean"},
"params": {"temperature": 0},
},
)
print(apology.slug)In Studio, scorers are listed under Evaluate → Judges. The same scorers can also run in offline evaluations on dataset records.
2. Create a live eval#
A live eval, called a pipeline in the API, selects spans with a filter and attaches scorers to them. The filter uses the same expression language as the trace explorer, with raw OpenTelemetry attribute names as keys. This live eval scores chat spans sent by this notebook's service.
Each entry in definitions attaches one scorer by slug, with:
mapping: fills each scorer variable from the span. A value is a span attribute name, or one oftranscript,input_messages, andoutput_messages.sampling: the share of selected spans to score. Leave it out to score every span. This cookbook scores every span for helpfulness and half of them for apologies.
Live eval names are unique in a workspace, so the cell reuses the live eval if it already exists.
LIVE_EVAL_NAME = "Support assistant quality (cookbook)"
selectors = [
{
"source_kind": "span",
"filter": f'gen_ai.operation.name = "chat" AND service.name = "{SERVICE_NAME}"',
}
]
definitions = [
{"slug": helpfulness.slug, "mapping": {"product": "app.product_name"}},
{"slug": apology.slug, "sampling": {"type": "probabilistic", "percentage": 50}},
]
existing = client.beta.observability.evaluations.list_pipelines(q=LIVE_EVAL_NAME)
matches = [p for p in existing.pipelines.results or [] if p.name == LIVE_EVAL_NAME]
if matches:
# Sending `definitions` again re-copies the latest version of each scorer.
live_eval = client.beta.observability.evaluations.update_pipeline(
pipeline_id=matches[0].id, selectors=selectors, definitions=definitions, enabled=True
)
else:
live_eval = client.beta.observability.evaluations.create_pipeline(
name=LIVE_EVAL_NAME,
description="Scores the cookbook support assistant.",
selectors=selectors,
definitions=definitions,
)
for config in live_eval.pipeline_configs:
print(f"{config.scorer_slug} v{config.scorer_version} -> results under 'judge:{config.slug}'")The live eval creates one pipeline config per attached scorer. Its slug names the results: every score from that scorer in this live eval has evaluation_name = "judge:<pipeline-config-slug>". The slugs of the live eval and of the scorer never appear in results, so keep the pipeline config slugs:
config_slug = {config.scorer_slug: config.slug for config in live_eval.pipeline_configs}
HELPFULNESS = f"judge:{config_slug[helpfulness.slug]}"
APOLOGY = f"judge:{config_slug[apology.slug]}"Live evals pin a scorer version. Editing a scorer later doesn't change running live evals. To roll out a new version, update the live eval with its
definitionsagain, as the cell above does when the live eval already exists.
A new or updated live eval takes effect on spans ingested after the workers reload their configuration, which can take up to a minute.
3. Send traffic#
The judges read the conversation, so the spans must carry the messages. Create each operation with include_content=True to record them as gen_ai.input.messages and gen_ai.output.messages. The app.product_name attribute feeds the product variable of the helpfulness scorer.
The assistant answers a few support questions. Its system prompt asks it to apologize when it can't help, so some answers are likely to trigger the apology detector.
import time
from mistralai.observability.otel import observability
from mistralai.observability.otel import semconv_constants as genai
observability.configure_mistral(service_name=SERVICE_NAME) # reads MISTRAL_API_KEY
SYSTEM_PROMPT = (
"You are the support assistant for Acme Cloud Storage. Answer in at most three sentences. "
"If the question is outside Acme Cloud Storage, apologize and say you can't help."
)
QUESTIONS = [
"How do I share a folder with a teammate?",
"I deleted a file yesterday. Can I get it back?",
"What's the maximum file size I can upload?",
"Can you recommend a good pizza place in Lyon?",
"My sync client says 'quota exceeded'. What should I do?",
"Write me a poem about the ocean.",
]
print("Waiting 60 seconds so the workers load the live eval...")
time.sleep(60)
spans = []
for question in QUESTIONS:
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": question},
]
with observability.operation(
genai.OPERATION_NAME_CHAT,
model=ASSISTANT_MODEL,
provider=genai.PROVIDER_NAME_MISTRAL_AI,
include_content=True,
attributes={"app.product_name": "Acme Cloud Storage"},
) as chat:
response = client.chat.complete(model=ASSISTANT_MODEL, messages=messages)
chat.mistral_completion(response, messages=messages)
spans.append((chat.trace_id, chat.span_id))
print(f"{question}\n -> {response.choices[0].message.content}\n")
observability.flush() # exports pending spans now instead of waiting for the next batchIn a real application, you configure observability once at startup and wrap each model call the same way. Call observability.shutdown() before the process exits.
4. Read the scores#
Scores usually arrive within seconds of ingestion. Search them with search_span_evaluations. The search_expression filters on result fields, and the time window is set with from_ and to, which default to the last hour.
The next cell waits until every span has a helpfulness score:
def search_scores(evaluation_name: str) -> list:
response = client.beta.observability.spans.search_span_evaluations(
from_=started_at,
search_expression=f"evaluation_name = '{evaluation_name}'",
page_size=100,
)
return response.span_evaluations.results or []
deadline = time.monotonic() + 180
while len(scores := search_scores(HELPFULNESS)) < len(spans) and time.monotonic() < deadline:
time.sleep(10)
print(f"{len(scores)}/{len(spans)} spans scored for helpfulness\n")
for score in scores:
print(f"{score.score_value:.0f}/5 span {score.span_id} {score.explanation}")Each result carries the scored trace_id and span_id, the score in score_value or score_label, and the judge's reason in explanation. If no result appears, see If no result appears.
Filter on the score itself to find the answers worth investigating. Every helpfulness score of 3 or less points to a trace you can open in Studio:
weak = client.beta.observability.spans.search_span_evaluations(
from_=started_at,
search_expression=f"evaluation_name = '{HELPFULNESS}' AND score_value <= 3",
).span_evaluations.results or []
if not weak:
print("No answer scored 3 or less.")
for score in weak:
print(f"{score.score_value:.0f}/5 https://console.mistral.ai/observability/traces/{score.trace_id}")See all scores of a span#
search_pipeline_results returns one row per span with the scores of every judge, keyed by evaluation name. This is the shape of the results table in Studio. Pass the pipeline config slugs without the judge: prefix.
A span can be missing an apology score: that scorer only sees half of the traffic.
rows = client.beta.observability.spans.search_pipeline_results(
from_=started_at,
pipeline_config_slugs=[config.slug for config in live_eval.pipeline_configs],
).pipeline_results.results or []
for row in rows:
print(
f"span {row.span_id} helpfulness={row.judge_scores.get(HELPFULNESS)} "
f"apology={row.judge_labels.get(APOLOGY, 'not sampled')}"
)Aggregate scores#
aggregate_span_evaluations computes one metric over the results, optionally grouped by dimensions and bucketed in time. These are the numbers behind the charts in Studio. Average a numeric scorer:
average = client.beta.observability.spans.aggregate_span_evaluations(
from_=started_at,
metric={"measure": "score_value", "aggregation": "avg"},
search_expression=f"evaluation_name = '{HELPFULNESS}'",
)
print(f"Average helpfulness: {average.data[0].metric_value:.2f}/5")For a categorical or boolean scorer, count the results grouped by score_label to get the label distribution. Add time_dimension={"granularity": "hour"} to get a time series instead of a single total.
distribution = client.beta.observability.spans.aggregate_span_evaluations(
from_=started_at,
metric={"measure": "score_label", "aggregation": "count"},
dimensions=["score_label"],
search_expression=f"evaluation_name = '{APOLOGY}'",
)
for row in distribution.data:
print(f"apology={row.dimensions['score_label']}: {row.metric_value} span(s)")The same results are in Studio, under Evaluate → Evaluations → Live: trend, distribution, and coverage charts, plus the per-span results table. Each score also shows on its span in the trace view.
5. Pause the live eval#
Pausing a live eval stops scoring new spans without losing its configuration or past results. Changes take effect without a deploy.
client.beta.observability.evaluations.update_pipeline(pipeline_id=live_eval.id, enabled=False)Resume it with enabled=True. To change which spans are scored, send new selectors. To change scorers, mappings, or sampling, send the full definitions list.
Clean up#
Deleting the live eval removes its configuration. Past results stay in the telemetry platform until they expire. Scorers have no delete endpoint, and a scorer that no live eval uses costs nothing.
client.beta.observability.evaluations.delete_pipeline(pipeline_id=live_eval.id)
observability.shutdown()Summary#
This cookbook scored a support assistant's production traffic with two LLM judges, without changing the request path, and read the scores back to find weak answers.
What you built
- A numeric helpfulness scorer and a boolean apology detector, reusable across live evals and offline evaluations
- A live eval that selects the assistant's chat spans, maps span attributes to scorer variables, and samples each scorer independently
- Queries that list scores, find low-scoring traces, pivot all scores per span, and aggregate them
Mistral features used
- Observability scorers and live evals (online evaluations)
- Mistral OpenTelemetry SDK (
mistralai-otel-observability) - Chat Completions API
To turn low-scoring spans into test cases for offline evaluation, see the evaluation datasets cookbook. To learn more, read the online evaluations documentation.