How to import and evaluate AI agent traces
An AI agent answers a request in several steps: it calls an LLM, which decides to call tools (a database, an API, a calculator), then calls the LLM again with what the tools returned, until it can answer. A tracing tool (OpenTelemetry, Langfuse, LangSmith, Braintrust, or your own logs) records each run of the agent as a trace: the request, every step with its input and output, and the final answer. An LLM judge often scores the trace too.
A judge's score tells you that a run failed. It rarely tells you which step failed and what the agent should have done. That is what your experts can answer in Kili: they review each trace step by step, mark the step that went wrong, say why, and write the correct behavior. Their answers are the ground truth that tells you whether to trust your judge, and the data that fixes your agent.
In this tutorial, you will:
- Create a Kili project to evaluate an agent, with questions on each step and on the whole run
- Turn traces into Kili conversations
- Import them, with your LLM judge's scores for the reviewers to see
- Export the evaluations, and find the steps where your agent fails
Tip: Exported your traces from OpenTelemetry (OTLP JSON), Langfuse, LangSmith or Braintrust? You can also drop the export files in Kili's Imports page, with no code: Kili converts each trace, imports the media its steps hold, and turns your judge's scores into an "LLM judge" label. See Labeling LLM data. Use the SDK, as below, to import traces from another tool, from your own logs, or on a schedule.
Installing and instantiating Kili
%pip install kili
import json
from collections import Counter
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
)
How Kili shows an agent trace
In Kili, an agent's run is a conversation of an LLM_STATIC project: one trace, one asset. Its chat items are, in order:
| Role | What it holds |
|---|---|
SYSTEM |
The agent's system prompt (optional, first item only). Kili keeps it with the conversation and in exports; the labeling interface doesn't show it |
USER |
The request that started the run |
TOOL |
One tool call: its name, its arguments, its result or its error |
ASSISTANT |
One LLM reply: an intermediate answer, or the final answer |
The TOOL and ASSISTANT items that follow a USER item are the steps of that round, in the order the agent ran them. The labeling interface numbers them (#1, #2, ...), shows each tool call with its arguments and its result, and lists every step in an outline beside the conversation. A session with several user messages is several rounds, each with its own steps.
Kili shows a conversation as an agent trace when:
- the project is an
LLM_STATICproject; - its interface has no comparison job;
- the
ASSISTANTitems of each round all have the samemodelName. Two models answering the same round show as a side-by-side model comparison instead.
Creating a project to evaluate your agent
Asking questions at three levels
Each job of the interface has a level, which says what a reviewer answers it about:
completion: one answer per step. Kili shows the job beside eachTOOLandASSISTANTitem, in an Evaluate step #n panel. Use it to find the step that went wrong.round: one answer per user request. For a trace of one request, it is asked once, about the request.conversation: one answer for the whole run. Use it for the outcome: did the agent do what the user asked?
The interface below asks, for each step, whether it is correct and what the agent should have done instead; for the request, whether the agent understood it; and for the run, whether the final answer is correct, and why. Classification and transcription jobs are supported at every level.
interface = {
"jobs": {
"STEP_VERDICT": {
"content": {
"categories": {
"CORRECT": {"children": [], "name": "Correct"},
"MISTAKE": {"children": [], "name": "A mistake"},
},
"input": "radio",
},
"instruction": "This step is",
"level": "completion",
"mlTask": "CLASSIFICATION",
"required": 0,
"isChild": False,
},
"STEP_FIX": {
"content": {"input": "textField"},
"instruction": "What should the agent have done?",
"level": "completion",
"mlTask": "TRANSCRIPTION",
"required": 0,
"isChild": False,
},
"UNDERSTOOD": {
"content": {
"categories": {
"YES": {"children": [], "name": "Yes"},
"NO": {"children": [], "name": "No"},
},
"input": "radio",
},
"instruction": "Did the agent understand the request?",
"level": "round",
"mlTask": "CLASSIFICATION",
"required": 0,
"isChild": False,
},
"OUTCOME": {
"content": {
"categories": {
"YES": {"children": [], "name": "Yes"},
"NO": {"children": [], "name": "No"},
},
"input": "radio",
},
"instruction": "Did the agent answer correctly?",
"level": "conversation",
"mlTask": "CLASSIFICATION",
"required": 1,
"isChild": False,
},
"WHY": {
"content": {"input": "textField"},
"instruction": "Why, in one sentence",
"level": "conversation",
"mlTask": "TRANSCRIPTION",
"required": 0,
"isChild": False,
},
}
}
Tip: If you also import traces by dropping export files in Kili, name each job after the score of your judge it answers: Kili fills the "LLM judge" label with the scores whose name is a job's key or instruction (here, a score named
outcomeanswersOUTCOME).
Now, we create the project with create_project, with type LLM_STATIC:
project = kili.create_project(
title="[Kili SDK Notebook]: Agent traces",
description="Evaluate each step of a bank assistant agent",
input_type="LLM_STATIC",
json_interface=interface,
)
project_id = project["id"]
Turning traces into Kili conversations
Your traces
Whatever records them, traces hold the same things: an id, the request, the steps with their inputs and outputs, the final answer, and often a judge's scores. Here are three runs of a bank assistant, in a neutral shape: replace them with your tracer's export or API.
run-001answers correctly.run-002converts the currency the wrong way: it multiplies by the EUR → USD rate instead of dividing.run-003answers although its tool call failed, and gives a wrong answer.
The judge scored each run (outcome), and the step it found wrong (step_verdict, with the step's id).
SYSTEM_PROMPT = "You are the assistant of a retail bank. Answer from the customer's contract and the tools only."
traces = [
{
"id": "run-001",
"agent": "bank-assistant v3",
"input": "What is my monthly transfer limit? My client id is CM-1042.",
"steps": [
{
"id": "run-001-span-1",
"type": "tool",
"name": "get_customer_contract",
"input": {"client_id": "CM-1042"},
"output": {
"client_id": "CM-1042",
"plan": "Premium",
"monthly_transfer_limit_eur": 5000,
},
},
{
"id": "run-001-span-2",
"type": "llm",
"name": "answer",
"model": "mistral-small-2503",
"output": "Your monthly transfer limit is €5,000, as set by your Premium plan.",
},
],
"scores": [
{"name": "outcome", "value": "yes", "comment": "Quotes the contract's limit."},
],
},
{
"id": "run-002",
"agent": "bank-assistant v3",
"input": "How much is 200 USD in euros?",
"steps": [
{
"id": "run-002-span-1",
"type": "tool",
"name": "get_exchange_rate",
"input": {"base": "EUR", "quote": "USD"},
"output": {"rate": 1.08, "meaning": "1 EUR = 1.08 USD"},
},
{
"id": "run-002-span-2",
"type": "tool",
"name": "calculate",
"input": {"expression": "200 * 1.08"},
"output": 216.0,
},
{
"id": "run-002-span-3",
"type": "llm",
"name": "answer",
"model": "mistral-small-2503",
"output": "200 USD is €216.00.",
},
],
"scores": [
{
"name": "outcome",
"value": "no",
"comment": "200 USD is about €185: it multiplied by the rate instead of dividing.",
},
{"name": "step_verdict", "step_id": "run-002-span-2", "value": "mistake"},
],
},
{
"id": "run-003",
"agent": "bank-assistant v3",
"input": "Can I transfer €8,000 to my landlord today? Client id CM-1042.",
"steps": [
{
"id": "run-003-span-1",
"type": "tool",
"name": "get_customer_contract",
"input": {"client_id": "CM-1042"},
"error": "Timeout after 10 s",
},
{
"id": "run-003-span-2",
"type": "llm",
"name": "answer",
"model": "mistral-small-2503",
"output": "Yes, you can transfer €8,000 today.",
},
],
"scores": [
{"name": "outcome", "value": "no", "comment": "The limit is €5,000 a month."},
{"name": "step_verdict", "step_id": "run-003-span-2", "value": "mistake"},
],
},
]
Where your tracing tool keeps these fields
| In this tutorial | OpenTelemetry (GenAI semantic conventions) | Langfuse | LangSmith | Braintrust |
|---|---|---|---|---|
| a step | a span | an observation | a run | a span |
| an LLM step | gen_ai.operation.name: chat, text_completion or generate_content |
GENERATION |
run_type: llm or chat_model |
span_attributes.type: llm |
| a tool step | gen_ai.operation.name: execute_tool |
TOOL, RETRIEVER |
run_type: tool or retriever |
span_attributes.type: tool |
| the model | gen_ai.response.model |
model |
extra.metadata.ls_model_name |
metadata.model |
| a judge's score | a gen_ai.evaluation.result event |
a score | a feedback | the scores of a span |
| the step a score is on | the span the event is on | the score's observationId |
the feedback's run_id |
the scored span |
Sort the steps by their start time: Kili shows them in the order you send them.
Converting a trace
Each trace becomes one conversation:
externalId: the trace's id. It names the asset in Kili and in the export.chatItems: the system prompt, the request, then one item per step. Each item'sexternalIdmust be unique in its conversation: the step's own id is the best choice, as the export keys each step's answers by it.- A tool step is a
TOOLitem whosecontentis a JSON object with the tool'sname, itsarguments, and itsresult, or itserrorwhen the call failed. Kili shows it as a tool call. Any other content shows as plain text. - An LLM step is an
ASSISTANTitem, with the reply as itscontentand amodelName. Give everyASSISTANTitem of a trace the samemodelName: the model the agent used, or the agent's name when it used several. metadata: anything your reviewers should see. Kili shows it in the labeling interface's information panel, as markdown. Here, it holds the agent, the source, and the judge's scores, so reviewers can check them.
def judge_summary(trace: dict) -> str:
"""The judge's scores as markdown, each step's score naming the step by its number in Kili."""
numbers = {
step["id"]: (number, step["name"]) for number, step in enumerate(trace["steps"], start=1)
}
lines = ["**Judge scores**"]
for score in trace["scores"]:
where = ""
if "step_id" in score:
number, name = numbers[score["step_id"]]
where = f"Step {number} ({name}) · "
comment = f" — {score['comment']}" if score.get("comment") else ""
lines.append(f"- {where}**{score['name']}**: {score['value']}{comment}")
return "\n".join(lines)
def to_kili_conversation(trace: dict) -> dict:
"""A trace as a Kili conversation: the system prompt, the request, then each step in order."""
models = {step["model"] for step in trace["steps"] if step["type"] == "llm"}
model_name = models.pop() if len(models) == 1 else trace["agent"]
chat_items = [
{"externalId": "system", "role": "SYSTEM", "content": SYSTEM_PROMPT},
{"externalId": "user", "role": "USER", "content": trace["input"]},
]
for step in trace["steps"]:
if step["type"] == "tool":
tool_call = {"name": step["name"], "arguments": step["input"]}
if "error" in step:
tool_call["error"] = step["error"]
else:
tool_call["result"] = step["output"]
chat_items.append(
{"externalId": step["id"], "role": "TOOL", "content": json.dumps(tool_call)}
)
else:
chat_items.append(
{
"externalId": step["id"],
"role": "ASSISTANT",
"content": step["output"],
"modelName": model_name,
}
)
return {
"externalId": trace["id"],
"chatItems": chat_items,
"metadata": {
"agent": trace["agent"],
"source": "bank-assistant logs",
"evaluation": judge_summary(trace),
},
}
conversations = [to_kili_conversation(trace) for trace in traces]
print(json.dumps(conversations[1], indent=2, ensure_ascii=False))
{
"externalId": "run-002",
"chatItems": [
{
"externalId": "system",
"role": "SYSTEM",
"content": "You are the assistant of a retail bank. Answer from the customer's contract and the tools only."
},
{
"externalId": "user",
"role": "USER",
"content": "How much is 200 USD in euros?"
},
{
"externalId": "run-002-span-1",
"role": "TOOL",
"content": "{\"name\": \"get_exchange_rate\", \"arguments\": {\"base\": \"EUR\", \"quote\": \"USD\"}, \"result\": {\"rate\": 1.08, \"meaning\": \"1 EUR = 1.08 USD\"}}"
},
{
"externalId": "run-002-span-2",
"role": "TOOL",
"content": "{\"name\": \"calculate\", \"arguments\": {\"expression\": \"200 * 1.08\"}, \"result\": 216.0}"
},
{
"externalId": "run-002-span-3",
"role": "ASSISTANT",
"content": "200 USD is €216.00.",
"modelName": "mistral-small-2503"
}
],
"metadata": {
"agent": "bank-assistant v3",
"source": "bank-assistant logs",
"evaluation": "**Judge scores**\n- **outcome**: no — 200 USD is about €185: it multiplied by the rate instead of dividing.\n- Step 2 (calculate) · **step_verdict**: mistake"
}
}
Importing the conversations
kili.llm.import_conversations creates one asset per conversation. It returns how many were created, and a warning for each conversation it refused, with the reason: for example a TOOL item before any USER item, or two chat items with the same externalId.
result = kili.llm.import_conversations(project_id=project_id, conversations=conversations)
print(result)
{'numberOfUploadedAssets': 3, 'warnings': []}
Reviewing the traces in Kili
Open the project and start labeling. Each trace shows its request, then its steps in order, each tool call with its arguments and its result. Beside each step, the Evaluate step #n panel holds the completion jobs; the round and conversation jobs follow the steps. The judge's scores are in the information panel (ⓘ).
Reviewers then review the labels in the project's workflow, as for any other asset.
Exporting the evaluations
Once your team has labeled the traces, kili.llm.export returns each labeled conversation with its chat items and its latest label. The label holds one key per level:
completion: for each job, the answer on each step, by the step'sexternalId;round: for each job, the answer on each round, by the round's index (0for the first request);conversation: for each job, its answer.
For run-002, reviewed by an expert, it looks like this:
"label": {
"completion": {
"STEP_VERDICT": {
"run-002-span-1": {"categories": ["CORRECT"]},
"run-002-span-2": {"categories": ["MISTAKE"]},
"run-002-span-3": {"categories": ["MISTAKE"]}
},
"STEP_FIX": {
"run-002-span-2": {"text": "Divide by the rate: 200 / 1.08 = 185.19."}
}
},
"conversation": {
"OUTCOME": {"categories": ["NO"]},
"WHY": {"text": "It converted with the rate the wrong way."}
},
"round": {"UNDERSTOOD": {"0": {"categories": ["YES"]}}}
}
exported = kili.llm.export(project_id) or []
print(f"{len(exported)} of {len(conversations)} traces labeled")
Where does the agent fail?
The step answers point at the failing tools and calls. Below, each step marked as a mistake is counted by its name, and each correction written for it is listed.
step_names = {step["id"]: step["name"] for trace in traces for step in trace["steps"]}
mistakes = Counter()
fixes = []
for conversation in exported:
label = conversation["label"]
for step_id, answer in label["completion"].get("STEP_VERDICT", {}).items():
if "MISTAKE" in answer.get("categories", []):
mistakes[step_names.get(step_id, step_id)] += 1
for step_id, answer in label["completion"].get("STEP_FIX", {}).items():
fixes.append((conversation["externalId"], step_names.get(step_id, step_id), answer["text"]))
print("Mistakes by step:", dict(mistakes) or "none labeled yet")
for trace_id, step, fix in fixes:
print(f"- {trace_id}, {step}: {fix}")
Can you trust your judge?
Comparing the judge's outcome with your experts' OUTCOME tells you how often the judge is right, and on which traces it is not.
Tip: Kili can compute this agreement for you, job by job and step by step, and show it in the Queue and Analytics pages: send the judge's scores as an inference label with
kili.append_labels(..., label_type="INFERENCE"). See How to use an LLM as a judge, and measure how far to trust it.
judge_outcomes = {
trace["id"]: score["value"].upper()
for trace in traces
for score in trace["scores"]
if score["name"] == "outcome"
}
agree = 0
for conversation in exported:
human = conversation["label"]["conversation"].get("OUTCOME", {}).get("categories", [None])[0]
judge = judge_outcomes.get(conversation["externalId"])
agree += human == judge
if human != judge:
print(f"{conversation['externalId']}: the judge said {judge}, the reviewer {human}")
if exported:
print(f"The judge agrees with the reviewers on {agree} of {len(exported)} traces")
Cleanup
We can remove the project that we created:
kili.delete_project(project_id)
Summary
In this tutorial, we've:
- Created an
LLM_STATICproject whose jobs evaluate each step of an agent, its understanding of the request, and the outcome of the run. - Converted traces into Kili conversations: the request, then a
TOOLitem per tool call and anASSISTANTitem per LLM reply, in order, with the judge's scores in the metadata. - Imported them with
kili.llm.import_conversations. - Exported the evaluations with
kili.llm.export, to find the failing steps and to measure the judge against the reviewers.