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
52 changes: 27 additions & 25 deletions examples/example-offline-evaluations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,35 @@ Upload evaluations you have already run, manage reusable scorers and datasets, a

Offline evaluations must be enabled for your PostHog project. Use the project's numeric ID and the app host (`https://us.posthog.com`, `https://eu.posthog.com`, or your self-hosted URL).

| Operation | Credential and scopes |
Use a project secret API key for the project ID you pass to the client, or a personal API key. Grant the scopes for the calls your script makes. Personal keys also need the user's resource access, including evaluation editor access for corrections. Dataset exports require a personal API key with `dataset:read`.

| Operation | Required scopes |
| --- | --- |
| Create experiments, upload results, complete/fail | Personal API key or project secret key with `offline_evaluation_ingestion:write` |
| Fetch scorers and versions | Personal API key with `llm_analytics:read` |
| Validate a composite formula without saving | Personal API key with `llm_analytics:read` |
| Calculate composites using previously stored inputs | Personal API key with ingestion access, `evaluation:read`, and `llm_analytics:read` |
| Create/update scorers and create versions | Personal API key with `llm_analytics:write` |
| Fetch datasets, items, and history | Personal API key with `dataset:read` |
| Create/update/archive/restore datasets and items | Personal API key with `dataset:write` |
| Read experiment tags | Personal API key with `evaluation:read` |
| Replace experiment tags | Personal API key with `evaluation:write` |
| Read an item or result revision | Personal API key with `evaluation:read`. Result reads also require `llm_analytics:read` and access to the scorer. |
| Update an item or update/delete its payload | Personal API key with `evaluation:write` and evaluation editor access |
| Delete an item, change/delete a result or its payload | Personal API key with `evaluation:write`, evaluation editor access, `llm_analytics:read`, and access to affected scorers and composite inputs |

A personal key can cover both scorer management and uploads. Project secret keys can upload using a known scorer-version UUID without scorer read access. All operations use the explicit project/environment; scorer names are not unique.

Dataset operations also require the datasets feature to be enabled. Dataset reads, scorer reads, and experiment uploads use their own scopes; an upload-only credential cannot fetch a dataset. Keep personal keys in server-side scripts or CI secrets.
| Create experiments, upload results, complete/fail | `offline_evaluation_ingestion:write` |
| Fetch scorers and versions | `llm_analytics:read` |
| Validate a composite formula without saving | `llm_analytics:read` |
| Calculate composites using previously stored inputs | `offline_evaluation_ingestion:write`, `evaluation:read`, and `llm_analytics:read` |
| Create/update scorers and create versions | `llm_analytics:write` |
| Fetch datasets, items, and history | `dataset:read` |
| Create/update/archive/restore datasets and items | `dataset:write` |
| Read experiment tags | `evaluation:read` |
| Replace experiment tags | `evaluation:write` |
| Read an item or result revision | `evaluation:read`. Result revision reads also require `llm_analytics:read`. |
| Update an item or update/delete its payload | `evaluation:write` |
| Delete an item, change/delete a result or its payload | `evaluation:write` and `llm_analytics:read` |

A single key can cover both scorer management and uploads. An ingestion-only key can upload using a known scorer-version UUID without scorer read access. All operations use the explicit project/environment; scorer names are not unique.

Dataset operations also require the datasets feature to be enabled. Dataset reads, scorer reads, and experiment uploads use their own scopes; an upload-only credential cannot fetch a dataset. Keep both types of key in server-side scripts or CI secrets.

From this repository's root:

```bash
export POSTHOG_PROJECT_ID=123
export POSTHOG_SECRET_KEY='your-secret-key'
export POSTHOG_SECRET_KEY="$POSTHOG_PROJECT_SECRET_API_KEY"
export POSTHOG_HOST='https://us.posthog.com'

# Optional one-time provisioning; requires a personal key.
# Optional one-time provisioning; requires `llm_analytics:write`.
uv run python examples/example-offline-evaluations/main.py --create-scorer

# Use the stable scorer ID printed above; its current version is fetched once.
Expand Down Expand Up @@ -101,7 +103,7 @@ The client context manager releases connections. Call `complete()` explicitly af

Composite scorers calculate one score per item on the PostHog server from exact reported scorer versions. They can return numeric, boolean, or categorical values. This requires a backend with composite scorer support; ordinary uploads remain compatible with older backends.

Provision a composite once, using a personal key with scorer write access. This example assumes `correctness_version_id` identifies a reported boolean scorer and `relevance_version_id` a reported numeric scorer:
Provision a composite once, using a key with `llm_analytics:write`. This example assumes `correctness_version_id` identifies a reported boolean scorer and `relevance_version_id` a reported numeric scorer:

```python
from posthog.ai.evaluations import ScorerComposition
Expand Down Expand Up @@ -149,7 +151,7 @@ experiment.complete()

Calculation declarations contain only the item reference, scorer version, and `calculate=True`. Do not supply a value, reasoning, metadata, evaluator trace, or evaluation time. An item may also be referenced by its already accepted UUID.

