Skip to content

Commit 700302d

Browse files
authored
chore(aio): document and test project secret keys for evaluations (#1307)
1 parent 521db27 commit 700302d

7 files changed

Lines changed: 79 additions & 40 deletions

File tree

‎examples/example-offline-evaluations/README.md‎

Lines changed: 27 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,33 +6,35 @@ Upload evaluations you have already run, manage reusable scorers and datasets, a
66

77
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).
88

9-
| Operation | Credential and scopes |
9+
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`.
10+
11+
| Operation | Required scopes |
1012
| --- | --- |
11-
| Create experiments, upload results, complete/fail | Personal API key or project secret key with `offline_evaluation_ingestion:write` |
12-
| Fetch scorers and versions | Personal API key with `llm_analytics:read` |
13-
| Validate a composite formula without saving | Personal API key with `llm_analytics:read` |
14-
| Calculate composites using previously stored inputs | Personal API key with ingestion access, `evaluation:read`, and `llm_analytics:read` |
15-
| Create/update scorers and create versions | Personal API key with `llm_analytics:write` |
16-
| Fetch datasets, items, and history | Personal API key with `dataset:read` |
17-
| Create/update/archive/restore datasets and items | Personal API key with `dataset:write` |
18-
| Read experiment tags | Personal API key with `evaluation:read` |
19-
| Replace experiment tags | Personal API key with `evaluation:write` |
20-
| Read an item or result revision | Personal API key with `evaluation:read`. Result reads also require `llm_analytics:read` and access to the scorer. |
21-
| Update an item or update/delete its payload | Personal API key with `evaluation:write` and evaluation editor access |
22-
| 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 |
23-
24-
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.
25-
26-
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.
13+
| Create experiments, upload results, complete/fail | `offline_evaluation_ingestion:write` |
14+
| Fetch scorers and versions | `llm_analytics:read` |
15+
| Validate a composite formula without saving | `llm_analytics:read` |
16+
| Calculate composites using previously stored inputs | `offline_evaluation_ingestion:write`, `evaluation:read`, and `llm_analytics:read` |
17+
| Create/update scorers and create versions | `llm_analytics:write` |
18+
| Fetch datasets, items, and history | `dataset:read` |
19+
| Create/update/archive/restore datasets and items | `dataset:write` |
20+
| Read experiment tags | `evaluation:read` |
21+
| Replace experiment tags | `evaluation:write` |
22+
| Read an item or result revision | `evaluation:read`. Result revision reads also require `llm_analytics:read`. |
23+
| Update an item or update/delete its payload | `evaluation:write` |
24+
| Delete an item, change/delete a result or its payload | `evaluation:write` and `llm_analytics:read` |
25+
26+
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.
27+
28+
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.
2729

2830
From this repository's root:
2931

3032
```bash
3133
export POSTHOG_PROJECT_ID=123
32-
export POSTHOG_SECRET_KEY='your-secret-key'
34+
export POSTHOG_SECRET_KEY="$POSTHOG_PROJECT_SECRET_API_KEY"
3335
export POSTHOG_HOST='https://us.posthog.com'
3436

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

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

102104
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.
103105

104-
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:
106+
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:
105107

106108
```python
107109
from posthog.ai.evaluations import ScorerComposition
@@ -149,7 +151,7 @@ experiment.complete()
149151

150152
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.
151153

152-
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.
154+
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.
153155

154156
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.
155157

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

175177
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.
176178

177-
Provision a dataset once with a personal key that has `dataset:write`:
179+
Provision a dataset once with a key that has `dataset:write`:
178180

179181
```python
180182
dataset = evaluations.datasets.create(
@@ -204,7 +206,7 @@ def capital_answer(question):
204206
question, "I don't know"
205207
)
206208

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

