Skip to content

opik.EvaluationDataset

kedro_datasets_experimental.opik.EvaluationDataset

EvaluationDataset(
    dataset_name,
    credentials,
    filepath=None,
    sync_policy="local",
    metadata=None,
)

Bases: AbstractDataset

Kedro dataset for Opik evaluation datasets.

Connects to an Opik evaluation dataset and returns an opik.Dataset on load(), which can be passed to opik.evaluation.evaluate() to run experiments. Supports an optional local JSON/YAML file as the authoring surface for evaluation items.

On load / save behaviour:

  • On load: Creates the remote dataset if it does not exist, synchronises based on sync_policy, and returns an opik.Dataset.
  • On save: Inserts all items to the remote dataset via Opik's upsert-by-ID API. Items with a UUID v7 id update the existing remote row in-place; items without a UUID v7 id create a new remote row on every call. In local mode, items are also merged into the local file (new items take precedence). In remote mode, only the remote insert occurs.

Item format:

The local file and save() data must be a list of dicts. Each item accepts the following keys:

  • input (required) — the evaluation input payload.
  • id — identifier used for local deduplication. The upload behaviour depends on whether id is a valid UUID v7:

    • Valid UUID v7: forwarded to Opik. Opik's API upserts by item ID — the first sync creates the remote row; subsequent syncs update that same row in-place if the content has changed. The remote row keeps the same UUID across all syncs. Whenever content changes, the existing remote row is updated in-place, while no new row is created.
    • All other values (human-readable strings, UUIDs of other versions, None, empty string, or no id key): stripped before upload. Opik auto-generates a new UUID v7. Unchanged content is deduplicated by content hash (no-op), but changed content creates a new remote row while the previous one remains, leading to row accumulation over time.
  • expected_output — ground-truth value for scoring.

  • metadata — arbitrary metadata dict attached to the item.

[
  {
    "id": "q1",
    "input": {"text": "cancel my order"},
    "expected_output": "cancel_order",
    "metadata": {"source": "production"}
  }
]
("q1" is used for local deduplication only, as it is not a UUID v7 and will be stripped on upload)

Sync policies:

  • local (default): The local file is the source of truth. On load(), all local items are re-inserted to remote on every sync. Opik's API upserts by item ID, so the outcome depends on whether each item carries a UUID v7 id:

    • Items with a UUID v7 id are updated in-place on the remote — content changes replace the existing row; unchanged items are a no-op.
    • Items without a UUID v7 id (non-UUID values are stripped) are deduplicated by content hash — unchanged content is a no-op, but changed content creates a new remote row (the previous row remains), leading to row accumulation over time. save() inserts to remote and merges into the local file (new data takes precedence).
  • remote: The remote Opik dataset is the sole source of truth. load() fetches the remote dataset as-is with no local file interaction. save() inserts all items to remote without writing to any local file. If the remote dataset does not exist yet, it is created empty — no items are pushed from the local file. To seed a new remote dataset, run with sync_policy="local" at least once, or create and populate the dataset directly via the Opik UI.

Examples:

Using catalog YAML configuration:

# Local sync policy — local file seeds and syncs to remote
evaluation_dataset:
  type: kedro_datasets_experimental.opik.EvaluationDataset
  dataset_name: intent-detection-eval
  filepath: data/evaluation/intent_items.json
  sync_policy: local
  credentials: opik_credentials
  metadata:
    project: intent-detection

# Remote sync policy — Opik is the source of truth
production_eval:
  type: kedro_datasets_experimental.opik.EvaluationDataset
  dataset_name: intent-detection-eval
  sync_policy: remote
  credentials: opik_credentials

Using Python API:

from kedro_datasets_experimental.opik import EvaluationDataset

dataset = EvaluationDataset(
    dataset_name="intent-detection-eval",
    credentials={"api_key": "..."},  # pragma: allowlist secret
    filepath="data/evaluation/intent_items.json",
)

# Load returns an opik.Dataset for running experiments
from opik.evaluation import evaluate

eval_dataset = dataset.load()
evaluate(
    dataset=eval_dataset,
    task=my_task,
    scoring_functions=[my_scorer],
    experiment_name="my-experiment",
)

# Save new evaluation items
dataset.save(
    [
        {"id": "q1", "input": {"text": "cancel order"}, "expected_output": "cancel"},
    ]
)

# Same as in the other example, "q1" is not a UUID v7 and will be stripped on upload

Parameters:

  • dataset_name (str) –

    Name of the evaluation dataset in Opik.

  • credentials (dict[str, str]) –

    Opik authentication credentials. Required: api_key. Optional: workspace, host, project_name.

  • filepath (str | None, default: None ) –

    Path to a local JSON/YAML file for authoring evaluation items. Supports .json, .yaml, and .yml extensions. When None, no local file interaction occurs.

  • sync_policy (Literal['local', 'remote'], default: 'local' ) –

    Controls the source of truth for reads and whether a local file is involved: "local" (default) — all local items are re-inserted to remote on load(); save() inserts to remote and merges into the local file (new data takes precedence). "remote" — load() fetches remote as-is; save() inserts to remote without local file interaction.

  • metadata (dict[str, Any] | None, default: None ) –

    Optional metadata dict stored locally and returned by _describe(). Note: Opik's create_dataset() does not accept a metadata argument, so this value is not propagated to the remote dataset.