Project secret keys and ingestion-only personal keys must supply **every pinned input result in the same HTTP request**, including on retries. Previously uploaded inputs may be resubmitted with their original values and metadata. Reusing stored inputs without resubmitting them requires both `evaluation:read` and `llm_analytics:read`, in addition to ingestion access. Composite requests and retries also require current access to the composite and its inputs.
Ingestion-only keys must supply **every pinned input result in the same HTTP request**, including on retries. Previously uploaded inputs may be resubmitted with their original values and metadata. Reusing stored inputs without resubmitting them requires both `evaluation:read` and `llm_analytics:read`, in addition to ingestion access. Composite requests and retries also require current access to the composite and its inputs.

The SDK keeps all supplied results for a composite-bearing item together without fetching scorer definitions. It preserves order, so interleaved composite items can form a larger indivisible group. Group each item's results together for large batches. If a group exceeds 1,000 items/results or 5 MiB, the entire call fails locally before any upload. The SDK cannot check that your supplied inputs match the pinned formula without read access; the server validates this. Missing inputs reject the whole HTTP request. Inputs can appear before or after their composite in that request.

Expand All @@ -174,7 +176,7 @@ The state file includes both reported and calculation declarations and the combi

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.

Provision a dataset once with a personal key that has `dataset:write`:
Provision a dataset once with a key that has `dataset:write`:

```python
dataset = evaluations.datasets.create(
Expand Down Expand Up @@ -204,7 +206,7 @@ def capital_answer(question):
question, "I don't know"
)

with OfflineEvaluations(project_id=123, secret_key=personal_api_key) as evaluations:
with OfflineEvaluations(project_id=123, secret_key=secret_key) as evaluations:
snapshot = evaluations.datasets.snapshot(dataset_id) # Resolve latest once.
scorer = evaluations.scorers.get(scorer_id) # A boolean exact-match scorer.
version_id = scorer.current_version_id
Expand Down Expand Up @@ -304,7 +306,7 @@ Await management methods and snapshot creation. Use `async for` on `iter_items()
from posthog.ai.evaluations import AsyncOfflineEvaluations, EvaluationItem

