跳到主要内容

提示词注册表

MLflow 提示词注册表是一个强大的工具,可简化您生成式 AI (GenAI) 应用中的提示词工程和管理。它使您能够在组织内部对提示词进行版本控制、跟踪和重用,从而帮助维护一致性并提高提示词开发中的协作效率。

主要优势

版本控制

通过受 Git 启发的基于提交的版本控制和带差异高亮显示的并排比较,跟踪您提示词的演变过程。MLflow 中的提示词版本是不可变的,为可重现性提供了有力保证。

别名

为提示词构建健壮而灵活的部署管道,允许您将提示词版本与主应用程序代码隔离,并轻松执行 A/B 测试和回滚等任务。

血缘

与 MLflow 现有功能(如模型跟踪和评估)无缝集成,以实现端到端的 GenAI 生命周期管理。

协作

通过中央注册表在您的组织内部共享提示词,使团队能够相互借鉴工作成果。

开始使用

1. 创建提示词

Create Prompt UI

  1. 在终端中运行 mlflow server 以启动 MLflow UI。
  2. 导航到 MLflow UI 中的提示词 (Prompts) 选项卡。
  3. 点击创建提示词 (Create Prompt) 按钮。
  4. 填写提示词详细信息,如名称、提示词模板文本和提交信息(可选)。
  5. 点击创建 (Create) 注册提示词。
注意

提示词模板文本可以包含 {{variable}} 格式的变量。当在 GenAI 应用中使用提示词时,这些变量可以用动态内容填充。MLflow 还提供了 to_single_brace_format() API,可将模板转换为单花括号格式,以适应 LangChain 或 LlamaIndex 等需要单花括号插值的框架。

这将创建具有指定模板文本和元数据的新提示词。该提示词现在可在 MLflow UI 中进行进一步管理。

Registered Prompt in UI

2. 使用新版本更新提示词

Update Prompt UI

  1. 上一步将进入已创建的提示词页面。(如果关闭了该页面,请导航到 MLflow UI 中的提示词 (Prompts) 选项卡,然后点击提示词名称。)
  2. 点击创建提示词版本 (Create prompt Version) 按钮。
  3. 弹出对话框中已预填充现有提示词文本。根据需要修改提示词。
  4. 点击创建 (Create) 注册新版本。

3. 比较提示词版本

拥有多个提示词版本后,您可以比较它们以了解版本之间的更改。要在 MLflow UI 中比较提示词版本,请在提示词详情页面点击比较 (Compare) 选项卡

Compare Prompt
Versions

4. 加载和使用提示词

要在 GenAI 应用中使用提示词,您可以使用 mlflow.genai.load_prompt() API 加载它,并使用提示词对象的 mlflow.entities.Prompt.format() 方法填充变量。

python
import mlflow
import openai

target_text = """
MLflow is an open source platform for managing the end-to-end machine learning lifecycle.
It tackles four primary functions in the ML lifecycle: Tracking experiments, packaging ML
code for reuse, managing and deploying models, and providing a central model registry.
MLflow currently offers these functions as four components: MLflow Tracking,
MLflow Projects, MLflow Models, and MLflow Registry.
"""

# Load the prompt
prompt = mlflow.genai.load_prompt("prompts:/summarization-prompt/2")

# Use the prompt with an LLM
client = openai.OpenAI()
response = client.chat.completions.create(
messages=[
{
"role": "user",
"content": prompt.format(num_sentences=1, sentences=target_text),
}
],
model="gpt-4o-mini",
)

print(response.choices[0].message.content)

5. 搜索提示词

您可以按名称、标签或其他注册表字段发现提示词

python
import mlflow

# Fluent API: returns a flat list of all matching prompts
prompts = mlflow.genai.search_prompts(filter_string="task='summarization'")
print(f"Found {len(prompts)} prompts")

# For pagination control, use the client API:
from mlflow.tracking import MlflowClient

client = MlflowClient()
all_prompts = []
token = None
while True:
page = client.search_prompts(
filter_string="task='summarization'",
max_results=50,
page_token=token,
)
all_prompts.extend(page)
token = page.token
if not token:
break
print(f"Total prompts across pages: {len(all_prompts)}")

提示词对象

Prompt 对象是 MLflow 提示词注册表中的核心实体。它代表一个可包含用于动态内容的变量的版本化模板文本。

