Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .sampo/changesets/experiment-scorers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: minor
---

Support selecting a run-level scorer version when creating an offline evaluation experiment. Manage experiment formulas and their suite defaults through the sync and async scorer clients.
33 changes: 33 additions & 0 deletions examples/example-offline-evaluations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,39 @@ uv run python examples/example-offline-evaluations/main.py \

The state file includes both reported and calculation declarations and the combined expected count. Reusing the file replays that saved run regardless of newly supplied scorer flags.

## Experiment scores

An experiment scorer combines item score statistics into one value for a completed run.
Create a formula and assign it to a suite to apply it to future runs in this environment.

```python
formula = evaluations.scorers.create(
name="Overall quality",
scope="experiment",
kind="numeric",
config={"min": 0, "max": 1},
calculation="composite",
composition={
"expression": "correct",
"inputs": [
{
"alias": "correct",
"scorer_version_id": correctness.current_version_id,
"statistic": "pass_rate",
}
],
},
apply_to_suite_keys=["agent-ci"],
)

experiment = evaluations.create_experiment(name="Baseline", suite_key="agent-ci")
```

Here `correctness` is an existing item scorer. Upload its item results normally and complete the run.
The server pins the suite default on first creation. Pass
`experiment_scorer_version_id=formula.current_version_id` to select a specific version.
The experiment score appears in PostHog after the run completes.

## Datasets and reproducible evaluations

Use `evaluations.datasets` to manage PostHog-hosted datasets with the same client configuration as scorers and experiments. Dataset names are unique within a project; keep the returned UUID for subsequent operations.
Expand Down
10 changes: 10 additions & 0 deletions posthog/ai/evaluations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@
CategoricalPassingRule,
CategoricalScorerConfig,
CategoricalScorerOption,
ExperimentScoreStatistic,
ExperimentScoreVersionPolicy,
ExperimentScorerComposition,
ExperimentScorerCompositionInput,
NumericPassingRule,
NumericScorerConfig,
Scorer,
Expand All @@ -45,6 +49,7 @@
ScorerKind,
ScorerOrder,
ScorerPage,
ScorerScope,
ScorerVersion,
ScorerVersionPage,
)
Expand Down Expand Up @@ -93,6 +98,10 @@
"Experiment",
"ExperimentOptions",
"ExperimentReceipt",
"ExperimentScoreStatistic",
"ExperimentScoreVersionPolicy",
"ExperimentScorerComposition",
"ExperimentScorerCompositionInput",
"ItemReceipt",
"ItemUpdate",
"JSONValue",
Expand All @@ -114,6 +123,7 @@
"ScorerKind",
"ScorerOrder",
"ScorerPage",
"ScorerScope",
"Scorers",
"ScorerVersion",
"ScorerVersionPage",
Expand Down
2 changes: 1 addition & 1 deletion posthog/ai/evaluations/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def _experiment_option(key: str, value: Any) -> Any:
return value
elif key in ("expected_item_count", "expected_result_count"):
return _count(value, key)
elif key == "dataset_revision_id":
elif key in ("dataset_revision_id", "experiment_scorer_version_id"):
return None if value is None else _uuid(value)
else:
return _identifier(value, key)
Expand Down
33 changes: 31 additions & 2 deletions posthog/ai/evaluations/_scorer_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

ScorerKind = Literal["boolean", "numeric", "categorical"]
ScorerCalculation = Literal["reported", "composite"]
ScorerScope = Literal["item", "experiment"]
ExperimentScoreStatistic = Literal["pass_rate", "mean", "true_rate", "category_rate"]
ExperimentScoreVersionPolicy = Literal["run", "exact", "combine"]
ScorerOrder = Literal[
"name",
"-name",
Expand Down Expand Up @@ -109,6 +112,25 @@ class ScorerComposition(TypedDict):
inputs: list[ScorerCompositionInput]


class ExperimentScorerCompositionInput(ScorerCompositionInput, total=False):
"""A statistic from an item scorer, anchored by a version UUID.

Omit version_policy to use the single version that scored items in the run.
Supply category only for category_rate.
"""

statistic: Required[ExperimentScoreStatistic]
version_policy: ExperimentScoreVersionPolicy
category: str


class ExperimentScorerComposition(TypedDict):
"""Server-evaluated formula over statistics from item scorers in one run."""

expression: str
inputs: list[ExperimentScorerCompositionInput]


@dataclass(frozen=True)
class ScorerInput:
"""Pinned input metadata alongside the source's latest version.
Expand All @@ -135,6 +157,8 @@ class Scorer(Generic[_ConfigT]):
Names are not unique; use ``id`` for subsequent management operations.
Configuration dictionaries are local snapshots, not live server state.
``tags`` contains normalized tag names and is independent of versions.
``suite_keys`` lists defaults on the current version. ``assigned_suite_keys``
spans visible versions and is available on detail responses.
"""

id: str
Expand All @@ -151,9 +175,12 @@ class Scorer(Generic[_ConfigT]):
team: int
tags: tuple[str, ...] = ()
calculation: ScorerCalculation = "reported"
composition: ScorerComposition | None = None
composition: ScorerComposition | ExperimentScorerComposition | None = None
input_scorers: tuple[ScorerInput, ...] = ()
dependent_composite_count: int = 0
scope: ScorerScope = "item"
suite_keys: tuple[str, ...] = ()
assigned_suite_keys: tuple[str, ...] | None = None


@dataclass(frozen=True)
Expand All @@ -168,7 +195,9 @@ class ScorerVersion(Generic[_ConfigT]):
created_at: datetime
created_by: dict[str, Any] | None
calculation: ScorerCalculation = "reported"
composition: ScorerComposition | None = None
composition: ScorerComposition | ExperimentScorerComposition | None = None
scope: ScorerScope = "item"
suite_keys: tuple[str, ...] = ()


@dataclass(frozen=True)
Expand Down
Loading