Overview
You finish with a Python agent that runs on your own machine and turns a support email into a validated triage object. Promptfoo grades it on 300 held-out tickets with and without a similar-ticket tool. The scores sit beside a majority baseline and a TF-IDF logistic regression, so the write-up says whether the agent earns its place.
- A
triagepackage whose agent returns a PydanticTriageobject and logs every validation retry to one JSON Lines file per run underlogs/. - Two Promptfoo result files,
results/with-tool.jsonandresults/no-tool.json, scored on the same 300 tickets with named queue and priority metrics. - A results table and a queue confusion matrix image that compare both runs with a majority baseline and a TF-IDF logistic regression.
- Fifty rubric verdicts from a local grader, ten of them checked by hand with your own agree or disagree note.
- A README with the model tag, the seed, the exact Promptfoo commands and the CC BY 4.0 dataset credit.
Tools
- Pydantic AI
Pydantic AI uses the MIT license and is free to use. Model providers, deployment infrastructure and optional Pydantic commercial services have separate terms and costs.
- Ollama
Ollama's runtime uses the MIT license, while model weights have their own licenses. Local execution has no Ollama usage charge; optional cloud inference uses metered credits, subscriptions and enterprise terms.
- Promptfoo
Promptfoo's open-source code is MIT licensed. Its Community plan is free with stated probe allowances; commercial Enterprise and on-premise offerings add features under separate service terms. Model-provider charges and additional enterprise probes can be separate costs.
Datasets
- Customer IT Support - Ticket Dataset Kaggle
Labeled email tickets with queues, priorities and agent answers supply the agent's inputs, the ground truth for grading and the reference replies.
Before you begin
Python 3.11 or newer
Free. Check with python --version; the current pandas, scikit-learn and Pydantic AI releases all require 3.11 or later.
Node.js 22.22 or newer
Free. Promptfoo's npm package requires Node >=22.22.0 and recommends Node 24 LTS. Check with node --version.
Ollama
Free for local use. Model weights carry their own licenses, so read the license on the model page before you publish outputs.
A free Kaggle account
Needed for the kaggle CLI download. You can also download the files from the dataset page in a browser.
A machine with 8 GB of RAM and 6 GB of free disk
The qwen3:4b-instruct model is 2.5 GB. A GPU makes the runs much faster but is optional.
Working knowledge of Python and pandas
You should be comfortable running commands in a terminal and reading a Python traceback.
Stage 01 · setup45 minutes
Set up the project
Create an isolated Python environment and confirm that every tool in the build runs.
Create one folder for the whole build and give it its own virtual environment. Run every Python command from the project root with that environment active.
mkdir ticket-triage && cd ticket-triage
python -m venv .venv
source .venv/bin/activate
mkdir -p triage data/raw tests logs results
touch triage/__init__.pymkdir ticket-triage; cd ticket-triage
python -m venv .venv
.venv\Scripts\Activate.ps1
mkdir triage, data\raw, tests, logs, results
New-Item triage\__init__.py -ItemType FilePin minimum versions that match the current releases. The openai extra of pydantic-ai-slim is the one Pydantic AI documents for Ollama, because Ollama speaks the OpenAI chat format.
pydantic-ai-slim[openai]>=2.77
pandas>=3.0
scikit-learn>=1.9
matplotlib>=3.10
tabulate>=0.9
kaggle>=2.2
sixpython -m pip install --upgrade pip
python -m pip install -r requirements.txt
npm install -g promptfooKeep generated and private files out of Git from the start. The raw Kaggle files are about 61 MB, and the training split can be rebuilt from them with one command.
.venv/
__pycache__/
data/raw/
data/train.csv
logs/smoke.jsonl
results/smoke.json
.envticket-triage/
.gitignore
README.md
requirements.txt
promptfooconfig.yaml # queue and priority suite
rubric.yaml # draft reply rubric on 50 tickets
provider.py # Promptfoo Python provider
writeup.md
triage/
__init__.py
config.py
data.py
schema.py
agent.py
similar.py
export_tests.py
baselines.py
report.py
rubric_check.py
data/
raw/ # Kaggle CSV files, not committed
train.csv
holdout.csv
tests/
holdout.csv # Promptfoo test cases
rubric50.csv
logs/
results/python -c "import pydantic_ai, pandas, sklearn; print(pydantic_ai.__version__, pandas.__version__, sklearn.__version__)"
promptfoo --version
kaggle --versionThe first command prints three version numbers with Pydantic AI at 2.77.0 or later, and promptfoo --version and kaggle --version each print a version instead of an error.
Stage 02 · data45 minutes
Download and split the tickets
Load the Kaggle tickets in pandas, then hold out 300 English tickets with a fixed seed.
Download the dataset into data/raw. The download holds five CSV files, and the code below reads aa_dataset-tickets-multi-lang-5-2-50-version.csv, the 26 MB file in the current version.
kaggle datasets download tobiasbueck/multilingual-customer-support-tickets -p data/raw --unzipInspect the columns before you trust any name in the code. Look for the ticket text, the queue label, the priority label and the agent answer, and check which languages the file holds.
python -c "import pandas as pd; df = pd.read_csv('data/raw/aa_dataset-tickets-multi-lang-5-2-50-version.csv'); print(df.columns.tolist()); print(df['language'].value_counts()); print(df[['queue', 'priority']].isna().sum())"['subject', 'body', 'answer', 'type', 'queue', 'priority', 'language', 'version', 'tag_1', ..., 'tag_8'] language en <count> de <count> Name: count, dtype: int64 queue <missing> priority <missing> dtype: int64
Put every path and setting in one module so the seed and the model tag live in a single place. The README later quotes these values.
"""Paths and run settings shared by every script."""
import os
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DATA = ROOT / "data"
RAW_CSV = DATA / "raw" / "aa_dataset-tickets-multi-lang-5-2-50-version.csv"
TRAIN_CSV = DATA / "train.csv"
HOLDOUT_CSV = DATA / "holdout.csv"
TESTS_DIR = ROOT / "tests"
RESULTS = ROOT / "results"
LOGS = ROOT / "logs"
SEED = 20261128
HOLDOUT_SIZE = 300
LANGUAGE = "en"
MODEL = os.environ.get("TRIAGE_MODEL", "qwen3:4b-instruct")
OLLAMA_URL = os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434/v1")The split keeps one language, drops rows without a queue or priority label and holds out 300 tickets with random_state=SEED. The bodies store line breaks as the two characters \n, so the cleaner turns them back into real line breaks.
"""Filter the Kaggle tickets to one language and hold out a fixed test set."""
import pandas as pd
from .config import HOLDOUT_CSV, HOLDOUT_SIZE, LANGUAGE, RAW_CSV, SEED, TRAIN_CSV
COLUMNS = ["subject", "body", "answer", "queue", "priority", "language"]
def load_raw() -> pd.DataFrame:
df = pd.read_csv(RAW_CSV)
missing = [c for c in COLUMNS if c not in df.columns]
if missing:
raise SystemExit(f"Missing columns {missing}; found {list(df.columns)}")
return df[COLUMNS]
def clean(df: pd.DataFrame) -> pd.DataFrame:
df = df[df["language"] == LANGUAGE]
df = df.dropna(subset=["body", "queue", "priority"])
df = df.drop_duplicates(subset=["body"])
df = df.assign(
subject=df["subject"].fillna("").str.replace("\\n", "\n", regex=False),
answer=df["answer"].fillna("").str.replace("\\n", "\n", regex=False),
body=df["body"].str.replace("\\n", "\n", regex=False),
)
df = df.reset_index(drop=True)
df.insert(0, "ticket_id", [f"{LANGUAGE}-{i:05d}" for i in range(len(df))])
df["text"] = (df["subject"] + "\n\n" + df["body"]).str.strip()
return df
def split(df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
holdout = df.sample(n=HOLDOUT_SIZE, random_state=SEED)
train = df.drop(index=holdout.index)
return train, holdout
if __name__ == "__main__":
tickets = clean(load_raw())
train, holdout = split(tickets)
train.to_csv(TRAIN_CSV, index=False)
holdout.to_csv(HOLDOUT_CSV, index=False)
print(f"kept {len(tickets)} {LANGUAGE} tickets")
print(f"train {len(train)} holdout {len(holdout)} seed {SEED}")
print(holdout["queue"].value_counts().to_string())python -m triage.datakept <n> en tickets train <n - 300> holdout 300 seed 20261128 queue Technical Support <count> Product Support <count> ...
data/train.csv and data/holdout.csv exist, the script reports holdout 300, and running it a second time prints the same queue counts.
Stage 03 · build30 minutes
Serve a local model with Ollama
Pull a small tool-calling model into Ollama and confirm the local API answers.
Install Ollama from its download page or with the official script. On Windows and macOS the desktop app runs the server at http://localhost:11434; on Linux, run ollama serve if the installer did not start a service.
curl -fsSL https://ollama.com/install.sh | shirm https://ollama.com/install.ps1 | iexPull qwen3:4b-instruct, a 2.5 GB build of Qwen3 that answers without a separate thinking pass. The Qwen3 family is listed with tool support, which the agent needs because Pydantic AI returns structured output through a tool call by default.
ollama pull qwen3:4b-instruct
ollama ls
ollama --versionSend one request to the OpenAI-compatible endpoint that Pydantic AI will call. A reply here rules out port and model-name problems before any Python is involved.
curl http://localhost:11434/v1/chat/completions -H "Content-Type: application/json" -d '{"model": "qwen3:4b-instruct", "seed": 1, "messages": [{"role": "user", "content": "Reply with the word ready."}]}'$body = @{ model = 'qwen3:4b-instruct'; seed = 1; messages = @(@{ role = 'user'; content = 'Reply with the word ready.' }) } | ConvertTo-Json -Depth 4
Invoke-RestMethod -Uri http://localhost:11434/v1/chat/completions -Method Post -ContentType 'application/json' -Body $bodyollama ls lists qwen3:4b-instruct, and the test request returns JSON whose choices[0].message.content holds a short reply.
Stage 04 · build30 minutes
Define the typed output
Build a Pydantic model whose queue and priority fields only accept labels from the training split.
Build the enums from data/train.csv instead of typing the labels by hand. A label that never appears in training cannot be predicted, and a typo in a hand-written list would fail without any warning.
"""Output model whose label fields only accept labels seen in the training split."""
from enum import Enum
import pandas as pd
from pydantic import BaseModel, Field
from .config import TRAIN_CSV
def _enum(name: str, column: str) -> type[Enum]:
labels = sorted(pd.read_csv(TRAIN_CSV, usecols=[column])[column].unique())
members = {label.upper().replace(" ", "_").replace("-", "_"): label for label in labels}
return Enum(name, members, type=str)
Queue = _enum("Queue", "queue")
Priority = _enum("Priority", "priority")
class Triage(BaseModel):
queue: Queue = Field(description="The team that should own this ticket.")
priority: Priority = Field(description="How urgent the ticket is.")
reply: str = Field(min_length=40, description="A short first reply to the customer.")
if __name__ == "__main__":
import json
print(json.dumps(Triage.model_json_schema(), indent=2))The reply field has a 40-character minimum so an empty or one-word draft fails validation and triggers a retry. Pydantic AI sends this schema to the model as the parameters of its output tool, so the enum values reach the model as the allowed choices.
python -m triage.schemaThe printed JSON schema has a Queue definition with ten enum values and a Priority definition listing high, low and medium.
Stage 05 · build1 hour 15 minutes
Write the agent and log retries
Call the Ollama model through Pydantic AI and log every validation retry.
Create the agent with OllamaModel and OllamaProvider, the Ollama classes Pydantic AI documents for a self-hosted server. The ticket text goes in as the user prompt and also as deps, so the tool added later can read it without asking the model to copy it.
"""Pydantic AI agent that triages one ticket and logs every validation retry."""
import json
import time
from datetime import datetime, timezone
from pydantic_ai import Agent, capture_run_messages
from pydantic_ai.exceptions import UnexpectedModelBehavior
from pydantic_ai.messages import ModelRequest
from pydantic_ai.models.ollama import OllamaModel
from pydantic_ai.providers.ollama import OllamaProvider
from .config import LOGS, MODEL, OLLAMA_URL, SEED
from .schema import Triage
INSTRUCTIONS = (
"You triage customer support emails for an IT helpdesk. "
"Choose the queue that should own the ticket and its priority, using only the allowed values. "
"Write a short, polite first reply that names the next step for the customer."
)
TOOL_INSTRUCTIONS = (
" Call similar_tickets once before you answer. "
"It returns past tickets with their correct queue and priority, which you should weigh as evidence."
)
def build_agent(use_tool: bool, model=None) -> Agent[str, Triage]:
model = model or OllamaModel(MODEL, provider=OllamaProvider(base_url=OLLAMA_URL))
agent = Agent(
model,
deps_type=str,
output_type=Triage,
instructions=INSTRUCTIONS + (TOOL_INSTRUCTIONS if use_tool else ""),
retries={"output": 1, "tools": 1},
model_settings={"temperature": 0.0, "seed": SEED},
)
if use_tool:
from .similar import add_similar_tool
add_similar_tool(agent)
return agent
retries={'output': 1} gives the model one more attempt after a response fails validation, and 'tools': 1 does the same for tool calls. Temperature 0 and a fixed seed make repeated runs on the same hardware as close to deterministic as Ollama allows.
Append the logging runner to the same file. It wraps the run in capture_run_messages() so the retry history survives when the second attempt also fails and Pydantic AI raises UnexpectedModelBehavior.
def _retries(messages) -> list[dict]:
"""Collect every part that asked the model to try again, with its cause."""
found = []
for message in messages:
if not isinstance(message, ModelRequest):
continue
for part in message.parts:
retry = getattr(part, "retry", None)
if retry is not None:
found.append({"tool": getattr(part, "tool_name", None), "cause": retry.cause,
"attempt": retry.attempt, "detail": str(part.content)[:500]})
return found
def triage_ticket(agent: Agent[str, Triage], text: str, ticket_id: str, run_name: str) -> dict:
"""Run the agent on one ticket and append a JSON line to logs/<run_name>.jsonl."""
started = time.perf_counter()
record = {"ticket_id": ticket_id, "run": run_name, "model": MODEL,
"at": datetime.now(timezone.utc).isoformat()}
with capture_run_messages() as messages:
try:
result = agent.run_sync(text, deps=text)
record |= {"ok": True, "output": result.output.model_dump(mode="json")}
except UnexpectedModelBehavior as exc:
record |= {"ok": False, "error": str(exc)}
retries = _retries(messages)
record |= {"retries": len(retries), "retry_messages": retries,
"seconds": round(time.perf_counter() - started, 2)}
LOGS.mkdir(exist_ok=True)
with open(LOGS / f"{run_name}.jsonl", "a", encoding="utf-8") as log:
log.write(json.dumps(record, ensure_ascii=False) + "\n")
return record
if __name__ == "__main__":
import sys
import pandas as pd
from .config import HOLDOUT_CSV
use_tool = "--no-tool" not in sys.argv
ticket = pd.read_csv(HOLDOUT_CSV, keep_default_na=False).iloc[0]
record = triage_ticket(build_agent(use_tool), ticket.text, ticket.ticket_id, "smoke")
print(json.dumps(record, indent=2, ensure_ascii=False))
print("label:", ticket.queue, "/", ticket.priority)Run the agent on the first held-out ticket without the tool. The --no-tool flag matters here, because triage/similar.py does not exist yet.
python -m triage.agent --no-tool{
"ticket_id": "en-<id>",
"run": "smoke",
"model": "qwen3:4b-instruct",
"at": "<timestamp>",
"ok": true,
"output": {
"queue": "<queue>",
"priority": "<priority>",
"reply": "<draft reply>"
},
"retries": <0 or 1>,
"retry_messages": [<cause, attempt and error detail per retry>],
"seconds": <seconds>
}
label: <true queue> / <true priority>The command prints a record with "ok": true, and logs/smoke.jsonl gains one line with a retries count and a retry_messages list.
Stage 06 · build45 minutes
Add the similar-ticket tool
Give the agent a TF-IDF tool that returns the three closest training tickets with their labels.
Fit a TF-IDF vectorizer on the training tickets once, when the agent is built. TfidfVectorizer scales each row to unit length by default, so linear_kernel gives cosine similarity without a second normalisation step.
"""TF-IDF nearest neighbours over the training split."""
import pandas as pd
from pydantic_ai import Agent, RunContext
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
class SimilarTickets:
def __init__(self, train: pd.DataFrame):
self.train = train.reset_index(drop=True)
self.vectorizer = TfidfVectorizer(sublinear_tf=True, ngram_range=(1, 2), min_df=2, stop_words="english")
self.matrix = self.vectorizer.fit_transform(self.train["text"])
@classmethod
def from_csv(cls, path) -> "SimilarTickets":
return cls(pd.read_csv(path, keep_default_na=False))
def search(self, text: str, k: int = 3) -> list[dict]:
scores = linear_kernel(self.vectorizer.transform([text]), self.matrix).ravel()
best = scores.argsort()[::-1][:k]
rows = self.train.iloc[best]
return [
{
"subject": row.subject,
"body": row.body[:500],
"queue": row.queue,
"priority": row.priority,
"similarity": round(float(scores[i]), 3),
}
for i, row in zip(best, rows.itertuples())
]
def add_similar_tool(agent: Agent) -> None:
"""Register a tool that looks up the current ticket (the run's deps) in the training split."""
from .config import TRAIN_CSV
index = SimilarTickets.from_csv(TRAIN_CSV)
@agent.tool
def similar_tickets(ctx: RunContext[str]) -> list[dict]:
"""Return the three most similar past tickets with their queue and priority labels."""
return index.search(ctx.deps, k=3)
if __name__ == "__main__":
from .config import HOLDOUT_CSV, TRAIN_CSV
index = SimilarTickets.from_csv(TRAIN_CSV)
ticket = pd.read_csv(HOLDOUT_CSV, keep_default_na=False).iloc[0]
print("ticket:", ticket.queue, "/", ticket.priority, "|", ticket.subject)
for hit in index.search(ticket.text):
print(hit["similarity"], hit["queue"], "/", hit["priority"], "|", hit["subject"])The tool takes no arguments from the model. It reads the ticket from ctx.deps, which keeps a small model from shortening or rewriting the query before the lookup.
python -m triage.similarticket: <queue> / <priority> | <subject> <similarity> <queue> / <priority> | <subject> <similarity> <queue> / <priority> | <subject> <similarity> <queue> / <priority> | <subject>
python -m triage.agentpython -m triage.similar prints the held-out ticket and three neighbours with similarity scores, and python -m triage.agent without --no-tool returns "ok": true.
Stage 07 · test2 hours
Grade both runs with Promptfoo
Export the held-out tickets as test cases and score queue and priority with and without the tool.
Write the 300 held-out tickets as a Promptfoo CSV, where each column becomes a test variable. The same script writes the first 50 rows to a second file for the rubric stage.
"""Write the held-out tickets as Promptfoo test files."""
import pandas as pd
from .config import HOLDOUT_CSV, TESTS_DIR
FIELDS = ["ticket_id", "subject", "body", "queue", "priority", "answer"]
if __name__ == "__main__":
holdout = pd.read_csv(HOLDOUT_CSV, keep_default_na=False)[FIELDS]
TESTS_DIR.mkdir(exist_ok=True)
holdout.to_csv(TESTS_DIR / "holdout.csv", index=False)
holdout.head(50).to_csv(TESTS_DIR / "rubric50.csv", index=False)
print(f"wrote {len(holdout)} tests to tests/holdout.csv and 50 to tests/rubric50.csv")python -m triage.export_testsPromptfoo loads provider.py once per worker and calls call_api(prompt, options, context) for each test. The provider reads its config block to choose the tool setting, then returns the validated object as a JSON string or an error.
"""Promptfoo Python provider that runs the triage agent on one test case."""
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from triage.agent import build_agent, triage_ticket # noqa: E402
_agents = {}
def call_api(prompt, options, context):
config = options.get("config", {})
use_tool = bool(config.get("use_tool", True))
if use_tool not in _agents:
_agents[use_tool] = build_agent(use_tool)
ticket_id = context["vars"]["ticket_id"]
record = triage_ticket(_agents[use_tool], prompt, ticket_id, config.get("run_name", "promptfoo"))
if not record["ok"]:
return {"error": f"{ticket_id}: {record['error']} after {record['retries']} retries"}
return {"output": json.dumps(record["output"]), "latencyMs": int(record["seconds"] * 1000)}Both providers point at the same file and differ only by label and config. Each equals assertion picks one field out of the JSON with transform, compares it with the label from the test row, and adds to a named metric.
# yaml-language-server: $schema=https://promptfoo.dev/config-schema.json
description: Ticket triage on 300 held-out English tickets
prompts:
- "Subject: {{subject}}\n\n{{body}}"
providers:
- id: file://provider.py
label: with-tool
config:
use_tool: true
run_name: with-tool
- id: file://provider.py
label: no-tool
config:
use_tool: false
run_name: no-tool
tests: file://tests/holdout.csv
defaultTest:
assert:
- type: equals
value: "{{queue}}"
transform: JSON.parse(output).queue
metric: queue_accuracy
- type: equals
value: "{{priority}}"
transform: JSON.parse(output).priority
metric: priority_accuracyTell Promptfoo which interpreter to use, since the default search may find a system Python without your packages. Set the variable in the same shell where you run promptfoo eval.
export PROMPTFOO_PYTHON="$PWD/.venv/bin/python"$env:PROMPTFOO_PYTHON = "$PWD\.venv\Scripts\python.exe"Run five tickets first to catch configuration errors in seconds rather than hours. Then run each provider on all 300 tickets, one at a time, with the cache off so every call reaches the model.
promptfoo eval -c promptfooconfig.yaml --filter-providers with-tool -n 5 -j 1 --no-cache -o results/smoke.json
promptfoo eval -c promptfooconfig.yaml --filter-providers with-tool -j 1 --no-cache -o results/with-tool.json
promptfoo eval -c promptfooconfig.yaml --filter-providers no-tool -j 1 --no-cache -o results/no-tool.jsonResults: <n> passed (<pass rate>%) <n> failed (<fail rate>%) <n> errors (<error rate>%) Duration: <duration> (concurrency: 1) Writing output to results/with-tool.json
results/with-tool.json and results/no-tool.json both exist, each run reports 300 tests, and logs/with-tool.jsonl and logs/no-tool.jsonl hold a line for every ticket with its retry count. The report keeps the last line per ticket, so the smoke run does no harm.
Stage 08 · test1 hour
Score against the baselines
Compare both runs with the baselines and save a queue confusion matrix beside the results.
Train the two baselines on the same split the agent saw. The majority class sets the floor, and a TF-IDF logistic regression is the bar the agent has to clear on queue macro F1.
"""Majority-class and TF-IDF logistic regression baselines on the same split."""
import json
import pandas as pd
from sklearn.dummy import DummyClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score
from sklearn.pipeline import make_pipeline
from .config import HOLDOUT_CSV, RESULTS, SEED, TRAIN_CSV
def score(y_true, y_pred) -> dict:
return {"accuracy": round(accuracy_score(y_true, y_pred), 4),
"macro_f1": round(f1_score(y_true, y_pred, average="macro", zero_division=0), 4)}
def main() -> None:
train = pd.read_csv(TRAIN_CSV, keep_default_na=False)
holdout = pd.read_csv(HOLDOUT_CSV, keep_default_na=False)
models = {
"majority": DummyClassifier(strategy="most_frequent"),
"tfidf_logreg": make_pipeline(
TfidfVectorizer(sublinear_tf=True, ngram_range=(1, 2), min_df=2, stop_words="english"),
LogisticRegression(max_iter=2000, class_weight="balanced", random_state=SEED),
),
}
report = {}
for name, model in models.items():
report[name] = {}
for target in ("queue", "priority"):
model.fit(train["text"], train[target])
report[name][target] = score(holdout[target], model.predict(holdout["text"]))
RESULTS.mkdir(exist_ok=True)
(RESULTS / "baselines.json").write_text(json.dumps(report, indent=2))
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()python -m triage.baselinesThe report reads the Promptfoo result files, so its numbers come from the same 300 graded outputs. It also reads the agent logs to count valid objects and retries, and it treats a ticket with no valid output as wrong.
"""Score both Promptfoo runs, draw the queue confusion matrix and list top confusions."""
import json
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
import pandas as pd # noqa: E402
from sklearn.metrics import ConfusionMatrixDisplay, accuracy_score, f1_score # noqa: E402
from .config import HOLDOUT_CSV, LOGS, RESULTS # noqa: E402
RUNS = ["with-tool", "no-tool"]
INVALID = "(no valid output)"
def load_run(name: str) -> pd.DataFrame:
data = json.loads((RESULTS / f"{name}.json").read_text(encoding="utf-8"))
rows = []
for row in data["results"]["results"]:
output = (row.get("response") or {}).get("output")
parsed = json.loads(output) if output else {}
named = row.get("namedScores") or {}
rows.append({"ticket_id": row["vars"]["ticket_id"],
"pred_queue": parsed.get("queue", INVALID),
"pred_priority": parsed.get("priority", INVALID),
"pf_queue": named.get("queue_accuracy", 0),
"pf_priority": named.get("priority_accuracy", 0)})
return pd.DataFrame(rows)
def retry_stats(name: str) -> dict:
log = pd.read_json(LOGS / f"{name}.jsonl", lines=True).drop_duplicates("ticket_id", keep="last")
return {"valid": int(log["ok"].sum()), "tickets_with_retry": int((log["retries"] > 0).sum()),
"retries": int(log["retries"].sum()), "mean_seconds": round(float(log["seconds"].mean()), 2)}
def confusion_plot(df: pd.DataFrame, name: str) -> None:
labels = sorted(df["queue"].unique()) + ([INVALID] if (df["pred_queue"] == INVALID).any() else [])
fig, ax = plt.subplots(figsize=(10, 9))
ConfusionMatrixDisplay.from_predictions(df["queue"], df["pred_queue"], labels=labels,
xticks_rotation="vertical", ax=ax, colorbar=False)
ax.set_title(f"Queue confusion, {name}, {len(df)} held-out tickets")
fig.tight_layout()
fig.savefig(RESULTS / f"confusion_queue_{name}.png", dpi=150)
plt.close(fig)
def top_confusions(df: pd.DataFrame, n: int = 5) -> pd.DataFrame:
wrong = df[df["queue"] != df["pred_queue"]]
pairs = wrong.groupby(["queue", "pred_queue"]).size().rename("count").reset_index()
pairs = pairs.sort_values("count", ascending=False).head(n)
examples = wrong.drop_duplicates(["queue", "pred_queue"])[["queue", "pred_queue", "ticket_id", "subject"]]
return pairs.merge(examples, on=["queue", "pred_queue"])
def main() -> None:
holdout = pd.read_csv(HOLDOUT_CSV, keep_default_na=False)
baselines = json.loads((RESULTS / "baselines.json").read_text())
table = []
for name in RUNS:
df = holdout.merge(load_run(name), on="ticket_id", how="left").fillna({"pred_queue": INVALID, "pred_priority": INVALID, "pf_queue": 0, "pf_priority": 0})
confusion_plot(df, name)
top_confusions(df).to_csv(RESULTS / f"top_confusions_{name}.csv", index=False)
table.append({"run": name, **retry_stats(name),
"queue_acc": accuracy_score(df["queue"], df["pred_queue"]),
"queue_macro_f1": f1_score(df["queue"], df["pred_queue"], average="macro", zero_division=0),
"priority_acc": accuracy_score(df["priority"], df["pred_priority"]),
"promptfoo_queue_acc": df["pf_queue"].mean(),
"promptfoo_priority_acc": df["pf_priority"].mean()})
for name, scores in baselines.items():
table.append({"run": name, "queue_acc": scores["queue"]["accuracy"],
"queue_macro_f1": scores["queue"]["macro_f1"],
"priority_acc": scores["priority"]["accuracy"]})
out = pd.DataFrame(table).round(3)
(RESULTS / "results.md").write_text(out.to_markdown(index=False) + "\n", encoding="utf-8")
print(out.to_string(index=False))
f1 = out.set_index("run")["queue_macro_f1"]
for name in RUNS:
verdict = "beats" if f1[name] > f1["tfidf_logreg"] else "does not beat"
print(f"{name} {verdict} the TF-IDF logistic regression on queue macro F1")
if __name__ == "__main__":
main()python -m triage.report run valid tickets_with_retry retries mean_seconds queue_acc queue_macro_f1 priority_acc promptfoo_queue_acc promptfoo_priority_acc
with-tool <295+> <n> <n> <s> <acc> <f1> <acc> <acc> <acc>
no-tool <295+> <n> <n> <s> <acc> <f1> <acc> <acc> <acc>
majority NaN ... <acc> <f1> <acc> NaN NaN
tfidf_logreg NaN ... <acc> <f1> <acc> NaN NaN
with-tool <beats or does not beat> the TF-IDF logistic regression on queue macro F1
no-tool <beats or does not beat> the TF-IDF logistic regression on queue macro F1Check that queue_acc equals promptfoo_queue_acc for each run. A mismatch means a ticket id was lost between the test file and the result file, and the table cannot be trusted until you find it.
Write writeup.md from results/top_confusions_with-tool.csv, which lists the five most frequent true and predicted queue pairs with one example ticket each. Open each example in data/holdout.csv and say in a few sentences why the agent's choice was wrong or defensible.
# Five most frequent queue confusions (with-tool run)
| True queue | Predicted queue | Count | Example ticket |
| --- | --- | --- | --- |
| <queue> | <pred_queue> | <count> | `<ticket_id>`: <subject> |
## <true queue> read as <predicted queue>
<Two or three sentences: what the example ticket asks for, why the agent's
choice is plausible or wrong, and whether the similar-ticket tool changed it.>
results/results.md holds four rows, results/confusion_queue_with-tool.png and results/confusion_queue_no-tool.png open as images beside it, and the last two printed lines say whether each run beats the logistic regression.
Stage 09 · test1 hour
Grade draft replies with a rubric
Score 50 draft replies against the dataset's agent answers with a local grader, then check ten verdicts yourself.
The rubric suite reuses the provider with the tool on and runs only the 50 tickets in tests/rubric50.csv. The grader is the same Ollama model, set under defaultTest.options.provider, and {{answer}} places each reference reply into the rubric.
# yaml-language-server: $schema=https://promptfoo.dev/config-schema.json
description: Draft replies graded against the dataset's agent answers
prompts:
- "Subject: {{subject}}\n\n{{body}}"
providers:
- id: file://provider.py
label: with-tool
config:
use_tool: true
run_name: rubric
tests: file://tests/rubric50.csv
defaultTest:
options:
provider:
text:
id: ollama:chat:qwen3:4b-instruct
config:
temperature: 0
assert:
- type: llm-rubric
transform: JSON.parse(output).reply
metric: reply_rubric
value: |
The output is a draft first reply to a customer support email.
A human support agent sent this reference reply to the same email:
{{answer}}
Pass the draft if it addresses the same problem as the reference and offers a next step that the reference does not contradict.
Fail the draft if it ignores the customer's issue, invents a fix the reference rules out, or asks for passwords or other secrets.promptfoo eval -c rubric.yaml -j 1 --no-cache -o results/rubric.json
python -m triage.rubric_check"""Pull rubric verdicts out of results/rubric.json and sample ten for a hand check."""
import json
import pandas as pd
from .config import HOLDOUT_CSV, RESULTS, SEED
if __name__ == "__main__":
data = json.loads((RESULTS / "rubric.json").read_text(encoding="utf-8"))
holdout = pd.read_csv(HOLDOUT_CSV, keep_default_na=False).set_index("ticket_id")
rows = []
for row in data["results"]["results"]:
output = (row.get("response") or {}).get("output")
draft = json.loads(output)["reply"] if output else ""
for part in (row.get("gradingResult") or {}).get("componentResults", []):
if part["assertion"]["type"] == "llm-rubric":
ticket_id = row["vars"]["ticket_id"]
rows.append({"ticket_id": ticket_id, "grader_pass": part["pass"], "grader_score": part["score"],
"grader_reason": part["reason"], "subject": holdout.loc[ticket_id, "subject"],
"draft_reply": draft, "reference_answer": holdout.loc[ticket_id, "answer"]})
verdicts = pd.DataFrame(rows)
verdicts.to_csv(RESULTS / "rubric_verdicts.csv", index=False)
sample = verdicts.sample(n=min(10, len(verdicts)), random_state=SEED).assign(i_agree="", note="")
sample.to_csv(RESULTS / "rubric_check.csv", index=False)
print(f"{len(verdicts)} verdicts, {int(verdicts['grader_pass'].sum())} passed")
print("fill in i_agree (yes or no) and note for each row of results/rubric_check.csv")50 verdicts, <n> passed fill in i_agree (yes or no) and note for each row of results/rubric_check.csv
Open results/rubric_check.csv in a spreadsheet or editor and read each draft beside its reference answer before you read the grader's reason. Write yes or no in i_agree and one sentence in note saying what the grader got right or missed.
results/rubric_verdicts.csv has 50 rows, and results/rubric_check.csv has 10 rows with i_agree and note filled in by you.
Stage 10 · ship30 minutes
Write the README and publish
Write a README that pins the model and seed, then publish the repository.
Copy the model ID from ollama ls and the version from ollama --version into the README. The tag alone can point at different weights after an update, while the ID pins the build you graded.
# Ticket triage agent on Ollama, graded with Promptfoo
A Pydantic AI agent reads an English support email and returns a validated queue, priority and draft reply.
Promptfoo scores queue and priority against the dataset labels on 300 held-out tickets.
## Reproduce
| Setting | Value |
| --- | --- |
| Ollama model | `qwen3:4b-instruct` (ID from `ollama ls`: `<model id>`) |
| Ollama version | `<output of ollama --version>` |
| Random seed | `20261128` (split, logistic regression and model requests) |
| Held-out tickets | 300 English tickets in `tests/holdout.csv` |
```
python -m triage.data
python -m triage.export_tests
promptfoo eval -c promptfooconfig.yaml --filter-providers with-tool -j 1 --no-cache -o results/with-tool.json
promptfoo eval -c promptfooconfig.yaml --filter-providers no-tool -j 1 --no-cache -o results/no-tool.json
promptfoo eval -c rubric.yaml -j 1 --no-cache -o results/rubric.json
python -m triage.baselines
python -m triage.report
python -m triage.rubric_check
```
## Results
See `results/results.md`, `results/confusion_queue_with-tool.png` and `writeup.md`.
Hand-checked rubric verdicts are in `results/rubric_check.csv`.
## Data credit
Tickets come from "Customer IT Support - Ticket Dataset" by Tobias Bueck on Kaggle
(https://www.kaggle.com/datasets/tobiasbueck/multilingual-customer-support-tickets),
licensed CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/).
Changes: kept English rows from `aa_dataset-tickets-multi-lang-5-2-50-version.csv`,
dropped rows missing a body, queue or priority, removed duplicate bodies, replaced
escaped `\n` with line breaks and drew a 300-ticket held-out sample with seed 20261128.
Stage the files by name so the raw Kaggle download and the training split stay out of the commit. git status --short should show no file under data/raw/ before you commit.
git init
git status --short
git add README.md writeup.md requirements.txt .gitignore promptfooconfig.yaml rubric.yaml provider.py triage tests data/holdout.csv logs/with-tool.jsonl logs/no-tool.jsonl logs/rubric.jsonl results
git commit -m "Ticket triage agent with Promptfoo results"A fresh clone holds the agent package, both Promptfoo configs, tests/holdout.csv, the result files and the confusion matrix image, and its README names qwen3:4b-instruct, seed 20261128 and the exact promptfoo eval commands.
Troubleshooting
Connection refused or ConnectError when the agent or the curl test calls localhost:11434.
Start the Ollama desktop app, or run ollama serve in a separate terminal on Linux. If Ollama listens on another address, set OLLAMA_BASE_URL to that address with /v1 at the end.
The API answers with a 404 and a message that the model is not found.
The tag in TRIAGE_MODEL or rubric.yaml must match ollama ls exactly. Run ollama pull qwen3:4b-instruct and check the spelling of the tag.
Many log lines show Exceeded maximum output retries (1) and valid drops below 295.
Read retry_messages for those tickets. Enum errors usually mean the model invented a queue name, so move to qwen3:8b; replies that never call a tool mean the model lacks tool support.
Promptfoo fails at provider start-up with ModuleNotFoundError: No module named 'pydantic_ai' or Python 3 not found.
Promptfoo picked a Python outside your virtual environment. Set PROMPTFOO_PYTHON to the full path of .venv/bin/python or .venv\Scripts\python.exe in the shell that runs promptfoo eval.
Promptfoo reports a provider timeout on slow tickets.
The Python provider times out after 5 minutes by default. Add timeout: 600000 under each provider's config in promptfooconfig.yaml, or use a smaller model.
The machine swaps heavily or Ollama reports that it is out of memory.
Close other large programs and keep -j 1. On 8 GB machines, qwen3:1.7b at 1.4 GB fits more easily, at some cost in accuracy.
kaggle datasets download returns 401 or 403.
Run kaggle auth login or set KAGGLE_API_TOKEN from your Kaggle settings page. You can also download the files from the dataset page in a browser and unzip them into data/raw.
python -m triage.data stops with Missing columns.
The dataset owner has changed the file. Compare the printed column list with COLUMNS in triage/data.py, and update RAW_CSV or the names to match.
Done when
- The agent returns a validated object for at least 295 of the 300 held-out tickets, and the log records every validation retry.
- Promptfoo reports queue accuracy and priority accuracy for both runs on the same 300 tickets.
- A confusion matrix of queue labels is saved as an image beside the results.
- The README lists the Ollama model name and tag, the random seed and the exact Promptfoo command.
- Ten hand-checked rubric verdicts are recorded with a note on whether you agree with each one.
Deliverables
- A repository with the agent package, the Promptfoo config and the held-out test file, crediting the dataset as its license requires.
- A results table comparing the runs with and without the similar-ticket tool.
- A short write-up of the five most frequent queue confusions with an example ticket for each.
How to measure it
Queue accuracy and macro F1 on the 300 held-out tickets, compared against a majority-class baseline and a TF-IDF logistic regression trained on the same split. The agent earns its place only if it beats the logistic regression on macro F1.
Going further
- Switch the output to
NativeOutput(Triage)so Ollama enforces the JSON schema, then compare the share of valid objects and the retry count with the tool-call output mode. - Add a confidence route: when the three neighbours disagree on the queue, send the ticket to a human review queue and measure how much accuracy rises on the rest.
- Score priority errors by cost, counting a
highticket markedlowas worse than the reverse, and report that weighted error beside plain accuracy. - Run the suite in CI with
promptfoo eval -n 20against a pinned model so a prompt change that drops queue accuracy fails the build.
Bounty stretch goals
- Run Promptfoo's red-team plugins with tickets that try to talk the agent into a different queue, and report how many succeed.
- Swap in a second local model and compare accuracy against seconds per ticket on the same hardware.
- Repeat the evaluation on a second language from the dataset and report whether the similar-ticket tool helps more or less.
References
- Kaggle dataset metadata: Customer IT Support - Ticket Dataset
- Kaggle CLI README
- Kaggle CLI datasets commands
- Pydantic AI: Ollama models
- Pydantic AI: Output
- Pydantic AI: Function tools
- Pydantic AI: Agents
- Ollama download
- Ollama CLI reference
- Ollama OpenAI compatibility
- Ollama qwen3 tags
- Promptfoo installation
- Promptfoo Python provider
- Promptfoo Ollama provider
- Promptfoo test cases and CSV format
- Promptfoo assertions and metrics
- Promptfoo llm-rubric
- Promptfoo command line
- scikit-learn TfidfVectorizer
- scikit-learn ConfusionMatrixDisplay
Reporting behind this quest
- Pydantic AI puts typed boundaries around agent work 2026-11-26 · source
- Promptfoo keeps application security tests close to development 2026-11-26 · source
- Ollama makes model serving part of the developer workstation 2026-11-26 · source
- Hugging Face publishes a guide to agent evaluation 2026-11-23 · source
An AI guide writer drafted this walkthrough against the official documentation above, automated template and style checks validated every block, and an independent AI reviewer verified commands, flags and claims before publication.
