Skip to content

opik.PromptDataset

kedro_datasets_experimental.opik.PromptDataset

PromptDataset(
    filepath,
    prompt_name,
    credentials,
    prompt_type="text",
    sync_policy="local",
    mode="sdk",
    load_args=None,
    save_args=None,
    **opik_kwargs
)

Bases: AbstractDataset

Kedro dataset for managing prompts with Opik versioning and synchronisation.

This dataset provides seamless integration between local prompt files (JSON/YAML) and Opik's prompt management system, supporting version control, metadata tracking, and different synchronisation policies.

On save / load behaviour:

  • On save: Creates a new version of the prompt in Opik with the local data.
  • On load: Synchronises based on sync_policy and returns either the raw Opik object (SDK mode) or a LangChain ChatPromptTemplate (LangChain mode).

Sync policies:

  • local: Local file takes precedence (default). load_args are ignored with a warning, since local files are the source of truth.
  • remote: Opik version takes precedence. load_args are respected if supported.
  • strict: Raises an error if local and remote differ. load_args are respected if supported

Examples:

Using catalog YAML configuration:

# Local sync policy - local files are source of truth
customer_prompt:
  type: kedro_datasets_experimental.opik.PromptDataset
  filepath: data/prompts/customer.json
  prompt_name: customer_support_v1
  prompt_type: chat
  credentials: opik_credentials
  sync_policy: local
  mode: langchain

# Remote sync policy - Opik versions are source of truth
production_prompt:
  type: kedro_datasets_experimental.opik.PromptDataset
  filepath: data/prompts/production.yaml
  prompt_name: customer_support_v1
  sync_policy: remote
  mode: sdk

Using Python API:

from kedro_datasets_experimental.opik import PromptDataset

# Create dataset for chat prompt
dataset = PromptDataset(
    filepath="data/prompts/customer_support.json",
    prompt_name="customer_support_v1",
    prompt_type="chat",
    credentials={
        "api_key": "opik_...",  # pragma: allowlist secret
        "workspace": "my-workspace",
    },
)

# Load prompt as LangChain ChatPromptTemplate
prompt_template = dataset.load()
formatted = prompt_template.format(question="How are you?")

# Save with metadata
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello, {question}"},
]
dataset.save(messages)

Parameters:

  • filepath (str | PathLike) –

    Local file path for storing prompt. Supports .json, .yaml, .yml extensions.

  • prompt_name (str) –

    Unique identifier for the prompt in Opik.

  • prompt_type (Literal['chat', 'text'], default: 'text' ) –

    Either "chat" for message-based prompts or "text" for simple strings.

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

    How to handle conflicts between local and remote: - "local": Local file takes precedence (default) - "remote": Opik version takes precedence - "strict": Error if local and remote differ

  • mode (Literal['langchain', 'sdk'], default: 'sdk' ) –

    Return type for load() method: - "sdk": Returns raw Opik prompt object (default) - "langchain": Returns ChatPromptTemplate object

  • credentials (dict[str, Any]) –

    Dictionary with Opik client configuration. Keys may include 'api_key', 'workspace', 'project_name', etc.

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

    Dictionary with loading parameters. Currently reserved for future use when Opik supports version/label retrieval.

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

    Dictionary with saving parameters. Keys may include: - metadata: Additional metadata to store with the prompt

  • **opik_kwargs (Any, default: {} ) –

    Additional kwargs passed to Opik client initialisation.

Raises:

  • DatasetError –

    If required parameters are missing or invalid.

  • ImportError –

    If langchain is required but not installed.

Source code in kedro_datasets_experimental/opik/prompt_dataset.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def __init__(  # noqa: PLR0913
    self,
    filepath: str | os.PathLike,
    prompt_name: str,
    credentials: dict[str, Any],
    prompt_type: Literal["chat", "text"] = "text",
    sync_policy: Literal["local", "remote", "strict"] = "local",
    mode: Literal["langchain", "sdk"] = "sdk",
    load_args: dict[str, Any] | None = None,
    save_args: dict[str, Any] | None = None,
    **opik_kwargs: Any
):
    """Initialise PromptDataset with local and remote configuration.

    Args:
        filepath: Local file path for storing prompt. Supports .json, .yaml, .yml extensions.
        prompt_name: Unique identifier for the prompt in Opik.
        prompt_type: Either "chat" for message-based prompts or "text" for simple strings.
        sync_policy: How to handle conflicts between local and remote:
            - "local": Local file takes precedence (default)
            - "remote": Opik version takes precedence
            - "strict": Error if local and remote differ
        mode: Return type for load() method:
            - "sdk": Returns raw Opik prompt object (default)
            - "langchain": Returns ChatPromptTemplate object
        credentials: Dictionary with Opik client configuration. Keys may include
            'api_key', 'workspace', 'project_name', etc.
        load_args: Dictionary with loading parameters. Currently reserved for future use
            when Opik supports version/label retrieval.
        save_args: Dictionary with saving parameters. Keys may include:
            - metadata: Additional metadata to store with the prompt
        **opik_kwargs: Additional kwargs passed to Opik client initialisation.

    Raises:
        DatasetError: If required parameters are missing or invalid.
        ImportError: If langchain is required but not installed.
    """
    # Validate parameters
    self._validate_init_params(filepath, prompt_type, sync_policy, mode)

    self._filepath = Path(filepath)
    self._prompt_name = prompt_name
    self._prompt_type = prompt_type or "text"
    self._sync_policy = sync_policy or "local"
    self._mode = mode or "sdk"
    self._load_args = load_args or {}
    self._save_args = save_args or {}
    self._file_dataset = None

    # Initialise Opik client
    try:
        self._opik_client = Opik(**build_opik_client_kwargs(credentials), **opik_kwargs)
    except Exception as e:
        raise DatasetError(f"Failed to initialise Opik client: {e}")

    # Ensure dataset exists for tracking
    self._ensure_dataset_exists()

