本頁介紹評估工具的一些常見使用模式,包括資料模式和 predict_fn 模式。
常見的資料輸入模式
使用 MLflow 評估資料集進行評估(建議)
MLflow 評估數據集提供版本控制、譜系追蹤,並與 Unity 目錄整合,以進行生產就緒評估。 當您需要評估數據的版本控制和譜系追蹤,以及需要將追蹤轉換成評估記錄時,它們非常有用。
import mlflow
from mlflow.genai.scorers import Correctness, Safety
from my_app import agent # Your GenAI app with tracing
# Load versioned evaluation dataset
dataset = mlflow.genai.datasets.get_dataset("catalog.schema.eval_dataset_name")
# Run evaluation
results = mlflow.genai.evaluate(
data=dataset,
predict_fn=agent,
scorers=[Correctness(), Safety()],
)
若要從追蹤或從零開始建立數據集,請參閱 建置評估數據集。
使用字典清單進行評估
使用簡單的字典清單進行快速原型設計,而不需建立正式的評估數據集。 這對於快速原型設計、小型資料集(少於 100 個範例)和非正式開發測試非常有用。
import mlflow
from mlflow.genai.scorers import Correctness, RelevanceToQuery
from my_app import agent # Your GenAI app with tracing
# Define test data as a list of dictionaries
eval_data = [
{
"inputs": {"question": "What is MLflow?"},
"expectations": {"expected_facts": ["open source AI engineering platform", "agents, LLMs, and ML models"]}
},
{
"inputs": {"question": "How do I track experiments?"},
"expectations": {"expected_facts": ["mlflow.start_run()", "log metrics", "log parameters"]}
},
{
"inputs": {"question": "What are MLflow's main components?"},
"expectations": {"expected_facts": ["Tracing", "Evaluation", "Prompt Engineering", "Model Registry"]}
}
]
# Run evaluation
results = mlflow.genai.evaluate(
data=eval_data,
predict_fn=agent,
scorers=[Correctness(), RelevanceToQuery()],
)
針對生產環境,請轉換成 MLflow 評估數據集。
利用 Pandas DataFrame 進行評估
使用 Pandas DataFrame 在處理 CSV 檔案或現有的數據科學工作流程時進行評估。 這對於快速原型設計、小型資料集(少於 100 個範例)和非正式開發測試非常有用。
import mlflow
import pandas as pd
from mlflow.genai.scorers import Correctness, Safety
from my_app import agent # Your GenAI app with tracing
# Create evaluation data as a Pandas DataFrame
eval_df = pd.DataFrame([
{
"inputs": {"question": "What is MLflow?"},
"expectations": {"expected_response": "MLflow is the largest open source AI engineering platform for agents, LLMs, and ML models."}
},
{
"inputs": {"question": "How do I log metrics?"},
"expectations": {"expected_response": "Use mlflow.log_metric() to log metrics"}
}
])
# Run evaluation
results = mlflow.genai.evaluate(
data=eval_df,
predict_fn=agent,
scorers=[Correctness(), Safety()],
)
使用Spark DataFrame評估
使用 Spark DataFrame 進行大規模評估,或當數據已在 Delta Lake 或 Unity 目錄中時。 當數據已存在於 Delta Lake 或 Unity 目錄中時,或者如果您需要在執行評估之前先篩選 MLflow 評估數據集中的記錄,這非常有用。
DataFrame 必須符合 評估數據集架構。
import mlflow
from mlflow.genai.scorers import Safety, RelevanceToQuery
from my_app import agent # Your GenAI app with tracing
# Load evaluation data from a Delta table in Unity Catalog
eval_df = spark.table("catalog.schema.evaluation_data")
# Or load from any Spark-compatible source
# eval_df = spark.read.parquet("path/to/evaluation/data")
# Run evaluation
results = mlflow.genai.evaluate(
data=eval_df,
predict_fn=agent,
scorers=[Safety(), RelevanceToQuery()],
)
常見 predict_fn 模式
直接呼叫您的應用程式
當參數名稱與評估資料集的鍵匹配時,直接將您的應用程式作為predict_fn傳遞。 這適用於具有符合 inputs 評估數據集中 之 參數名稱的應用程式。
import mlflow
from mlflow.genai.scorers import RelevanceToQuery, Safety
# Your GenAI app that accepts 'question' as a parameter
@mlflow.trace
def my_chatbot_app(question: str) -> dict:
# Your app logic here
response = f"I can help you with: {question}"
return {"response": response}
# Evaluation data with 'question' key matching the function parameter
eval_data = [
{"inputs": {"question": "What is MLflow?"}},
{"inputs": {"question": "How do I track experiments?"}}
]
# Pass your app directly since parameter names match
results = mlflow.genai.evaluate(
data=eval_data,
predict_fn=my_chatbot_app, # Direct reference, no wrapper needed
scorers=[RelevanceToQuery(), Safety()]
)
將您的應用程式包裝在可調用物件中
如果您的應用程式預期與評估數據集 inputs的參數名稱或數據結構不同,請將它包裝在可呼叫的函式中。 當您的應用程式參數與評估數據集 input 的索引鍵之間存在參數名稱不一致時,或者需要進行數據格式轉換時(例如,將字串轉換成列表或進行 JSON 剖析),這會非常有用。
import mlflow
from mlflow.genai.scorers import RelevanceToQuery, Safety
# Your existing GenAI app with different parameter names
@mlflow.trace
def customer_support_bot(user_message: str, chat_history: list = None) -> dict:
# Your app logic here
context = f"History: {chat_history}" if chat_history else "New conversation"
return {
"bot_response": f"Helping with: {user_message}. {context}",
"confidence": 0.95
}
# Wrapper function to translate evaluation data to your app's interface
def evaluate_support_bot(question: str, history: str = None) -> dict:
# Convert evaluation dataset format to your app's expected format
chat_history = history.split("|") if history else []
# Call your app with the translated parameters
result = customer_support_bot(
user_message=question,
chat_history=chat_history
)
# Translate output to standard format if needed
return {
"response": result["bot_response"],
"confidence_score": result["confidence"]
}
# Evaluation data with different key names
eval_data = [
{"inputs": {"question": "Reset password", "history": "logged in|forgot email"}},
{"inputs": {"question": "Track my order"}}
]
# Use the wrapper function for evaluation
results = mlflow.genai.evaluate(
data=eval_data,
predict_fn=evaluate_support_bot, # Wrapper handles translation
scorers=[RelevanceToQuery(), Safety()]
)
評估已部署的端點
使用此功能 to_predict_fn 來評估 Agent Framework、Model Serving 聊天端點以及自訂端點。
此函式會建立與這些端點相容的預測函式,並自動從已啟用追蹤的端點擷取追蹤,以取得完整的可檢視性。
備註
函式 to_predict_fn 會直接執行 kwargs 傳遞至您的端點。 您的評估數據必須符合端點預期的輸入格式。 如果格式不相符,評估會失敗,並出現無法辨識輸入鍵值的錯誤訊息。
模型預測服務對話
模型服務聊天端點需要以 messages 金鑰格式化的數據。
import mlflow
from mlflow.genai.scorers import RelevanceToQuery
# Create predict function for a chat endpoint
predict_fn = mlflow.genai.to_predict_fn("endpoints:/my-chatbot-endpoint")
# Evaluate the chat endpoint
results = mlflow.genai.evaluate(
data=[{"inputs": {"messages": [{"role": "user", "content": "How does MLflow work?"}]}}],
predict_fn=predict_fn,
scorers=[RelevanceToQuery()]
)
代理架構
Agent Framework 端點可以有不同的輸入介面。 下列範例顯示 input 鍵:
import mlflow
from mlflow.genai.scorers import RelevanceToQuery
# Create a predict function for a Knowledge Assistant agent endpoint
predict_fn = mlflow.genai.to_predict_fn("endpoints:/ka-56a301ab-endpoint")
# Evaluate the agent endpoint
results = mlflow.genai.evaluate(
data=[{"inputs": {"input": [{"role": "user", "content": "How do I use the Models from Code feature in MLflow?"}]}}],
predict_fn=predict_fn,
scorers=[RelevanceToQuery()]
)
自訂端點
自定義端點可能會有完全不同的存取模式,以便將數據提交至它們。 確定 data 輸入格式與用於評估的端點相容。
如果您的評估數據格式與您的端點不相容,請封裝模型的介面。 轉譯層可確保正確的承載已提交至評估端點。
import mlflow
from mlflow.genai.scorers import RelevanceToQuery
def custom_predict_fn(inputs):
# Transform inputs to match your endpoint's expected format
# For example, if your endpoint expects a 'query' key instead of 'messages'
transformed_inputs = {
"query": inputs["messages"][0]["content"],
"context": inputs.get("context", "")
}
# Call your endpoint with the transformed data
original_predict_fn = mlflow.genai.to_predict_fn("endpoints:/my-custom-endpoint")
return original_predict_fn(transformed_inputs)
# Use your wrapper function for evaluation
results = mlflow.genai.evaluate(
data=[{"inputs": {"messages": [{"role": "user", "content": "What is machine learning?"}], "context": "technical documentation"}}],
predict_fn=custom_predict_fn,
scorers=[RelevanceToQuery()]
)
評估已記錄的模型
封裝已記錄的 MLflow 模型,以便在評估的具名參數與模型的單一參數介面之間進行轉換。
大部分記錄的模型(例如使用 PyFunc 或 LangChain 等記錄類別的模型)都接受單一輸入參數(例如 model_inputs ,適用於 PyFunc),而 predict_fn 預期具名參數會對應至評估數據集中的索引鍵。
import mlflow
from mlflow.genai.scorers import Safety
# Make sure to load your logged model outside of the predict_fn so MLflow only loads it once!
model = mlflow.pyfunc.load_model("models:/chatbot/staging")
def evaluate_model(question: str) -> dict:
return model.predict({"question": question})
results = mlflow.genai.evaluate(
data=[{"inputs": {"question": "Tell me about MLflow"}}],
predict_fn=evaluate_model,
scorers=[Safety()]
)