# Make Your Own AI Benchmark from Your Own Logs

Build a small AI benchmark from your own request logs: scrub personal data, cluster tasks with TF-IDF and k-means, sample cases, grade and track results.

Author: Steven Phan
Published: 2026-11-12
Article: https://stevenphan.ca/blog/build-your-own-benchmark-from-your-logs/

A custom AI benchmark built from your own request logs tells you more about your work than a public leaderboard can, because the questions come from the tasks you actually run. The recipe is short: export a slice of your logs, scrub personal data and secrets, group the requests into task types, sample a few cases from each group, write a grader per group, keep a held-out split, and rerun the whole thing whenever something changes.

We'll build that pipeline in Python with a log file that is entirely synthetic. A script we wrote generates it with a fixed seed, so there is no real user data anywhere in this post. The model being graded is a stub as well, so the pass rates show the pipeline working, not how any real model performs.

## Quick answer

Export a time slice of requests, remove everything personal before anyone else sees it, and cluster the text with TF-IDF and k-means to find your task types. Sample a capped number of cases per cluster so one busy task can't dominate. Set aside about 40 percent of each cluster as a held-out split you don't tune against. Write a small grader per task type, run it on every model or prompt change, and append the results to a history file. The demo below ran this end to end on 360 synthetic requests and produced a 59 case benchmark. Real model results will differ from the stub's.

<nav class="toc" aria-label="Table of contents"><p><strong>On this page</strong></p><ol><li><a href="#why-public-benchmarks-miss-your-tasks">Why public benchmarks miss your tasks</a></li><li><a href="#download-the-demo-project">Download the demo project</a></li><li><a href="#step-1-export-the-logs-and-keep-only-what-you-need">Step 1: Export the logs and keep only what you need</a></li><li><a href="#step-2-scrub-personal-data-and-secrets">Step 2: Scrub personal data and secrets</a></li><li><a href="#step-3-cluster-requests-into-task-types">Step 3: Cluster requests into task types</a></li><li><a href="#step-4-sample-cases-and-keep-a-held-out-split">Step 4: Sample cases and keep a held-out split</a></li><li><a href="#step-5-write-a-grader-for-each-task-type">Step 5: Write a grader for each task type</a></li><li><a href="#step-6-track-results-over-time">Step 6: Track results over time</a></li><li><a href="#privacy-and-retention-rules">Privacy and retention rules</a></li><li><a href="#limits-of-this-demo">Limits of this demo</a></li><li><a href="#faq">FAQ</a></li><li><a href="#where-to-go-next">Where to go next</a></li></ol></nav>

