アプリケーションのバージョンと共にプロンプト のバージョンを追跡する

Von Bedeutung

この機能は ベータ版です。

このガイドでは、MLflowプロンプトレジストリのプロンプトをエージェントに統合し、プロンプトとアプリケーションのバージョンを同時に追跡する方法を紹介します。 レジストリからのプロンプトで mlflow.set_active_model() を使用すると、MLflow によってプロンプトのバージョンとアプリケーションのバージョンの間に系列が自動的に作成されます。

このガイドでは、次の手順について説明します。

  • アプリケーションの MLflow プロンプト レジストリからプロンプトを読み込んで使用します。
  • LoggedModelsを使用してアプリケーションのバージョンを追跡します。
  • プロンプト バージョンとアプリケーション バージョンの間の自動系列を表示します。
  • プロンプトを更新し、変更がアプリケーションにどのように反映されるかを確認します。

このページのすべてのコードは、 サンプル ノートブックに含まれています。

[前提条件]

  1. MLflow と必要なパッケージをインストールする

    pip install --upgrade "mlflow[databricks]>=3.14.0" openai
    
  2. 環境のセットアップのクイックスタートに従って、MLflow 実験を作成します。

  3. プロンプト レジストリを使用するための CREATE FUNCTION、 EXECUTE、および MANAGE のアクセス許可を持つ Unity カタログ スキーマにアクセスできることを確認します。

手順 1: レジストリにプロンプトを作成する

まず、アプリケーションで使用するプロンプトを作成しましょう。 「プロンプトの 作成と編集 」ガイドに従ってプロンプトを既に作成している場合は、この手順をスキップできます。

import mlflow

# Replace with a Unity Catalog schema where you have CREATE FUNCTION, EXECUTE, and MANAGE permission
uc_schema = "workspace.default"
prompt_name = "customer_support_prompt"

# Define the prompt template with variables
initial_template = """\
You are a helpful customer support assistant for {{company_name}}.

Please help the customer with their inquiry about: {{topic}}

Customer Question: {{question}}

Provide a friendly, professional response that addresses their concern.
"""

# Register a new prompt
prompt = mlflow.genai.register_prompt(
    name=f"{uc_schema}.{prompt_name}",
    template=initial_template,
    commit_message="Initial customer support prompt",
    tags={
        "author": "support-team@company.com",
        "use_case": "customer_service",
        "department": "customer_support",
        "language": "en"
    }
)

print(f"Created prompt '{prompt.name}' (version {prompt.version})")

手順 2: プロンプトを使用するバージョン管理が有効なアプリケーションを作成する

次に、レジストリからこのプロンプトを読み込み、使用するエージェントを作成しましょう。 mlflow.set_active_model()を使用して、アプリケーションのバージョンを追跡します。