Prompt 对象的主要属性

  • 名称 (Name):提示词的唯一标识符。
  • 模板 (Template):提示词的内容,可以是
    • 包含 {{variable}} 格式变量的字符串(文本提示)
    • 代表具有 'role' 和 'content' 键的消息字典的列表(聊天提示)
  • 版本 (Version):表示提示词修订版的序列号。
  • 提交信息 (Commit Message):对提示词版本中所做更改的描述,类似于 Git 提交信息。
  • 标签 (Tags):可选的应用于提示词版本的键值对,用于分类和筛选。例如,您可以为项目名称、语言等添加标签,这些标签适用于提示词的所有版本。
  • 别名 (Alias):对提示词的可变命名引用。例如,您可以创建一个名为 production 的别名来引用生产系统中使用的版本。有关更多详细信息,请参阅别名
  • is_text_prompt:一个布尔属性,指示提示词是文本提示(True)还是聊天提示(False)。
  • response_format:一个可选属性,包含预期的响应结构规范,可用于验证或构建来自 LLM 调用的输出。
  • model_config:一个可选字典,包含特定于模型的配置,如模型名称、temperature、max_tokens 和其他推理参数。有关更多详细信息,请参阅模型配置

提示词类型

文本提示

文本提示使用简单的字符串模板,变量用双花括号括起来

python
text_template = "Hello {{ name }}, how are you today?"

聊天提示

聊天提示使用消息字典列表,每个字典都包含 'role' 和 'content' 键

python
chat_template = [
{"role": "system", "content": "You are a helpful {{ style }} assistant."},
{"role": "user", "content": "{{ question }}"},
]

Jinja2 提示词

对于高级模板需求,MLflow 支持带有条件、循环和过滤器的 Jinja2 模板。当模板包含控制流语法 ({% %}) 时,Jinja2 提示词会自动检测到

python
import mlflow

# Jinja2 template with conditionals and loops
jinja_template = """\
Hello {% if name %}{{ name }}{% else %}Guest{% endif %}!

{% if items %}
Here are your items:
{% for item in items %}
- {{ item }}
{% endfor %}
{% endif %}
"""

# Register the Jinja2 prompt
prompt = mlflow.genai.register_prompt(
name="greeting-prompt",
template=jinja_template,
)

# Format with variables
result = prompt.format(name="Alice", items=["Book", "Pen", "Notebook"])
注意
  • 仅包含 {{ variable }} 语法的模板被视为文本提示,使用简单的字符串替换
  • 包含 {% %} 控制流语法的模板被视为Jinja2 提示词,并支持完整的 Jinja2 功能集
  • Jinja2 渲染默认使用 SandboxedEnvironment 以确保安全。如果您需要不受限制的 Jinja2 功能,请向 format() 传递 use_jinja_sandbox=False

响应格式

response_format 属性允许您指定 LLM 调用预期响应的结构。它可以是 Pydantic 模型类或定义模式的字典

python
from pydantic import BaseModel


class SummaryResponse(BaseModel):
summary: str
key_points: list[str]
word_count: int


# Or as a dictionary
response_format_dict = {
"type": "object",
"properties": {
"summary": {"type": "string"},
"key_points": {"type": "array", "items": {"type": "string"}},
"word_count": {"type": "integer"},
},
}

管理提示词和版本标签

MLflow 允许您在注册提示词后修改和检查标签。标签可以应用于提示词级别或单个提示词版本。

python
import mlflow

# Prompt-level tag operations
mlflow.genai.set_prompt_tag("summarization-prompt", "language", "en")
mlflow.genai.get_prompt_tags("summarization-prompt")
mlflow.genai.delete_prompt_tag("summarization-prompt", "language")

# Prompt-version tag operations
mlflow.genai.set_prompt_version_tag("summarization-prompt", 1, "author", "alice")
mlflow.genai.load_prompt("prompts:/summarization-prompt/1").tags
mlflow.genai.delete_prompt_version_tag("summarization-prompt", 1, "author")

模型配置

MLflow 提示词注册表允许您将特定于模型的配置与提示词一起存储,确保了可重现性以及关于特定提示词版本使用了哪个模型和参数的清晰度。当您想要执行以下操作时,这特别有用:

  • 同时对提示词模板和模型参数进行版本控制
  • 与团队共享带有推荐模型设置的提示词
  • 重现先前实验的确切推理配置
  • 为不同的提示词版本维护不同的模型配置

基本用法

您可以在注册时通过传递 model_config 参数来附加模型配置到提示词

python
import mlflow

# Using a dictionary
model_config = {
"model_name": "gpt-4",
"temperature": 0.7,
"max_tokens": 1000,
"top_p": 0.9,
}

