Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(growth): turn suggestion judge benchmark (#106433)

Rafael Audibert8fa8ac9755c0
diff --git a/products/posthog_ai/backend/management/__init__.py b/products/posthog_ai/backend/management/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/posthog_ai/backend/management/commands/README.md b/products/posthog_ai/backend/management/commands/README.md
new file mode 100644
index 000000000000..9ea21ca89535
--- /dev/null
+++ b/products/posthog_ai/backend/management/commands/README.md
@@ -0,0 +1,143 @@
+# Turn suggestion benchmark
+
+`turn_suggestions_benchmark` scores the turn suggestion judge against labeled PostHog AI turns.
+Use it to check a prompt change, a new show threshold, or a new System One model before it reaches users.
+
+The cases live in [`turn_suggestions/benchmark_cases.yaml`](../../turn_suggestions/benchmark_cases.yaml).
+Each case is an invented turn with the offers that would be a good outcome.
+The file header explains the case format.
+
+## Before you start
+
+The command calls Jev the way production does: through the ai-gateway, which needs `AI_GATEWAY_URL` and `AI_GATEWAY_API_KEY`.
+Set them in the environment or in `.env.local` at the repo root.
+Other endpoints need neither, so `--skip-jev` runs without them.
+
+Every run sends the invented cases to the judge. It sends no data from your local database.
+
+## Run it
+
+```sh
+python manage.py turn_suggestions_benchmark
+```
+
+With no endpoints configured, the command judges every case with Jev and prints:
+
+1. One line per case, as each answer arrives: the offer the judge picked, the show probability, the offer probabilities, and the time the request took.
+2. The show probabilities grouped by label, so you can see how far apart the "should offer" and "should not offer" cases sit.
+3. A sweep of show thresholds from 0.20 to 0.90, with the current threshold and the best F1 marked.
+4. The threshold closest to the target offer rate (see [Target offer rate](#target-offer-rate)).
+
+Run a subset while you iterate:
+
+```sh
+python manage.py turn_suggestions_benchmark --category diagnostic --category recurring_metric
+python manage.py turn_suggestions_benchmark --case signups --state
+```
+
+## Compare Jev with other endpoints
+
+List other System One endpoints in `TURN_SUGGESTIONS_BENCHMARK_ENDPOINTS`, in the environment or in `.env.local`.
+With at least one endpoint, the command judges the cases with Jev and with every endpoint, then compares them.
+
+Each entry is a URL:
+
+```text
+http[s]://[username:password@]host[:port][/path][#model]
+```
+
+- The credentials, when present, go out as HTTP basic auth.
+- The path defaults to `/v1/systemone`.
+- The part after `#` names the model to send in the request body. Without it, the request names no model. A URL fragment never reaches the server.
+- Separate entries with spaces, commas, or semicolons.
+- Percent-encode a `:`, `@`, or `#` inside a username or password, for example `%40` for `@`.
+
+```sh
+TURN_SUGGESTIONS_BENCHMARK_ENDPOINTS="https://user:[email protected]#candidate-1, https://user:[email protected]#candidate-2"
+```
+
+`.env.local` is gitignored, so it is the right place for credentials.
+Do not pass credentials in `--endpoint`, because the shell keeps them in its history.
+
+To choose the judges for one run:
+
+- `--endpoint URL` judges with that URL instead of the variable. Repeat it to add more.
+- `--skip-jev` judges with the endpoints only.
+- `--jev-only` ignores the variable and judges with Jev alone, which gives the single-judge output above.
+
+An endpoint must accept the same request body as the ai-gateway's `POST /v1/systemone` and return answers in the same shape.
+
+### Read the comparison
+
+The command runs one judge at a time and prints one progress line for each judge.
+When requests fail, it prints each distinct error once with its count, for example `9x HTTP 400: {"error": ...}`.
+A judge that answers no case at all is left out of the tables.
+
+**Scores at the show threshold.** Every judge at the same `--threshold`:
+
+| Column | Meaning |
+| ---------- | ---------------------------------------------------------------------- |
+| failed | Cases where the request failed |
+| offer rate | Share of judged cases that get a card |
+| precision | Share of cards that were a good pick |
+| recall | Share of "should offer" cases that got a good card |
+| F1 | The balance of precision and recall |
+| best F1 | The best F1 across the sweep, and the threshold that gets it |
+| agrees | Share of cases where the judge picks the same offer as the first judge |
+| median | Median request time |
+
+**Closest to the target offer rate.** Each judge at its own threshold for the target rate, with false offers, misses, and wrong kinds counted.
+Compare judges here, because two models can put their show probabilities in different ranges.
+At one shared threshold, a model that scores everything lower offers less often, and its precision is not comparable.
+
+**Cases where the judges pick differently.** Only the cases where the judges disagree, each judge at its threshold for the target rate.
+A failed request alone does not add a row.
+
+| Mark | Meaning |
+| ---- | ----------------------------------------------------------------------- |
+| ✓ | A good pick |
+| ✗ | A card on a "should not offer" case, a miss, or the wrong kind of offer |
+| ~ | A borderline case, and the pick is one of its acceptable outcomes |
+| ! | The request failed |
+
+The number after the offer is the show probability.
+
+`--sweep` also prints the full threshold sweep for every judge.
+
+## Target offer rate
+
+`--target-offer-rate` (default 0.45) finds the show threshold whose offer rate lands closest to the target.
+It checks thresholds in steps of 0.01, and a tie goes to the higher threshold, which shows fewer cards.
+
+This is a different question from best F1.
+Best F1 finds the threshold with the best balance of precision and recall, whatever offer rate that gives.
+The target search finds the threshold that offers as often as you want, whatever the quality there.
+
+A threshold can only change how often a card shows.
+It cannot fix the wrong kind of offer, because the judge picks the offer in a separate question.
+If a judge cannot reach the target at any threshold, the closest threshold shows the highest rate it can reach.
+
+## Options
+
+| Option | Default | Effect |
+| --------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------- |
+| `--threshold` | the production value | The show threshold for the per-case lines and the first scores table |
+| `--target-offer-rate` | 0.45 | The offer rate to match, as a share between 0 and 1 |
+| `--case NAME` | all | Only cases whose name contains this text. Repeat it for more |
+| `--category NAME` | all | Only cases in this category. Repeat it for more |
+| `--workers` | 8 | Parallel requests per judge |
+| `--cases-file` | the bundled file | Another YAML file with cases |
+| `--state` | off | Print the masked state the judge reads for each case. One judge only |
+| `--draft` | off | Also ask the language model to write the scout or notebook text. Needs a team in the local database. One judge only |
+| `--endpoint URL` | the variable | Judge with this URL instead of `TURN_SUGGESTIONS_BENCHMARK_ENDPOINTS` |
+| `--skip-jev` | off | Judge with the endpoints only |
+| `--jev-only` | off | Ignore the endpoints and judge with Jev alone |
+| `--sweep` | off | With more than one judge, print every judge's full sweep |
+
+## Things to keep in mind
+
+- Jev does not give the same probabilities on every run. The same prompt can move a case by about 0.05. Run twice before you trust a change that moves one or two cases.
+- The prompts are tuned on these same cases, so a good score here is not proof of a good score on real traffic.
+- The case file has more "should offer" cases than real traffic, so a threshold offers less often in production than it does here.
+- Several judges share the same prompts. A prompt change that helps one model can hurt another, so compare every judge before you keep a change.
+- A new case must be written from scratch with invented names and ids. Do not paste real conversations, even with names changed.
diff --git a/products/posthog_ai/backend/management/commands/__init__.py b/products/posthog_ai/backend/management/commands/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/posthog_ai/backend/management/commands/turn_suggestions_benchmark.py b/products/posthog_ai/backend/management/commands/turn_suggestions_benchmark.py
new file mode 100644
index 000000000000..3ad49ea0acb1
--- /dev/null
+++ b/products/posthog_ai/backend/management/commands/turn_suggestions_benchmark.py
@@ -0,0 +1,452 @@
+import os
+import json
+import time
+import statistics
+from collections import Counter
+from collections.abc import Sequence
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+from django.test import override_settings
+
+from posthog.models import Team
+
+from products.posthog_ai.backend.turn_suggestions.benchmark import (
+ CASES_PATH,
+ BenchmarkCase,
+ CaseResult,
+ Expectation,
+ JudgeRun,
+ Outcome,
+ SystemOneEndpoint,
+ ThresholdScore,
+ agreement,
+ best_threshold,
+ closest_to_offer_rate,
+ disagreements,
+ load_cases,
+ on_shared_cases,
+ parse_endpoints,
+ run_cases,
+ score,
+ sweep,
+ sweep_thresholds,
+)
+from products.posthog_ai.backend.turn_suggestions.classifier import SHOW_THRESHOLD, build_draft, card_copy
+from products.posthog_ai.backend.turn_suggestions.judgment import build_judge_state, judge_model
+from products.posthog_ai.backend.turn_suggestions.verdict import NotebookDraft, OfferKind, ScoutDraft
+
+_MARKS = {
+ Outcome.CORRECT: "✓",
+ Outcome.FALSE_OFFER: "✗",
+ Outcome.MISSED: "✗",
+ Outcome.WRONG_KIND: "✗",
+ Outcome.EITHER: "~",
+ Outcome.FAILED: "!",
+}
+
+
+def _percent(value: float | None) -> str:
+ return " -" if value is None else f"{value * 100:3.0f}%"
+
+
+def _f1(value: float | None) -> str:
+ return " -" if value is None else f"{value:.2f}"
+
+
+ENDPOINTS_VARIABLE = "TURN_SUGGESTIONS_BENCHMARK_ENDPOINTS"
+_SERVER_SETTINGS = ("AI_GATEWAY_URL", "AI_GATEWAY_API_KEY")
+DEFAULT_TARGET_OFFER_RATE = 0.45
+
+# A judge is Jev through the configured System One server (no endpoint) or one candidate endpoint.
+type Judge = tuple[str, SystemOneEndpoint | None]
+
+
+def _from_env_local(name: str) -> str | None:
+ env_local = Path(settings.BASE_DIR) / ".env.local"
+ if not env_local.is_file():
+ return None
+ for line in env_local.read_text().splitlines():
+ key, _, value = line.partition("=")
+ if key.strip() == name and value.strip():
+ return value.strip()
+ return None
+
+
+def _judges(options: dict[str, Any], jev_label: str | None) -> list[Judge]:
+ judges: list[Judge] = []
+ if not options["skip_jev"]:
+ if jev_label is None:
+ raise CommandError(
+ "Set AI_GATEWAY_URL and AI_GATEWAY_API_KEY in the environment or in .env.local, or pass --skip-jev."
+ )
+ judges.append((jev_label, None))
+ if options["jev_only"]:
+ return judges
+ # Flags replace the variable, so one run can try an endpoint without editing the environment.
+ value = " ".join(options["endpoint"]) or os.environ.get(ENDPOINTS_VARIABLE) or _from_env_local(ENDPOINTS_VARIABLE)
+ try:
+ endpoints = parse_endpoints(value or "")
+ except ValueError as error:
+ raise CommandError(str(error)) from None
+ for endpoint in endpoints:
+ label = endpoint.label
+ # Two specs can share a host and a model, so number the repeats to keep the columns apart.
+ taken = {existing for existing, _ in judges}
+ if label in taken:
+ label = next(f"{label} #{index}" for index in range(2, len(judges) + 2) if f"{label} #{index}" not in taken)
+ judges.append((label, endpoint))
+ if not judges:
+ raise CommandError(f"--skip-jev needs at least one endpoint in {ENDPOINTS_VARIABLE} or --endpoint.")
+ if len(judges) > 1 and (options["state"] or options["draft"]):
+ raise CommandError("--state and --draft work with one judge only.")
+ return judges
+
+
+class Command(BaseCommand):
+ help = (
+ "Run the labeled turn suggestion cases through live Jev, or through candidate System One endpoints, "
+ "and score the policy across show thresholds. With more than one judge, compare them side by side. "
+ f"{ENDPOINTS_VARIABLE} in the environment or in .env.local lists the endpoints, separated by spaces, "
+ "commas, or semicolons. Each one is http[s]://[username:password@]host[:port][/path][#model]. "
+ "The path defaults to /v1/systemone, and the fragment names the model to send."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument(
+ "--threshold",
+ type=float,
+ default=SHOW_THRESHOLD,
+ help=f"Show threshold for the per-case verdicts (default {SHOW_THRESHOLD}).",
+ )
+ parser.add_argument("--case", action="append", default=[], help="Only run cases whose name contains this.")
+ parser.add_argument("--category", action="append", default=[], help="Only run cases in this category.")
+ parser.add_argument("--workers", type=int, default=8, help="Parallel requests per judge (default 8).")
+ parser.add_argument("--cases-file", type=Path, default=CASES_PATH, help="YAML file with the cases.")
+ parser.add_argument("--state", action="store_true", help="Print the masked state Jev reads for each case.")
+ parser.add_argument(
+ "--draft",
+ action="store_true",
+ help="Also ask the language model to write the scout or notebook text for picked offers.",
+ )
+ parser.add_argument(
+ "--endpoint",
+ action="append",
+ default=[],
+ metavar="URL",
+ help=(
+ "Also judge with this System One URL, in the same form as "
+ f"{ENDPOINTS_VARIABLE}. Repeat it to compare several. It replaces the variable for this run."
+ ),
+ )
+ judge_choice = parser.add_mutually_exclusive_group()
+ judge_choice.add_argument("--skip-jev", action="store_true", help="Judge with the endpoints only.")
+ judge_choice.add_argument(
+ "--jev-only", action="store_true", help=f"Ignore {ENDPOINTS_VARIABLE} and judge with Jev."
+ )
+ parser.add_argument(
+ "--target-offer-rate",
+ type=float,
+ default=DEFAULT_TARGET_OFFER_RATE,
+ help=(
+ "Find each judge's show threshold whose offer rate over the cases lands nearest this share "
+ f"(default {DEFAULT_TARGET_OFFER_RATE}). With more than one judge, compare the judges there."
+ ),
+ )
+ parser.add_argument(
+ "--sweep",
+ action="store_true",
+ help="With more than one judge, also print each judge's full threshold sweep.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ # Only the ai-gateway answers, as in production.
+ servers = {name: getattr(settings, name) or _from_env_local(name) or "" for name in _SERVER_SETTINGS}
+ with override_settings(**servers):
+ judges = _judges(options, judge_model())
+ for label, endpoint in judges:
+ if endpoint is not None and endpoint.sends_credentials_in_clear:
+ self.stderr.write(
+ self.style.WARNING(f"{label} gets its username and password over plain http. Use https:// ")
+ + self.style.WARNING("unless the network to that host is trusted.")
+ )
+ self._run(options, judges)
+
+ def _run(self, options: dict[str, Any], judges: list[Judge]) -> None:
+ threshold: float = options["threshold"]
+ if not 0 <= threshold <= 1:
+ raise CommandError("--threshold is a probability between 0 and 1, such as 0.5.")
+ if not 0 <= options["target_offer_rate"] <= 1:
+ raise CommandError("--target-offer-rate is a share between 0 and 1, such as 0.45.")
+ try:
+ all_cases = load_cases(options["cases_file"])
+ except ValueError as error:
+ raise CommandError(str(error)) from None
+ cases = [
+ case
+ for case in all_cases
+ if (not options["case"] or any(needle in case.name for needle in options["case"]))
+ and (not options["category"] or case.category in options["category"])
+ ]
+ if not cases:
+ raise CommandError("No case matches those filters.")
+ if len(judges) == 1:
+ self._run_one(options, cases, judges[0], threshold)
+ else:
+ self._run_comparison(options, cases, judges, threshold)
+
+ def _run_one(self, options: dict[str, Any], cases: list[BenchmarkCase], judge: Judge, threshold: float) -> None:
+ label, endpoint = judge
+ self.stdout.write(f"Judging {len(cases)} cases with {label} at show threshold {threshold}\n\n")
+ team_id = self._team_id() if options["draft"] else 0
+
+ def on_result(result: CaseResult) -> None:
+ self._print_result(result, threshold)
+ if options["state"]:
+ state = json.dumps(build_judge_state(result.case.transcript), indent=2, ensure_ascii=False)
+ self.stdout.write(self.style.HTTP_INFO("\n".join(f" {line}" for line in state.splitlines())))
+ if options["draft"]:
+ self._print_draft(result, threshold, team_id)
+
+ results = run_cases(cases, workers=options["workers"], on_result=on_result, endpoint=endpoint)
+ self._print_distribution(results)
+ self._print_sweep(sweep(results, sweep_thresholds(threshold)), threshold)
+ target: float = options["target_offer_rate"]
+ closest = closest_to_offer_rate(results, target)
+ if closest is not None:
+ f1 = _f1(closest.f1).strip()
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"\nClosest to a {_percent(target).strip()} offer rate: threshold {closest.threshold:.2f} offers on "
+ f"{_percent(closest.offer_rate).strip()} of cases, with precision {_percent(closest.precision).strip()}, "
+ f"recall {_percent(closest.recall).strip()}, and F1 {f1}."
+ )
+ )
+
+ def _run_comparison(
+ self, options: dict[str, Any], cases: list[BenchmarkCase], judges: list[Judge], threshold: float
+ ) -> None:
+ self.stdout.write(f"Judging {len(cases)} cases with {len(judges)} judges at show threshold {threshold}\n")
+ width = max(len(label) for label, _ in judges)
+ runs = []
+ for label, endpoint in judges:
+ started = time.monotonic()
+ results = run_cases(cases, workers=options["workers"], on_result=lambda _: None, endpoint=endpoint)
+ failed = [result for result in results if result.judgment is None]
+ line = f" {label:{width}} {len(results) - len(failed)} judged, {len(failed)} failed, {time.monotonic() - started:.0f}s"
+ self.stdout.write(self.style.ERROR(line) if failed else line)
+ # One repeated error, such as a 401, usually explains every failure, so print each distinct one once.
+ errors = Counter(result.error or "Jev request failed" for result in failed)
+ for error, count in errors.most_common():
+ self.stdout.write(self.style.ERROR(f" {count}x {error}"))
+ runs.append(JudgeRun(label=label, results=tuple(results)))
+
+ answered = [run for run in runs if any(result.judgment is not None for result in run.results)]
+ for run in runs:
+ if run not in answered:
+ self.stdout.write(self.style.ERROR(f"\n{run.label} answered no case, so the tables leave it out."))
+ if not answered:
+ return
+ scored = on_shared_cases(answered)
+ shared = len(scored[0].results)
+ if shared < len(cases):
+ self.stdout.write(
+ self.style.WARNING(f"\nThe scores cover the {shared} of {len(cases)} cases every judge answered.")
+ )
+ if not shared:
+ return
+ self._print_summary(answered, scored, threshold, width)
+ target: float = options["target_offer_rate"]
+ matched = self._print_target(scored, target, width)
+ if len(scored) > 1:
+ self._print_disagreements(
+ scored, matched, f"each at its threshold for a {_percent(target).strip()} offer rate"
+ )
+ if options["sweep"]:
+ for run in scored:
+ self.stdout.write(self.style.MIGRATE_HEADING(f"\n{run.label}"))
+ self._print_sweep(sweep(run.results, sweep_thresholds(threshold)), threshold)
+
+ def _print_summary(
+ self, runs: Sequence[JudgeRun], scored: Sequence[JudgeRun], threshold: float, width: int
+ ) -> None:
+ reference = scored[0]
+ self.stdout.write(self.style.MIGRATE_HEADING(f"\nScores at show threshold {threshold}"))
+ self.stdout.write(
+ f" {'judge':{width}} failed offer rate precision recall F1 best F1 agrees median"
+ )
+ for run, scored_run in zip(runs, scored):
+ current = score(scored_run.results, threshold)
+ best = best_threshold(sweep(scored_run.results, sweep_thresholds(threshold)))
+ failed = sum(1 for result in run.results if result.judgment is None)
+ f1 = _f1(current.f1)
+ best_f1 = f"{best.f1:.2f} at {best.threshold:.2f}" if best is not None and best.f1 is not None else "-"
+ agrees = (
+ " -"
+ if scored_run is reference
+ else f"{_percent(agreement(scored_run, threshold, reference, threshold))} "
+ )
+ # A failed request often waits out the timeout, which says nothing about how fast the judge answers.
+ # Another judge's failures leave this judge's answers in, so the median reads every one of them.
+ answered = [result.seconds for result in run.results if result.judgment is not None]
+ median = f"{statistics.median(answered):5.1f}s" if answered else " -"
+ self.stdout.write(
+ f" {run.label:{width}} {failed:6} {_percent(current.offer_rate)} {_percent(current.precision)}"
+ f" {_percent(current.recall)} {f1} {best_f1:12} {agrees} {median}"
+ )
+ self.stdout.write(
+ f"\n agrees: the share of cases where the judge picks the same offer as {reference.label}. "
+ "best F1: the judge's best score across thresholds, with the threshold that gets it. "
+ "median: the latency of answered requests."
+ )
+
+ def _print_target(self, runs: Sequence[JudgeRun], target: float, width: int) -> list[float]:
+ """Prints each judge's scores at the threshold nearest the target offer rate, and returns those thresholds."""
+ reference = runs[0]
+ matched = [closest_to_offer_rate(run.results, target) for run in runs]
+ thresholds = [entry.threshold if entry is not None else 1.0 for entry in matched]
+ self.stdout.write(self.style.MIGRATE_HEADING(f"\nClosest to a {_percent(target).strip()} offer rate"))
+ self.stdout.write(
+ f" {'judge':{width}} threshold offer rate precision recall F1 false offers missed wrong kind agrees"
+ )
+ for run, entry, run_threshold in zip(runs, matched, thresholds):
+ if entry is None:
+ continue
+ f1 = _f1(entry.f1)
+ agrees = (
+ " -"
+ if run is reference
+ else _percent(agreement(run, run_threshold, reference, thresholds[0])).rjust(5)
+ )
+ self.stdout.write(
+ f" {run.label:{width}} {entry.threshold:9.2f} {_percent(entry.offer_rate)} "
+ f"{_percent(entry.precision)} {_percent(entry.recall)} {f1} {entry.false_offers:12} "
+ f"{entry.missed:6} {entry.wrong_kind:10} {agrees}"
+ )
+ self.stdout.write(
+ "\n Compare judges here rather than at one shared threshold, because two models can calibrate their "
+ "show probability differently. The case file leans toward offers, so the same threshold offers less "
+ "often on real traffic."
+ )
+ return thresholds
+
+ def _print_disagreements(self, runs: Sequence[JudgeRun], thresholds: Sequence[float], at: str) -> None:
+ rows = disagreements(runs, thresholds)
+ total = len(runs[0].results)
+ self.stdout.write(
+ self.style.MIGRATE_HEADING(f"\nCases where the judges pick differently, {at} ({len(rows)} of {total})")
+ )
+ if not rows:
+ self.stdout.write(" Every judge picks the same offer on every case.")
+ return
+ widths = [max(len(run.label), 18) for run in runs]
+ name_width = max(len(row[0].case.name) for row in rows)
+ header = f" {'case':{name_width}} {'want':24}" + "".join(f" {run.label:{w}}" for run, w in zip(runs, widths))
+ self.stdout.write(header)
+ for row in rows:
+ case = row[0].case
+ want = case.want_label
+ cells = "".join(
+ f" {self._cell(result, threshold):{w}}" for result, threshold, w in zip(row, thresholds, widths)
+ )
+ self.stdout.write(f" {case.name:{name_width}} {want:24}{cells}".rstrip())
+ self.stdout.write(
+ "\n ✓ good pick ✗ wrong pick ~ either is fine ! failed. The number is the show probability."
+ )
+
+ def _cell(self, result: CaseResult, threshold: float) -> str:
+ if result.judgment is None:
+ return "! failed"
+ return f"{_MARKS[result.outcome(threshold)]} {result.picked(threshold)} {result.judgment.show_probability:.2f}"
+
+ def _team_id(self) -> int:
+ team = Team.objects.order_by("id").first()
+ if team is None:
+ raise CommandError("--draft needs a team in the local database to attribute the language model calls.")
+ return team.id
+
+ def _print_result(self, result: CaseResult, threshold: float) -> None:
+ case = result.case
+ outcome = result.outcome(threshold)
+ want = case.want_label
+ line = f"{_MARKS[outcome]} {case.name:28} want {want:24}"
+ judgment = result.judgment
+ if judgment is None:
+ self.stdout.write(self.style.ERROR(f"{line} judge request failed {result.error or ''}".rstrip()))
+ return
+ picked = result.picked(threshold)
+ probabilities = " · ".join(
+ f"{kind} {probability:.2f}"
+ for kind, probability in sorted(judgment.offer_probabilities.items(), key=lambda item: -item[1])
+ if probability >= 0.01
+ )
+ line += f" got {picked:12} show {judgment.show_probability:.2f} {probabilities} {result.seconds:.1f}s"
+ style = {
+ Outcome.CORRECT: self.style.SUCCESS,
+ Outcome.EITHER: self.style.WARNING,
+ }.get(outcome, self.style.ERROR)
+ self.stdout.write(style(line))
+
+ def _print_draft(self, result: CaseResult, threshold: float, team_id: int) -> None:
+ judgment = result.judgment
+ picked = result.picked(threshold)
+ if judgment is None or picked == OfferKind.NONE:
+ return
+ draft = build_draft(picked, judgment, result.case.transcript, team_id=team_id, today=datetime.now(UTC).date())
+ if draft is None:
+ self.stdout.write(self.style.ERROR(" The draft failed, so the card would not show."))
+ return
+ copy = card_copy(draft)
+ lines = [f" {copy.title}", f" {copy.description}"]
+ match draft:
+ case ScoutDraft():
+ lines += [f" Scout: {draft.display_name} ({draft.mode}, {draft.cadence})", ""]
+ lines += [f" {line}" for line in draft.body.splitlines()]
+ case NotebookDraft():
+ lines += [f" Notebook: {draft.title}", f" {draft.summary}"]
+ if draft.incident is not None:
+ lines += [f" Cause: {draft.incident.cause}", f" Fix: {draft.incident.fix}"]
+ self.stdout.write("\n".join(lines) + "\n")
+
+ def _print_distribution(self, results: Sequence[CaseResult]) -> None:
+ self.stdout.write("\nShow probability by label\n")
+ for expectation, label in (
+ (Expectation.OFFER, "should offer"),
+ (Expectation.EITHER, "either is fine"),
+ (Expectation.NOTHING, "should not offer"),
+ ):
+ values = sorted(
+ result.judgment.show_probability
+ for result in results
+ if result.judgment is not None and result.case.expectation == expectation
+ )
+ self.stdout.write(f" {label:17} {' '.join(f'{value:.2f}' for value in values) or '-'}")
+
+ def _print_sweep(self, scores: Sequence[ThresholdScore], threshold: float) -> None:
+ best = best_threshold(scores)
+ self.stdout.write("\nthreshold offer rate precision recall F1 false offers missed wrong kind")
+ for entry in scores:
+ f1 = _f1(entry.f1)
+ row = (
+ f" {entry.threshold:.2f} {_percent(entry.offer_rate)} {_percent(entry.precision)}"
+ f" {_percent(entry.recall)} {f1} {entry.false_offers:12} {entry.missed:6} {entry.wrong_kind:10}"
+ )
+ notes = [
+ note
+ for note, applies in (("current", entry.threshold == threshold), ("best F1", entry is best))
+ if applies
+ ]
+ self.stdout.write(row + (f" <- {', '.join(notes)}" if notes else ""))
+ if best is not None:
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"\nBest F1 at {best.threshold:.2f}. A tie goes to the higher threshold, which shows fewer cards."
+ )
+ )
+ self.stdout.write(
+ "Offer rate counts every case. The cases lean toward offers compared with real traffic, "
+ "so expect a lower rate in production."
+ )
diff --git a/products/posthog_ai/backend/tests/test_turn_suggestions.py b/products/posthog_ai/backend/tests/test_turn_suggestions.py
index 56d1171bf2de..192d5d79a2aa 100644
--- a/products/posthog_ai/backend/tests/test_turn_suggestions.py
+++ b/products/posthog_ai/backend/tests/test_turn_suggestions.py
@@ -1,6 +1,8 @@
import json
+import tempfile
from dataclasses import replace
from datetime import date
+from pathlib import Path
from typing import Any
from posthog.test.base import BaseTest
@@ -18,6 +20,19 @@ from posthog.llm.system_one import Answer, ChoiceAnswer, ChoiceQuestion, NoulAns
from posthog.redis import get_client
from products.posthog_ai.backend.tasks import generate_turn_suggestion_task
+from products.posthog_ai.backend.turn_suggestions.benchmark import (
+ BenchmarkCase,
+ CaseResult,
+ JudgeRun,
+ SystemOneEndpoint,
+ best_threshold,
+ closest_to_offer_rate,
+ load_cases,
+ on_shared_cases,
+ parse_endpoints,
+ run_cases,
+ score,
+)
from products.posthog_ai.backend.turn_suggestions.classifier import CardCopy, card_copy, classify_turn, pick_offer
from products.posthog_ai.backend.turn_suggestions.dispatch import (
TURN_SETTLE_SECONDS,
@@ -684,6 +699,139 @@ class TestPickOffer(SimpleTestCase):
assert pick_offer(_judgment(**overrides), available) == expected
+class TestBenchmark(SimpleTestCase):
+ def test_every_case_expects_offers_its_turn_can_make(self):
+ cases = load_cases()
+
+ assert len({case.name for case in cases}) == len(cases)
+ for case in cases:
+ assert case.acceptable - {OfferKind.NONE} <= case.available, case.name
+
+ def test_scores_count_false_offers_misses_and_acceptable_borderline_offers(self):
+ transcript = build_turn_transcript(_metric_turn())
+
+ def result(acceptable: set[OfferKind], show: float) -> CaseResult:
+ case = BenchmarkCase(
+ name="case",
+ category="test",
+ acceptable=frozenset(acceptable),
+ transcript=transcript,
+ available=ALL_OFFERS,
+ )
+ return CaseResult(case=case, judgment=_judgment(show_probability=show), seconds=0.1)
+
+ results = [
+ result({OfferKind.SCOUT}, 0.9),
+ result({OfferKind.SCOUT}, 0.55),
+ result({OfferKind.NONE}, 0.6),
+ result({OfferKind.NONE}, 0.1),
+ result({OfferKind.SCOUT, OfferKind.NONE}, 0.9),
+ result({OfferKind.NOTEBOOK, OfferKind.NONE}, 0.9),
+ ]
+
+ low = score(results, 0.5)
+ high = score(results, 0.7)
+
+ assert (low.offer_rate, low.precision, low.recall) == (5 / 6, 0.6, 1.0)
+ assert (low.false_offers, low.wrong_kind) == (1, 1)
+ assert (high.offer_rate, high.precision, high.recall, high.missed) == (0.5, 2 / 3, 0.5, 1)
+ assert best_threshold([low, high]) == low
+ # Every threshold from 0.61 to 0.90 offers on half the cases, and the tie goes to the highest.
+ closest = closest_to_offer_rate(results, 0.5)
+ assert closest is not None and (closest.threshold, closest.offer_rate) == (0.9, 0.5)
+ # Offering nothing where offers are wanted scores zero, so that threshold still ranks.
+ silent = score(results, 0.95)
+ assert (silent.precision, silent.recall, silent.f1) == (None, 0.0, 0.0)
+
+ @parameterized.expand(
+ [
+ (
+ "repeated_name",
+ "- {name: same, category: c, acceptable: [none], question: q, answer: a, tools: [query-trends]}\n"
+ "- {name: same, category: c, acceptable: [none], question: q, answer: a, tools: [query-trends]}\n",
+ ),
+ (
+ "repeated_key",
+ "- name: one\n category: c\n acceptable: [none]\n acceptable: [scout]\n"
+ " question: q\n answer: a\n tools: [query-trends]\n",
+ ),
+ (
+ "no_offer_available",
+ "- {name: one, category: c, acceptable: [none], question: q, answer: a, scouts_available: false}\n",
+ ),
+ ]
+ )
+ def test_a_case_file_that_would_mislabel_or_crash_is_rejected(self, _name: str, content: str):
+ with tempfile.NamedTemporaryFile("w", suffix=".yaml") as cases_file:
+ cases_file.write(content)
+ cases_file.flush()
+
+ with self.assertRaises(ValueError):
+ load_cases(Path(cases_file.name))
+
+ def test_judges_are_compared_on_the_cases_every_judge_answered(self):
+ cases = load_cases()[:3]
+ answered = [CaseResult(case=case, judgment=_judgment(show_probability=0.9), seconds=0.1) for case in cases]
+ one_failure = [*answered[:2], CaseResult(case=cases[2], judgment=None, seconds=60.0, error="Timeout")]
+
+ scored = on_shared_cases(
+ [JudgeRun(label="a", results=tuple(answered)), JudgeRun(label="b", results=tuple(one_failure))]
+ )
+
+ assert [[result.case.name for result in run.results] for run in scored] == [
+ [case.name for case in cases[:2]]
+ ] * 2
+
+ def test_endpoints_keep_credentials_out_of_the_url_and_label(self):
+ endpoints = parse_endpoints(
+ "http://judge:p%[email protected]:8080#candidate-2, https://api.example.com/v2/systemone"
+ )
+
+ assert endpoints == [
+ SystemOneEndpoint(
+ url="http://10.0.0.1:8080/v1/systemone", model="candidate-2", username="judge", password="p@ss"
+ ),
+ SystemOneEndpoint(url="https://api.example.com/v2/systemone"),
+ ]
+ assert [endpoint.label for endpoint in endpoints] == ["10.0.0.1:8080 candidate-2", "api.example.com default"]
+ assert "p@ss" not in repr(endpoints)
+
+ @parameterized.expand(
+ [
+ ("http_remote_host", "http://judge:[email protected]:8080", True),
+ ("https", "https://judge:[email protected]", False),
+ ("loopback", "http://judge:[email protected]:8080", False),
+ ("no_credentials", "http://203.0.113.7:8080", False),
+ ]
+ )
+ def test_flags_credentials_sent_over_plain_http(self, _name: str, entry: str, expected: bool):
+ [endpoint] = parse_endpoints(entry)
+
+ assert endpoint.sends_credentials_in_clear is expected
+
+ @parameterized.expand([("no_scheme", "judge:[email protected]"), ("bad_port", "http://judge:[email protected]:99999")])
+ def test_endpoint_errors_do_not_echo_the_entry(self, _name: str, entry: str):
+ with self.assertRaises(ValueError) as raised:
+ parse_endpoints(f"https://api.example.com {entry}")
+
+ assert str(raised.exception).startswith("Endpoint 2 ")
+ assert "secret" not in str(raised.exception)
+
+ def test_a_malformed_endpoint_reply_fails_only_its_case(self):
+ case = load_cases()[0]
+ reply = MagicMock(status_code=200)
+ reply.json.return_value = {"model": "candidate", "answers": {}}
+
+ with patch("products.posthog_ai.backend.turn_suggestions.benchmark.requests.post", return_value=reply) as post:
+ [result] = run_cases(
+ [case], workers=1, on_result=lambda _: None, endpoint=SystemOneEndpoint(url="http://judge")
+ )
+
+ assert result.judgment is None
+ assert result.error is not None and result.error.startswith("malformed answer: ")
+ assert "model" not in post.call_args.kwargs["json"]
+
+
class TestClassifyTurn(SimpleTestCase):
def _classify(self, judgment: TurnJudgment | None, scout_draft: ScoutDraft | None = None):
with (
diff --git a/products/posthog_ai/backend/turn_suggestions/benchmark.py b/products/posthog_ai/backend/turn_suggestions/benchmark.py
new file mode 100644
index 000000000000..163124ba1e70
--- /dev/null
+++ b/products/posthog_ai/backend/turn_suggestions/benchmark.py
@@ -0,0 +1,429 @@
+"""Runs labeled PostHog AI turns through live Jev and scores the policy at a range of show thresholds.
+
+The cases live in ``benchmark_cases.yaml``. Each case lists the offers that would be a good outcome,
+so one Jev run per case scores every threshold: the policy is re-applied to the same judgment
+instead of asking Jev again.
+"""
+
+import re
+import time
+import ipaddress
+from collections.abc import Callable, Iterable, Sequence
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from dataclasses import field
+from enum import StrEnum
+from pathlib import Path
+from typing import Any
+from urllib.parse import unquote, urlsplit, urlunsplit
+
+import yaml
+import requests
+
+from posthog.dataclasses import frozen
+from posthog.llm.system_one import SystemOneRequestFailed, build_system_one_body, parse_system_one_response
+
+from products.posthog_ai.backend.turn_suggestions.classifier import pick_offer
+from products.posthog_ai.backend.turn_suggestions.judgment import (
+ TurnJudgment,
+ build_judge_questions,
+ build_judge_state,
+ judge_turn,
+ read_judgment,
+)
+from products.posthog_ai.backend.turn_suggestions.service import available_offers
+from products.posthog_ai.backend.turn_suggestions.transcript import (
+ EarlierTurn,
+ ErrorIssueRef,
+ SavedInsightRef,
+ TranscriptToolCall,
+ TurnTranscript,
+)
+from products.posthog_ai.backend.turn_suggestions.verdict import OfferKind
+
+CASES_PATH = Path(__file__).with_name("benchmark_cases.yaml")
+
+DEFAULT_THRESHOLDS: tuple[float, ...] = tuple(round(0.2 + step * 0.05, 2) for step in range(15))
+# Fine enough that a small case file can land within a case or two of a target offer rate.
+FINE_THRESHOLDS: tuple[float, ...] = tuple(round(step * 0.01, 2) for step in range(1, 100))
+
+# A candidate server can answer slower than the ai-gateway. The benchmark prints the seconds per case, so a
+# slow answer shows up there instead of as a failure.
+ENDPOINT_TIMEOUT: tuple[float, float] = (5.0, 60.0)
+
+
+class Expectation(StrEnum):
+ OFFER = "offer"
+ NOTHING = "nothing"
+ EITHER = "either"
+
+
+class Outcome(StrEnum):
+ CORRECT = "correct"
+ FALSE_OFFER = "false_offer"
+ MISSED = "missed"
+ WRONG_KIND = "wrong_kind"
+ EITHER = "either"
+ FAILED = "failed"
+
+
+@frozen
+class BenchmarkCase:
+ name: str
+ category: str
+ acceptable: frozenset[OfferKind]
+ transcript: TurnTranscript
+ available: frozenset[OfferKind]
+
+ @property
+ def expectation(self) -> Expectation:
+ if self.acceptable == {OfferKind.NONE}:
+ return Expectation.NOTHING
+ return Expectation.EITHER if OfferKind.NONE in self.acceptable else Expectation.OFFER
+
+ @property
+ def want_label(self) -> str:
+ return "nothing" if self.expectation == Expectation.NOTHING else "|".join(sorted(self.acceptable))
+
+
+@frozen
+class SystemOneEndpoint:
+ """A server other than the ai-gateway that serves the System One API. ``model`` is sent only when
+ set, because a candidate server can reject the gateway's model ids. Basic auth is sent only when
+ ``username`` is set."""
+
+ url: str
+ model: str | None = None
+ username: str | None = None
+ password: str = field(default="", repr=False)
+
+ @property
+ def label(self) -> str:
+ return f"{urlsplit(self.url).netloc} {self.model or 'default'}"
+
+ @property
+ def sends_credentials_in_clear(self) -> bool:
+ """Basic auth over http to a host off this machine, where anyone on the path can read it."""
+ parts = urlsplit(self.url)
+ return bool(self.username) and parts.scheme == "http" and not _is_loopback(parts.hostname or "")
+
+
+def _is_loopback(host: str) -> bool:
+ if host == "localhost":
+ return True
+ try:
+ return ipaddress.ip_address(host).is_loopback
+ except ValueError:
+ return False
+
+
+SYSTEM_ONE_PATH = "/v1/systemone"
+
+# A URL never holds a space, a comma, or a semicolon, so any of them can separate the entries.
+_ENTRY_SEPARATORS = re.compile(r"[\s,;]+")
+
+
+def parse_endpoint(entry: str, position: int = 1) -> SystemOneEndpoint:
+ """Reads ``http[s]://[username:password@]host[:port][/path][#model]``. The path defaults to
+ ``/v1/systemone``. The fragment names the model, and a URL fragment never reaches the server.
+ Percent-encode a ``:``, ``@``, or ``#`` inside the username or password."""
+ parts = urlsplit(entry)
+ # The entry can hold a password, so the errors name its position, never its text.
+ if parts.scheme not in {"http", "https"} or not parts.hostname:
+ raise ValueError(f"Endpoint {position} is not an http:// or https:// URL")
+ try:
+ port = parts.port
+ except ValueError:
+ raise ValueError(f"Endpoint {position} has an invalid port") from None
+ host = f"[{parts.hostname}]" if ":" in parts.hostname else parts.hostname
+ netloc = f"{host}:{port}" if port else host
+ path = parts.path if parts.path not in {"", "/"} else SYSTEM_ONE_PATH
+ return SystemOneEndpoint(
+ url=urlunsplit((parts.scheme, netloc, path, parts.query, "")),
+ model=unquote(parts.fragment) or None,
+ username=unquote(parts.username) if parts.username else None,
+ password=unquote(parts.password or ""),
+ )
+
+
+def parse_endpoints(value: str) -> list[SystemOneEndpoint]:
+ entries = [entry for entry in _ENTRY_SEPARATORS.split(value) if entry]
+ return [parse_endpoint(entry, position) for position, entry in enumerate(entries, start=1)]
+
+
+@frozen
+class CaseResult:
+ case: BenchmarkCase
+ judgment: TurnJudgment | None
+ seconds: float
+ error: str | None = None
+
+ def picked(self, show_threshold: float) -> OfferKind:
+ if self.judgment is None:
+ return OfferKind.NONE
+ return pick_offer(self.judgment, self.case.available, show_threshold=show_threshold)
+
+ def outcome(self, show_threshold: float) -> Outcome:
+ if self.judgment is None:
+ return Outcome.FAILED
+ expectation = self.case.expectation
+ picked = self.picked(show_threshold)
+ if expectation == Expectation.EITHER:
+ return Outcome.EITHER if picked in self.case.acceptable else Outcome.WRONG_KIND
+ if expectation == Expectation.NOTHING:
+ return Outcome.CORRECT if picked == OfferKind.NONE else Outcome.FALSE_OFFER
+ if picked == OfferKind.NONE:
+ return Outcome.MISSED
+ return Outcome.CORRECT if picked in self.case.acceptable else Outcome.WRONG_KIND
+
+
+@frozen
+class ThresholdScore:
+ threshold: float
+ offer_rate: float
+ precision: float | None
+ recall: float | None
+ false_offers: int
+ missed: int
+ wrong_kind: int
+
+ @property
+ def f1(self) -> float | None:
+ if self.recall == 0:
+ # Offering nothing on cases that want an offer scores zero, not unmeasured.
+ return 0.0
+ if self.precision is None or self.recall is None:
+ return None
+ total = self.precision + self.recall
+ return 2 * self.precision * self.recall / total if total else 0.0
+
+
+def _transcript_from_case(raw: dict[str, Any]) -> TurnTranscript:
+ status = raw.get("tool_status", "completed")
+ earlier = [
+ EarlierTurn(question=turn["question"], tool_names=tuple(turn.get("tools", [])), answer_excerpt=turn["answer"])
+ for turn in raw.get("earlier", [])
+ ]
+ return TurnTranscript(
+ human_messages=(*(turn.question for turn in earlier), raw["question"]),
+ latest_turn_complete=True,
+ assistant_text=raw["answer"],
+ tool_calls=tuple(
+ TranscriptToolCall(name=tool, args_preview="", status=status) for tool in raw.get("tools", [])
+ ),
+ earlier_turns=tuple(earlier),
+ saved_insights=tuple(
+ SavedInsightRef(short_id=ref["short_id"], insight_id=None, name=ref["name"], query_kind=ref["kind"])
+ for ref in raw.get("insights", [])
+ ),
+ error_issues=tuple(ErrorIssueRef(issue_id=ref["id"], name=ref["name"]) for ref in raw.get("issues", [])),
+ )
+
+
+class _UniqueKeyLoader(yaml.SafeLoader):
+ """A safe loader that rejects a repeated key, where plain YAML keeps the last value without a word."""
+
+ def construct_mapping(self, node: yaml.MappingNode, deep: bool = False) -> dict[Any, Any]:
+ keys = [self.construct_object(key_node, deep=deep) for key_node, _ in node.value]
+ repeated = sorted({str(key) for key in keys if keys.count(key) > 1})
+ if repeated:
+ raise ValueError(f"Duplicate benchmark case keys: {', '.join(repeated)}")
+ return super().construct_mapping(node, deep=deep)
+
+
+def _load_yaml(text: str) -> Any:
+ loader = _UniqueKeyLoader(text)
+ try:
+ return loader.get_single_data()
+ finally:
+ loader.dispose()
+
+
+def load_cases(path: Path = CASES_PATH) -> list[BenchmarkCase]:
+ cases = []
+ names: set[str] = set()
+ for raw in _load_yaml(path.read_text()):
+ # Results are matched across judges by case name, so a repeated name would mix two cases.
+ if raw["name"] in names:
+ raise ValueError(f"Duplicate benchmark case name: {raw['name']}")
+ names.add(raw["name"])
+ transcript = _transcript_from_case(raw)
+ available = available_offers(transcript, scouts_available=raw.get("scouts_available", True))
+ # Production never asks the judge about a turn with nothing to offer.
+ if not available:
+ raise ValueError(f"Benchmark case {raw['name']} has no offer its turn can make")
+ cases.append(
+ BenchmarkCase(
+ name=raw["name"],
+ category=raw["category"],
+ acceptable=frozenset(OfferKind(kind) for kind in raw["acceptable"]),
+ transcript=transcript,
+ available=available,
+ )
+ )
+ return cases
+
+
+def _judge_at_endpoint(case: BenchmarkCase, endpoint: SystemOneEndpoint) -> TurnJudgment:
+ questions = build_judge_questions(case.transcript, case.available)
+ body = build_system_one_body(state=build_judge_state(case.transcript), questions=questions, model=endpoint.model)
+ response = requests.post(
+ endpoint.url,
+ json=body,
+ auth=(endpoint.username, endpoint.password) if endpoint.username else None,
+ timeout=ENDPOINT_TIMEOUT,
+ allow_redirects=False,
+ )
+ response.raise_for_status()
+ return read_judgment(parse_system_one_response(response.json(), questions), case.transcript, case.available)
+
+
+def _judge(case: BenchmarkCase, endpoint: SystemOneEndpoint | None) -> CaseResult:
+ started = time.monotonic()
+ judgment: TurnJudgment | None = None
+ failure: str | None = None
+ if endpoint is None:
+ judgment = judge_turn(case.transcript, available=case.available)
+ else:
+ try:
+ judgment = _judge_at_endpoint(case, endpoint)
+ except requests.HTTPError as error:
+ response = error.response
+ # The start of the body usually names the rejected field, which is what a 400 needs to be fixed.
+ failure = f"HTTP {response.status_code}: {response.text[:200]}" if response is not None else "HTTP error"
+ except requests.RequestException as error:
+ failure = type(error).__name__
+ except SystemOneRequestFailed as error:
+ # A malformed answer, such as a choice outside the options, fails only this case.
+ failure = f"malformed answer: {error}"
+ return CaseResult(case=case, judgment=judgment, seconds=time.monotonic() - started, error=failure)
+
+
+def run_cases(
+ cases: Sequence[BenchmarkCase],
+ *,
+ workers: int,
+ on_result: Callable[[CaseResult], None],
+ endpoint: SystemOneEndpoint | None = None,
+) -> list[CaseResult]:
+ """Judge every case, calling ``on_result`` as each answer arrives so a caller can print it live.
+ ``endpoint`` sends the judgments to that server instead of the configured one. The results come back in
+ the order of ``cases``."""
+ results = []
+ with ThreadPoolExecutor(max_workers=workers) as pool:
+ for future in as_completed([pool.submit(_judge, case, endpoint) for case in cases]):
+ result = future.result()
+ on_result(result)
+ results.append(result)
+ order = {case.name: index for index, case in enumerate(cases)}
+ return sorted(results, key=lambda result: order[result.case.name])
+
+
+@frozen
+class JudgeRun:
+ """Every case's result from one judge: Jev through the configured System One server, or one candidate endpoint."""
+
+ label: str
+ results: tuple[CaseResult, ...]
+
+ def by_case(self) -> dict[str, CaseResult]:
+ return {result.case.name: result for result in self.results}
+
+
+def agreement(run: JudgeRun, run_threshold: float, reference: JudgeRun, reference_threshold: float) -> float | None:
+ """The share of cases both judges answered where they pick the same offer, each at its own threshold."""
+ reference_results = reference.by_case()
+ pairs = [
+ (result, reference_results[result.case.name])
+ for result in run.results
+ if result.judgment is not None
+ and result.case.name in reference_results
+ and reference_results[result.case.name].judgment is not None
+ ]
+ same = sum(1 for result, other in pairs if result.picked(run_threshold) == other.picked(reference_threshold))
+ return _ratio(same, len(pairs))
+
+
+def disagreements(runs: Sequence[JudgeRun], thresholds: Sequence[float]) -> list[tuple[CaseResult, ...]]:
+ """The cases where the judges that answered pick different offers, each judge at its threshold in
+ ``thresholds``, in case file order. A failed request alone does not make a disagreement, because
+ the failure counts show those."""
+ per_run = [run.by_case() for run in runs]
+ rows = []
+ for name in (result.case.name for result in runs[0].results):
+ row = tuple(results[name] for results in per_run if name in results)
+ if len(row) != len(runs):
+ continue
+ picks = {result.picked(threshold) for result, threshold in zip(row, thresholds) if result.judgment is not None}
+ if len(picks) > 1:
+ rows.append(row)
+ return rows
+
+
+def _ratio(numerator: int, denominator: int) -> float | None:
+ return numerator / denominator if denominator else None
+
+
+def score(results: Iterable[CaseResult], threshold: float) -> ThresholdScore:
+ judged = [result for result in results if result.judgment is not None]
+ outcomes = [result.outcome(threshold) for result in judged]
+ offered = sum(1 for result in judged if result.picked(threshold) != OfferKind.NONE)
+ correct_offers = sum(
+ 1
+ for result, outcome in zip(judged, outcomes)
+ if outcome == Outcome.CORRECT and result.case.expectation == Expectation.OFFER
+ )
+ # A wrong kind on an either-is-fine case counts against precision, so an acceptable card there counts for it.
+ acceptable_optional_offers = sum(
+ 1
+ for result, outcome in zip(judged, outcomes)
+ if outcome == Outcome.EITHER and result.picked(threshold) != OfferKind.NONE
+ )
+ false_offers = outcomes.count(Outcome.FALSE_OFFER)
+ wrong_kind = outcomes.count(Outcome.WRONG_KIND)
+ expecting_offer = sum(1 for result in judged if result.case.expectation == Expectation.OFFER)
+ return ThresholdScore(
+ threshold=threshold,
+ offer_rate=_ratio(offered, len(judged)) or 0.0,
+ precision=_ratio(
+ correct_offers + acceptable_optional_offers,
+ correct_offers + acceptable_optional_offers + false_offers + wrong_kind,
+ ),
+ recall=_ratio(correct_offers, expecting_offer),
+ false_offers=false_offers,
+ missed=outcomes.count(Outcome.MISSED),
+ wrong_kind=wrong_kind,
+ )
+
+
+def sweep(results: Sequence[CaseResult], thresholds: Iterable[float] = DEFAULT_THRESHOLDS) -> list[ThresholdScore]:
+ return [score(results, threshold) for threshold in thresholds]
+
+
+def sweep_thresholds(current: float) -> list[float]:
+ """The default sweep plus ``current``, so the threshold under test always has its own row."""
+ return sorted({*DEFAULT_THRESHOLDS, current})
+
+
+def on_shared_cases(runs: Sequence[JudgeRun]) -> list[JudgeRun]:
+ """Each run cut down to the cases every run answered, so no judge is scored on an easier set
+ because it failed the hard cases."""
+ answered = [{result.case.name for result in run.results if result.judgment is not None} for run in runs]
+ shared = set.intersection(*answered) if answered else set()
+ return [
+ JudgeRun(label=run.label, results=tuple(result for result in run.results if result.case.name in shared))
+ for run in runs
+ ]
+
+
+def best_threshold(scores: Sequence[ThresholdScore]) -> ThresholdScore | None:
+ """The threshold with the best F1. A tie goes to the higher threshold, which interrupts fewer people."""
+ ranked = [entry for entry in scores if entry.f1 is not None]
+ return max(ranked, key=lambda entry: (entry.f1 or 0.0, entry.threshold)) if ranked else None
+
+
+def closest_to_offer_rate(results: Sequence[CaseResult], target: float) -> ThresholdScore | None:
+ """The fine-grained threshold whose offer rate lands nearest ``target``. A tie goes to the higher
+ threshold, which interrupts fewer people. ``None`` when no case was judged."""
+ if not any(result.judgment is not None for result in results):
+ return None
+ return min(sweep(results, FINE_THRESHOLDS), key=lambda entry: (abs(entry.offer_rate - target), -entry.threshold))
diff --git a/products/posthog_ai/backend/turn_suggestions/benchmark_cases.yaml b/products/posthog_ai/backend/turn_suggestions/benchmark_cases.yaml
new file mode 100644
index 000000000000..c3aa1699772f
--- /dev/null
+++ b/products/posthog_ai/backend/turn_suggestions/benchmark_cases.yaml
@@ -0,0 +1,587 @@
+# Labeled PostHog AI turns for tuning the turn suggestion thresholds against live Jev.
+# Run them with `python manage.py turn_suggestions_benchmark`.
+#
+# Every question and answer is written from scratch with invented names and ids. The mix of case
+# kinds (openers with no question, dashboard and flag edits, lookups of one person, monitoring asks,
+# investigations) follows the kinds of conversations people have. Do not paste real conversations
+# here, even with names changed.
+#
+# `acceptable` lists every offer that would be a good outcome. `[none]` means the card must stay
+# hidden. A case that lists `none` next to offers is borderline: no card or one of those offers is
+# fine, so only an offer of another kind counts against it.
+#
+# Optional fields: `tool_status` (default completed), `earlier` turns, `insights`, `issues`, and
+# `scouts_available` (default true).
+
+# Recurring metrics
+- name: weekly-signups
+ category: basic_count
+ acceptable: [scout, none]
+ question: How many signups did we get this week compared to last week?
+ tools: [query-trends]
+ answer: You had 412 signups this week, up 8% from 381 last week. Most of the growth came from organic search.
+
+- name: signups-down-today
+ category: recurring_metric
+ acceptable: [scout]
+ question: Are signups down today? It feels slow.
+ tools: [query-trends]
+ answer: Signups today are at 31 so far, about 40% below the same time yesterday (52). The drop started around 09:00 UTC and affects every channel.
+
+- name: revenue-month-to-date
+ category: basic_count
+ acceptable: [scout, none]
+ question: What's our revenue month to date and how does it compare to last month?
+ tools: [execute-sql]
+ answer: Revenue month to date is $48,200, 6% ahead of the same point last month ($45,470). Annual plans make up 38% of it.
+
+- name: checkout-conversion-worry
+ category: recurring_metric
+ acceptable: [scout]
+ question: Is checkout conversion getting worse? I want to keep an eye on it.
+ tools: [query-funnel]
+ answer: Checkout conversion is 31.2% this week against 33.8% last week. It has slipped for three weeks in a row, mostly on mobile.
+
+- name: p95-latency-concern
+ category: performance
+ acceptable: [notebook]
+ question: Is the p95 page load time on the dashboard page OK this week?
+ tools: [execute-sql]
+ answer: The p95 load time for /dashboard is 2.8s this week, up from 2.1s last week. The rise lines up with the new charts rollout.
+
+- name: several-metrics-digest
+ category: recurring_metric
+ acceptable: [scout]
+ question: And what's the trial to paid conversion rate?
+ tools: [query-funnel]
+ answer: Trial to paid conversion is 14.2% for trials that started last month, up from 12.9% the month before.
+ earlier:
+ - question: How many weekly active users do we have?
+ tools: [query-trends]
+ answer: You have 3,420 weekly active users, up 4% on last week.
+ - question: How many new signups this week?
+ tools: [query-trends]
+ answer: 412 signups this week, up 8% on last week.
+
+- name: llm-spend-yesterday
+ category: recurring_metric
+ acceptable: [scout, none]
+ question: How much did we spend on LLM calls yesterday?
+ tools: [execute-sql]
+ answer: LLM spend yesterday was $182.40 across 41,000 generations. The summarization feature accounts for 61% of it.
+
+- name: dau-last-30-days
+ category: basic_count
+ acceptable: [none]
+ question: Show me daily active users for the last 30 days
+ tools: [query-trends]
+ answer: Daily active users averaged 1,210 over the last 30 days, with weekday peaks around 1,450 and weekend lows near 760.
+
+# Investigations
+- name: checkout-drop-cause-found
+ category: diagnostic
+ acceptable: [notebook]
+ question: Why did checkout conversion drop on Tuesday?
+ tools: [query-funnel, query-session-recordings-list, query-trends]
+ answer: Checkout conversion fell from 34% to 21% on Tuesday starting at 14:10 UTC. The drop lines up with the 14:05 release, which broke the payment form on Safari. Recordings show users stuck on the card step. Conversion recovered after the 17:30 rollback.
+
+- name: churn-spike-cause-found
+ category: diagnostic
+ acceptable: [notebook]
+ question: Why did so many accounts cancel last week?
+ tools: [execute-sql, query-trends, query-cohorts-list]
+ answer: Cancellations rose to 58 last week from a usual 20. Most of them were accounts on the legacy plan that received the price change email on Monday. 41 of the 58 cancellations came within two days of that email.
+
+- name: retention-exploration
+ category: diagnostic
+ acceptable: [notebook, none]
+ question: Why do users who sign up on mobile retain worse than on desktop?
+ tools: [query-retention, query-trends, query-funnel]
+ answer: Mobile signups retain 18% at week 4 against 31% on desktop. Mobile users rarely finish the onboarding checklist (22% against 58%), and those who do finish retain about as well as desktop users.
+
+# Saved insights
+- name: saved-insight-alert
+ category: saved_insight
+ acceptable: [alert, scout]
+ question: Save a chart of daily signups and let me know if it tanks
+ tools: [insight-create]
+ answer: I saved the insight Daily signups. It shows 58 signups yesterday, in line with the last two weeks.
+ insights:
+ - short_id: sgn001
+ name: Daily signups
+ kind: TrendsQuery
+
+- name: saved-insight-subscription
+ category: saved_insight
+ acceptable: [subscription, scout]
+ question: Make a chart of weekly active users and I'd like the team to see it every Monday
+ tools: [insight-create]
+ answer: I saved the insight Weekly active users. You're at 3,420 this week.
+ insights:
+ - short_id: wau001
+ name: Weekly active users
+ kind: TrendsQuery
+
+- name: saved-funnel-no-alert
+ category: saved_insight
+ acceptable: [subscription, scout, none]
+ question: Save the signup funnel as an insight
+ tools: [insight-create]
+ answer: I saved the insight Signup funnel. 42% of visitors who start signup finish it.
+ insights:
+ - short_id: fnl001
+ name: Signup funnel
+ kind: FunnelsQuery
+
+# Error tracking
+- name: error-resolved
+ category: error_tracking
+ acceptable: [error_alert]
+ question: Is the checkout TypeError fixed now?
+ tools: [query-error-tracking-issues-list, error-tracking-issue-get]
+ answer: Yes. The TypeError in checkout stopped at 14:32 UTC, right after the 14:30 deploy, and I marked the issue resolved. There are no new occurrences in the last 6 hours.
+ issues:
+ - id: 0199c0de-1111-7000-8000-0000000000aa
+ name: "TypeError: cannot read properties of undefined (reading 'total')"
+
+- name: error-still-active
+ category: error_tracking
+ acceptable: [none]
+ question: What's the most common error this week?
+ tools: [query-error-tracking-issues-list]
+ answer: The most common error is a TypeError in checkout with 1,204 occurrences affecting 312 users. It is still happening.
+ issues:
+ - id: 0199c0de-2222-7000-8000-0000000000bb
+ name: 'TypeError: cart.items is not iterable'
+
+# Turns that should get nothing
+- name: docs-install
+ category: knowledge
+ acceptable: [none]
+ question: How do I install posthog-js in a Next.js app?
+ tools: [docs-search]
+ answer: Install the package with npm install posthog-js, then initialize it in a client-side provider component with your project token and host.
+
+- name: docs-cohorts-how-to
+ category: knowledge
+ acceptable: [none]
+ question: How do I make a cohort of users who did an event at least 3 times?
+ tools: [docs-search]
+ answer: Create a new cohort, add a behavioral filter "Completed event", pick the event, and set the count to "at least 3 times" in the time range you want.
+
+- name: concept-explanation
+ category: knowledge
+ acceptable: [none]
+ question: What's the difference between a session and a pageview?
+ tools: []
+ answer: A pageview is one page load. A session groups all of a user's activity until they are inactive for 30 minutes, so one session usually holds several pageviews.
+
+- name: create-feature-flag
+ category: action
+ acceptable: [none]
+ question: Create a feature flag called beta-dashboard for users in the beta cohort
+ tools: [create-feature-flag]
+ answer: Done. I created the feature flag beta-dashboard, rolled out to 100% of the Beta users cohort.
+
+- name: create-survey
+ category: action
+ acceptable: [none]
+ question: Make an NPS survey that shows on the settings page
+ tools: [survey-create]
+ answer: I created the survey Settings NPS. It shows on URLs containing /settings to 10% of users and is saved as a draft.
+
+- name: rename-dashboard
+ category: action
+ acceptable: [none]
+ question: Rename the Growth dashboard to Growth weekly
+ tools: [dashboard-update]
+ answer: Renamed. The dashboard is now called Growth weekly.
+
+- name: clarification
+ category: follow_up
+ acceptable: [none]
+ question: What does DAU mean in that chart?
+ tools: []
+ answer: DAU means daily active users, the number of unique users who sent at least one event that day.
+ earlier:
+ - question: Show me DAU for the last 30 days
+ tools: [query-trends]
+ answer: DAU averaged 1,200 over the last 30 days.
+
+- name: breakdown-follow-up
+ category: follow_up
+ acceptable: [scout, none]
+ question: Break that down by country
+ tools: [query-trends]
+ answer: The US brought 162 of the 412 signups, followed by Germany with 48 and the UK with 41.
+ earlier:
+ - question: How many signups did we get this week?
+ tools: [query-trends]
+ answer: You had 412 signups this week, up 8% on last week.
+
+- name: thanks
+ category: small_talk
+ acceptable: [none]
+ question: Thanks, that's helpful!
+ tools: []
+ answer: Glad it helped. Let me know if you want to dig into anything else.
+ earlier:
+ - question: How many signups did we get this week?
+ tools: [query-trends]
+ answer: You had 412 signups this week, up 8% on last week.
+
+- name: no-data
+ category: failure
+ acceptable: [none]
+ question: How many people used the export feature last week?
+ tools: [read-data-schema]
+ answer: I couldn't find any events related to export in this project. Which event tracks exports?
+
+- name: asks-back
+ category: failure
+ acceptable: [none]
+ question: Show me retention
+ tools: []
+ answer: Which event should count as returning, any event or a specific one like $pageview or purchase_completed?
+
+- name: tool-failed
+ category: failure
+ acceptable: [none]
+ question: What's our revenue this month?
+ tools: [execute-sql]
+ tool_status: failed
+ answer: The query timed out. Do you want me to try a smaller date range?
+
+- name: single-user-lookup
+ category: one_off
+ acceptable: [none]
+ question: When did [email protected] last log in?
+ tools: [execute-sql]
+ answer: [email protected] last logged in on September 14 at 16:02 UTC from Chrome on macOS.
+
+- name: rage-click-recordings
+ category: one_off
+ acceptable: [none]
+ question: Find recordings where users rage clicked on the pricing page yesterday
+ tools: [query-session-recordings-list]
+ answer: I found 7 recordings with rage clicks on /pricing yesterday. Most of them are on the plan toggle, which doesn't respond on the first click.
+
+- name: fix-sql
+ category: one_off
+ acceptable: [none]
+ question: Why does my HogQL query fail with "unknown column"?
+ tools: [execute-sql]
+ answer: The column is called properties.$browser, not browser. Here is the fixed query, and it returns 12 rows.
+
+- name: schema-question
+ category: one_off
+ acceptable: [none]
+ question: What events do we track?
+ tools: [read-data-schema]
+ answer: The project tracks 46 custom events. The most frequent are $pageview, button_clicked, signed_up and purchase_completed.
+
+- name: browser-share
+ category: one_off
+ acceptable: [none]
+ question: Which browser do most of our users use?
+ tools: [query-trends]
+ answer: Chrome leads with 64% of users, then Safari with 21% and Firefox with 8%.
+
+# Openers with no question yet
+- name: greeting-first-turn
+ category: small_talk
+ acceptable: [none]
+ question: hey
+ tools: []
+ answer: Hi! I can look at your product data, build insights and dashboards, or answer questions about PostHog. What would you like to do?
+
+- name: help-request-first-turn
+ category: small_talk
+ acceptable: [none]
+ question: can you help me with something
+ tools: []
+ answer: Sure. What do you need help with?
+
+# Prompts people start from a suggestion
+- name: pirate-funnel-template
+ category: saved_insight
+ acceptable: [subscription, scout, none]
+ question: Build me a pirate metrics funnel
+ tools: [read-data-schema, insight-create]
+ answer: I built an AARRR funnel from $pageview to signed_up, activated, subscription_started and invite_sent. 12% of visitors reach activation and 3% start a subscription. The biggest drop is between signup and activation.
+ insights:
+ - short_id: aar001
+ name: Pirate metrics funnel
+ kind: FunnelsQuery
+
+- name: retention-two-weeks-template
+ category: recurring_metric
+ acceptable: [scout, none]
+ question: How is retention looking over the last two weeks?
+ tools: [query-retention]
+ answer: Of the users active two weeks ago, 38% came back last week and 27% this week. Users who signed up in that window retain worse, at 21% after one week.
+
+- name: dashboard-weekly-review
+ category: recurring_metric
+ acceptable: [scout]
+ question: What changed on my Product overview dashboard this week?
+ tools: [dashboard-get, query-trends, query-funnel, query-trends]
+ answer: Three things stand out this week. Signups are up 11%, the activation funnel fell from 42% to 37%, and mobile sessions grew 19%. The other tiles are flat.
+
+# Explicit monitoring
+- name: campaign-signups-tracking
+ category: recurring_metric
+ acceptable: [scout]
+ question: Keep track of signups coming from the spring launch campaign
+ tools: [query-trends]
+ answer: Signups with utm_campaign=spring_launch reached 64 in the last 7 days, 9 of them yesterday. Most arrive from paid social.
+
+- name: hourly-job-failure-rate
+ category: recurring_metric
+ acceptable: [scout, none]
+ question: What share of export jobs failed each hour today?
+ tools: [execute-sql]
+ answer: Failures peaked at 14% between 10:00 and 11:00 UTC and stayed under 2% after 13:00. The rest of the day averaged 1.5%.
+
+- name: weekly-llm-cost-per-user
+ category: recurring_metric
+ acceptable: [scout]
+ question: Show me LLM cost per active user by week
+ tools: [execute-sql]
+ answer: Cost per weekly active user went from $0.41 to $0.63 over the last 8 weeks. It has risen every week since the summaries feature launched.
+
+- name: mobile-checkout-spanish
+ category: recurring_metric
+ acceptable: [scout]
+ question: ¿Cuántos usuarios de la app móvil completaron el checkout esta semana, comparado con la anterior? Me preocupa que esté bajando.
+ tools: [query-funnel]
+ answer: En la app móvil, 1.140 usuarios completaron el checkout esta semana, un 9% menos que la semana anterior. La caída se concentra en Android.
+
+# Edits and configuration
+- name: build-health-dashboard
+ category: action
+ acceptable: [subscription, scout, none]
+ question: Make a dashboard with daily signups, activation rate and churned accounts
+ tools: [dashboard-create, insight-create, insight-create, insight-create]
+ answer: I created the dashboard Growth health with three tiles, daily signups, activation rate and churned accounts per week, all over the last 30 days.
+ insights:
+ - short_id: gh0001
+ name: Daily signups
+ kind: TrendsQuery
+ - short_id: gh0002
+ name: Activation rate
+ kind: FunnelsQuery
+ - short_id: gh0003
+ name: Churned accounts per week
+ kind: TrendsQuery
+
+- name: dashboard-date-range
+ category: action
+ acceptable: [none]
+ question: Set the default date range on the Engagement dashboard to the last 30 days
+ tools: [dashboard-update]
+ answer: Done. The Engagement dashboard now opens on the last 30 days.
+
+- name: fix-chart-axis
+ category: action
+ acceptable: [none]
+ question: The percent sign shows up twice on this chart's axis, can you fix it?
+ tools: [insight-get, insight-update]
+ answer: Fixed. The y axis now formats values as percentages without the extra suffix.
+ insights:
+ - short_id: fx0001
+ name: Checkout completion rate
+ kind: TrendsQuery
+
+- name: disable-flag
+ category: action
+ acceptable: [none]
+ question: Turn off the new-checkout-flow flag
+ tools: [update-feature-flag]
+ answer: The new-checkout-flow flag is now disabled for everyone.
+
+- name: remove-member
+ category: action
+ acceptable: [none]
+ question: Remove a former teammate from this project
+ tools: []
+ answer: I can't change project members. Go to Settings, then Members, and remove them from there.
+
+- name: drop-noisy-event
+ category: action
+ acceptable: [none]
+ question: Stop ingesting the debug_ping event
+ tools: [create-hog-function]
+ answer: I added a transformation that drops debug_ping events before they are stored. It applies to new events from now on.
+
+- name: exclude-internal-users
+ category: action
+ acceptable: [none]
+ question: Filter out our own team from insights
+ tools: [update-project]
+ answer: I added a test account filter that excludes emails ending in @example.com. Insights with "filter out internal and test users" turned on now skip them.
+
+# Lookups of one person, session or list
+- name: session-id-lookup
+ category: one_off
+ acceptable: [none]
+ question: Find the recording for session 0199d2aa-5b1c-7e00-9f10-00000000c0de
+ tools: [query-session-recordings-list]
+ answer: Here is that recording. It lasts 6 minutes and ends on the checkout page after two failed payment attempts.
+
+- name: feature-users-list
+ category: one_off
+ acceptable: [none]
+ question: Which accounts tried the CSV export last month?
+ tools: [execute-sql]
+ answer: 23 accounts used the CSV export last month. The five heaviest users exported between 40 and 120 files each.
+
+# Experiments
+- name: experiment-significance
+ category: recurring_metric
+ acceptable: [scout, none]
+ question: Is the pricing page experiment significant yet?
+ tools: [experiment-results-get]
+ answer: Not yet. The test variant converts at 4.1% against 3.8% for control, with a 71% chance to beat control. At current traffic it needs about 9 more days.
+
+- name: experiment-variant-lost
+ category: diagnostic
+ acceptable: [notebook, none]
+ question: Why did the test variant lose?
+ tools: [experiment-results-get, query-funnel, query-trends]
+ answer: The test variant added a plan picker before checkout. Users who saw it dropped off 18% more at that step, mostly on mobile, which accounts for nearly all of the gap.
+
+# Costs and data quality
+- name: llm-bill-up-usage-down
+ category: diagnostic
+ acceptable: [notebook]
+ question: Why did our LLM bill go up last week when usage went down?
+ tools: [execute-sql, query-trends]
+ answer: Generations fell 9%, but the average cost per generation doubled after the default model switched to a larger one on Tuesday. That switch explains about 85% of the increase.
+
+- name: duplicate-order-events
+ category: diagnostic
+ acceptable: [notebook, none]
+ question: Why is order_completed firing twice for some users?
+ tools: [execute-sql, query-session-recordings-list]
+ answer: About 6% of orders have two order_completed events less than a second apart. All of them come from the web app when people double-click the pay button. The mobile apps don't have the problem.
+
+- name: ios-data-still-arriving
+ category: recurring_metric
+ acceptable: [scout, none]
+ question: Is data still coming in from the iOS app?
+ tools: [execute-sql]
+ answer: Yes. The iOS app sent 48,000 events in the last hour, in line with the same hour last week. The latest event arrived 20 seconds ago.
+
+# Errors
+- name: top-errors-by-users
+ category: error_tracking
+ acceptable: [none]
+ question: Which errors affect the most users right now?
+ tools: [query-error-tracking-issues-list]
+ answer: The top issue is a NetworkError on file upload, affecting 540 users today. Next is a TypeError on the settings page with 210 users. Both are still active.
+ issues:
+ - id: 0199d2aa-0001-7000-8000-0000000000e1
+ name: 'NetworkError: upload request failed'
+ - id: 0199d2aa-0002-7000-8000-0000000000e2
+ name: 'TypeError: preferences is undefined'
+
+- name: not-found-spike
+ category: diagnostic
+ acceptable: [notebook]
+ question: Which pages are causing the spike in 404s since yesterday?
+ tools: [query-trends, execute-sql]
+ answer: Most new 404s come from /docs/v1/ links, which stopped resolving after yesterday's docs migration at 16:00 UTC. They account for 82% of the spike.
+
+# One-off breakdowns
+- name: top-referrers
+ category: one_off
+ acceptable: [none]
+ question: What are our top referring domains this month?
+ tools: [query-trends]
+ answer: Google leads with 41% of referred visits, then news.example.com with 12% and a partner blog with 7%.
+
+- name: device-split
+ category: one_off
+ acceptable: [none]
+ question: What's the split between mobile and desktop sessions?
+ tools: [query-trends]
+ answer: 58% of sessions in the last 30 days were on mobile and 42% on desktop.
+
+# Advice and setup questions
+- name: kpi-brainstorm
+ category: knowledge
+ acceptable: [none]
+ question: What KPIs should we track for our marketing site each quarter?
+ tools: []
+ answer: A good starting set is unique visitors, signup conversion rate, the share of traffic from organic search, and time to first key action. I can build insights for any of these.
+
+- name: ad-objective-advice
+ category: knowledge
+ acceptable: [none]
+ question: Which campaign objective should I pick for a lead generation ad?
+ tools: []
+ answer: For lead generation, pick the leads objective if you collect details in the ad, or conversions if people sign up on your site. PostHog can then track what those signups do next.
+
+- name: replay-setup
+ category: knowledge
+ acceptable: [none]
+ question: How do I turn on session replay?
+ tools: [docs-search]
+ answer: Go to Settings, then Session replay, and turn on "Record user sessions". Recordings start appearing within a few minutes of the next visit.
+
+# Performance turns rank a notebook first
+- name: search-api-p99
+ category: performance
+ acceptable: [notebook]
+ question: What's the p99 response time of the search API this week?
+ tools: [execute-sql]
+ answer: The p99 for /api/search is 1,840 ms this week against 1,210 ms last week. Queries with more than three filters are the slowest, at a p99 of 3,100 ms.
+
+- name: mobile-inp-pricing
+ category: performance
+ acceptable: [notebook]
+ question: Why is INP so bad on the pricing page on mobile?
+ tools: [execute-sql, query-session-recordings-list]
+ answer: Mobile INP on /pricing is 480 ms at p75, well over the 200 ms target. Most slow interactions are taps on the plan toggle, which re-renders the whole comparison table.
+
+# One area of the product counts for more than the whole product
+- name: onboarding-errors-this-week
+ category: error_tracking
+ acceptable: [scout]
+ question: Did we get any errors in the onboarding flow this week?
+ tools: [query-error-tracking-issues-list]
+ answer: Yes, two. A ValidationError on the company details step hit 38 users, and a timeout on the invite teammates step hit 9. Both are still happening.
+ issues:
+ - id: 0199d2aa-0003-7000-8000-0000000000e3
+ name: 'ValidationError: company size is required'
+ - id: 0199d2aa-0004-7000-8000-0000000000e4
+ name: 'TimeoutError: invite request took too long'
+
+- name: onboarding-checklist-completion
+ category: recurring_metric
+ acceptable: [scout]
+ question: How many people finished the new onboarding checklist this week?
+ tools: [query-funnel]
+ answer: 214 people finished the new onboarding checklist this week, 31% of those who started it. The connect data step loses the most people.
+
+- name: total-events-this-week
+ category: basic_count
+ acceptable: [none]
+ question: How many events did we get this week?
+ tools: [query-trends]
+ answer: The project received 12.4 million events this week, 3% more than last week.
+
+- name: people-yesterday
+ category: basic_count
+ acceptable: [none]
+ question: How many people used the app yesterday?
+ tools: [query-trends]
+ answer: 1,380 people used the app yesterday, about the same as the day before.
+
+- name: pro-plan-export-usage
+ category: recurring_metric
+ acceptable: [scout]
+ question: How many Pro plan accounts used the new bulk export this week, compared to last week?
+ tools: [query-trends]
+ answer: 86 Pro plan accounts used the bulk export this week, up from 61 last week. Accounts created in the last 90 days make up most of the growth.