@posthog/ai 8.21.1 → 8.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -195,8 +195,8 @@ Set `modelVersion` on `new EvaluationItem({ modelVersion, output })` or
195
195
  that execution. Each item can override the experiment's `modelVersion`; omitted or null values
196
196
  inherit the experiment default on the server. Dataset metadata never supplies this model.
197
197
  Model identifiers must be nonempty strings of at most 255 characters and are preserved without
198
- trimming. Explicit models survive serialization, retries, and recovery. Changing a model requires
199
- a new item UUID because model attribution is part of the immutable execution declaration.
198
+ trimming. For a new model execution, declare a new item UUID. To correct the attribution of an
199
+ accepted item, use `updateItem` with `modelVersion`. Keep the original declaration for upload retries.
200
200
 
201
201
  `scorers` provides create/get/list/update/createVersion/getVersion/listVersions/validateComposition. Configurations
202
202
  are typed by `kind`: `boolean`, `numeric`, or `categorical`. Store `currentVersionId` to pin a
@@ -275,7 +275,9 @@ bulk call before any request is sent.
275
275
  Receipts expose stored `status` and `errorCode`. Input errors propagate as `composite_input_error`;
276
276
  formula or output-rule failures use `composite_formula_error`. Accepted composite errors count
277
277
  toward `expectedResultCount`, while derived results add no uploaded-result billing usage.
278
- Exact retries return stored outcomes, subject to current access checks. Older reported receipts
278
+ For retained results, exact upload retries acknowledge the original outcome and preserve later
279
+ corrections, subject to current access checks. Re-uploading a deleted result while the experiment
280
+ is open creates it again and counts as new usage for a reported result. Older reported receipts
279
281
  without outcomes expose `status: null` and `errorCode: null`. Save and restore calculation
280
282
  declarations with the same serialization and recovery methods as reported results.
281
283
 
@@ -286,11 +288,49 @@ declarations with the same serialization and recovery methods as reported result
286
288
  | Formula validation | Personal key: `llm_analytics:read` |
287
289
  | Experiment create/upload/complete/fail | Personal or project secret key: `offline_evaluation_ingestion:write` |
288
290
  | Experiment tags | Personal key: `evaluation:read` / `evaluation:write` |
291
+ | Item and result revision reads | Personal key: `evaluation:read` |
292
+ | Item, result, and payload mutations | Personal key: `evaluation:write` and evaluation editor access |
293
+
294
+ Reading a result revision, editing or deleting a result or its payload, and deleting an item
295
+ also require `llm_analytics:read` and access to the affected scorers and composite inputs.
289
296
 
290
297
  Feature availability and permissions are enforced by the service. Known ingestion hosts map to
291
298
  the app API host; custom host path prefixes are preserved. Pagination exposes `nextOffset` or,
292
299
  for scorer versions, `nextCursor`. Retain the original filters when requesting the next page.
293
300
 
301
+ ### Correcting an accepted result
302
+
303
+ Use the stored IDs from the upload receipt. You can correct a score even after the experiment
304
+ closes. The service recomputes any dependent composite scores.
305
+
306
+ ```ts
307
+ const experiment = evaluations.resumeExperiment(experimentId)
308
+ const resultId = uploadReceipt.results[0].id
309
+ const revision = await experiment.getResultRevision(resultId)
310
+ const corrected = await experiment.updateResult(resultId, { revision, status: 'ok', value: false })
311
+ await experiment.updateResultPayload(resultId, { revision: corrected, payload: { reasoning: 'Reviewed manually' } })
312
+ ```
313
+
314
+ Use `getItemRevision`, `updateItem`, and `updateItemPayload` for item corrections.
315
+ Omitted fields keep their stored values. An explicit `null` clears a nullable field.
316
+ Each payload shares its owner's revision. A result change also advances the parent item's revision.
317
+ Updates return the current revision, including when an unchanged score keeps the same revision.
318
+ If an update acknowledgment returns a lower revision than you submitted, the promise rejects
319
+ with code `invalid_response` and persistence `unknown`.
320
+
321
+ Passing `payload: {}` stores an empty first payload or preserves the fields of an existing payload.
322
+ Either write advances the owner's revision. A deleted or expired payload rejects even `{}` with
323
+ HTTP 409 `payload_unavailable`. When you change a result's status from `error` to another status,
324
+ the server removes any stored `errorMessage` (wire field `error_message`) from its payload.
325
+
326
+ `deleteItemPayload` and `deleteResultPayload` remove only the stored payload. A deleted payload
327
+ cannot be restored on that record. `deleteItem` permanently removes the item and its results.
328
+ `deleteResult` removes the result and any dependent composites. Each delete takes the stored ID
329
+ and `{ revision }` and resolves to `undefined`.
330
+
331
+ The SDK sends each mutation once. If a write returns HTTP 409 `revision_conflict`, or the
332
+ response is lost, read the current state before deciding whether to submit another change.
333
+
294
334
  ### Recovery, cancellation, and payloads
