@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.
@@ -237,6 +237,12 @@ type EvaluationResultOptions = Outcome & {
237
237
  evaluatorTraceId?: string | null;
238
238
  evaluatedAt?: string | Date | null;
239
239
  };
240
+ declare const EDITABLE_ITEM_IDS: {
241
+ readonly modelVersion: 'model_version';
242
+ readonly caseKey: 'case_key';
243
+ readonly trial: 'trial';
244
+ readonly applicationTraceId: 'application_trace_id';
245
+ };
240
246
  /** One immutable execution. Reuse across scorers; construct a new item for each trial. */
241
247
  declare class EvaluationItem {
242
248
  readonly id: string;
@@ -308,6 +314,37 @@ declare class EvaluationAPIError extends Error {
308
314
  get submission(): ExperimentOptions | undefined;
309
315
  }
310
316
  //#endregion
317
+ //#region src/evaluations/mutations.d.ts
318
+ interface RevisionOptions {
319
+ /** The revision last observed for this item or result. Its payload shares the same revision. */
320
+ revision: number;
321
+ }
322
+ type AtLeastOne<T> = { [K in keyof T]-?: Required<Pick<T, K>> & Omit<T, K>; }[keyof T];
323
+ /** Omit a field to keep its stored value, or pass null to clear it. */
324
+ type ItemUpdate = AtLeastOne<Pick<ItemIdentifiers, keyof typeof EDITABLE_ITEM_IDS>>;
325
+ /** Omit the status to correct a field against the result's stored status. */
326
+ type ResultUpdate = {
327
+ status: 'ok';
328
+ value?: ScoreInput;
329
+ errorCode?: null;
330
+ } | {
331
+ status: 'error';
332
+ value?: null;
333
+ errorCode?: string | null;
334
+ } | {
335
+ status: 'skipped' | 'not_applicable';
336
+ value?: null;
337
+ errorCode?: null;
338
+ } | {
339
+ status?: undefined;
340
+ value: ScoreInput | null;
341
+ errorCode?: null;
342
+ } | {
343
+ status?: undefined;
344
+ value?: null;
345
+ errorCode: string | null;
346
+ };
347
+ //#endregion
311
348
  //#region src/evaluations/scorers.d.ts
312
349
  interface BooleanScorerConfig {
313
350
  trueLabel?: string;
@@ -547,6 +584,30 @@ declare class Experiment {
547
584
  fail(request?: RequestOptions): Promise<ExperimentReceipt>;
548
585
  getTags(request?: RequestOptions): Promise<string[]>;
549
586
  setTags(names: readonly string[], request?: RequestOptions): Promise<string[]>;
587
+ /** Read the current revision shared by an item and its payload. */
588
+ getItemRevision(itemId: string, request?: RequestOptions): Promise<number>;
589
+ /** The result payload endpoint includes its owner's revision even when the payload is unavailable. */
590
+ getResultRevision(resultId: string, request?: RequestOptions): Promise<number>;
591
+ /** Update the supplied item identifiers and return the current item revision. */
592
+ updateItem(itemId: string, options: RevisionOptions & ItemUpdate, request?: RequestOptions): Promise<number>;
593
+ /** Correct a reported outcome. The service recomputes dependent composite scores. */
594
+ updateResult(resultId: string, options: RevisionOptions & ResultUpdate, request?: RequestOptions): Promise<number>;
595
+ /** Replace the supplied top-level payload fields and return the current item revision. */
596
+ updateItemPayload(itemId: string, options: RevisionOptions & {
597
+ payload: ItemPayload;
598
+ }, request?: RequestOptions): Promise<number>;
599
+ /** Replace the supplied top-level payload fields and return the current result revision. */
600
+ updateResultPayload(resultId: string, options: RevisionOptions & {
601
+ payload: ResultPayload;
602
+ }, request?: RequestOptions): Promise<number>;
603
+ /** Permanently delete the item, its results, and their payloads. */
604
+ deleteItem(itemId: string, options: RevisionOptions, request?: RequestOptions): Promise<void>;
605
+ /** Permanently delete the result, its payload, and any dependent composites. */
606
+ deleteResult(resultId: string, options: RevisionOptions, request?: RequestOptions): Promise<void>;
607
+ /** Permanently remove the stored payload and retain the item and scores. */
608
+ deleteItemPayload(itemId: string, options: RevisionOptions, request?: RequestOptions): Promise<void>;
609
+ /** Permanently remove the stored payload and retain the result. */
610
+ deleteResultPayload(resultId: string, options: RevisionOptions, request?: RequestOptions): Promise<void>;
550
611
  }
551
612
  /** Acknowledged management APIs, independent of analytics capture and flush. */
552
613
  declare class OfflineEvaluations {
@@ -561,5 +622,5 @@ declare class OfflineEvaluations {
561
622
  close(): void;
562
623
  }
563
624
  //#endregion
564
- export { type BooleanScorerConfig, BulkUploadError, type BulkUploadReceipt, type CategoricalScorerConfig, type CategoricalScorerOption, type CreateDatasetItemOptions, type CreateScorerOptions, type Dataset, type DatasetItem, type DatasetItemPage, type DatasetListOptions, type DatasetMetadata, type DatasetOrder, type DatasetPage, type DatasetRevision, type DatasetRevisionPage, DatasetSnapshot, Datasets, EvaluationAPIError, type EvaluationCount, type EvaluationErrorFields, EvaluationItem, type EvaluationItemOptions, EvaluationResult, type EvaluationResultOptions, Experiment, ExperimentCreationAbortedError, type ExperimentOptions, type ExperimentReceipt, type ItemIdentifiers, type ItemListOptions, type ItemPayload, type ItemReceipt, type JSONObject, type JSONValue, type NumericPassingRule, type NumericScorerConfig, OfflineEvaluations, type OfflineEvaluationsOptions, type PageOptions, type Persistence, type RequestOptions, type ResultPayload, type ResultReceipt, type ResultStatus, type ScoreInput, type ScoreValue, type Scorer, type ScorerCalculation, type ScorerComposition, type ScorerCompositionInput, type ScorerConfig, type ScorerConfigs, type ScorerInput, type ScorerKind, type ScorerListOptions, type ScorerMetadata, type ScorerOrder, type ScorerPage, type ScorerVersion, type ScorerVersionPage, Scorers, type UpdateDatasetItemOptions, type UploadReceipt, type ValidateCompositionOptions };
625
+ export { type BooleanScorerConfig, BulkUploadError, type BulkUploadReceipt, type CategoricalScorerConfig, type CategoricalScorerOption, type CreateDatasetItemOptions, type CreateScorerOptions, type Dataset, type DatasetItem, type DatasetItemPage, type DatasetListOptions, type DatasetMetadata, type DatasetOrder, type DatasetPage, type DatasetRevision, type DatasetRevisionPage, DatasetSnapshot, Datasets, EvaluationAPIError, type EvaluationCount, type EvaluationErrorFields, EvaluationItem, type EvaluationItemOptions, EvaluationResult, type EvaluationResultOptions, Experiment, ExperimentCreationAbortedError, type ExperimentOptions, type ExperimentReceipt, type ItemIdentifiers, type ItemListOptions, type ItemPayload, type ItemReceipt, type ItemUpdate, type JSONObject, type JSONValue, type NumericPassingRule, type NumericScorerConfig, OfflineEvaluations, type OfflineEvaluationsOptions, type PageOptions, type Persistence, type RequestOptions, type ResultPayload, type ResultReceipt, type ResultStatus, type ResultUpdate, type RevisionOptions, type ScoreInput, type ScoreValue, type Scorer, type ScorerCalculation, type ScorerComposition, type ScorerCompositionInput, type ScorerConfig, type ScorerConfigs, type ScorerInput, type ScorerKind, type ScorerListOptions, type ScorerMetadata, type ScorerOrder, type ScorerPage, type ScorerVersion, type ScorerVersionPage, Scorers, type UpdateDatasetItemOptions, type UploadReceipt, type ValidateCompositionOptions };
565
626
  //# sourceMappingURL=index.d.ts.map
@@ -623,21 +623,39 @@ const RESULT_FIELDS = {
623
623
  errorMessage: "error_message",
624
624
  metadata: "metadata"
625
625
  };
626
- const ITEM_IDS = {
626
+ const EDITABLE_ITEM_IDS = {
627
627
  modelVersion: "model_version",
628
628
  caseKey: "case_key",
629
629
  trial: "trial",
630
- datasetItemIdentifier: "dataset_item_identifier",
631
- datasetItemVersionIdentifier: "dataset_item_version_identifier",
632
630
  applicationTraceId: "application_trace_id"
633
631
  };
632
+ const ITEM_IDS = {
633
+ ...EDITABLE_ITEM_IDS,
634
+ datasetItemIdentifier: "dataset_item_identifier",
635
+ datasetItemVersionIdentifier: "dataset_item_version_identifier"
636
+ };
634
637
  const items = /* @__PURE__ */ new WeakMap();
635
638
  const results = /* @__PURE__ */ new WeakMap();
636
- function payload(options, fields, limit) {
639
+ const PAYLOADS = {
640
+ item: {
641
+ fields: ITEM_FIELDS,
642
+ limit: 1048576
643
+ },
644
+ result: {
645
+ fields: RESULT_FIELDS,
646
+ limit: 262144
647
+ }
648
+ };
649
+ function payload(options, kind) {
650
+ const { fields } = PAYLOADS[kind];
637
651
  const supplied = Object.keys(fields).filter((key) => options[key] !== void 0);
638
652
  if (options.payload !== void 0 && supplied.length) throw new TypeError("Supply payload or individual fields, not both.");
639
653
  if (options.payload === void 0 && !supplied.length) return void 0;
640
- const source = options.payload === void 0 ? Object.fromEntries(supplied.map((key) => [key, options[key]])) : object(options.payload);
654
+ return checkedPayload(options.payload === void 0 ? Object.fromEntries(supplied.map((key) => [key, options[key]])) : options.payload, kind);
655
+ }
656
+ function checkedPayload(value, kind) {
657
+ const { fields, limit } = PAYLOADS[kind];
658
+ const source = object(value);
641
659
  keys(source, Object.keys(fields));
642
660
  const snapshot = json(Object.fromEntries(Object.entries(source).map(([key, v]) => {
643
661
  if (key === "metadata" && v !== null) metadata(v);
@@ -691,7 +709,7 @@ var EvaluationItem = class EvaluationItem {
691
709
  if (value !== void 0 && value !== null) body[wire] = identifier(value);
692
710
  }
693
711
  if (options.datasetItemVersionId != null) body.dataset_item_version_id = uuid(options.datasetItemVersionId);
694
- const data = payload(options, ITEM_FIELDS, 1048576);
712
+ const data = payload(options, "item");
695
713
  if (data !== void 0) body.payload = data;
696
714
  items.set(this, encode(body));
697
715
  Object.freeze(this);
@@ -740,6 +758,16 @@ var EvaluationItem = class EvaluationItem {
740
758
  });
741
759
  }
742
760
  };
761
+ function validateResultStatus(status, value, errorCode) {
762
+ if (![
763
+ "ok",
764
+ "error",
765
+ "skipped",
766
+ "not_applicable"
767
+ ].includes(status)) throw new TypeError("Unsupported result status.");
768
+ if (status !== "ok" && value != null) throw new TypeError("Only ok results can contain a score.");
769
+ if (status !== "error" && errorCode != null) throw new TypeError("Only error results can contain an error code.");
770
+ }
743
771
  /** An evaluator outcome pinned to an exact scorer version. `ok` does not imply passing. */
744
772
  var EvaluationResult = class EvaluationResult {
745
773
  constructor(options) {
@@ -763,14 +791,7 @@ var EvaluationResult = class EvaluationResult {
763
791
  this.calculate = options.calculate === true;
764
792
  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.");
765
793
  const status = options.status ?? "ok";
766
- if (![
767
- "ok",
768
- "error",
769
- "skipped",
770
- "not_applicable"
771
- ].includes(status)) throw new TypeError("Unsupported result status.");
772
- if (status !== "ok" && options.value !== void 0 && options.value !== null) throw new TypeError("Only ok results can contain a score.");
773
- if (status !== "error" && options.errorCode != null) throw new TypeError("Only error results can contain an error code.");
794
+ validateResultStatus(status, options.value, options.errorCode);
774
795
  const body = {
775
796
  item_id: this.itemId,
776
797
  scorer_version_id: this.scorerVersionId
@@ -783,7 +804,7 @@ var EvaluationResult = class EvaluationResult {
783
804
  if (options.errorCode != null) body.error_code = identifier(options.errorCode, 128);
784
805
  if (options.evaluatorTraceId != null) body.evaluator_trace_id = identifier(options.evaluatorTraceId);
785
806
  if (options.evaluatedAt != null) body.evaluated_at = timestamp(options.evaluatedAt);
786
- const data = payload(options, RESULT_FIELDS, 262144);
807
+ const data = payload(options, "result");
787
808
  if (data !== void 0) {
788
809
  if (status !== "error" && data.error_message != null) throw new TypeError("Only error results can contain an error message.");
789
810
  body.payload = data;
@@ -839,6 +860,32 @@ function resultJSON(result) {
839
860
  return value;
840
861
  }
841
862
  //#endregion
863
+ //#region src/evaluations/mutations.ts
864
+ function itemChanges(options) {
865
+ const source = object(options);
866
+ keys(source, ["revision", ...Object.keys(EDITABLE_ITEM_IDS)]);
867
+ const changes = {};
868
+ for (const [key, wire] of Object.entries(EDITABLE_ITEM_IDS)) if (source[key] !== void 0) changes[wire] = nullable(source[key], identifier);
869
+ return changes;
870
+ }
871
+ function resultChanges(options) {
872
+ keys(object(options), [
873
+ "revision",
874
+ "status",
875
+ "value",
876
+ "errorCode"
877
+ ]);
878
+ const changes = {};
879
+ if (options.status !== void 0) {
880
+ if (options.status === "ok" && options.value === null) throw new TypeError("A successful result cannot clear its score.");
881
+ validateResultStatus(options.status, options.value, options.errorCode);
882
+ changes.status = options.status;
883
+ }
884
+ if (options.value !== void 0) changes.value = nullable(options.value, score);
885
+ if (options.errorCode !== void 0) changes.error_code = nullable(options.errorCode, (value) => identifier(value, 128));
886
+ return changes;
887
+ }
888
+ //#endregion
842
889
  //#region src/evaluations/scorers.ts
843
890
  const CONFIG_KEYS = {
844
891
  trueLabel: "true_label",
@@ -1303,6 +1350,13 @@ var Transport = class {
1303
1350
  });
1304
1351
  const raw = await response.text();
1305
1352
  operation.signal.throwIfAborted();
1353
+ if (response.ok && method === "DELETE") {
1354
+ if (response.status === 204) return {};
1355
+ throw new EvaluationAPIError({
1356
+ status: response.status,
1357
+ code: "invalid_response"
1358
+ });
1359
+ }
1306
1360
  let payload;
1307
1361
  try {
1308
1362
  payload = decode(raw);
@@ -1672,6 +1726,79 @@ var Experiment = class {
1672
1726
  return responseTags(data.tags);
1673
1727
  }), request.signal);
1674
1728
  }
1729
+ /** Read the current revision shared by an item and its payload. */
1730
+ async getItemRevision(itemId, request = {}) {
1731
+ const id = uuid(itemId);
1732
+ return this.#readRevision(`items/${id}/`, id, request);
1733
+ }
1734
+ /** The result payload endpoint includes its owner's revision even when the payload is unavailable. */
1735
+ async getResultRevision(resultId, request = {}) {
1736
+ const id = uuid(resultId);
1737
+ return this.#readRevision(`results/${id}/payload/`, id, request);
1738
+ }
1739
+ async #readRevision(path, id, { signal }) {
1740
+ return this.#queue.run(async () => {
1741
+ return parseResponse(await this.#transport.request("GET", this.#base + path, { signal }), (resource) => {
1742
+ if (uuid(resource.id) !== id) throw new TypeError("Mismatched resource ID.");
1743
+ return integer(resource.revision, 0);
1744
+ });
1745
+ }, signal);
1746
+ }
1747
+ /** Update the supplied item identifiers and return the current item revision. */
1748
+ async updateItem(itemId, options, request = {}) {
1749
+ return this.#patch(`items/${uuid(itemId)}/`, itemChanges(options), options.revision, request);
1750
+ }
1751
+ /** Correct a reported outcome. The service recomputes dependent composite scores. */
1752
+ async updateResult(resultId, options, request = {}) {
1753
+ return this.#patch(`results/${uuid(resultId)}/`, resultChanges(options), options.revision, request);
1754
+ }
1755
+ /** Replace the supplied top-level payload fields and return the current item revision. */
1756
+ async updateItemPayload(itemId, options, request = {}) {
1757
+ keys(object(options), ["revision", "payload"]);
1758
+ return this.#patch(`items/${uuid(itemId)}/payload/`, { payload: checkedPayload(options.payload, "item") }, options.revision, request);
1759
+ }
1760
+ /** Replace the supplied top-level payload fields and return the current result revision. */
1761
+ async updateResultPayload(resultId, options, request = {}) {
1762
+ keys(object(options), ["revision", "payload"]);
1763
+ return this.#patch(`results/${uuid(resultId)}/payload/`, { payload: checkedPayload(options.payload, "result") }, options.revision, request);
1764
+ }
1765
+ async #patch(path, changes, revision, { signal }) {
1766
+ if (!Object.keys(changes).length) throw new TypeError("Supply at least one field to update.");
1767
+ const body = encode({
1768
+ revision: integer(revision, 0),
1769
+ ...changes
1770
+ });
1771
+ return this.#queue.run(async () => {
1772
+ return parseResponse(await this.#transport.request("PATCH", this.#base + path, {
1773
+ signal,
1774
+ body
1775
+ }), (ack) => integer(ack.revision, revision));
1776
+ }, signal);
1777
+ }
1778
+ /** Permanently delete the item, its results, and their payloads. */
1779
+ async deleteItem(itemId, options, request = {}) {
1780
+ return this.#delete(`items/${uuid(itemId)}/`, options, request);
1781
+ }
1782
+ /** Permanently delete the result, its payload, and any dependent composites. */
1783
+ async deleteResult(resultId, options, request = {}) {
1784
+ return this.#delete(`results/${uuid(resultId)}/`, options, request);
1785
+ }
1786
+ /** Permanently remove the stored payload and retain the item and scores. */
1787
+ async deleteItemPayload(itemId, options, request = {}) {
1788
+ return this.#delete(`items/${uuid(itemId)}/payload/`, options, request);
1789
+ }
1790
+ /** Permanently remove the stored payload and retain the result. */
1791
+ async deleteResultPayload(resultId, options, request = {}) {
1792
+ return this.#delete(`results/${uuid(resultId)}/payload/`, options, request);
1793
+ }
1794
+ async #delete(path, options, { signal }) {
1795
+ keys(object(options), ["revision"]);
1796
+ const revision = integer(options.revision, 0);
1797
+ await this.#queue.run(() => this.#transport.request("DELETE", this.#base + path, {
1798
+ signal,
1799
+ params: { revision }
1800
+ }), signal);
1801
+ }
1675
1802
  };
1676
1803
  function submissionOptions(data) {
1677
1804
  const result = {