# Attempting to create a text prompt with the same name will raise an error
try:
    text_prompt = opik.Prompt(
        name="my-prompt",
        prompt="Hello {{name}}"
    )
except opik.exceptions.PromptTemplateStructureMismatch as e:
    print("Error: Cannot change prompt structure from chat to text")
```

Similarly, if you create a text prompt first, you cannot later create a chat prompt with the same name.

Both [`Prompt`](https://www.comet.com/docs/opik/python-sdk-reference/library/Prompt.html) and [`ChatPrompt`](https://www.comet.com/docs/opik/python-sdk-reference/library/ChatPrompt.html) classes will raise a [`PromptTemplateStructureMismatch`](https://www.comet.com/docs/opik/python-sdk-reference/exceptions.html#opik.exceptions.PromptTemplateStructureMismatch) exception if you attempt to change the structure of an existing prompt.

## Working with prompt versions

### Viewing prompt history (all versions)

<Tabs>
  <Tab value="Text prompts" title="Text prompts">
    Use [`get_prompt_history`](https://www.comet.com/docs/opik/python-sdk-reference/Opik.html#opik.Opik.get_prompt_history) for text prompts:

    ```python maxLines=1000
    import opik

    opik.configure()
    client = opik.Opik()

    # Get the complete version history for a text prompt
    prompt_history = client.get_prompt_history(name="prompt-summary")

    # Iterate through all versions
    for version in prompt_history:
        print(f"Name: {version.name}")
        print(f"Commit: {version.commit}")
        print(f"Prompt text: {version.prompt}")
        print(f"Metadata: {version.metadata}")
        print(f"Type: {version.type}")
        print("-" * 50)
    ```

    This returns a list of Prompt objects (each representing a specific version) for the given prompt name.
  </Tab>

  <Tab value="Chat prompts" title="Chat prompts">
    Use [`get_chat_prompt_history`](https://www.comet.com/docs/opik/python-sdk-reference/Opik.html#opik.Opik.get_chat_prompt_history) for chat prompts:

    ```python maxLines=1000
    import opik

    opik.configure()
    client = opik.Opik()

    # Get the complete version history for a chat prompt
    chat_prompt_history = client.get_chat_prompt_history(name="assistant-prompt")

    # Iterate through all versions
    for version in chat_prompt_history:
        print(f"Name: {version.name}")
        print(f"Commit: {version.commit}")
        print(f"Messages: {version.template}")
        print(f"Metadata: {version.metadata}")
        print(f"Type: {version.type}")
        print("-" * 50)
    ```

    This returns a list of ChatPrompt objects (each representing a specific version) for the given prompt name.
  </Tab>
</Tabs>

You can use this information to:

* **Audit changes** to understand how prompts evolved
* **Identify the best performing version** by linking commit IDs to experiment results
* **Document prompt changes** for compliance or review purposes
* **Retrieve specific versions** by commit ID for testing or rollback

### Accessing specific prompt versions

<Tabs>
  <Tab value="Text prompts" title="Text prompts">
    Use the `commit` parameter with [`get_prompt`](https://www.comet.com/docs/opik/python-sdk-reference/Opik.html#opik.Opik.get_prompt):

    ```python maxLines=1000
    import opik

    opik.configure()
    client = opik.Opik()

    # Get a specific version of a text prompt by commit ID
    prompt = client.get_prompt(name="prompt-summary", commit="abc123def456")

    # Use the prompt in your application
    formatted_prompt = prompt.format(text="Hello, world!")
    print(formatted_prompt)
    ```
  </Tab>

  <Tab value="Chat prompts" title="Chat prompts">
    Use the `commit` parameter with [`get_chat_prompt`](https://www.comet.com/docs/opik/python-sdk-reference/Opik.html#opik.Opik.get_chat_prompt):

    ```python maxLines=1000
    import opik

    opik.configure()
    client = opik.Opik()

    # Get a specific version of a chat prompt by commit ID
    chat_prompt = client.get_chat_prompt(name="assistant-prompt", commit="abc123def456")

    # Use the prompt in your application
    formatted_messages = chat_prompt.format(variables={"name": "Alice"})
    print(formatted_messages)
    ```
  </Tab>
</Tabs>

The `commit` parameter accepts the commit ID (also called commit hash) of the specific prompt version you want to retrieve. You can find commit IDs in the prompt history in the Opik UI or by using the `get_prompt_history` or `get_chat_prompt_history` methods (see above).

This is particularly useful when you want to:

* **Pin to a specific version** in production to ensure consistent behavior
* **Test different versions** side by side in experiments
* **Roll back** to a previous version if issues are discovered
* **Compare results** across different prompt versions

## Using prompts in experiments

### Linking prompts to experiments

<Tabs>
  <Tab value="Text prompt" title="Text prompt">
    ```python maxLines=1000
    import opik
    from opik.evaluation import evaluate
    from opik.evaluation.metrics import Hallucination
    from openai import OpenAI

    opik.configure()
    opik_client = opik.Opik()
    openai_client = OpenAI()

    # Get a dataset
    dataset = opik_client.get_or_create_dataset("test_dataset")

    # Create a text prompt
    prompt = opik.Prompt(name="My prompt", prompt="Summarize: {{text}}")

    # Create an evaluation task
    def evaluation_task(dataset_item):
        # Use the prompt in your task
        formatted_prompt = prompt.format(text=dataset_item["input"])
        
        # Call OpenAI API with formatted prompt
        response = openai_client.chat.completions.create(
            model="gpt-4",
            messages=[{"role": "user", "content": formatted_prompt}]
        )
        
        return {"output": response.choices[0].message.content}

    # Run the evaluation
    evaluation = evaluate(
        experiment_name="My experiment",
        dataset=dataset,
        task=evaluation_task,
        prompts=[prompt],
    )
    ```
  </Tab>

  <Tab value="Chat prompt" title="Chat prompt">
    ```python maxLines=1000
    import opik
    from opik.evaluation import evaluate
    from opik.evaluation.metrics import Hallucination
    from openai import OpenAI

    opik.configure()
    opik_client = opik.Opik()
    openai_client = OpenAI()

    # Get a dataset
    dataset = opik_client.get_or_create_dataset("test_dataset")

    # Create a chat prompt
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Summarize: {{text}}"}
    ]
    chat_prompt = opik.ChatPrompt(name="My chat prompt", messages=messages)

    # Create an evaluation task
    def evaluation_task(dataset_item):
        # Use the chat prompt in your task
        formatted_messages = chat_prompt.format(
            variables={"text": dataset_item["input"]}
        )
        
        # Call OpenAI API with formatted messages
        response = openai_client.chat.completions.create(
            model="gpt-4",
            messages=formatted_messages
        )
        
        return {"output": response.choices[0].message.content}

    # Run the evaluation
    evaluation = evaluate(
        experiment_name="My experiment",
        dataset=dataset,
        task=evaluation_task,
        prompts=[chat_prompt],
    )
    ```
  </Tab>
</Tabs>

The experiment will now be linked to the prompt, allowing you to view all experiments that use a specific prompt:

<Frame>
  <img src="https://files.buildwithfern.com/https://opik.docs.buildwithfern.com/docs/opik/2026-01-30T17:33:07.444Z/img/evaluation/linked_prompt.png" />
</Frame>

### Comparing prompt versions in experiments

<Tabs>
  <Tab value="Text prompts" title="Text prompts">
    ```python maxLines=1000
    import opik
    from opik.evaluation import evaluate

    opik.configure()
    client = opik.Opik()

    # Get the dataset
    dataset = client.get_or_create_dataset("test_dataset")

    # Get different versions of the same text prompt
    prompt_v1 = client.get_prompt(name="prompt-summary", commit="abc123")
    prompt_v2 = client.get_prompt(name="prompt-summary", commit="def456")

    # Define evaluation task that uses the prompt
    def evaluation_task_v1(dataset_item):
        formatted_prompt = prompt_v1.format(text=dataset_item["input"])
        # Call your LLM with the formatted prompt
        return {"output": "llm_response"}

    def evaluation_task_v2(dataset_item):
        formatted_prompt = prompt_v2.format(text=dataset_item["input"])
        # Call your LLM with the formatted prompt
        return {"output": "llm_response"}

    # Run experiments with different prompt versions
    experiment_v1 = evaluate(
        experiment_name="My experiment - v1",
        dataset=dataset,
        task=evaluation_task_v1,
        prompts=[prompt_v1],
    )

    experiment_v2 = evaluate(
        experiment_name="My experiment - v2",
        dataset=dataset,
        task=evaluation_task_v2,
        prompts=[prompt_v2],
    )

    # Compare results in the Opik UI
    ```
  </Tab>

  <Tab value="Chat prompts" title="Chat prompts">
    ```python maxLines=1000
    import opik
    from opik.evaluation import evaluate

    opik.configure()
    client = opik.Opik()

    # Get the dataset
    dataset = client.get_or_create_dataset("test_dataset")

    # Get different versions of the same chat prompt
    chat_prompt_v1 = client.get_chat_prompt(name="assistant-prompt", commit="abc123")
    chat_prompt_v2 = client.get_chat_prompt(name="assistant-prompt", commit="def456")

    # Define evaluation tasks that use the prompts
    def evaluation_task_v1(dataset_item):
        formatted_messages = chat_prompt_v1.format(
            variables={"text": dataset_item["input"]}
        )
        # Call your LLM with the formatted messages
        return {"output": "llm_response"}

    def evaluation_task_v2(dataset_item):
        formatted_messages = chat_prompt_v2.format(
            variables={"text": dataset_item["input"]}
        )
        # Call your LLM with the formatted messages
        return {"output": "llm_response"}

    # Run experiments with different chat prompt versions
    experiment_v1 = evaluate(
        experiment_name="My experiment - v1",
        dataset=dataset,
        task=evaluation_task_v1,
        prompts=[chat_prompt_v1],
    )

    experiment_v2 = evaluate(
        experiment_name="My experiment - v2",
        dataset=dataset,
        task=evaluation_task_v2,
        prompts=[chat_prompt_v2],
    )

    # Compare results in the Opik UI
    ```
  </Tab>
</Tabs>

This workflow allows you to systematically test and compare different prompt versions to identify the most effective one for your use case.