Use prompts in chat completions

Prompts store, version, and share prompt templates centrally in Studio. A chat completion request doesn't reference a stored prompt directly: you fetch the prompt through the Prompts API, then pass its content as a message. This guide shows how to use a stored prompt as the system message in a chat completion.

Use a stored prompt

Use a stored prompt

Fetch the prompt by its ID, or by its name with the prompt: prefix, such as prompt:coding-assistant. Then pass its content as the system message.

import os
from mistralai.client import Mistral

client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])

prompt = client.beta.prompts.get(prompt_id="prompt:coding-assistant")
system_content = prompt.definition.content

response = client.chat.complete(
    model="mistral-large-latest",
    messages=[
        {"role": "system", "content": system_content},
        {"role": "user", "content": "Help me debug this function."},
    ],
)
print(response.choices[0].message.content)
Template variables

Template variables

Prompts can contain {{variable}} placeholders, listed in the prompt's definition.variables. Replace them before passing the content to the completion.

For example, take a prompt stored as follows:

You are a coding assistant. You specialize in {{language}}.

Replace {{language}} before you pass the content:

prompt = client.beta.prompts.get(prompt_id="prompt:coding-assistant")
system_content = prompt.definition.content.replace("{{language}}", "Python")
Pin a version

Pin a version

Without a version or an alias, get returns the latest version of the prompt. To keep production behavior from changing each time someone saves a new version, pin a version number or an alias.

# Pin by version number
pinned = client.beta.prompts.get(prompt_id="prompt:coding-assistant", version=3)

# Pin by alias
production = client.beta.prompts.get(prompt_id="prompt:coding-assistant", alias="production")
Tip

Use named aliases, such as production or staging, to decouple your code from version numbers. You can update which version an alias points to from Studio without changing your application. For more information, see Versions and aliases.