295
335
 
296
336
  `resumeExperiment(id)` is local and sends no request. Save creation `submission` and item/result
@@ -3,7 +3,7 @@ let _google_adk = require("@google/adk");
3
3
  let uuid = require("uuid");
4
4
  let _posthog_core = require("@posthog/core");
5
5
  //#region package.json
6
- var version = "8.21.1";
6
+ var version = "8.22.0";
7
7
  //#endregion
8
8
  //#region src/typeGuards.ts
9
9
  const isObject = (value) => {
@@ -2,7 +2,7 @@ import { BasePlugin } from "@google/adk";
2
2
  import { v4 } from "uuid";
3
3
  import { acceptsEventOptions, eventOptionsAsLegacyProperties, toJsonSafeValue, uuidv7 } from "@posthog/core";
4
4
  //#region package.json
5
- var version = "8.21.1";
5
+ var version = "8.22.0";
6
6
  //#endregion
7
7
  //#region src/typeGuards.ts
8
8
  const isObject = (value) => {
@@ -494,7 +494,7 @@ function addDefaults(params) {
494
494
  }
495
495
  //#endregion
496
496
  //#region package.json
497
- var version = "8.21.1";
497
+ var version = "8.22.0";
498
498
  //#endregion
499
499
  //#region src/serializeError.ts
500
500
  const DEFAULT_MAX_DEPTH = 3;
@@ -467,7 +467,7 @@ function addDefaults(params) {
467
467
  }
468
468
  //#endregion
469
469
  //#region package.json
470
- var version = "8.21.1";
470
+ var version = "8.22.0";
471
471
  //#endregion
472
472
  //#region src/serializeError.ts
473
473
  const DEFAULT_MAX_DEPTH = 3;
@@ -3,7 +3,7 @@ let _anthropic_ai_claude_agent_sdk = require("@anthropic-ai/claude-agent-sdk");
3
3
  let uuid = require("uuid");
4
4
  let _posthog_core = require("@posthog/core");
5
5
  //#region package.json
6
- var version = "8.21.1";
6
+ var version = "8.22.0";
7
7
  //#endregion
8
8
  //#region src/captureAiEvent.ts
9
9
  /** @internal */
@@ -2,7 +2,7 @@ import { SYSTEM_PROMPT_DYNAMIC_BOUNDARY, query as query$1 } from "@anthropic-ai/
2
2
  import { v4 } from "uuid";
3
3
  import { acceptsEventOptions, eventOptionsAsLegacyProperties, toJsonSafeValue, uuidv7 } from "@posthog/core";
4
4
  //#region package.json
5
- var version = "8.21.1";
5
+ var version = "8.22.0";
6
6
  //#endregion
7
7
  //#region src/captureAiEvent.ts
8
8
  /** @internal */
@@ -624,21 +624,39 @@ const RESULT_FIELDS = {
624
624
  errorMessage: "error_message",
625
625
  metadata: "metadata"
626
626
  };
627
- const ITEM_IDS = {
627
+ const EDITABLE_ITEM_IDS = {
628
628
  modelVersion: "model_version",
629
629
  caseKey: "case_key",
630
630
  trial: "trial",
631
- datasetItemIdentifier: "dataset_item_identifier",
632
- datasetItemVersionIdentifier: "dataset_item_version_identifier",
633
631
  applicationTraceId: "application_trace_id"
634
632
  };
633
+ const ITEM_IDS = {
634
+ ...EDITABLE_ITEM_IDS,
635
+ datasetItemIdentifier: "dataset_item_identifier",
636
+ datasetItemVersionIdentifier: "dataset_item_version_identifier"
637
+ };
635
638
  const items = /* @__PURE__ */ new WeakMap();
636
639
  const results = /* @__PURE__ */ new WeakMap();
637
- function payload(options, fields, limit) {
640
+ const PAYLOADS = {
641
+ item: {
642
+ fields: ITEM_FIELDS,
643
+ limit: 1048576
644
+ },
645
+ result: {
646
+ fields: RESULT_FIELDS,
647
+ limit: 262144
648
+ }
649
+ };
650
+ function payload(options, kind) {
651
+ const { fields } = PAYLOADS[kind];
638
652
  const supplied = Object.keys(fields).filter((key) => options[key] !== void 0);
639
653
  if (options.payload !== void 0 && supplied.length) throw new TypeError("Supply payload or individual fields, not both.");
640
654
  if (options.payload === void 0 && !supplied.length) return void 0;
641
- const source = options.payload === void 0 ? Object.fromEntries(supplied.map((key) => [key, options[key]])) : object(options.payload);
655
+ return checkedPayload(options.payload === void 0 ? Object.fromEntries(supplied.map((key) => [key, options[key]])) : options.payload, kind);
656
+ }
657
+ function checkedPayload(value, kind) {
658
+ const { fields, limit } = PAYLOADS[kind];
659
+ const source = object(value);
642
660
  keys(source, Object.keys(fields));
643
661
  const snapshot = json(Object.fromEntries(Object.entries(source).map(([key, v]) => {
644
662
  if (key === "metadata" && v !== null) metadata(v);
@@ -692,7 +710,7 @@ var EvaluationItem = class EvaluationItem {
692
710
  if (value !== void 0 && value !== null) body[wire] = identifier(value);
693
711
  }
694
712
  if (options.datasetItemVersionId != null) body.dataset_item_version_id = uuid(options.datasetItemVersionId);
695
- const data = payload(options, ITEM_FIELDS, 1048576);
713
+ const data = payload(options, "item");
696
714
  if (data !== void 0) body.payload = data;
697
715
  items.set(this, encode(body));
698
716
  Object.freeze(this);
@@ -741,6 +759,16 @@ var EvaluationItem = class EvaluationItem {
741
759
  });
742
760
  }
743
761
  };
762
+ function validateResultStatus(status, value, errorCode) {
763
+ if (![
764
+ "ok",
765
+ "error",
766
+ "skipped",
767
+ "not_applicable"
768
+ ].includes(status)) throw new TypeError("Unsupported result status.");
769
+ if (status !== "ok" && value != null) throw new TypeError("Only ok results can contain a score.");
770
+ if (status !== "error" && errorCode != null) throw new TypeError("Only error results can contain an error code.");
771
+ }
744
772
  /** An evaluator outcome pinned to an exact scorer version. `ok` does not imply passing. */
745
773
  var EvaluationResult = class EvaluationResult {
746
774
  constructor(options) {
@@ -764,14 +792,7 @@ var EvaluationResult = class EvaluationResult {
764
792
  this.calculate = options.calculate === true;
765
793
  if (this.calculate && (options.value != null || options.status !== void 0 && options.status !== "ok" || options.errorCode != null || options.evaluatorTraceId != null || options.evaluatedAt != null || ["payload", ...Object.keys(RESULT_FIELDS)].some((key) => options[key] !== void 0))) throw new TypeError("A calculation accepts only item, scorerVersionId, and calculate: true.");
766
794
  const status = options.status ?? "ok";
767
- if (![
768
- "ok",
769
- "error",
770
- "skipped",
771
- "not_applicable"
772
- ].includes(status)) throw new TypeError("Unsupported result status.");
773
- if (status !== "ok" && options.value !== void 0 && options.value !== null) throw new TypeError("Only ok results can contain a score.");
774
- if (status !== "error" && options.errorCode != null) throw new TypeError("Only error results can contain an error code.");
795
+ validateResultStatus(status, options.value, options.errorCode);
775
796
  const body = {
776
797
  item_id: this.itemId,
777
798
  scorer_version_id: this.scorerVersionId
@@ -784,7 +805,7 @@ var EvaluationResult = class EvaluationResult {
784
805
  if (options.errorCode != null) body.error_code = identifier(options.errorCode, 128);
785
806
  if (options.evaluatorTraceId != null) body.evaluator_trace_id = identifier(options.evaluatorTraceId);
786
807
  if (options.evaluatedAt != null) body.evaluated_at = timestamp(options.evaluatedAt);
787
- const data = payload(options, RESULT_FIELDS, 262144);
808
+ const data = payload(options, "result");
788
809
  if (data !== void 0) {
789
810
  if (status !== "error" && data.error_message != null) throw new TypeError("Only error results can contain an error message.");
790
811
  body.payload = data;
@@ -840,6 +861,32 @@ function resultJSON(result) {
840
861
  return value;
841
862
  }
842
863
  //#endregion
864
+ //#region src/evaluations/mutations.ts
865
+ function itemChanges(options) {
866
+ const source = object(options);
867
+ keys(source, ["revision", ...Object.keys(EDITABLE_ITEM_IDS)]);
868
+ const changes = {};
869
+ for (const [key, wire] of Object.entries(EDITABLE_ITEM_IDS)) if (source[key] !== void 0) changes[wire] = nullable(source[key], identifier);
870
+ return changes;
871
+ }
872
+ function resultChanges(options) {
873
+ keys(object(options), [
874
+ "revision",
875
+ "status",
876
+ "value",
877
+ "errorCode"
878
+ ]);
879
+ const changes = {};
880
+ if (options.status !== void 0) {
881
+ if (options.status === "ok" && options.value === null) throw new TypeError("A successful result cannot clear its score.");
882
+ validateResultStatus(options.status, options.value, options.errorCode);
883
+ changes.status = options.status;
884
+ }
885
+ if (options.value !== void 0) changes.value = nullable(options.value, score);
886
+ if (options.errorCode !== void 0) changes.error_code = nullable(options.errorCode, (value) => identifier(value, 128));
887
+ return changes;
888
+ }
889
+ //#endregion
843
890
  //#region src/evaluations/scorers.ts
844
891
  const CONFIG_KEYS = {
845
892
  trueLabel: "true_label",
@@ -1304,6 +1351,13 @@ var Transport = class {
1304
1351
  });
1305
1352
  const raw = await response.text();
1306
1353
  operation.signal.throwIfAborted();
1354
+ if (response.ok && method === "DELETE") {
1355
+ if (response.status === 204) return {};
1356
+ throw new EvaluationAPIError({
1357
+ status: response.status,
1358
+ code: "invalid_response"
1359
+ });
1360
+ }
1307
1361
  let payload;
1308
1362
  try {
1309
1363
  payload = decode(raw);
@@ -1673,6 +1727,79 @@ var Experiment = class {
1673
1727
  return responseTags(data.tags);
1674
1728
  }), request.signal);
1675
1729
  }
1730
+ /** Read the current revision shared by an item and its payload. */
1731
+ async getItemRevision(itemId, request = {}) {
1732
+ const id = uuid(itemId);
1733
+ return this.#readRevision(`items/${id}/`, id, request);
1734
+ }
1735
+ /** The result payload endpoint includes its owner's revision even when the payload is unavailable. */
1736
+ async getResultRevision(resultId, request = {}) {
1737
+ const id = uuid(resultId);
1738
+ return this.#readRevision(`results/${id}/payload/`, id, request);
1739
+ }
1740
+ async #readRevision(path, id, { signal }) {
1741
+ return this.#queue.run(async () => {
1742
+ return parseResponse(await this.#transport.request("GET", this.#base + path, { signal }), (resource) => {
1743
+ if (uuid(resource.id) !== id) throw new TypeError("Mismatched resource ID.");
1744
+ return integer(resource.revision, 0);
1745
+ });
1746
+ }, signal);
1747
+ }
1748
+ /** Update the supplied item identifiers and return the current item revision. */
1749
+ async updateItem(itemId, options, request = {}) {
1750
+ return this.#patch(`items/${uuid(itemId)}/`, itemChanges(options), options.revision, request);
1751
+ }
1752
+ /** Correct a reported outcome. The service recomputes dependent composite scores. */
1753
+ async updateResult(resultId, options, request = {}) {
1754
+ return this.#patch(`results/${uuid(resultId)}/`, resultChanges(options), options.revision, request);
1755
+ }
1756
+ /** Replace the supplied top-level payload fields and return the current item revision. */
1757
+ async updateItemPayload(itemId, options, request = {}) {
1758
+ keys(object(options), ["revision", "payload"]);
1759
+ return this.#patch(`items/${uuid(itemId)}/payload/`, { payload: checkedPayload(options.payload, "item") }, options.revision, request);
1760
+ }
1761
+ /** Replace the supplied top-level payload fields and return the current result revision. */
1762
+ async updateResultPayload(resultId, options, request = {}) {
1763
+ keys(object(options), ["revision", "payload"]);
1764
+ return this.#patch(`results/${uuid(resultId)}/payload/`, { payload: checkedPayload(options.payload, "result") }, options.revision, request);
1765
+ }
1766
+ async #patch(path, changes, revision, { signal }) {
1767
+ if (!Object.keys(changes).length) throw new TypeError("Supply at least one field to update.");
1768
+ const body = encode({
1769
+ revision: integer(revision, 0),
1770
+ ...changes
1771
+ });
1772
+ return this.#queue.run(async () => {
1773
+ return parseResponse(await this.#transport.request("PATCH", this.#base + path, {
1774
+ signal,
1775
+ body
1776
+ }), (ack) => integer(ack.revision, revision));
1777
+ }, signal);
1778
+ }
1779
+ /** Permanently delete the item, its results, and their payloads. */
1780
+ async deleteItem(itemId, options, request = {}) {
1781
+ return this.#delete(`items/${uuid(itemId)}/`, options, request);
1782
+ }
1783
+ /** Permanently delete the result, its payload, and any dependent composites. */
1784
+ async deleteResult(resultId, options, request = {}) {
1785
+ return this.#delete(`results/${uuid(resultId)}/`, options, request);
1786
+ }
1787
+ /** Permanently remove the stored payload and retain the item and scores. */
1788
+ async deleteItemPayload(itemId, options, request = {}) {
1789
+ return this.#delete(`items/${uuid(itemId)}/payload/`, options, request);
1790
+ }
1791
+ /** Permanently remove the stored payload and retain the result. */
1792
+ async deleteResultPayload(resultId, options, request = {}) {
1793
+ return this.#delete(`results/${uuid(resultId)}/payload/`, options, request);
1794
+ }
1795
+ async #delete(path, options, { signal }) {
1796
+ keys(object(options), ["revision"]);
1797
+ const revision = integer(options.revision, 0);
1798
+ await this.#queue.run(() => this.#transport.request("DELETE", this.#base + path, {
1799
+ signal,
1800
+ params: { revision }
1801
+ }), signal);
1802
+ }
1676
1803
  };
1677
1804
  function submissionOptions(data) {
1678
1805
  const result = {