![Six step flow in two rows. 1, raw request log: export a time slice and keep only the fields you need. 2, scrub personal data and secrets. 3, cluster into task types with TF-IDF and k-means. 4, sample 6 to 12 cases per task and hold out about 40 percent, never tuned on. 5, one grader per task type. 6, a results history file with a row per task and run, to compare over time.](https://stevenphan.ca/_astro/log-benchmark-flow.D6vtaNxT_Z1dSoBg.webp)

## Why public benchmarks miss your tasks

A public benchmark measures the tasks its authors picked. Your traffic is probably different: shorter requests, odd formats and a few task types that make up most of the volume. A model that scores well on general reasoning can still fumble your invoice extraction or your habit of asking for exactly three bullets.

Your logs already hold the answer to "what do we really ask?" Turning them into a benchmark does two things public sets can't: it weights the test by how often each task really occurs, and it keeps the wording and mess of real requests.

If you haven't built a small task test before, start with [How to Choose an AI Model: Build a Simple Task Test](https://stevenphan.ca/blog/choose-ai-model-task-test/), which covers labelled cases and a runnable grader. This post is the step before it: where the cases come from. When you want repeatable scoring from a hand-picked set, [Build a 30 Case Eval Set and Run It Three Times](https://stevenphan.ca/blog/build-30-case-eval-set-run-three-times/) covers that side. Once the benchmark exists, [Prompt Regression Gates in CI](https://stevenphan.ca/blog/prompt-regression-gates-ci/) shows how to make it block a bad change automatically.

## Download the demo project

Download the [benchmark-from-logs demo](https://stevenphan.ca/downloads/build-your-own-benchmark-from-your-logs.zip) and unzip it into a new folder. You need Python 3.10 or newer and scikit-learn. We tested with Python 3.13 and scikit-learn 1.9.1 (checked 2026-11-12). Install scikit-learn with `pip install scikit-learn`. Everything else uses the standard library, and no network calls or API keys are involved.

```text
make_synthetic_logs.py   writes the fake log (synthetic, seeded)
scrub.py                 removes personal data and secrets
cluster.py               TF-IDF + k-means, size report, keyword fallback
sample_split.py          per-cluster sampling and the held-out split
run_benchmark.py         stub model, graders, history file
report.py                prints the results tables
run_all.sh               runs every step in order
README.md
```

Run `bash run_all.sh` on macOS, Linux, Git Bash or WSL. On plain Windows, run the scripts by hand in the README's order with `py -3` in place of `python3`. Every output in this post comes from running that script from a fresh unzip, and the data is seeded, so you should see the same numbers.

## Step 1: Export the logs and keep only what you need

Pull a bounded slice. A few months of requests is plenty for a first benchmark, and fewer rows means less to scrub and protect. Export only an ID, a coarse date, a user key and the request text, and leave out email addresses, IP addresses and device IDs.

Where the logs live depends on your stack, so the export is yours to write. A generic pattern looks like this (not run here, because it depends on your own database):

```bash
# not run here: adapt the table and column names to your own log store
psql "$LOG_DB_URL" -c "\copy (
  SELECT id, date_trunc('month', created_at) AS month, user_id, request_text
  FROM request_log
  WHERE created_at >= now() - interval '90 days'
) TO 'raw_logs.csv' CSV HEADER"
```

Do the export on a machine you already trust with that data, and keep the raw file out of any repository from the first minute.

For the demo, `make_synthetic_logs.py` plays the role of that export. It is a script, it uses a fixed random seed, and it invents everything: names from a short list, emails at example.com, phone numbers in the fictional 555-01xx range and key-like strings that are plainly placeholders. It writes 360 lines across six task types: summaries, invoice extraction, ticket classification, polite rewrites, SQL questions and translations. It also drops personal details into nearly half of the requests, so the scrubber has something to find. One generated line looks like this:

```text
Classify this support ticket as billing, bug or access: please refund the duplicate payment. Use key sk-EXAMPLE-not-a-real-key-9815abcdef if you need it.
```

The generator also writes `hidden_truth.jsonl`, which stands in for the labels you would write by hand later. Real logs don't come with answers. The pipeline reads that file only at the sampling step, plus one check at the clustering step that we'll flag.

## Step 2: Scrub personal data and secrets

Scrubbing happens before clustering, sampling, sharing or pasting anything into a chat window. We use plain regular expressions in `scrub.py`, applied in order from most to least dangerous:

```python
RULES = [
    ("secret", re.compile(r"\b(?:sk|pk|ghp|xox[bp])[-_][A-Za-z0-9_-]{12,}\b"), "[SECRET]"),
    ("card",   re.compile(r"\b(?:\d[ -]?){13,16}\b"), "[CARD]"),
    ("email",  re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"), "[EMAIL]"),
    ("phone",  re.compile(r"\b\d{3}[-. ]\d{3}[-. ]\d{4}\b"), "[PHONE]"),
    ("name",   re.compile("|".join(map(re.escape, KNOWN_NAMES))), "[NAME]"),
]
```

Two more habits matter as much as the patterns. The scrubber drops the email column entirely rather than masking it, and it replaces the user key with a salted hash so you can still tell that two requests came from the same person without knowing who. The date is cut down to the month. The salt in the demo is a placeholder string, so change it, and keep your real one out of git. A salted hash is pseudonymization, not anonymization: if someone gets the salt and your list of user IDs, they can recompute the hashes and match people again, so keep the hashed file private too.

Here is a real before and after from the run:

```text
raw:      Extract the invoice number and total from this text and return JSON. Acme Placeholder invoice INV-7043, total due $3028.59, net 30. Contact me at riley92@example.com.
scrubbed: Extract the invoice number and total from this text and return JSON. Acme Placeholder invoice INV-7043, total due $3028.59, net 30. Contact me at [EMAIL]
```

Notice that the email pattern swallowed the full stop after the address. That's harmless here, but loose patterns do eat neighbouring text, so read a sample of scrubbed lines yourself. The output for the whole file:

```text
scrubbed 360 rows -> data/scrubbed.jsonl
  secret  replacements: 23
  card    replacements: 12
  email   replacements: 70
  phone   replacements: 42
  name    replacements: 115
  leak check: 0 rows still match the leak patterns
```

The leak check is a second, stricter pass that fails the whole run if anything resembling an at sign, a key prefix or a phone pattern survives. "Zero rows" here only means the patterns we thought of found nothing. The demo knows its six names because it invented them. Real logs contain names the script has never seen, street addresses and order numbers. Regexes catch only formats you can describe, so for names and addresses add a named entity detection pass or a manual review, and treat any scrubbed file as sensitive until you've looked at it.

## Step 3: Cluster requests into task types

Now we want to know what kinds of requests are in the log without reading all of them. TF-IDF turns each request into a vector that weights words by how distinctive they are, and k-means groups similar vectors. Both are in scikit-learn; see the docs for [TfidfVectorizer](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html) and [KMeans](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html). The heart of `cluster.py`:

```python
vec = TfidfVectorizer(lowercase=True, stop_words="english", ngram_range=(1, 2), min_df=3)
X = vec.fit_transform(texts)
km = KMeans(n_clusters=K, n_init=10, random_state=7).fit(X)
```

Choosing the number of clusters is the awkward part. The script sweeps k from 4 to 9 and prints a silhouette score, which needs no labels. Because the data is synthetic it also prints purity against the hidden truth, which you can't do with real logs. Use the silhouette score as a hint and your own eyes as the judge:

```text
k sweep (silhouette needs no labels; purity only exists because this data is synthetic)
  k=4  silhouette=0.309  purity=0.858
  k=5  silhouette=0.348  purity=0.950
  k=6  silhouette=0.349  purity=0.950
  k=7  silhouette=0.380  purity=1.000
  k=8  silhouette=0.356  purity=1.000
  k=9  silhouette=0.318  purity=1.000
```

The silhouette peaked at k=7 and we used it, even though the data holds six task types. The extra cluster is a split of the ticket classification requests (one group is mostly "twice plan charged" wording). That's fine, because two clusters can share a task name and be merged later. With k=6 the clusters weren't clean: purity was 0.95, meaning some requests landed with the wrong neighbours. Here is the cluster size report at k=7:

```text
360 requests, 266 TF-IDF features, k=7
cluster  size  share  name          top terms
      1    95  26.4%  json_fields   total, invoice, 30, total text, invoice inv, inv
      2    82  22.8%  bullets3      points, points wrote, need update, email thread, summarise, summarise email
      6    76  21.1%  label         ticket billing, classify, classify support, support, ticket, support ticket
      4    37  10.3%  sql           days, created, query, query returns, returns, returns rows
      0    33   9.2%  polite        sound, fix, sound polite, rewrite, professional, polite professional
      5    19   5.3%  label         twice plan, twice, access charged, plan month, month, plan
      3    18   5.0%  contains_any  translate, translate french, french, hello, french hello, thank
agreement with hidden truth: k-means 360/360 (100.0%), keyword rule 360/360 (100.0%)
```

The "name" column holds grader type names, like `json_fields` for invoice extraction and `contains_any` for the translation task. Picking those names is a human job: you read the top terms and a handful of example requests, then decide what the cluster is and which grader fits. In the demo a small keyword table does that so the script can run unattended. Don't skip the reading in real use.

The keyword rule fallback is worth knowing about. It's only a few lines: if the request contains "translate", it's a translation; if it contains "extract", it's extraction; and so on. On this tidy synthetic data it matched the truth on all 360 rows, as did k-means. When your tasks come from a few known templates, a keyword rule is easier to explain and never changes between runs. Use clustering to find task types you didn't know about, then keep rules once you know them.

The last line of that report compares against hidden truth, so it only exists for synthetic data. That 100 percent reflects how simple the synthetic text is, and says nothing about your logs.

## Step 4: Sample cases and keep a held-out split

If invoice extraction is 26 percent of traffic and translation is 5 percent, a fully proportional sample leaves you with a handful of translation checks. So `sample_split.py` takes about a quarter of each task's requests, with a floor of 6 and a cap of 12 cases per task. Then it sets 40 percent of each task's cases aside as a held-out split.

```python
n = min(len(pool), max(PER_CLUSTER_MIN, min(PER_CLUSTER_MAX, round(len(pool) * 0.25))))
n_held = max(1, round(n * HELD_OUT_SHARE))
```

Read every failure in the dev cases and fix your prompt. Run the held-out cases only to check whether those fixes generalise, because tuning against them turns them into dev cases. The output:

```text
task           in_log  sampled  dev  held_out
bullets3          82       12    7         5
contains_any      18        6    4         2
json_fields       95       12    7         5
label             95       12    7         5
polite            33        8    5         3
sql               37        9    5         4
total cases: 59 -> data/benchmark_cases.jsonl
```

The cap and floor are choices. A benchmark this size is quick to run, but each case moves a task's pass rate by roughly 8 to 17 points, and the held-out side is even smaller. That's the main limit of the approach. For how many repeats you need before trusting a number, see [Build a 30 Case Eval Set and Run It Three Times](https://stevenphan.ca/blog/build-30-case-eval-set-run-three-times/).

Each case in `benchmark_cases.jsonl` carries its prompt, task, split and a grader spec. The reference in the spec stands in for the answer you'd write by hand, using `hidden_truth.jsonl`. For real logs, label the sampled cases yourself or review each other's labels. Remember too that a logged request has no known right answer, because the original response might have been wrong.

## Step 5: Write a grader for each task type

A grader is a function from the model's answer and the case's spec to pass or fail. Prefer deterministic checks wherever the task allows one, because they're cheap, repeatable and easy to argue about. The demo has six, one per task type:

- `bullets3`: exactly three lines, each starting with "- ", and the topic keyword appears.
- `json_fields`: the answer parses as JSON and the invoice number and total match the reference.
- `label`: the answer equals the expected label (billing, bug or access).
- `polite`: contains a polite marker such as "please" and none of the banned rude words.
- `sql`: names the right table and includes `select` and `where`.
- `contains_any`: includes the expected French word.

```python
if t == "json_fields":
    try: d = json.loads(o)
    except ValueError: return False
    return all(str(d.get(k)) == v for k, v in g["fields"].items())
```

These are deliberately rough. The SQL check can't tell whether the query is correct, only that it mentions the table and a filter. For open-ended work a rule can only check format, so add a rubric scored by a person or a second model, and spot check that scorer. Choose the simplest grader that fails on the failures you care about, and write down what it can't see.

The model in `run_benchmark.py` is a deterministic stub. It builds a correct answer from the grader spec, then breaks a share of answers on purpose, using a hash of the case ID and a version label. That gives the grader real failures to catch without calling any API. The failure rates are made up per task, so nothing here says anything about a real model. One function, `answer()`, is marked as the place to swap in a call to your own model client.

## Step 6: Track results over time

A benchmark is useful when you can compare today's run to last month's. `run_benchmark.py` appends one row per split and task to `results/history.csv`, with the run date, a model label, passed count and total. We ran it twice with two stub versions. The dates are labels in the demo, not real run dates, and "stub-v1" and "stub-v2" are not real models.

```text
run 2026-11-01 model=stub-v1
  dev       25/35 passed (71%)
  held_out  15/24 passed (62%)
run 2026-11-12 model=stub-v2
  dev       28/35 passed (80%)
  held_out  18/24 passed (75%)
```

`report.py` then prints per-task tables, with dev and held-out side by side:

```text
[held_out]  passed/total
task         2026-11-01 stub-v1  2026-11-12 stub-v2
bullets3     3/5                  3/5
contains_any 1/2                  2/2
json_fields  2/5                  5/5
label        4/5                  4/5
polite       2/3                  3/3
sql          3/4                  1/4
ALL          15/24                18/24
```

Look at the SQL row. On held-out cases the stub's pass count dropped from 3 of 4 to 1 of 4, while the overall number went up. Here that's an artefact of how the stub's failures fall on four cases, and the dev SQL count also slipped from 5 of 5 to 4 of 5. It's still the reason to track per task: an average can rise while one task type gets worse, and on four cases you can't tell noise from regression. Look at the individual cases and rerun before you decide.

For real runs, store the exact model name, prompt version, settings and date too. Then wire the run into your build, as in [Prompt Regression Gates in CI](https://stevenphan.ca/blog/prompt-regression-gates-ci/), so a change that makes a task worse fails before it ships.

## Privacy and retention rules

This is general guidance, not legal advice. Privacy law and your own contracts differ by place and by business, so check what applies to you and ask a qualified person where the stakes are real.

- Collect less. Export only the columns and time range you need. Data you never copy can't leak.
- Scrub before you cluster, sample, share or paste. Don't send raw logs to a hosted model or a teammate to clean up later.
- Scrub in layers. Drop identifying columns, hash user keys with a secret salt, reduce dates to months and run pattern rules. Then add a name and address check and read a sample yourself.
- Never put customer data in a public repository. That covers the raw export, the scrubbed file and the benchmark cases. If a scrubbed log is still too revealing to publish, it stays private. A public repo should carry only code and synthetic data like the demo's. If a real key or secret ever lands in a repo, follow [What to Do If an API Key Leaks in a GitHub Repo](https://stevenphan.ca/blog/what-to-do-if-api-key-leaked-in-github-repo/), and consider scanning with [secret scanning tools](https://stevenphan.ca/blog/github-secret-scanning-dependabot-trufflehog-gitleaks/) before you push.
- Set a retention rule. Keep the raw export only as long as the scrub job needs it, then delete it. Keep the scrubbed benchmark cases only as long as the benchmark is live. Write the deletion date down.
- Restrict access. Keep the benchmark in private storage with a short access list, and keep the salt and raw exports out of it.
- Check your terms. Your privacy policy and agreements may limit how you can reuse other people's data as test material.

## Limits of this demo

The log is synthetic and unusually tidy, which is why the clustering scored 100 percent. Real requests are longer and more ambiguous, and clustering them leaves leftovers that need a human decision. The stub isn't a model, and the graders are simple, so a pass doesn't mean the answer is good.

The sample is also small: 59 cases, with between 2 and 5 held-out cases per task. That's enough to catch a broken pipeline and large regressions, and too small for fine comparisons between close models. Grow each task's cases over time, adding one whenever a real failure shows up in your logs. We checked scikit-learn 1.9.1 on 2026-11-12, and parameters may change, so read the current docs.

## FAQ

### How many log lines do you need for a custom AI benchmark?

The demo clustered 360 synthetic requests and sampled 59 cases. That runs fast and can catch big regressions, but each case moves a task's pass rate by roughly 8 to 17 points. Add cases over time.

### How do you find task types in your request logs?

Scrub the logs, then cluster the text with TF-IDF and k-means from scikit-learn. Sweep a few values of k, read the top terms and example requests in each cluster, and name them yourself. A keyword rule fallback works when you already know your task templates.

### Why keep a held-out split in a log based benchmark?

The dev cases are the ones you read and tune against. The held-out cases only check whether your fixes generalise, so they stop working as a test if you tune against them. The demo held out about 40 percent of each task's sampled cases.

### What should you scrub from logs before using them?

Emails, phone numbers, card numbers, key-like strings and known names were removed in the demo, and the email column was dropped. User keys were hashed with a salt and dates were cut to the month. Regexes don't catch every name or address, so review a sample by hand. This is general guidance, not legal advice.

### Can you put your scrubbed logs in a public GitHub repo?

No. Customer data, including scrubbed customer data, shouldn't go in a public repository. Publish code and synthetic data only, and keep real exports and benchmark cases in private storage with a retention date.

### Do the demo pass rates show how good a model is?

No. The model in the demo is a deterministic stub that breaks answers on purpose, and the data is synthetic. The numbers show that the pipeline runs and records results. Real model results will differ.

## Where to go next

- Try the pipeline on a small, scrubbed slice of your own logs, and read every cluster's examples before you accept its name.
- Turn the sampled cases into a repeatable eval with [Build a 30 Case Eval Set and Run It Three Times](https://stevenphan.ca/blog/build-30-case-eval-set-run-three-times/).
- Compare candidate models on those cases with [How to Choose an AI Model: Build a Simple Task Test](https://stevenphan.ca/blog/choose-ai-model-task-test/).
- Make a worse result block a change with [Prompt Regression Gates in CI](https://stevenphan.ca/blog/prompt-regression-gates-ci/).
