会話シミュレーション
会話シミュレーションを使用すると、会話型 AI エージェントをテストするための合成マルチターン会話を生成できます。テスト会話を手動で作成したり、本番運用データを待ったりする代わりに、テスト シナリオを定義して、 MLflow現実的なユーザー インタラクションを自動的にシミュレートすることができます。
会話シミュレーションは実験的なものです。API と動作は将来のリリースで変更される可能性があります。
前提条件
MLflow 3.10.0 をインストールするまたはそれ以降:
pip install --upgrade 'mlflow[databricks]>=3.10'
会話をシミュレートする理由は何ですか?
観点 | 手動テストデータ | 会話シミュレーション |
|---|---|---|
バージョンテスト | 同じ会話で新しいエージェント バージョンを再テストすることはできません | エージェントのバージョン間で同一のシナリオを再生する |
カバレッジ | 人間の創造性と時間によって制限される | 多様なエッジケースを大規模に生成する |
一貫性 | 手動テスト作成のバリエーション | 明確な目標を持つ再現可能なテストシナリオ |
スケール | 多くのテストケースを作成するのに時間がかかる | 数百の会話を瞬時に生成 |
メンテナンス | テストデータを手動で更新する必要がある | 要件が変更されたときに会話を再生成する |
会話シミュレーションは、定義された目標とペルソナに基づいて会話をプログラムで生成することでこれらの課題に対処し、次のことを可能にします。
- 体系的な評価 : 一貫した目標とペルソナを持つさまざまなエージェント バージョンをテストします。
- レッドチーム :多様なユーザー行動を大規模にエージェントにストレステストする
- 迅速な反復 : 要件が変更されると、新しいテスト会話を即座に生成します。
ワークフロー
- テスト ケースを定義するか、既存の会話から抽出します - シミュレートされた会話ごとに目標、ペルソナ、コンテキストを指定するか、本番運用セッションからそれらを生成します。
- シミュレーターの作成 - テスト ケースと構成を使用して
ConversationSimulator初期化します。 - エージェントを定義する - 会話履歴を受け入れる関数にエージェントを実装します。
- 評価を実行 - スコアラーとともにシミュレーターを
mlflow.genai.evaluate()に渡します。
クイックスタート
会話をシミュレートして評価する完全な例を次に示します。
import mlflow
from mlflow.genai.simulators import ConversationSimulator
from mlflow.genai.scorers import ConversationCompleteness, Safety
from openai import OpenAI
client = OpenAI()
# 1. Define test cases with goals (required) and optional persona/context
test_cases = [
{
"goal": "Successfully configure experiment tracking",
},
{
"goal": "Identify and fix a model deployment error",
"persona": "You are a frustrated data scientist who has been stuck on this issue for hours",
},
{
"goal": "Set up model versioning for a production pipeline",
"persona": "You are a beginner who needs step-by-step guidance",
"context": {
"user_id": "beginner_123"
}, # user_id is passed to predict_fn via kwargs
},
]
# 2. Create the simulator
simulator = ConversationSimulator(
test_cases=test_cases,
max_turns=5,
)
# 3. Define your agent function
def predict_fn(input: list[dict], **kwargs):
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=input,
)
return response.choices[0].message.content
# 4. Run evaluation with conversation and single-turn scorers
results = mlflow.genai.evaluate(
data=simulator,
predict_fn=predict_fn,
scorers=[
ConversationCompleteness(), # Multi-turn scorer
Safety(), # Single-turn scorer (applied to each turn)
],
)
テストケースの定義
各テスト ケースは会話シナリオを表します。テスト ケースでは、次の 3 つのフィールドがサポートされます。
フィールド | 必須 | 説明 |
|---|---|---|
| はい | シミュレーションユーザーが達成しようとしていること |
| No | ユーザーの性格とコミュニケーションスタイルの説明 |
| No | 予測関数に渡される追加のkwargs |
ゴール
目標は、シミュレートされたユーザーが達成したいことを説明します。会話を導くのに十分具体的である一方、自然な対話を可能にするのに十分自由度が高いものでなければなりません。適切な目標は、期待される結果を記述し、シミュレーターがユーザーの意図が達成されたことを認識できるようにします。
# Good goals - specific, actionable, and describe expected outcomes
{"goal": "Successfully configure MLflow tracking for a distributed training job"}
{"goal": "Understand when to use experiments vs. runs in MLflow"}
{"goal": "Identify and fix why model artifacts aren't being logged"}
# Less effective goals - too vague, no expected outcome
{"goal": "Learn about MLflow"}
{"goal": "Get help"}
ペルソナ
ペルソナは、シミュレートされたユーザーがどのようにコミュニケーションするかを決定します。指定されていない場合は、デフォルトの役立つユーザー ペルソナが使用されます。
# Technical expert who asks detailed questions
{
"goal": "Reduce model serving latency below 100ms",
"persona": "You are a senior ML engineer who asks precise technical questions",
}
# Beginner who needs more guidance
{
"goal": "Successfully set up experiment tracking",
"persona": "You are new to MLflow and need step-by-step explanations",
}
# Frustrated user testing agent resilience
{
"goal": "Fix a deployment blocking production",
"persona": "You are impatient because this is blocking a release",
}
コンテクスト
コンテキスト フィールドは、予測関数に追加のパラメーターを渡します。これは次の場合に役立ちます:
- パーソナライゼーションのためにユーザー識別子を渡す
- セッション状態または構成の提供
- エージェントに必要なメタデータを含める
{
"goal": "Get personalized model recommendations",
"context": {
"user_id": "enterprise_user_42", # user_id is passed to predict_fn via kwargs
"subscription_tier": "premium",
"preferred_framework": "pytorch",
},
}
テストケースを定義する
テストケースを定義する最も簡単な方法は、辞書のリストまたは DataFrame として定義することです。
test_cases = [
{"goal": "Successfully configure experiment tracking"},
{"goal": "Debug a deployment error", "persona": "Senior engineer"},
{"goal": "Set up a CI/CD pipeline for ML", "context": {"team": "platform"}},
]
simulator = ConversationSimulator(test_cases=test_cases)
DataFrame を使用することもできます。
import pandas as pd
df = pd.DataFrame(
[
{"goal": "Successfully configure experiment tracking"},
{"goal": "Debug a deployment error", "persona": "Senior engineer"},
{"goal": "Set up a CI/CD pipeline for ML"},
]
)
simulator = ConversationSimulator(test_cases=df)
既存の会話からテストケースを生成する
generate_test_casesを使用して、既存の会話セッションからテスト ケースを生成します。これは、本番運用の会話から実際のユーザーの行動を反映するテスト ケースを作成するのに役立ちます。
import mlflow
from mlflow.genai.simulators import generate_test_cases, ConversationSimulator
# Get existing sessions from your experiment
sessions = mlflow.search_sessions(
locations=["<experiment-id>"],
max_results=50,
)
# Generate test cases by extracting goals and personas from sessions
test_cases = generate_test_cases(sessions)
# Optionally, save generated test cases as a dataset for reproducibility
from mlflow.genai.datasets import create_dataset
dataset = create_dataset(name="generated_scenarios")
dataset.merge_records([{"inputs": tc} for tc in test_cases])
# Use generated test cases with the simulator
simulator = ConversationSimulator(test_cases=test_cases)
テストケースをMLflowセットとして追跡
再現可能なテストを行うには、テストケースをMLflow 評価データセットとして保存します。
from mlflow.genai.datasets import create_dataset, get_dataset
# Create and populate a dataset
dataset = create_dataset(name="conversation_test_cases")
dataset.merge_records(
[
{"inputs": {"goal": "Successfully configure experiment tracking"}},
{"inputs": {"goal": "Debug a deployment error", "persona": "Senior engineer"}},
]
)
# Use the dataset with the simulator
dataset = get_dataset(name="conversation_test_cases")
simulator = ConversationSimulator(test_cases=dataset)
エージェント機能インターフェース
エージェント関数は会話履歴を受け取り、応答を返します。次の 2 つの問題名がサポートされています。
input: メッセージ辞書のリストとしての会話履歴 (チャット完了応答形式)messages: 同等の代替名 (チャット完了リクエスト形式)
def predict_fn(input: list[dict], **kwargs) -> str:
"""
Args:
input: Conversation history as a list of message dicts.
Each message has "role" ("user" or "assistant") and "content".
Alternatively, use "messages" as the parameter name.
**kwargs: Additional arguments including:
- mlflow_session_id: Unique ID for this conversation session
- Any fields from your test case's "context"
Returns:
The assistant's response as a string.
"""
- Basic
- With context
- Stateful agent
from openai import OpenAI
client = OpenAI()
def predict_fn(input: list[dict], **kwargs):
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=input,
)
return response.choices[0].message.content
from openai import OpenAI
client = OpenAI()
def predict_fn(input: list[dict], **kwargs):
# user_id is passed from test case's "context" field
user_id = kwargs.get("user_id")
# Customize system prompt based on context
system_message = f"You are helping user {user_id}. Be helpful and concise."
messages = [{"role": "system", "content": system_message}] + input
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
)
return response.choices[0].message.content
ターン間で状態を維持するエージェントの場合は、 mlflow_session_idを使用して会話の状態を管理します。
# Simple in-memory state management for stateful agents
conversation_state = {} # Maps session_id -> conversation context
def predict_fn(input: list[dict], **kwargs):
session_id = kwargs.get("mlflow_session_id")
# Initialize or retrieve state for this session
if session_id not in conversation_state:
conversation_state[session_id] = {
"turn_count": 0,
"topics_discussed": [],
}
state = conversation_state[session_id]
state["turn_count"] += 1
# Your agent logic here - can use state for context
system_message = f"You are a helpful assistant. This is turn {state['turn_count']} of the conversation."
messages = [{"role": "system", "content": system_message}] + input
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
)
return response.choices[0].message.content
設定オプション
ConversationSimulator 問題
パラメーター | Type | デフォルト | 説明 |
|---|---|---|---|
|
| 必須 | テストケースの定義 |
|
| 10 | 会話が止まる前に最大限に会話を続ける |
|
| (Databricks ホスト) | ユーザーメッセージをシミュレートするモデル |
|
|
| ユーザーシミュレーションLLMの追加の問題 |
モデルの選択
シミュレーターは LLM を使用して現実的なユーザー メッセージを生成します。user_modelを使用して別のモデルを指定できます。
simulator = ConversationSimulator(
test_cases=test_cases,
user_model="anthropic:/claude-sonnet-4-20250514",
temperature=0.7, # Passed to the user simulation LLM
)
サポートされているモデル形式はパターン"<provider>:/<model>"に従います。サポートされているプロバイダーの完全なリストについては、 MLflow のドキュメントを参照してください。
会話シミュレーションを実現するモデルに関する情報
LLM ベースの会話シミュレーションでは、Microsoft が運営する Azure OpenAI などのサードパーティ サービスを使用してユーザー インタラクションをシミュレートする場合があります。
Azure OpenAIの場合、Databricksは不正行為モニタリングをオプトアウトしているため、プロンプトや応答はAzure OpenAIに保存されません。
欧州連合 (EU) ワークスペースの場合、会話シミュレーションでは EU でホストされているモデルが使用されます。その他の地域では、米国でホストされているモデルが使用されます。
パートナー利用のAI機能を無効にすると、会話シミュレーションでパートナー利用のモデルを呼び出すことができなくなります。 独自のモデルを提供することで、会話シミュレーションを引き続き使用できます。
会話が止まる
次のいずれかの条件が満たされると、会話は停止します。
- 最大ターン数に到達しました :
max_turns制限に達しました - 目標達成 : シミュレータはユーザーの目標が達成されたことを検出します
結果の表示
シミュレートされた会話は、特別なメタデータとともに MLflow UI に表示されます。
- セッション ID : 各会話には一意のセッション ID (先頭に
sim-が付く) があります。 - シミュレーションメタデータ : 目標、ペルソナ、ターン数が各トレースに保存されます
エクスペリメントの [セッション] タブに移動して、セッションごとにグループ化された会話を表示します。 セッションを選択すると、個々のターンとその評価が表示されます。