Nota
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
重要
此功能在 Beta 版中。
本指南介绍如何在 MLflow 提示注册表中创建新提示和管理其版本。 其中包括有关使用 MLflow Python SDK 和 Databricks MLflow UI 的说明。 本页上的所有代码都包含在 示例笔记本中。
先决条件
安装 MLflow 和所需包
pip install --upgrade "mlflow[databricks]>=3.1.0" openai
请按照设置环境快速入门创建 MLflow 试验。
创建或标识用于存储提示的 Unity 目录架构。 必须具有 Unity Catalog 架构的
CREATE FUNCTION
、EXECUTE
和MANAGE
权限。
步骤 1. 创建新提示
可以在 Databricks MLflow UI 中创建提示,也可以使用 Python SDK 以编程方式创建提示。
使用 Databricks MLflow UI
若要在 UI 中创建提示,请执行以下作:
导航到 MLflow 试验。
单击“Prompts”选项卡。
单击 “选择架构 ”,然后单击要在其中存储提示的目录和架构。
单击“确认”。
单击
。
输入提示的名称,然后单击“ 创建”。
单击“ 创建新版本”。
键入提示,然后单击“ 保存”。 可以使用语法在提示文本中使用
{{variable_name}}
变量。
提示显示在 UI 中:
使用 Python SDK
使用 mlflow.genai.register_prompt()
.. 以编程方式创建提示。 提示对模板变量使用双大括号语法 ({{variable}}
)。
import mlflow
# Replace with a Unity Catalog schema where you have CREATE FUNCTION, EXECUTE, and MANAGE privileges
uc_schema = "workspace.default"
# This table will be created in the UC schema specified in the previous line
prompt_name = "summarization_prompt"
# Define the prompt template with variables
initial_template = """\
Summarize content you are provided with in {{num_sentences}} sentences.
Content: {{content}}
"""
# Register a new prompt
prompt = mlflow.genai.register_prompt(
name=f"{uc_schema}.{prompt_name}",
template=initial_template,
# all parameters below are optional
commit_message="Initial version of summarization prompt",
tags={
"author": "data-science-team@company.com",
"use_case": "document_summarization",
"task": "summarization",
"language": "en",
"model_compatibility": "gpt-4"
}
)
print(f"Created prompt '{prompt.name}' (version {prompt.version})")
步骤 2:在应用程序中使用提示
以下步骤创建使用提示模板的简单应用程序。
从注册表加载提示
# Load a specific version using URI syntax
prompt = mlflow.genai.load_prompt(name_or_uri=f"prompts:/{uc_schema}.{prompt_name}/1")
# Alternative syntax without URI
prompt = mlflow.genai.load_prompt(name_or_uri=f"{uc_schema}.{prompt_name}", version="1")
在应用程序中使用提示
初始化 OpenAI 客户端以连接到由 Databricks 托管的 LLM 或者由 OpenAI 托管的 LLM。
Databricks 托管的 LLM
使用 MLflow 获取一个 OpenAI 客户端,以连接到由 Databricks 托管的 LLMs。 从可用的基础模型中选择一个模型。
import mlflow from databricks.sdk import WorkspaceClient # Enable MLflow's autologging to instrument your application with Tracing mlflow.openai.autolog() # Set up MLflow tracking to Databricks mlflow.set_tracking_uri("databricks") mlflow.set_experiment("/Shared/docs-demo") # Create an OpenAI client that is connected to Databricks-hosted LLMs w = WorkspaceClient() client = w.serving_endpoints.get_open_ai_client() # Select an LLM model_name = "databricks-claude-sonnet-4"
OpenAI 托管的 LLM
使用本地 OpenAI SDK 连接到由 OpenAI 托管的模型。 从 可用的 OpenAI 模型中选择一个模型。
import mlflow import os import openai # Ensure your OPENAI_API_KEY is set in your environment # os.environ["OPENAI_API_KEY"] = "<YOUR_API_KEY>" # Uncomment and set if not globally configured # Enable auto-tracing for OpenAI mlflow.openai.autolog() # Set up MLflow tracking to Databricks mlflow.set_tracking_uri("databricks") mlflow.set_experiment("/Shared/docs-demo") # Create an OpenAI client connected to OpenAI SDKs client = openai.OpenAI() # Select an LLM model_name = "gpt-4o-mini"
定义应用程序:
# Use the trace decorator to capture the application's entry point @mlflow.trace def my_app(content: str, num_sentences: int): # Format with variables formatted_prompt = prompt.format( content=content, num_sentences=num_sentences ) response = client.chat.completions.create( model=model_name, # This example uses a Databricks hosted LLM - you can replace this with any AI Gateway or Model Serving endpoint. If you provide your own OpenAI credentials, replace with a valid OpenAI model e.g., gpt-4o, etc. messages=[ { "role": "system", "content": "You are a helpful assistant.", }, { "role": "user", "content": formatted_prompt, }, ], ) return response.choices[0].message.content result = my_app(content="This guide shows you how to integrate prompts from the MLflow Prompt Registry into your GenAI applications. You'll learn to load prompts, format them with dynamic data, and ensure complete lineage by linking prompt versions to your MLflow Models.", num_sentences=1) print(result)
步骤 3. 编辑提示
提示版本一旦创建,就不可更改。 若要编辑提示,必须创建新版本。 类似 Git 的这种版本控制确保完整的历史记录,并支持回滚功能。
使用 Databricks MLflow UI
若要创建新版本::
导航到要编辑的提示。
单击“ 创建新版本”。
键入提示,然后单击“ 保存”。 新的提示版本将显示在 UI 中。
若要比较提示版本,请单击左上角的 “比较 ”,然后选择要比较的版本。
使用 Python SDK
使用现有提示名称调用 mlflow.genai.register_prompt()
创建新版本:
import mlflow
# Define the improved template
new_template = """\
You are an expert summarizer. Condense the following content into exactly {{ num_sentences }} clear and informative sentences that capture the key points.
Content: {{content}}
Your summary should:
- Contain exactly {{num_sentences}} sentences
- Include only the most important information
- Be written in a neutral, objective tone
- Maintain the same level of formality as the original text
"""
# Register a new version
updated_prompt = mlflow.genai.register_prompt(
name=f"{uc_schema}.{prompt_name}",
template=new_template,
commit_message="Added detailed instructions for better output quality",
tags={
"author": "data-science-team@company.com",
"improvement": "Added specific guidelines for summary quality"
}
)
print(f"Created version {updated_prompt.version} of '{updated_prompt.name}'")
步骤 4. 使用新提示
以下代码演示如何使用提示。
# Load a specific version using URI syntax
prompt = mlflow.genai.load_prompt(name_or_uri=f"prompts:/{uc_schema}.{prompt_name}/2")
# Or load from specific version
prompt = mlflow.genai.load_prompt(name_or_uri=f"{uc_schema}.{prompt_name}", version="2")
步骤 5. 搜索和发现提示
若要在 Unity Catalog 架构中查找提示,请执行以下操作:
# REQUIRED format for Unity Catalog - specify catalog and schema
results = mlflow.genai.search_prompts("catalog = 'workspace' AND schema = 'default'")
# Using variables for your schema
catalog_name = uc_schema.split('.')[0] # 'workspace'
schema_name = uc_schema.split('.')[1] # 'default'
results = mlflow.genai.search_prompts(f"catalog = '{catalog_name}' AND schema = '{schema_name}'")
# Limit results
results = mlflow.genai.search_prompts(
filter_string=f"catalog = '{catalog_name}' AND schema = '{schema_name}'",
max_results=50
)
示例笔记本
创建和编辑提示语示例笔记本
后续步骤
- 评估提示版本 - 比较不同的提示版本以识别性能最佳的版本。
- 跟踪应用程序版本提示 - 将提示版本关联到您的应用程序版本。
- 在已部署的应用程序中使用提示 - 将提示与别名一起部署到生产环境。