mlflow.genai.register_prompt(
name="qa-prompt",
template="Answer the following question: {{question}}",
model_config=model_config,
commit_message="QA prompt with model config",
)

# Load and access the model config
prompt = mlflow.genai.load_prompt("qa-prompt")
print(f"Model: {prompt.model_config['model_name']}")
print(f"Temperature: {prompt.model_config['temperature']}")

使用 PromptModelConfig 类

为了更好的类型安全性和验证,您可以使用 mlflow.entities.model_registry.PromptModelConfig()

python
import mlflow
from mlflow.entities.model_registry import PromptModelConfig

# Create a validated config object
config = PromptModelConfig(
model_name="gpt-4-turbo",
temperature=0.5,
max_tokens=2000,
top_p=0.95,
frequency_penalty=0.2,
presence_penalty=0.1,
stop_sequences=["END", "\n\n"],
)

mlflow.genai.register_prompt(
name="creative-prompt",
template="Write a creative story about {{topic}}",
model_config=config,
)

PromptModelConfig 类提供验证功能,以尽早捕获错误

python
# This will raise a ValueError
config = PromptModelConfig(temperature=-1.0) # temperature must be non-negative

# This will raise a ValueError
config = PromptModelConfig(max_tokens=-100) # max_tokens must be positive

支持的配置参数

PromptModelConfig 支持以下标准参数

  • model_name (str):模型的名称或标识符(例如,“gpt-4”,“claude-3-opus”)
  • temperature (float):用于控制随机性的采样温度(通常为 0.0-2.0)
  • max_tokens (int):生成响应中的最大 token 数
  • top_p (float):Top-p 采样参数(通常为 0.0-1.0)
  • top_k (int):Top-k 采样参数
  • frequency_penalty (float):Token 频率惩罚(通常为 -2.0 至 2.0)
  • presence_penalty (float):Token 存在惩罚(通常为 -2.0 至 2.0)
  • stop_sequences (list[str]):将导致模型停止生成的序列列表
  • extra_params (dict):额外的特定于提供商的或实验性参数

特定于提供商的参数

您可以使用 extra_params 字段包含特定于提供商的参数

python
# Anthropic-specific configuration with extended thinking
# See: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
anthropic_thinking_config = PromptModelConfig(
model_name="claude-sonnet-4-20250514",
max_tokens=16000,
extra_params={
# Enable extended thinking for complex reasoning tasks
"thinking": {
"type": "enabled",
"budget_tokens": 10000, # Max tokens for internal reasoning
},
# User tracking for abuse detection
"metadata": {
"user_id": "user-123",
},
},
)

# OpenAI-specific configuration with reproducibility and structured output
# See: https://platform.openai.com/docs/api-reference/chat/create
openai_config = PromptModelConfig(
model_name="gpt-4o",
temperature=0.7,
max_tokens=2000,
extra_params={
# Seed for reproducible outputs
"seed": 42,
# Bias specific tokens (token_id: bias from -100 to 100)
"logit_bias": {"50256": -100}, # Discourage <|endoftext|>
# User identifier for abuse tracking
"user": "user-123",
# Service tier for priority processing
"service_tier": "default",
},
)

管理模型配置

模型配置是可变的,可以在创建提示词版本后更新。这使得无需创建新版本即可轻松修复错误或迭代模型参数。

设置或更新模型配置

使用 mlflow.genai.set_prompt_model_config() 为提示词版本设置或更新模型配置

python
import mlflow
from mlflow.entities.model_registry import PromptModelConfig

# Register a prompt without model config
mlflow.genai.register_prompt(
name="my-prompt",
template="Analyze: {{text}}",
)

# Later, add model config
mlflow.genai.set_prompt_model_config(
name="my-prompt",
version=1,
model_config={"model_name": "gpt-4", "temperature": 0.7},
)

# Or update existing model config
mlflow.genai.set_prompt_model_config(
name="my-prompt",
version=1,
model_config={"model_name": "gpt-4-turbo", "temperature": 0.8, "max_tokens": 2000},
)

# Verify the update
prompt = mlflow.genai.load_prompt("my-prompt", version=1)
print(prompt.model_config)

删除模型配置

使用 mlflow.genai.delete_prompt_model_config() 从提示词版本中删除模型配置

python
import mlflow

# Remove model config
mlflow.genai.delete_prompt_model_config(name="my-prompt", version=1)

# Verify removal
prompt = mlflow.genai.load_prompt("my-prompt", version=1)
assert prompt.model_config is None