mlflow.set_active_model()を呼び出すと、MLflow によって、アプリケーション バージョンのメタデータ ハブとして機能するLoggedModelが作成されます。 この LoggedModel では、実際のアプリケーション コードは格納されません。代わりに、外部コード (Git コミットなど) にリンクする中央レコードとして機能し、構成パラメーターを使用して、アプリケーションが使用するレジストリからのプロンプトを自動的に追跡します。

  1. OpenAI クライアントを初期化して、Databricks でホストされる LLM または OpenAI によってホストされている LLM に接続します。

    Databricks でホストされる LLM

    databricks-openaiを使用して、Databricks でホストされる LLM に接続する OpenAI クライアントを取得します。 使用可能な基礎モデルからモデルを選択します。

    import mlflow
    from databricks_openai import DatabricksOpenAI
    from mlflow.entities.trace_location import UnityCatalog
    
    # 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(
        experiment_name="/Shared/docs-demo",
        trace_location=UnityCatalog(
            catalog_name="<UC_CATALOG_NAME>",
            schema_name="<UC_SCHEMA_NAME>",
            table_prefix="<UC_TABLE_PREFIX>",
        ),
    )
    
    # Create an OpenAI client that is connected to Databricks-hosted LLMs
    client = DatabricksOpenAI()
    
    # Select an LLM
    model_name = "databricks-claude-sonnet-4"
    

    OpenAI でホストされる LLM

    ネイティブの OpenAI SDK を使用して、OpenAI でホストされるモデルに接続します。 使用可能な OpenAI モデルからモデルを選択します。

    import mlflow
    import os
    import openai
    from mlflow.entities.trace_location import UnityCatalog
    
    # 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(
        experiment_name="/Shared/docs-demo",
        trace_location=UnityCatalog(
            catalog_name="<UC_CATALOG_NAME>",
            schema_name="<UC_SCHEMA_NAME>",
            table_prefix="<UC_TABLE_PREFIX>",
        ),
    )
    
    # Create an OpenAI client connected to OpenAI SDKs
    client = openai.OpenAI()
    
    # Select an LLM
    model_name = "gpt-4o-mini"
    
  2. バージョン管理を使用してアプリケーションを定義します。

    import subprocess
    
    
    # Define your application and its version identifier
    app_name = "customer_support_agent"
    
    # Get current git commit hash for versioning
    try:
        git_commit = (
            subprocess.check_output(["git", "rev-parse", "HEAD"])
            .decode("ascii")
            .strip()[:8]
        )
        version_identifier = f"git-{git_commit}"
    except subprocess.CalledProcessError:
        version_identifier = "local-dev"  # Fallback if not in a git repo
    logged_model_name = f"{app_name}-{version_identifier}"
    
    # Set the active model context - this creates a LoggedModel that represents this version of your application
    active_model_info = mlflow.set_active_model(name=logged_model_name)
    print(
        f"Active LoggedModel: '{active_model_info.name}', Model ID: '{active_model_info.model_id}'"
    )
    
    # Log application parameters
    # These parameters help you track the configuration of this app version
    app_params = {
        "llm": model_name,
        "temperature": 0.7,
        "max_tokens": 500
    }
    mlflow.log_model_params(model_id=active_model_info.model_id, params=app_params)
    
    # Load the prompt from the registry
    # NOTE: Loading the prompt AFTER calling set_active_model() is what enables
    # automatic lineage tracking between the prompt version and the LoggedModel
    prompt = mlflow.genai.load_prompt(f"prompts:/{uc_schema}.{prompt_name}/1")
    print(f"Loaded prompt version {prompt.version}")
    
    # Use the trace decorator to capture the application's entry point
    # Each trace created by this function is automatically linked to the LoggedModel (application version) we set above. In turn, the LoggedModel is linked to the prompt version that was loaded from the registry
    @mlflow.trace
    def customer_support_app(company_name: str, topic: str, question: str):
        # Format the prompt with variables
        formatted_prompt = prompt.format(
            company_name=company_name,
            topic=topic,
            question=question
        )
    
        # Call the LLM
        response = client.chat.completions.create(
            model=model_name,  # Replace with your model
            messages=[
                {
                    "role": "user",
                    "content": formatted_prompt,
                },
            ],
            temperature=0.7,
            max_tokens=500
        )
        return response.choices[0].message.content
    
    # Test the application
    result = customer_support_app(
        company_name="TechCorp",
        topic="billing",
        question="I was charged twice for my subscription last month. Can you help?"
    )
    print(f"\nResponse: {result}")
    

手順 3: UI で自動系列を表示する

アクティブなモデルが設定されているアプリケーションでレジストリからのプロンプトを使用すると、MLflow はプロンプトのバージョンとアプリケーションのバージョンの関係を自動的に追跡します。

MLflow 実験 UI で実験に移動します。 [実験] ページで、[バージョン] タブ を クリックします。次のように、プロンプトのバージョンがテーブルに表示されます。

プロンプトのバージョンが設定された実験の [バージョン] タブ。

手順 4: プロンプトを更新し、変更を追跡する

