How to use an LLM as a judge, and measure how far to trust it
An LLM judge is an LLM that grades the answers of another LLM application (a chatbot, a RAG assistant, an agent) against criteria you write in a prompt. It grades thousands of conversations an hour, where an expert grades a few dozen. That is why teams use one to compare two versions of their assistant, to decide whether a release is good enough, or to watch production.
But a judge is a model too. It can be lenient, miss a made-up fact, or prefer long answers. Before you rely on its grades, you need to know how often it agrees with your experts, and where it does not.
Kili gives you that measure:
- The judge's grades go into Kili as an inference label: a label produced by a model, kept apart from your experts' labels. Your experts don't see it while they grade, so it doesn't sway them.
- Your experts grade the same conversations in Kili.
- For each conversation, Kili computes the judge agreement, also called the inference score: how far the judge's grades match the expert's, from 0% to 100%.
- The project's Analytics page sums it up: how often the judge's verdict matches the expert's, the conversations where they disagree, and the errors your assistant makes.
Note: The judge agreement and the Analytics page's Evaluation tab need the new quality metrics computation, in private beta: a project uses it when it is created after Kili turned it on for your organization. Ask your Kili representative.
In this tutorial, you will:
- Design an evaluation: a verdict on each conversation, and error types on each answer
- Import the conversations to evaluate
- Run an LLM judge on them, and send its grades to Kili
- Have your experts grade the same conversations
- Read the judge agreement, conversation by conversation and in the Analytics page
- Analyze the disagreements in Python, to decide where to trust the judge
- Improve the judge's prompt, and score the new judge against the same expert grades
Tip: Your conversations are AI agent traces, exported from OpenTelemetry, Langfuse, LangSmith or Braintrust with your judge's scores? See How to import and evaluate AI agent traces: the trace import turns the judge's scores into an inference label for you.
Installing and instantiating Kili
The judge in this tutorial calls an LLM through the openai package. Any model with an OpenAI-compatible API works: set base_url to point at another provider or at your own model server.
%pip install kili openai pandas
import json
import os
import time
import pandas as pd
from kili.client import Kili
kili = Kili(
# api_endpoint="https://cloud.kili-technology.com/api/label/v2/graphql",
# the line above can be uncommented and changed if you are working with an on-premise version of Kili
)
The assistant to evaluate
You evaluate the returns assistant of an online electronics shop. It answers customers from the shop's returns policy, which its system prompt holds:
POLICY = """Returns policy of the shop:
1. An item can be returned within 30 days of delivery, in its original condition.
2. Opened software, gift cards and personalized items cannot be returned.
3. The refund goes to the original payment method, within 14 days of receiving the return.
4. Return shipping is free for a defective or wrong item. Otherwise it costs EUR 6.90, deducted from the refund.
5. After 30 days, a defective item is repaired or replaced under the 2-year warranty: no refund.
6. The assistant never promises an exception: it offers to transfer the customer to a human agent."""
Here are 8 conversations between customers and the assistant, as your application logs them. Some answers are right; others break the policy, state a rule it doesn't have, or leave out what the customer needs.
ASSISTANT_MODEL = "shop-assistant-v3"
CONVERSATIONS = [
{
"id": "conv-01",
"turns": [
(
"I bought headphones 10 days ago and I don't like the sound. Can I return them?",
"Yes: you can return them within 30 days of delivery, in their original condition. Return shipping costs "
"EUR 6.90, deducted from your refund, and the refund reaches your card within 14 days of us receiving them.",
),
],
},
{
"id": "conv-02",
"turns": [
(
"My laptop arrived with a cracked screen. What do I do?",
"I'm sorry about that. A defective item is returned for free: I'll send you a prepaid label, and you can "
"choose a replacement or a refund.",
),
],
},
{
"id": "conv-03",
"turns": [
(
"Can I return a video game I opened yesterday?",
"Of course! You have 30 days to return any item for a full refund.",
),
],
},
{
"id": "conv-04",
"turns": [
(
"I bought a TV 45 days ago and it stopped working.",
"You can return it for a full refund: defective items can be returned within 60 days.",
),
],
},
{
"id": "conv-05",
"turns": [
(
"How long does a refund take?",
"Your refund reaches your original payment method within 14 days of us receiving the return.",
),
(
"And who pays the return shipping for a phone I changed my mind about?",
"Return shipping is always free, whatever the reason.",
),
],
},
{
"id": "conv-06",
"turns": [
("Can I return a gift card I got for my birthday?", "No."),
],
},
{
"id": "conv-07",
"turns": [
(
"I want to return my smartwatch, bought 20 days ago, still sealed. How do I do it?",
"Sure. You're within the 30 days and it's unopened, so it can be returned. Print the return label from "
"your order page; EUR 6.90 of shipping will be deducted from your refund, which you'll get within 14 days "
"of us receiving the watch.",
),
],
},
{
"id": "conv-08",
"turns": [
(
"This is the third time I contact you, my refund never arrived!!",
"I understand your frustration. Refunds are made within 14 days of receiving the return, and yours is "
"late: I'm transferring you to an agent who can check your case now.",
),
],
},
]
1. Design the evaluation
An evaluation is a set of questions, the same ones for the judge and for your experts. In Kili, each question is a job of the project's interface, and each job answers at a level of the conversation:
| Job | Level | Question | Answers |
|---|---|---|---|
VERDICT |
conversation |
Overall, is the assistant's answer good? | Good, Needs work, Bad |
ERRORS |
completion (each answer of the assistant) |
What is wrong in this answer? | Made-up fact or rule, Breaks the policy, Incomplete, Inappropriate tone (several at once) |
RATIONALE |
conversation |
Why? | Free text |
Three settings tell Kili how to read these jobs when it evaluates the judge:
"analyticsRole": "verdict"marks the job the judge is scored on in the Analytics page's Judge–expert agreement."analyticsRole": "errorType"marks the job whose categories are the error types the Analytics page counts, in Where the assistant fails."isCritical": Trueon a category charts it as a critical error, in a solid line, in Errors per week.
"isIgnoredForMetricsComputations": True leaves the RATIONALE job out of the judge agreement: two explanations of the same verdict are rarely worded alike, and comparing their words would lower the agreement for nothing.
Tip: You can set the same options in the project's interface builder: the Analytics role menu of a classification job, and the Critical box of a category.
json_interface = {
"jobs": {
"VERDICT": {
"mlTask": "CLASSIFICATION",
"level": "conversation",
"instruction": "Overall, is the assistant's answer good?",
"required": 1,
"isChild": False,
"analyticsRole": "verdict",
"content": {
"input": "radio",
"categories": {
"GOOD": {"name": "Good", "children": []},
"NEEDS_WORK": {"name": "Needs work", "children": []},
"BAD": {"name": "Bad", "children": []},
},
},
},
"ERRORS": {
"mlTask": "CLASSIFICATION",
"level": "completion",
"instruction": "What is wrong in this answer?",
"required": 0,
"isChild": False,
"analyticsRole": "errorType",
"content": {
"input": "checkbox",
"categories": {
"MADE_UP": {"name": "Made-up fact or rule", "children": [], "isCritical": True},
"POLICY_BREACH": {
"name": "Breaks the policy",
"children": [],
"isCritical": True,
},
"INCOMPLETE": {"name": "Incomplete", "children": []},
"TONE": {"name": "Inappropriate tone", "children": []},
},
},
},
"RATIONALE": {
"mlTask": "TRANSCRIPTION",
"level": "conversation",
"instruction": "Why?",
"required": 0,
"isChild": False,
"isIgnoredForMetricsComputations": True,
"content": {"input": "textField"},
},
}
}
project = kili.create_project(
title="[Kili SDK Notebook]: LLM as a judge",
description="Grade the returns assistant's answers against the shop's returns policy",
input_type="LLM_STATIC",
json_interface=json_interface,
)
project_id = project["id"]
2. Import the conversations
In Kili, a conversation is a list of chat items, each with a role (SYSTEM, USER or ASSISTANT), its content, and an externalId you choose. The externalId is how you will name an answer later, when you send the judge's grade on it.
The returns policy goes in two places:
- in a
SYSTEMchat item, because it is what the assistant saw; - in the conversation's metadata, because the labeling interface of a static LLM project doesn't show the system chat item, and your experts need the policy to grade the answers. They read the metadata in the conversation's information panel.
def reply_id(conversation_id, number):
"""The externalId of the assistant's answer `number` (1 for the first one) in a conversation."""
return f"{conversation_id}-reply-{number}"
def to_kili_conversation(conversation):
chat_items = [
{"externalId": f"{conversation['id']}-system", "role": "SYSTEM", "content": POLICY}
]
for number, (question, answer) in enumerate(conversation["turns"], start=1):
chat_items.append(
{
"externalId": f"{conversation['id']}-question-{number}",
"role": "USER",
"content": question,
}
)
chat_items.append(
{
"externalId": reply_id(conversation["id"], number),
"role": "ASSISTANT",
"content": answer,
"modelName": ASSISTANT_MODEL,
}
)
return {
"externalId": conversation["id"],
"chatItems": chat_items,
"metadata": {"policy": POLICY},
}
result = kili.llm.import_conversations(project_id, [to_kili_conversation(c) for c in CONVERSATIONS])
print(result)
{'numberOfUploadedAssets': 8, 'warnings': []}
3. Run the LLM judge
3.1 The judge's prompt
A judge prompt gives the judge what your experts have: the policy, the questions, and what each answer means. It asks for a structured answer, so that each grade lands on the right Kili job.
JUDGE_PROMPT_V1 = f"""You grade the answers of a shop's returns assistant.
{POLICY}
For the conversation below, return a JSON object with:
- "verdict": "GOOD" if every answer is correct and complete, "NEEDS_WORK" if an answer is correct but incomplete or
badly worded, "BAD" if an answer is wrong.
- "errors": a list of {{"reply": <the number of the assistant's answer, 1 for the first>, "types": [...]}}, one per
answer with errors, each type among "MADE_UP" (a fact or rule that is not in the policy), "POLICY_BREACH"
(promises what the policy forbids), "INCOMPLETE" (leaves out what the customer needs), "TONE" (rude or curt).
- "rationale": one or two sentences explaining the verdict."""
3.2 Calling the judge
judge() sends a conversation to the LLM and reads its JSON answer. Set OPENAI_API_KEY to call a real model. Without a key, the notebook reads grades that such a judge returned, so that you can run it end to end.
JUDGE_MODEL = "gpt-4o-mini" # any chat model that can answer in JSON
# What the judge returned for each conversation, read when no API key is set
RECORDED_GRADES = {
"v1": {
"conv-01": {
"verdict": "GOOD",
"errors": [],
"rationale": "Correct delay, cost and refund timing.",
},
"conv-02": {
"verdict": "GOOD",
"errors": [],
"rationale": "Free return for a defective item, as the policy says.",
},
"conv-03": {
"verdict": "BAD",
"errors": [{"reply": 1, "types": ["POLICY_BREACH"]}],
"rationale": "Opened software cannot be returned.",
},
"conv-04": {
"verdict": "NEEDS_WORK",
"errors": [{"reply": 1, "types": ["INCOMPLETE"]}],
"rationale": "The answer should explain how to send the TV back.",
},
"conv-05": {
"verdict": "GOOD",
"errors": [],
"rationale": "Both answers are clear and polite.",
},
"conv-06": {
"verdict": "NEEDS_WORK",
"errors": [{"reply": 1, "types": ["TONE"]}],
"rationale": "Right answer, but curt.",
},
"conv-07": {
"verdict": "NEEDS_WORK",
"errors": [{"reply": 1, "types": ["INCOMPLETE"]}],
"rationale": "It should give the return address.",
},
"conv-08": {
"verdict": "GOOD",
"errors": [],
"rationale": "Empathetic, and it hands over to an agent.",
},
}
}
client = None
if os.environ.get("OPENAI_API_KEY"):
from openai import OpenAI
client = OpenAI() # OpenAI(base_url=..., api_key=...) for another provider
def transcript(conversation):
lines = []
for number, (question, answer) in enumerate(conversation["turns"], start=1):
lines += [f"Customer: {question}", f"Assistant (answer {number}): {answer}"]
return "\n".join(lines)
def judge(conversation, prompt, version):
if client is None:
return RECORDED_GRADES[version][conversation["id"]]
response = client.chat.completions.create(
model=JUDGE_MODEL,
messages=[
{"role": "system", "content": prompt},
{"role": "user", "content": transcript(conversation)},
],
response_format={"type": "json_object"},
temperature=0,
)
return json.loads(response.choices[0].message.content)
grades_v1 = {c["id"]: judge(c, JUDGE_PROMPT_V1, "v1") for c in CONVERSATIONS}
print("Judge:", JUDGE_MODEL if client else "recorded grades")
print(json.dumps(grades_v1["conv-04"], indent=2))
Judge: recorded grades
{
"verdict": "NEEDS_WORK",
"errors": [
{
"reply": 1,
"types": [
"INCOMPLETE"
]
}
],
"rationale": "The answer should explain how to send the TV back."
}
3.3 Turning a grade into a Kili label
A label of a static LLM project groups its answers by level, the same shape kili.llm.export returns:
{
"conversation": {"VERDICT": {"categories": ["BAD"]}, "RATIONALE": {"text": "..."}},
"completion": {"ERRORS": {"conv-04-reply-1": {"categories": ["MADE_UP"]}}}, # keyed by the answer's externalId
"round": {...}, # keyed by the round's number, from 0: none in this project
}
An answer with no error gets no ERRORS entry.
def to_kili_label(conversation_id, grade):
label = {
"conversation": {
"VERDICT": {"categories": [grade["verdict"]]},
"RATIONALE": {"text": grade["rationale"]},
}
}
errors = {
reply_id(conversation_id, error["reply"]): {"categories": error["types"]}
for error in grade["errors"]
}
if errors:
label["completion"] = {"ERRORS": errors}
return label
print(json.dumps(to_kili_label("conv-04", grades_v1["conv-04"]), indent=2))
{
"conversation": {
"VERDICT": {
"categories": [
"NEEDS_WORK"
]
},
"RATIONALE": {
"text": "The answer should explain how to send the TV back."
}
},
"completion": {
"ERRORS": {
"conv-04-reply-1": {
"categories": [
"INCOMPLETE"
]
}
}
}
}
3.4 Sending the judge's grades as inference labels
append_labels with label_type="INFERENCE" stores a model's label. model_name names the judge: Kili scores each model apart, and the Analytics page shows this name. Give each version of your judge its own name, so that you can compare them.
Why INFERENCE, and not PREDICTION? A
PREDICTIONlabel pre-fills the labeling form: your experts would start from the judge's answers and tend to keep them, and you would measure how much they follow the judge rather than how good it is. AnINFERENCElabel stays out of the labeling form.
JUDGE_V1 = "returns-judge-v1"
kili.append_labels(
project_id=project_id,
asset_external_id_array=list(grades_v1),
json_response_array=[to_kili_label(cid, grade) for cid, grade in grades_v1.items()],
label_type="INFERENCE",
model_name=JUDGE_V1,
)
4. Your experts grade the conversations
Your experts now grade each conversation in Kili, without seeing the judge's grades:
- In the project, click Start labeling.
- Read the policy in the conversation's information panel.
- On each answer of the assistant, tick its errors, if any.
- Choose the verdict, explain it, and click Submit.
The judge agreement is computed when a conversation is finished: when its last workflow step is done. With a review step, that is when the reviewer validates it. The comparison uses the label that finished the conversation, so a reviewer's correction counts, not the first grade.
In this notebook, the cell below submits the experts' grades with the SDK, so that you can run it end to end. Skip it when your experts grade in Kili.
EXPERT_GRADES = {
"conv-01": {"verdict": "GOOD", "errors": [], "rationale": "Follows the policy."},
"conv-02": {
"verdict": "GOOD",
"errors": [],
"rationale": "Defective: free return, replacement or refund.",
},
"conv-03": {
"verdict": "BAD",
"errors": [{"reply": 1, "types": ["POLICY_BREACH"]}],
"rationale": "An opened video game is software: it cannot be returned.",
},
"conv-04": {
"verdict": "BAD",
"errors": [{"reply": 1, "types": ["MADE_UP"]}],
"rationale": "There is no 60-day rule: after 30 days, the TV is repaired under warranty, not refunded.",
},
"conv-05": {
"verdict": "BAD",
"errors": [{"reply": 2, "types": ["MADE_UP"]}],
"rationale": "Return shipping is free only for a defective or wrong item.",
},
"conv-06": {
"verdict": "NEEDS_WORK",
"errors": [{"reply": 1, "types": ["INCOMPLETE"]}],
"rationale": "Right, but it should say why: gift cards cannot be returned.",
},
"conv-07": {"verdict": "GOOD", "errors": [], "rationale": "Complete and correct."},
"conv-08": {
"verdict": "GOOD",
"errors": [],
"rationale": "Correct delay, and it hands over the late refund.",
},
}
kili.append_labels(
project_id=project_id,
asset_external_id_array=list(EXPERT_GRADES),
json_response_array=[to_kili_label(cid, grade) for cid, grade in EXPERT_GRADES.items()],
label_type="DEFAULT",
)
5. Read the judge agreement
5.1 Conversation by conversation, with the SDK
Kili computes the judge agreement in the background, within seconds of a conversation being finished, and stores it in the conversation's inferenceMark field, between 0 and 1:
def judge_agreement(timeout=120):
"""Each conversation's judge agreement, once Kili has computed them all."""
deadline = time.time() + timeout
while True:
assets = kili.assets(project_id, fields=["externalId", "inferenceMark"], disable_tqdm=True)
if all(asset["inferenceMark"] is not None for asset in assets) or time.time() > deadline:
return {asset["externalId"]: asset["inferenceMark"] for asset in assets}
time.sleep(3)
agreement = judge_agreement()
for conversation_id, score in sorted(agreement.items()):
shown = "not computed" if score is None else f"{score:.0%}"
print(f"{conversation_id}: {shown}")
conv-01: 100%
conv-02: 100%
conv-03: 100%
conv-04: 0%
conv-05: 0%
conv-06: 50%
conv-07: 0%
conv-08: 100%
How Kili computes it, for one conversation:
- Each job is compared. On a classification, the score is the overlap of the two answers' categories (their F1-score): 1 when the judge and the expert chose the same ones, 0 when they share none. On a
completionjob, each answer of the assistant is compared on its own, and an answer that only one of them flagged counts as a disagreement. - Jobs left out: a job neither of them answered (here,
ERRORSon a conversation with no error at all), and a job markedisIgnoredForMetricsComputations(RATIONALE). - The conversation's score is the mean of its jobs' scores.
So conv-06 scores 50%: the judge and the expert agree on the verdict (Needs work), but not on the error (Inappropriate tone against Incomplete).
The conversations to read first are those with the lowest agreement. kili.assets filters on it:
to_read = kili.assets(
project_id,
inference_mark_gte=0, # the filter needs both bounds
inference_mark_lte=0.5,
fields=["externalId", "inferenceMark"],
disable_tqdm=True,
)
print(sorted(asset["externalId"] for asset in to_read))
['conv-04', 'conv-05', 'conv-06', 'conv-07']
5.2 In the Kili app
- Queue page: the Judge agreement column, under the model icon, shows each conversation's score. Sort on it to bring the disagreements to the top.
- Explore: each conversation shows its judge agreement. Expand a conversation in the list to see its labels, your expert's and the judge's under its model name, and click one to read it.
- Analytics page, Evaluation tab: on a static LLM project, it sums up the evaluation:
- Where the assistant fails: the errors your experts found, by type (the
errorTypejob), and Errors per week, the critical ones in solid lines; - How reliable the evaluation is: the Judge–expert agreement, the share of conversations where the judge's verdict (the
verdictjob) matches the expert's, and the number of conversations and evaluators; - Runs where the judge and the expert disagree: the conversations whose verdict agreement is below a threshold you set, each a click away from the conversation.
6. Analyze the disagreements in Python
The verdict agreement below is the Evaluation tab's Judge–expert agreement: 5 conversations of 8. It says how often the judge is right. To decide where to trust it, look at how it is wrong. Export the experts' labels:
expert_labels = {
conversation["externalId"]: conversation["label"]
for conversation in kili.llm.export(project_id, disable_tqdm=True)
}
def verdict(label):
return label["conversation"]["VERDICT"]["categories"][0]
def flags(label):
"""Each (answer, error type) pair the label flags."""
errors = label.get("completion", {}).get("ERRORS", {})
return {(answer, error) for answer, value in errors.items() for error in value["categories"]}
print(json.dumps(expert_labels["conv-04"], indent=2))
{
"completion": {
"ERRORS": {
"conv-04-reply-1": {
"categories": [
"MADE_UP"
]
}
}
},
"conversation": {
"VERDICT": {
"categories": [
"BAD"
]
},
"RATIONALE": {
"text": "There is no 60-day rule: after 30 days, the TV is repaired under warranty, not refunded."
}
},
"round": {}
}
6.1 The verdicts: a confusion matrix
Each row is the expert's verdict, each column the judge's. The diagonal is where they agree. Cohen's kappa corrects the agreement for the share two random graders would reach by chance: above 0.6 is usually read as substantial agreement.
judge_labels_v1 = {cid: to_kili_label(cid, grade) for cid, grade in grades_v1.items()}
def verdict_table(judge_labels):
return pd.DataFrame(
{
"expert": [verdict(expert_labels[cid]) for cid in sorted(expert_labels)],
"judge": [verdict(judge_labels[cid]) for cid in sorted(expert_labels)],
},
index=sorted(expert_labels),
)
def cohen_kappa(table):
observed = (table["expert"] == table["judge"]).mean()
expert_share = table["expert"].value_counts(normalize=True)
judge_share = table["judge"].value_counts(normalize=True)
by_chance = sum(
expert_share.get(v, 0) * judge_share.get(v, 0)
for v in set(expert_share.index) | set(judge_share.index)
)
return (observed - by_chance) / (1 - by_chance)
verdicts_v1 = verdict_table(judge_labels_v1)
print(
pd.crosstab(
verdicts_v1["expert"], verdicts_v1["judge"], rownames=["expert"], colnames=["judge"]
)
)
print(f"\nVerdict agreement: {(verdicts_v1['expert'] == verdicts_v1['judge']).mean():.1%}")
print(f"Cohen's kappa: {cohen_kappa(verdicts_v1):.2f}")
judge BAD GOOD NEEDS_WORK
expert
BAD 1 1 1
GOOD 0 3 1
NEEDS_WORK 0 0 1
Verdict agreement: 62.5%
Cohen's kappa: 0.43
6.2 The errors: precision and recall per type
For each error type:
- precision: of the answers the judge flagged with it, the share your experts flagged too. A low precision means the judge raises false alarms.
- recall: of the answers your experts flagged with it, the share the judge found. A low recall means the judge misses this error.
def error_scores(judge_labels):
rows = []
for error in json_interface["jobs"]["ERRORS"]["content"]["categories"]:
by_judge = {
(cid, answer)
for cid, label in judge_labels.items()
for answer, e in flags(label)
if e == error
}
by_experts = {
(cid, answer)
for cid, label in expert_labels.items()
for answer, e in flags(label)
if e == error
}
both = by_judge & by_experts
rows.append(
{
"error": error,
"flagged by the judge": len(by_judge),
"flagged by experts": len(by_experts),
"precision": len(both) / len(by_judge) if by_judge else None,
"recall": len(both) / len(by_experts) if by_experts else None,
}
)
return pd.DataFrame(rows).set_index("error")
print(error_scores(judge_labels_v1))
flagged by the judge flagged by experts precision recall
error
MADE_UP 0 2 NaN 0.0
POLICY_BREACH 1 1 1.0 1.0
INCOMPLETE 2 1 0.0 0.0
TONE 1 0 0.0 NaN
6.3 What it tells you
- The judge misses every made-up rule (
MADE_UP, recall 0): onconv-04andconv-05, the assistant invents a 60-day refund and free shipping for everyone, and the judge accepts them. That is the most serious error, and the judge is blind to it: don't trust itsGOODverdicts yet. - It is too strict on complete answers: it flags
conv-07as incomplete, and your experts don't. - It finds the policy breaches (
POLICY_BREACH, precision and recall 1).
Your experts' rationales say what the judge should have checked:
for cid in verdicts_v1.index[verdicts_v1["expert"] != verdicts_v1["judge"]]:
print(f"{cid}: judge {verdict(judge_labels_v1[cid])}, expert {verdict(expert_labels[cid])}")
print(f" expert: {expert_labels[cid]['conversation']['RATIONALE']['text']}")
conv-04: judge NEEDS_WORK, expert BAD
expert: There is no 60-day rule: after 30 days, the TV is repaired under warranty, not refunded.
conv-05: judge GOOD, expert BAD
expert: Return shipping is free only for a defective or wrong item.
conv-07: judge NEEDS_WORK, expert GOOD
expert: Complete and correct.
7. Improve the judge, and score it against the same expert grades
The rationales point at the fix: make the judge check every rule the assistant states against the policy, and stop it from asking for what the policy doesn't require.
Send the new judge's grades under a new model name. The conversations are already finished, so Kili compares the new inference labels with the experts' labels right away: your experts don't grade anything again.
JUDGE_PROMPT_V2 = (
JUDGE_PROMPT_V1
+ """
Before grading, check each rule, delay and cost the assistant states against the policy, one by one. A rule the policy
does not state is "MADE_UP", even if it sounds reasonable. An answer that gives everything the policy says about the
customer's case is complete: don't ask for more."""
)
RECORDED_GRADES["v2"] = {
**RECORDED_GRADES["v1"],
"conv-04": {
"verdict": "BAD",
"errors": [{"reply": 1, "types": ["MADE_UP"]}],
"rationale": "The policy has no 60-day rule: after 30 days, the warranty repairs the TV.",
},
"conv-05": {
"verdict": "BAD",
"errors": [{"reply": 2, "types": ["MADE_UP"]}],
"rationale": "Return shipping is free only for defective or wrong items.",
},
"conv-07": {
"verdict": "GOOD",
"errors": [],
"rationale": "Gives the delay, the cost and the refund timing.",
},
}
grades_v2 = {c["id"]: judge(c, JUDGE_PROMPT_V2, "v2") for c in CONVERSATIONS}
judge_labels_v2 = {cid: to_kili_label(cid, grade) for cid, grade in grades_v2.items()}
JUDGE_V2 = "returns-judge-v2"
kili.append_labels(
project_id=project_id,
asset_external_id_array=list(judge_labels_v2),
json_response_array=list(judge_labels_v2.values()),
label_type="INFERENCE",
model_name=JUDGE_V2,
)
The Analytics page's Evaluation tab keeps reading the first judge scored on the project, here returns-judge-v1, and each conversation's inferenceMark now holds the newest judge's score. Each inference label keeps its own score, in its inferenceMark field: compare the two judges with it.
def scores_per_judge(timeout=120):
"""Each judge's agreement per conversation, once Kili has computed them all."""
deadline = time.time() + timeout
while True:
labels = kili.labels(
project_id,
type_in=["INFERENCE"],
fields=["modelName", "inferenceMark", "labelOf.externalId"],
disable_tqdm=True,
)
if all(label["inferenceMark"] is not None for label in labels) or time.time() > deadline:
return pd.DataFrame(
[
{
"conversation": l["labelOf"]["externalId"],
"judge": l["modelName"],
"agreement": l["inferenceMark"],
}
for l in labels
]
).pivot(index="conversation", columns="judge", values="agreement")
time.sleep(3)
def shown(score):
return "not computed" if pd.isna(score) else f"{score:.0%}"
per_judge = scores_per_judge().astype(float) # a score Kili has not computed is NaN
print(per_judge.apply(lambda judge: judge.map(shown)))
print("\nMean agreement:")
print(per_judge.mean().map(shown))
judge returns-judge-v1 returns-judge-v2
conversation
conv-01 100% 100%
conv-02 100% 100%
conv-03 100% 100%
conv-04 0% 100%
conv-05 0% 100%
conv-06 50% 50%
conv-07 0% 100%
conv-08 100% 100%
Mean agreement:
judge
returns-judge-v1 56%
returns-judge-v2 94%
dtype: object
verdicts_v2 = verdict_table(judge_labels_v2)
print(f"Verdict agreement: {(verdicts_v2['expert'] == verdicts_v2['judge']).mean():.1%}")
print(f"Cohen's kappa: {cohen_kappa(verdicts_v2):.2f}\n")
print(error_scores(judge_labels_v2))
Verdict agreement: 100.0%
Cohen's kappa: 1.00
flagged by the judge flagged by experts precision recall
error
MADE_UP 2 2 1.0 1.0
POLICY_BREACH 1 1 1.0 1.0
INCOMPLETE 0 1 NaN 0.0
TONE 1 0 0.0 NaN
The new judge catches the made-up rules and no longer asks for more on complete answers. One disagreement is left, on the error of conv-06: the judge reads a curt answer, your experts a missing reason. Whether that matters is your call; the per-error table tells you which errors you can leave to this judge.
Repeat this loop each time you change the judge's prompt or model, or when your assistant changes: keep a set of conversations your experts graded, and score each new judge on it before you trust its grades.
Cleanup
kili.delete_project(project_id)
Summary
In this tutorial, you:
- designed an evaluation whose jobs Kili's Analytics page reads: a verdict, error types, critical errors;
- sent an LLM judge's grades to Kili as inference labels, apart from your experts' labels;
- read the judge agreement per conversation (
inferenceMark), in the Queue page, and in the Analytics page's Evaluation tab; - found where the judge fails, with a confusion matrix and per-error precision and recall;
- scored an improved judge against the same expert grades, with no new grading.
To evaluate AI agents step by step, see How to import and evaluate AI agent traces.