file_dataset property

file_dataset

Get appropriate Kedro dataset based on file extension (cached).

Returns:

load

load()

Load prompt with synchronisation logic.

Returns:

  • ChatPromptTemplate –

    If mode="langchain", ready-to-use LangChain template.

  • Any –

    If mode="sdk", raw Opik prompt object.

Raises:

  • DatasetError –

    If prompt cannot be loaded or has invalid format.

Source code in kedro_datasets_experimental/opik/prompt_dataset.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
def load(self) -> Union["ChatPromptTemplate", Any]:
    """Load prompt with synchronisation logic.

    Returns:
        ChatPromptTemplate: If mode="langchain", ready-to-use LangChain template.
        Any: If mode="sdk", raw Opik prompt object.

    Raises:
        DatasetError: If prompt cannot be loaded or has invalid format.
    """
    # Warn about load_args in local mode
    if self._sync_policy == "local" and self._load_args:
        logger.warning(
            f"Ignoring load_args for prompt '{self._prompt_name}' "
            f"because sync_policy='local'. Local files are the source of truth."
        )

    # Try to fetch from Opik with error handling
    try:
        opik_prompt, prompt_data = self._get_prompt_data()
    except (ConnectionError, TimeoutError) as e:
        logger.warning(
            f"Network error when fetching prompt '{self._prompt_name}' from Opik: {e}. "
            f"Falling back to local file."
        )
        opik_prompt, prompt_data = None, None
    except Exception as e:
        logger.warning(
            f"Error when fetching prompt '{self._prompt_name}' from Opik: {e}. "
            f"Falling back to local file."
        )
        opik_prompt, prompt_data = None, None

    # Load local data if file exists
    local_data = None
    if self._filepath.exists():
        try:
            local_data = self.file_dataset.load()
        except Exception as e:
            raise DatasetError(f"Failed to read local prompt file: {e}")

    # Sync and get final data
    opik_prompt, prompt_data = self._sync_with_opik(local_data, opik_prompt)

    # Return based on mode
    if self._mode == "sdk":
        return opik_prompt
    elif self._mode == "langchain":
        return self._convert_to_langchain_template(prompt_data)
    else:
        raise DatasetError(f"Unsupported mode: {self._mode}")

preview

preview()

Generate a JSON-compatible preview for Kedro-Viz.

Returns:

  • JSONPreview –

    A Kedro-Viz-compatible preview of the prompt.

Source code in kedro_datasets_experimental/opik/prompt_dataset.py
574
575
576
577
578
579
580
def preview(self) -> JSONPreview:
    """Generate a JSON-compatible preview for Kedro-Viz.

    Returns:
        JSONPreview: A Kedro-Viz-compatible preview of the prompt.
    """
    return build_preview(self._filepath, self.file_dataset)

save

save(data)

Save prompt to Opik.

Parameters:

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

    The prompt content to save. Can be string for text prompts or list of message dictionaries for chat prompts.

Raises:

Source code in kedro_datasets_experimental/opik/prompt_dataset.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def save(self, data: str | list[dict[str, str]]) -> None:
    """Save prompt to Opik.

    Args:
        data: The prompt content to save. Can be string for text prompts
            or list of message dictionaries for chat prompts.

    Raises:
        DatasetError: If data format is invalid or save fails.
    """
    # Validate data format
    if self._prompt_type == "chat" and not isinstance(data, list):
        raise DatasetError("Chat prompts must be a list of message dicts")
    if self._prompt_type == "text" and not isinstance(data, str):
        raise DatasetError("Text prompts must be a string")

    try:
        create_kwargs = {
            "name": self._prompt_name,
            "prompt": json.dumps(data, ensure_ascii=False) if not isinstance(data, str) else data,
        }

        # Add metadata if provided
        metadata = {"type": self._prompt_type}
        if "metadata" in self._save_args:
            metadata.update(self._save_args["metadata"])
        create_kwargs["metadata"] = metadata

        self._opik_client.create_prompt(**create_kwargs)
        logger.info(f"Successfully saved prompt '{self._prompt_name}' to Opik")
    except Exception as e:
        raise DatasetError(f"Failed to save prompt to Opik: {e}")