重要说明

  • 模型配置更改是特定于版本的 - 更新一个版本不会影响其他版本
  • 模型配置是可变的 - 与提示词模板不同,可以在创建后更改
  • 更改是即时的 - 无需创建新版本即可修复模型参数
  • 应用验证 - 更新时适用与创建时相同的验证规则

提示词缓存

MLflow 自动将加载的提示词缓存在内存中,以提高性能并减少重复的 API 调用。缓存行为取决于您是按版本还是按别名加载提示词。

默认缓存行为

  • 基于版本的提示词(例如 prompts:/summarization-prompt/1):默认情况下,以无限 TTL 缓存。由于提示词版本是不可变的,因此可以安全地无限期缓存它们。
  • 基于别名的提示词(例如 prompts:/summarization-prompt@latestprompts:/summarization-prompt@production):默认情况下,以60 秒 TTL 缓存。别名可能会随时间指向不同的版本,因此较短的 TTL 可确保您的应用程序捕获更新。

自定义缓存行为

按请求缓存控制

您可以使用 cache_ttl_seconds 参数按请求控制缓存

python
import mlflow

# Custom TTL: Cache for 5 minutes
prompt = mlflow.genai.load_prompt(
"prompts:/summarization-prompt/1", cache_ttl_seconds=300
)

# Bypass cache entirely: Always fetch from registry
prompt = mlflow.genai.load_prompt(
"prompts:/summarization-prompt@production", cache_ttl_seconds=0
)

# Use infinite TTL even for alias-based prompts
prompt = mlflow.genai.load_prompt(
"prompts:/summarization-prompt@latest", cache_ttl_seconds=float("inf")
)

全局缓存配置

您可以使用环境变量全局设置默认 TTL 值

bash
# Set alias-based prompt cache TTL to 5 minutes
export MLFLOW_ALIAS_PROMPT_CACHE_TTL_SECONDS=300

# Set version-based prompt cache TTL to 1 hour (instead of infinite)
export MLFLOW_VERSION_PROMPT_CACHE_TTL_SECONDS=3600

# Disable caching globally
export MLFLOW_ALIAS_PROMPT_CACHE_TTL_SECONDS=0
export MLFLOW_VERSION_PROMPT_CACHE_TTL_SECONDS=0

缓存失效

当您修改提示词版本或别名时(包括以下操作),缓存会自动失效

  • mlflow.genai.set_prompt_version_tag
  • mlflow.genai.set_prompt_alias
  • mlflow.genai.delete_prompt_version_tag
  • mlflow.genai.delete_prompt_alias

常见问题

问:如何删除提示词版本?

答:您可以使用 MLflow UI 或 Python API 删除提示词版本

python
import mlflow

# Delete a prompt version
client = mlflow.MlflowClient()
client.delete_prompt_version("summarization-prompt", version=2)

为避免意外删除,API 只能一次删除一个版本。如果删除提示词的所有版本,则提示词本身将被删除。

问:我可以更新现有提示词版本的提示词模板吗?

答:不可以,提示词版本创建后即不可变。要更新提示词,请创建包含所需更改的新版本。

问:如何动态加载提示词的最新版本?

答:您可以仅传入名称或使用 @latest 别名来加载提示词的最新版本。这是保留的别名名称,MLflow 将自动查找提示词的最新可用版本。

python
prompt = mlflow.genai.load_prompt("summarization-prompt")
# or
prompt = mlflow.genai.load_prompt("prompts:/summarization-prompt@latest")

问:我可以在 LangChain 或 LlamaIndex 等框架中使用提示词模板吗?

答:是的,您可以从 MLflow 加载提示词并将其与任何框架一起使用。例如,以下示例演示了如何将注册在 MLflow 中的提示词与 LangChain 结合使用。另请参阅使用 LangChain 记录提示词了解更多详细信息。

python
import mlflow
from langchain.prompts import PromptTemplate

# Load prompt from MLflow
prompt = mlflow.genai.load_prompt("question_answering")

# Convert the prompt to single brace format for LangChain (MLflow uses double braces),
# using the `to_single_brace_format` method.
langchain_prompt = PromptTemplate.from_template(prompt.to_single_brace_format())
print(langchain_prompt.input_variables)
# Output: ['num_sentences', 'sentences']

问:提示词注册表是否与提示词工程 UI 集成?

答:提示词注册表与提示词工程 UI 的直接集成即将推出。在此期间,您可以在提示词工程 UI 中迭代提示词模板,并通过手动复制提示词模板将最终版本注册到提示词注册表中。