async with AsyncOfflineEvaluations(
project_id=123, secret_key=personal_api_key,
project_id=123, secret_key=secret_key,
) as evaluations:
snapshot = await evaluations.datasets.snapshot(dataset_id)
scorer = await evaluations.scorers.get(scorer_id)
Expand Down Expand Up @@ -424,7 +426,7 @@ print(experiment.get_tags())
experiment.set_tags([]) # Remove all tags.
```

Reading and writing experiment tags require the personal-key scopes listed above; an upload-only project secret key cannot manage tags. Tag updates do not change the saved `submission`, lifecycle `receipt`, or scorer versions. They are not retried automatically: after a lost acknowledgment, read the current tags before deciding whether to repeat the replacement, since another caller may have edited them.
Reading and writing experiment tags require `evaluation:read` and `evaluation:write`, respectively; an upload-only project secret key cannot manage tags. Tag updates do not change the saved `submission`, lifecycle `receipt`, or scorer versions. They are not retried automatically: after a lost acknowledgment, read the current tags before deciding whether to repeat the replacement, since another caller may have edited them.

The async client exposes the same API: await scorer methods and `experiment.get_tags()` / `experiment.set_tags(...)`.

Expand Down
7 changes: 6 additions & 1 deletion examples/example-offline-evaluations/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
"""Run a synthetic offline evaluation, with explicit scorer setup and durable replay."""
"""Run a synthetic offline evaluation, with explicit scorer setup and durable replay.

Set POSTHOG_SECRET_KEY to a project secret API key or a personal API key.
Uploads need offline_evaluation_ingestion:write. Looking up a scorer needs
llm_analytics:read and --create-scorer needs llm_analytics:write.
"""

import argparse
import json
Expand Down
2 changes: 1 addition & 1 deletion posthog/ai/evaluations/_async_datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
class AsyncDatasets:
"""Manage datasets through ``AsyncOfflineEvaluations.datasets``.

Requires a personal key with ``dataset:read`` or ``dataset:write`` and the
Requires a key with ``dataset:read`` or ``dataset:write`` and the
datasets feature enabled. Mutations return after acknowledgment; only item
creates with a caller-supplied ``client_item_id`` are automatically retried.
Other lost write responses require inspecting state before retrying.
Expand Down
14 changes: 7 additions & 7 deletions posthog/ai/evaluations/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,15 +277,15 @@ def submission(self) -> dict[str, Any] | None:
return None if self._submission is None else json.loads(self._submission)

def get_tags(self) -> tuple[str, ...]:
"""Fetch current tags using a personal key with ``evaluation:read``."""
"""Fetch current tags using a key with ``evaluation:read``."""
with self._lock:
data = self._transport.request("GET", self._path)
return _experiment_tags(data, self.id)

def set_tags(self, tags: Sequence[str]) -> tuple[str, ...]:
"""Replace tags and return the server's normalized names; [] clears them.

Requires a personal key with ``evaluation:write``. Tags can change after
Requires a key with ``evaluation:write``. Tags can change after
completion and are separate from the immutable creation ``submission``.
Updates are not retried automatically: inspect tags after a lost response.
"""
Expand Down Expand Up @@ -645,11 +645,11 @@ async def fail(self) -> ExperimentReceipt:
class OfflineEvaluations:
"""Upload offline evaluations and manage scorers and datasets in one project.

``secret_key`` accepts personal or project secret keys with
offline_evaluation_ingestion:write. Scorer reads/writes require a personal
key with llm_analytics:read/write; datasets require dataset:read/write.
Editing accepted data requires an evaluation editor's personal key with
evaluation:write. Result operations and item deletion also need scorer access.
Pass a personal API key or a project secret API key for this project.
Uploads require offline_evaluation_ingestion:write. Scorers use
llm_analytics:read/write and datasets use dataset:read/write. Corrections
require evaluation:write. Result edits and item deletion also require
llm_analytics:read. Personal keys need the user's resource permissions.
Each operation requires its corresponding product feature to be enabled.
``host`` defaults to the US app API; known ingestion hosts are mapped to
their app hosts. Custom hosts are preserved. Requests use a 15 second
Expand Down
2 changes: 1 addition & 1 deletion posthog/ai/evaluations/_datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
class Datasets:
"""Manage datasets through ``OfflineEvaluations.datasets``.

Requires a personal key with ``dataset:read`` or ``dataset:write`` and the
Requires a key with ``dataset:read`` or ``dataset:write`` and the
datasets feature enabled. Mutations return after acknowledgment; only item
creates with a caller-supplied ``client_item_id`` are automatically retried.
Other lost write responses require inspecting state before retrying.
Expand Down
2 changes: 1 addition & 1 deletion posthog/ai/evaluations/_scorers.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ def _version_params(limit: int, cursor: str | None) -> dict[str, str | int]:


class Scorers:
"""Manage scorers using a personal key with ``llm_analytics`` scopes.
"""Manage scorers using a key with ``llm_analytics`` scopes.

Access through ``OfflineEvaluations.scorers``. Creating a scorer or version
is not idempotent: mutations are never retried automatically. If a response
Expand Down
40 changes: 36 additions & 4 deletions posthog/test/ai/test_evaluations_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,37 @@ def response(status=200, payload=None, headers=None):
return result


def test_project_secret_key_authenticates_management_requests():
page = {"count": 0, "next": None, "previous": None, "results": []}
tags = {"id": EXPERIMENT_ID, "tags": ["ci"]}
with (
OfflineEvaluations(project_id=123, secret_key="phs_example_only") as client,
patch.object(
requests.Session,
"send",
side_effect=[
response(payload=page),
response(payload=page),
response(payload=tags),
],
) as send,
):
client.datasets.list()
client.scorers.list()
client.resume_experiment(EXPERIMENT_ID).set_tags(["ci"])

requests_sent = [call.args[0] for call in send.call_args_list]
assert [(req.method, req.path_url.split("?")[0]) for req in requests_sent] == [
("GET", "/api/projects/123/datasets/"),
("GET", "/api/projects/123/llm_analytics/score_definitions/"),
("PATCH", f"{PATH}{EXPERIMENT_ID}/"),
]
assert all(
req.headers["Authorization"] == "Bearer phs_example_only"
for req in requests_sent
)


@pytest.fixture
def transport():
client = SyncTransport(123, "phx_test_secret")
Expand Down Expand Up @@ -357,13 +388,14 @@ def test_closed_client_does_not_send(transport):


@pytest.mark.asyncio
async def test_async_native_request_uses_auth_host_and_preserves_bytes():
@pytest.mark.parametrize("secret_key", ["phx_example_only", "phs_example_only"])
async def test_async_native_request_uses_auth_host_and_preserves_bytes(secret_key):
seen = []

async def handle(request):
seen.append(request)
if len(seen) == 1:
raise httpx.ReadTimeout("phx_test_secret")
raise httpx.ReadTimeout(secret_key)
return httpx.Response(201, json={"id": "stable-id"})

real_client = httpx.AsyncClient
Expand All @@ -374,7 +406,7 @@ async def handle(request):
),
) as factory:
transport = AsyncTransport(
123, "phx_test_secret", host="https://eu.i.posthog.com", timeout=9
123, secret_key, host="https://eu.i.posthog.com", timeout=9
)
with patch(
"posthog.ai.evaluations._transport.asyncio.sleep", new_callable=AsyncMock
Expand All @@ -383,7 +415,7 @@ async def handle(request):
assert len(seen) == 2
assert seen[0].content == seen[1].content == BODY
assert str(seen[0].url) == "https://eu.posthog.com" + PATH
assert seen[0].headers["Authorization"] == "Bearer phx_test_secret"
assert seen[0].headers["Authorization"] == f"Bearer {secret_key}"
assert factory.call_args.kwargs["follow_redirects"] is False
assert factory.call_args.kwargs["timeout"] == 9
sleep.assert_awaited_once()
Expand Down