プロンプトを改善し、アプリケーションで新しいバージョンを使用したときに新しいバージョンがどのように自動的に追跡されるかを確認しましょう。

# Create an improved version of the prompt
improved_template = """\
You are a helpful and empathetic customer support assistant for {{company_name}}.

Customer Topic: {{topic}}
Customer Question: {{question}}

Please provide a response that:
1. Acknowledges the customer's concern with empathy
2. Provides a clear solution or next steps
3. Offers additional assistance if needed
4. Maintains a friendly, professional tone

Remember to:
- Use the customer's name if provided
- Be concise but thorough
- Avoid technical jargon unless necessary
"""

# Register the new version
updated_prompt = mlflow.genai.register_prompt(
    name=f"{uc_schema}.{prompt_name}",
    template=improved_template,
    commit_message="Added structured response guidelines for better customer experience",
    tags={
        "author": "support-team@company.com",
        "improvement": "Added empathy guidelines and response structure"
    }
)

print(f"Created version {updated_prompt.version} of '{updated_prompt.name}'")

手順 5: アプリケーションで更新されたプロンプトを使用する

次に、新しいプロンプト バージョンを使用し、新しいアプリケーション バージョンを作成して、この変更を追跡してみましょう。

# Create a new application version
new_version_identifier = "v2-improved-prompt"
new_logged_model_name = f"{app_name}-{new_version_identifier}"

# Set the new active model
active_model_info_v2 = mlflow.set_active_model(name=new_logged_model_name)
print(
    f"Active LoggedModel: '{active_model_info_v2.name}', Model ID: '{active_model_info_v2.model_id}'"
)

# Log updated parameters
app_params_v2 = {
    "llm": "databricks-claude-sonnet-4",
    "temperature": 0.7,
    "max_tokens": 500,
    "prompt_version": "2"  # Track which prompt version we're using
}
mlflow.log_model_params(model_id=active_model_info_v2.model_id, params=app_params_v2)

# Load the new prompt version
prompt_v2 = mlflow.genai.load_prompt(f"prompts:/{uc_schema}.{prompt_name}/2")

# Update the app to use the new prompt
@mlflow.trace
def customer_support_app_v2(company_name: str, topic: str, question: str):
    # Format the prompt with variables
    formatted_prompt = prompt_v2.format(
        company_name=company_name,
        topic=topic,
        question=question
    )

    # Call the LLM
    response = client.chat.completions.create(
        model="databricks-claude-sonnet-4",
        messages=[
            {
                "role": "user",
                "content": formatted_prompt,
            },
        ],
        temperature=0.7,
        max_tokens=500
    )
    return response.choices[0].message.content

# Test with the same question to see the difference
result_v2 = customer_support_app_v2(
    company_name="TechCorp",
    topic="billing",
    question="I was charged twice for my subscription last month. Can you help?"
)
print(f"\nImproved Response: {result_v2}")

ノートブックの例

次のノートブックには、このページのすべてのコードが含まれています。

プロンプトとアプリのバージョンを記録するノートブック

ノートブックを入手

次の手順: プロンプトのバージョンを評価する

プロンプトとアプリケーションのさまざまなバージョンを追跡したので、どのプロンプト バージョンが最適に動作するかを体系的に評価できます。 MLflow の評価フレームワークを使用すると、LLM のジャッジとカスタム メトリックを使用して、複数のプロンプト バージョンを並べて比較できます。

さまざまなプロンプト バージョンの品質を評価する方法については、プロンプトの評価に関 するページを参照してください。 このガイドでは、次の方法について説明します。

  • さまざまなプロンプト バージョンで評価を実行します。
  • 評価 UI を使用して、バージョン間で結果を比較します。
  • 組み込みの LLM ジャッジとカスタム メトリックの両方を使用します。
  • デプロイするプロンプト のバージョンに関するデータドリブンの決定を行います。

プロンプトのバージョン管理と評価を組み合わせることで、各変更が品質メトリックに与える影響を正確に把握しながら、プロンプトを自信を持って反復的に改善できます。