306308
async with AsyncOfflineEvaluations(
307-
project_id=123, secret_key=personal_api_key,
309+
project_id=123, secret_key=secret_key,
308310
) as evaluations:
309311
snapshot = await evaluations.datasets.snapshot(dataset_id)
310312
scorer = await evaluations.scorers.get(scorer_id)
@@ -424,7 +426,7 @@ print(experiment.get_tags())
424426
experiment.set_tags([]) # Remove all tags.
425427
```
426428

427-
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.
429+
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.
428430

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

‎examples/example-offline-evaluations/main.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
"""Run a synthetic offline evaluation, with explicit scorer setup and durable replay."""
1+
"""Run a synthetic offline evaluation, with explicit scorer setup and durable replay.
2+
3+
Set POSTHOG_SECRET_KEY to a project secret API key or a personal API key.
4+
Uploads need offline_evaluation_ingestion:write. Looking up a scorer needs
5+
llm_analytics:read and --create-scorer needs llm_analytics:write.
6+
"""
27

38
import argparse
49
import json

‎posthog/ai/evaluations/_async_datasets.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
class AsyncDatasets:
4141
"""Manage datasets through ``AsyncOfflineEvaluations.datasets``.
4242
43-
Requires a personal key with ``dataset:read`` or ``dataset:write`` and the
43+
Requires a key with ``dataset:read`` or ``dataset:write`` and the
4444
datasets feature enabled. Mutations return after acknowledgment; only item
4545
creates with a caller-supplied ``client_item_id`` are automatically retried.
4646
Other lost write responses require inspecting state before retrying.

‎posthog/ai/evaluations/_client.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -277,15 +277,15 @@ def submission(self) -> dict[str, Any] | None:
277277
return None if self._submission is None else json.loads(self._submission)
278278

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

285285
def set_tags(self, tags: Sequence[str]) -> tuple[str, ...]:
286286
"""Replace tags and return the server's normalized names; [] clears them.
287287
288-
Requires a personal key with ``evaluation:write``. Tags can change after
288+
Requires a key with ``evaluation:write``. Tags can change after
289289
completion and are separate from the immutable creation ``submission``.
290290
Updates are not retried automatically: inspect tags after a lost response.
291291
"""
@@ -645,11 +645,11 @@ async def fail(self) -> ExperimentReceipt:
645645
class OfflineEvaluations:
646646
"""Upload offline evaluations and manage scorers and datasets in one project.
647647
648-
``secret_key`` accepts personal or project secret keys with
649-
offline_evaluation_ingestion:write. Scorer reads/writes require a personal
650-
key with llm_analytics:read/write; datasets require dataset:read/write.
651-
Editing accepted data requires an evaluation editor's personal key with
652-
evaluation:write. Result operations and item deletion also need scorer access.
648+
Pass a personal API key or a project secret API key for this project.
649+
Uploads require offline_evaluation_ingestion:write. Scorers use
650+
llm_analytics:read/write and datasets use dataset:read/write. Corrections
651+
require evaluation:write. Result edits and item deletion also require
652+
llm_analytics:read. Personal keys need the user's resource permissions.
653653
Each operation requires its corresponding product feature to be enabled.
654654
``host`` defaults to the US app API; known ingestion hosts are mapped to
655655
their app hosts. Custom hosts are preserved. Requests use a 15 second

‎posthog/ai/evaluations/_datasets.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
class Datasets:
4141
"""Manage datasets through ``OfflineEvaluations.datasets``.
4242
43-
Requires a personal key with ``dataset:read`` or ``dataset:write`` and the
43+
Requires a key with ``dataset:read`` or ``dataset:write`` and the
4444
datasets feature enabled. Mutations return after acknowledgment; only item
4545
creates with a caller-supplied ``client_item_id`` are automatically retried.
4646
Other lost write responses require inspecting state before retrying.

‎posthog/ai/evaluations/_scorers.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ def _version_params(limit: int, cursor: str | None) -> dict[str, str | int]:
379379

380380

381381
class Scorers:
382-
"""Manage scorers using a personal key with ``llm_analytics`` scopes.
382+
"""Manage scorers using a key with ``llm_analytics`` scopes.
383383
384384
Access through ``OfflineEvaluations.scorers``. Creating a scorer or version
385385
is not idempotent: mutations are never retried automatically. If a response

‎posthog/test/ai/test_evaluations_transport.py‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,37 @@ def response(status=200, payload=None, headers=None):
3434
return result
3535

3636

37+
def test_project_secret_key_authenticates_management_requests():
38+
page = {"count": 0, "next": None, "previous": None, "results": []}
39+
tags = {"id": EXPERIMENT_ID, "tags": ["ci"]}
40+
with (
41+
OfflineEvaluations(project_id=123, secret_key="phs_example_only") as client,
42+
patch.object(
43+
requests.Session,
44+
"send",
45+
side_effect=[
46+
response(payload=page),
47+
response(payload=page),
48+
response(payload=tags),
49+
],
50+
) as send,
51+
):
52+
client.datasets.list()
53+
client.scorers.list()
54+
client.resume_experiment(EXPERIMENT_ID).set_tags(["ci"])
55+
56+
requests_sent = [call.args[0] for call in send.call_args_list]
57+
assert [(req.method, req.path_url.split("?")[0]) for req in requests_sent] == [
58+
("GET", "/api/projects/123/datasets/"),
59+
("GET", "/api/projects/123/llm_analytics/score_definitions/"),
60+
("PATCH", f"{PATH}{EXPERIMENT_ID}/"),
61+
]
62+
assert all(
63+
req.headers["Authorization"] == "Bearer phs_example_only"
64+
for req in requests_sent
65+
)
66+
67+
3768
@pytest.fixture
3869
def transport():
3970
client = SyncTransport(123, "phx_test_secret")
@@ -357,13 +388,14 @@ def test_closed_client_does_not_send(transport):
357388

358389

359390
@pytest.mark.asyncio
360-
async def test_async_native_request_uses_auth_host_and_preserves_bytes():
391+
@pytest.mark.parametrize("secret_key", ["phx_example_only", "phs_example_only"])
392+
async def test_async_native_request_uses_auth_host_and_preserves_bytes(secret_key):
361393
seen = []
362394

363395
async def handle(request):
364396
seen.append(request)
365397
if len(seen) == 1:
366-
raise httpx.ReadTimeout("phx_test_secret")
398+
raise httpx.ReadTimeout(secret_key)
367399
return httpx.Response(201, json={"id": "stable-id"})
368400

369401
real_client = httpx.AsyncClient
@@ -374,7 +406,7 @@ async def handle(request):
374406
),
375407
) as factory:
376408
transport = AsyncTransport(
377-
123, "phx_test_secret", host="https://eu.i.posthog.com", timeout=9
409+
123, secret_key, host="https://eu.i.posthog.com", timeout=9
378410
)
379411
with patch(
380412
"posthog.ai.evaluations._transport.asyncio.sleep", new_callable=AsyncMock
@@ -383,7 +415,7 @@ async def handle(request):
383415
assert len(seen) == 2
384416
assert seen[0].content == seen[1].content == BODY
385417
assert str(seen[0].url) == "https://eu.posthog.com" + PATH
386-
assert seen[0].headers["Authorization"] == "Bearer phx_test_secret"
418+
assert seen[0].headers["Authorization"] == f"Bearer {secret_key}"
387419
assert factory.call_args.kwargs["follow_redirects"] is False
388420
assert factory.call_args.kwargs["timeout"] == 9
389421
sleep.assert_awaited_once()

0 commit comments

Comments
 (0)