Source code in kedro_datasets_experimental/opik/evaluation_dataset.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def __init__(
    self,
    dataset_name: str,
    credentials: dict[str, str],
    filepath: str | None = None,
    sync_policy: Literal["local", "remote"] = "local",
    metadata: dict[str, Any] | None = None,
):
    """Initialise ``EvaluationDataset``.

    Args:
        dataset_name: Name of the evaluation dataset in Opik.
        credentials: Opik authentication credentials.
            Required: ``api_key``.
            Optional: ``workspace``, ``host``, ``project_name``.
        filepath: Path to a local JSON/YAML file for authoring evaluation
            items. Supports ``.json``, ``.yaml``, and ``.yml`` extensions.
            When ``None``, no local file interaction occurs.
        sync_policy: Controls the source of truth for reads and whether
            a local file is involved:
            ``"local"`` (default) — all local items are re-inserted to
            remote on ``load()``; ``save()`` inserts to remote and
            merges into the local file (new data takes precedence).
            ``"remote"`` — ``load()`` fetches remote as-is; ``save()``
            inserts to remote without local file interaction.
        metadata: Optional metadata dict stored locally and returned by
            ``_describe()``. Note: Opik's ``create_dataset()`` does not
            accept a metadata argument, so this value is not propagated
            to the remote dataset.
    """
    self._validate_init_params(credentials, filepath, sync_policy)

    self._dataset_name = dataset_name
    self._filepath = Path(filepath) if filepath else None
    self._sync_policy = sync_policy
    self._metadata = metadata
    self._file_dataset = None

    try:
        self._client = Opik(**build_opik_client_kwargs(credentials))
    except Exception as e:
        raise DatasetError(f"Failed to initialise Opik client: {e}") from e

file_dataset property

file_dataset

Return a JSON or YAML file dataset based on the filepath extension.

load

load()

Load the Opik dataset, syncing local items to remote if sync_policy is local.

Creates the remote dataset if it does not exist. In local mode, all local items are re-inserted to remote on every load via Opik's create_or_update API (upsert by item ID). On items with a valid UUID v7 id, update the existing remote row in-place, and no new row is created. On items where the id is not a valid UUID v7 (including missing, None, or empty), the id is stripped before upload and Opik auto-generates a new UUID v7. Unchanged content is deduplicated (no-op), but changed content creates a new remote row while the previous one remains.

Returns:

  • Dataset –

    The Opik dataset ready for use in experiments.

Raises:

  • DatasetError –

    If the Opik API returns an unexpected error or the server is unreachable.

Source code in kedro_datasets_experimental/opik/evaluation_dataset.py
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
def load(self) -> Dataset:
    """Load the Opik dataset, syncing local items to remote if sync_policy is ``local``.

    Creates the remote dataset if it does not exist. In ``local`` mode, all
    local items are re-inserted to remote on every load via Opik's
    ``create_or_update`` API (upsert by item ID). On items with a valid UUID v7
    ``id``, update the existing remote row in-place, and no new row is created.
    On items where the ``id`` is not a valid UUID v7 (including missing, ``None``, or empty),
    the ``id`` is stripped before upload and Opik auto-generates a new UUID v7.
    Unchanged content is deduplicated (no-op), but changed content creates a
    new remote row while the previous one remains.

    Returns:
        Dataset: The Opik dataset ready for use in experiments.

    Raises:
        DatasetError: If the Opik API returns an unexpected error or the
            server is unreachable.
    """
    dataset = self._get_or_create_remote_dataset()

    if self._sync_policy == "local":
        dataset = self._sync_local_to_remote(dataset)

    logger.info(
        "Loaded dataset '%s' (sync_policy='%s').",
        self._dataset_name,
        self._sync_policy,
    )
    return dataset

preview

preview()

Generate a JSON-compatible preview of the local evaluation data for Kedro-Viz.

Returns:

  • JSONPreview –

    A Kedro-Viz-compatible object containing a serialized JSON string. Returns a descriptive message if filepath is not configured or does not exist.

Source code in kedro_datasets_experimental/opik/evaluation_dataset.py
547
548
549
550
551
552
553
554
def preview(self) -> JSONPreview:
    """Generate a JSON-compatible preview of the local evaluation data for Kedro-Viz.

    Returns:
        JSONPreview: A Kedro-Viz-compatible object containing a serialized JSON string.
            Returns a descriptive message if filepath is not configured or does not exist.
    """
    return build_preview(self._filepath, self.file_dataset if self._filepath else None)

save

save(data)

Insert items into the Opik dataset and optionally update the local file.

In remote mode, only the remote upload occurs. In local mode, items are also merged into the local file.

Parameters:

  • data (list[dict[str, Any]]) –

    List of dicts, each containing at least an input key.

Raises:

  • DatasetError –

    If the Opik API call fails or any item is missing input.

Source code in kedro_datasets_experimental/opik/evaluation_dataset.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def save(self, data: list[dict[str, Any]]) -> None:
    """Insert items into the Opik dataset and optionally update the local file.

    In ``remote`` mode, only the remote upload occurs. In ``local`` mode,
    items are also merged into the local file.

    Args:
        data: List of dicts, each containing at least an ``input`` key.

    Raises:
        DatasetError: If the Opik API call fails or any item is missing ``input``.
    """
    if self._sync_policy == "remote":
        logger.warning(
            "sync_policy='remote': save() uploads to remote only, "
            "local file '%s' will not be updated.",
            self._filepath,
        )

    self._validate_items(data)

    dataset = self._get_or_create_remote_dataset()
    self._upload_items(dataset, data)
    try:
        self._client.flush()
    except Exception as e:
        raise DatasetError(
            f"Failed to flush items to Opik dataset '{self._dataset_name}': {e}"
        ) from e

    if self._sync_policy == "local" and self._filepath:
        existing: list[dict] = []
        if self._filepath.exists():
            existing = self.file_dataset.load()
        self.file_dataset.save(self._merge_items(existing, data))