UNPKG

@mastra/core

Version:
354 lines • 14.7 kB
import type { Mastra } from '../mastra/index.js'; import type { DatasetRecord, DatasetItem, DatasetItemPayload, DatasetItemRow, DatasetTenancyFilters, DatasetVersion, Experiment, ExperimentProvenance, ExperimentResult, ExperimentResultStatus, ExperimentStatus, ExperimentTenancyFilters, ListDatasetItemsInput, ListDatasetItemsOutput, ListExperimentResultsOutput, ListExperimentsInput, ListExperimentsOutput, ListExperimentResultsInput, TargetType, UpdateDatasetInput, UpdateDatasetItemInput, UpdateExperimentResultInput } from '../storage/types.js'; import { executeExperimentItem } from './experiment/index.js'; import type { StartExperimentConfig, ExperimentSummary } from './experiment/types.js'; /** * Public API for interacting with a single dataset. * * Provides methods for item CRUD, versioning, and experiment management. * Obtained via `DatasetsManager.get()` or `DatasetsManager.create()`. */ export declare class Dataset { #private; readonly id: string; constructor(id: string, mastra: Mastra, scope?: DatasetTenancyFilters); /** * Get the full dataset record from storage. */ getDetails(): Promise<DatasetRecord>; /** * Update dataset metadata and/or schemas. * * Accepts Zod schemas for `inputSchema` / `groundTruthSchema` (widened to * `unknown`); they are normalized to JSON Schema before being forwarded to * the storage-canonical {@link UpdateDatasetInput} shape. All other fields * mirror {@link UpdateDatasetInput} exactly (minus `id`, which is supplied * from `this.id`). */ update(input: Omit<UpdateDatasetInput, 'id' | 'inputSchema' | 'groundTruthSchema'> & { inputSchema?: unknown; groundTruthSchema?: unknown; }): Promise<DatasetRecord>; /** * Add a single item to the dataset. */ addItem(input: DatasetItemPayload): Promise<DatasetItem>; /** * Add multiple items to the dataset in bulk. */ addItems(input: { items: DatasetItemPayload[]; }): Promise<DatasetItem[]>; /** * Get a single item by ID, optionally at a specific version. */ getItem(args: { itemId: string; version?: number; }): Promise<DatasetItem | null>; /** * List items in the dataset, optionally at a specific version, with * optional substring search and pagination. * * Return shape depends on the arguments: * * - When `version` is the only argument provided (no `search`, `page`, or * `perPage`), returns a bare `DatasetItem[]` snapshot of every item at * that version. This shape is retained for callers that predate * server-side pagination on the versioned path; new code should pass * `page` / `perPage` (or `search`) to opt into the paginated shape. * - In all other cases (no arguments, or `search` / `page` / `perPage` * provided with or without `version`), returns the paginated * `{ items, pagination }` shape. * * @deprecated The `DatasetItem[]` branch of the return type is retained * for backwards compatibility with the `version`-only call form; pass * `page` / `perPage` (or `search`) to always receive the paginated * `{ items, pagination }` shape. */ listItems(args?: { version?: number; page?: number; perPage?: number; search?: string; orderBy?: ListDatasetItemsInput['orderBy']; }): Promise<DatasetItem[] | ListDatasetItemsOutput>; /** * Update an existing item in the dataset. Only the provided payload fields * are patched. */ updateItem(input: { itemId: string; } & Omit<UpdateDatasetItemInput, 'id' | 'datasetId' | 'filters'>): Promise<DatasetItem>; /** * Delete a single item from the dataset. */ deleteItem(args: { itemId: string; }): Promise<void>; /** * Permanently scrub user-supplied content from every version of an item and * from experiment results that reference it. */ purgeItem(args: { itemId: string; }): Promise<void>; /** * Delete multiple items from the dataset in bulk. */ deleteItems(args: { itemIds: string[]; }): Promise<void>; /** * List all versions of this dataset. */ listVersions(args?: { page?: number; perPage?: number; }): Promise<{ versions: DatasetVersion[]; pagination: { total: number; page: number; perPage: number | false; hasMore: boolean; }; }>; /** * Get full SCD-2 history of a specific item across all dataset versions. */ getItemHistory(args: { itemId: string; }): Promise<DatasetItemRow[]>; /** * Run an experiment on this dataset and wait for completion. */ startExperiment<I = unknown, O = unknown, E = unknown>(config: StartExperimentConfig<I, O, E>): Promise<ExperimentSummary>; /** * Start an experiment asynchronously (fire-and-forget). * Returns immediately with the experiment ID and pending status. */ startExperimentAsync<I = unknown, O = unknown, E = unknown>(config: StartExperimentConfig<I, O, E>): Promise<{ experimentId: string; status: 'pending'; totalItems: number; }>; /** * List experiments (runs) for this dataset, with optional filters and * pagination. All filters are pushed to the storage layer. * * @param args.targetType Restrict to a specific target type (e.g. `agent`). * @param args.targetId Restrict to a specific target ID. * @param args.agentVersion Restrict to a specific agent version — useful for * baseline vs variant read patterns. * @param args.status Restrict to a specific experiment status. * @param args.filters Multi-tenant scoping filters (organization/project). * @param args.page Page number. Defaults to `0`. * @param args.perPage Page size. Defaults to `20`. */ listExperiments(args?: { targetType?: TargetType; targetId?: string; agentVersion?: string; status?: ExperimentStatus; experimentSetId?: string; comparisonId?: string; variantId?: string; trialIndex?: number; filters?: ExperimentTenancyFilters; page?: number; perPage?: number; orderBy?: ListExperimentsInput['orderBy']; }): Promise<ListExperimentsOutput>; /** * Get a specific experiment (run) by ID. */ getExperiment(args: { experimentId: string; }): Promise<Experiment | null>; /** * Update an experiment's user-facing label (name, description, metadata). * Status and counters are owned by the runtime and cannot be changed here. * Throws EXPERIMENT_NOT_FOUND for unknown or cross-dataset experiments. */ updateExperiment(args: { experimentId: string; name?: string; description?: string; metadata?: Record<string, unknown>; }): Promise<Experiment>; /** * List results for a specific experiment, with optional filters and * pagination. All filters are pushed to the storage layer. * * @param args.experimentId The experiment whose results to list. * @param args.traceId Restrict to results linked to a specific trace. * @param args.status Restrict to a specific per-result review status. * @param args.tags Restrict to results that have *all* of these tags. * @param args.filters Multi-tenant scoping filters (organization/project). * @param args.page Page number. Defaults to `0`. * @param args.perPage Page size. Defaults to `20`. */ listExperimentResults(args: { experimentId: string; traceId?: string; status?: ExperimentResultStatus; tags?: string[]; filters?: ExperimentTenancyFilters; page?: number; perPage?: number; orderBy?: ListExperimentResultsInput['orderBy']; }): Promise<ListExperimentResultsOutput>; /** * Update an experiment result's status or tags. */ updateExperimentResult(input: UpdateExperimentResultInput & { experimentId: string; }): Promise<ExperimentResult>; /** * Create an experiment whose execution loop is owned by the caller * (e.g. a Temporal workflow). No runner is spawned. Two shapes: * * - With `targetType`/`targetId`: the caller drives the loop and Mastra * executes each item on demand via {@link Dataset.runExperimentItem}. * Optional `scorers` are pinned on the experiment as the run-level * scorer source. * - Without a target: pure ingestion — the caller executes and scores * everything itself and upserts rows via * {@link Dataset.submitExperimentResult}. * * Either way the caller closes the run with * {@link Dataset.finalizeExperiment}. * * Idempotent on `id`: passing a caller-supplied id (e.g. a workflow run id) * and retrying the create converges on the same experiment instead of * creating duplicates. */ createExperiment(args?: { /** Caller-supplied experiment id (e.g. a workflow run id) for idempotent creates. */ id?: string; /** Target to execute per item via {@link Dataset.runExperimentItem}. Both or neither of targetType/targetId. */ targetType?: TargetType; targetId?: string; /** Run-level scorer IDs, resolved server-side by {@link Dataset.runExperimentItem}. Requires a target. */ scorers?: string[]; name?: string; description?: string; metadata?: Record<string, unknown>; provenance?: ExperimentProvenance; grouping?: { experimentSetId?: string; comparisonId?: string; variantId?: string; trialIndex?: number; }; /** Dataset version to pin. Defaults to the dataset's current version. */ version?: number; }): Promise<{ experimentId: string; status: ExperimentStatus; totalItems: number; datasetVersion: number; /** The persisted start timestamp — stable across retried creates with the same `id`. */ startedAt: Date | null; }>; /** * Execute one experiment item server-side: run the experiment's target * against the item, run the resolved scorers, and upsert the result row * keyed by `(experimentId, itemId, attempt)`. * * Built for caller-driven loops (mode 2): a durable orchestrator (e.g. a * Temporal workflow) fans out one call per item and owns retries/timeouts — * a retried call converges on the same row. Requires an experiment created * with a target via {@link Dataset.createExperiment}. * * Scorer precedence: experiment `scorers` → item `scorerIds` → dataset * `scorerIds` → none. */ runExperimentItem(args: { experimentId: string; itemId: string; /** Zero-based repetition index for repeated trials. Defaults to `0`. */ attempt?: number; /** Request context merged with the item's own request context (item wins). */ requestContext?: Record<string, unknown>; }): Promise<{ result: ExperimentResult; scores: Awaited<ReturnType<typeof executeExperimentItem>>['scores']; }>; /** * Submit (or re-submit) one item result for a target-less (pure-ingestion) * experiment created with {@link Dataset.createExperiment}. * * Upsert semantics: the row is identified by the natural key * `(experimentId, itemId, attempt)`, so a retried submission (e.g. a * retried Temporal activity) converges on a single row instead of * duplicating. `attempt` defaults to `0`; use it only for intentional * repeated trials of the same item. * * `input` / `groundTruth` default to the dataset item's values at the * experiment's pinned dataset version when omitted. * * Inline `scores` are persisted to the scores store keyed by * `runId = experimentId`, the same shape the native runner writes, so * comparisons and Studio aggregation work unchanged. Score persistence is * best-effort and never fails the submission. */ submitExperimentResult(args: { experimentId: string; itemId: string; /** Zero-based repetition index for repeated trials. Defaults to `0`. */ attempt?: number; input?: unknown; output?: unknown; groundTruth?: unknown; error?: { message: string; stack?: string; code?: string; } | null; startedAt?: Date; completedAt?: Date; traceId?: string; scores?: { scorerId: string; scorerName?: string; score: number; reason?: string; metadata?: Record<string, unknown>; }[]; }): Promise<ExperimentResult>; /** * Finalize a caller-driven experiment: compute per-item * succeeded/failed/skipped counts from the persisted result rows and mark * the experiment completed. The caller sends no bookkeeping — the server is * the source of truth. Works for both targeted (runExperimentItem) and * target-less (submitExperimentResult) experiments. * * Idempotent: finalizing an already-completed experiment recomputes nothing * and returns the stored record. */ finalizeExperiment(args: { experimentId: string; }): Promise<Experiment>; /** * Delete an experiment (run) by ID. * * The ownership check above already refuses cross-tenant / cross-dataset * requests, but we still forward `this.#scope` to storage so the delete * is defense-in-depth: a leaked handle or race that skipped the assertion * still cannot delete another tenant's experiment (storage silently no-ops * on tenancy mismatch). * * Also deletes the observability traces this experiment produced, cascading to * their spans and trace-linked signals. An experiment's traces are excluded from * normal trace reads, so leaving them behind would make them invisible but * still-retained data. Stores without an observability domain (or without * tenant-scoped trace deletion) log a warning and skip the trace cascade so the * relational delete still succeeds. */ deleteExperiment(args: { experimentId: string; }): Promise<void>; } //# sourceMappingURL=dataset.d.ts.map