DSPy のトレース
DSPy は、モジュール式のAIシステムを構築するためのオープンソースのフレームワークであり、プロンプトと重みを最適化するためのアルゴリズムを提供します。
MLflow Tracing は、DSPyの自動トレース機能を提供します。mlflow.dspy.autolog
関数を呼び出すことで、DSPyのトレースを有効にすることができます、ネストされたトレースは、 DSPyモジュールの呼び出し時にアクティブな MLflowエクスペリメントに自動的に記録されます。
import mlflow
mlflow.dspy.autolog()
前提 条件
DSPyでMLflow Tracingを使用するには、MLflowdspy-ai
ライブラリをインストールする必要があります。
- Development
- Production
開発環境の場合は、Databricks の追加機能と dspy-ai
を含む完全な MLflow パッケージをインストールします。
pip install --upgrade "mlflow[databricks]>=3.1" dspy-ai
フル mlflow[databricks]
パッケージには、Databricks でのローカル開発と実験のためのすべての機能が含まれています。
本番運用デプロイメントの場合は、 mlflow-tracing
と dspy-ai
をインストールします。
pip install --upgrade mlflow-tracing dspy-ai
mlflow-tracing
パッケージは、本番運用での使用に最適化されています。
MLflow 3 は、DSPy で最適なトレース エクスペリエンスを実現することを強くお勧めします。
例を実行する前に、環境を構成する必要があります。
Databricks ノートブックの外部ユーザーの場合 : Databricks 環境変数を設定します。
export DATABRICKS_HOST="https://your-workspace.cloud.databricks.com"
export DATABRICKS_TOKEN="your-personal-access-token"
Databricks ノートブック内のユーザーの場合 : これらの資格情報は自動的に設定されます。
API キー : LLM プロバイダーの API キーが構成されていることを確認します。本番運用環境では、安全な キー管理のために、ハードコードされた値の代わりにMosaic AI Gateway またはDatabricksシークレットAPI を使用します。
export OPENAI_API_KEY="your-openai-api-key"
# Add other provider keys as needed
使用例
import dspy
import mlflow
import os
# Ensure your OPENAI_API_KEY (or other LLM provider keys) is set in your environment
# os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # Uncomment and set if not globally configured
# Enabling tracing for DSPy
mlflow.dspy.autolog()
# Set up MLflow tracking to Databricks
mlflow.set_tracking_uri("databricks")
mlflow.set_experiment("/Shared/dspy-tracing-demo")
# Define a simple ChainOfThought model and run it
lm = dspy.LM("openai/gpt-4o-mini")
dspy.configure(lm=lm)
# Define a simple summarizer model and run it
class SummarizeSignature(dspy.Signature):
"""Given a passage, generate a summary."""
passage: str = dspy.InputField(desc="a passage to summarize")
summary: str = dspy.OutputField(desc="a one-line summary of the passage")
class Summarize(dspy.Module):
def __init__(self):
self.summarize = dspy.ChainOfThought(SummarizeSignature)
def forward(self, passage: str):
return self.summarize(passage=passage)
summarizer = Summarize()
summarizer(
passage=(
"MLflow Tracing is a feature that enhances LLM observability in your Generative AI (GenAI) applications "
"by capturing detailed information about the execution of your application's services. Tracing provides "
"a way to record the inputs, outputs, and metadata associated with each intermediate step of a request, "
"enabling you to easily pinpoint the source of bugs and unexpected behaviors."
)
)
本番運用環境では、安全な キー管理のために、ハードコードされた値の代わりにMosaic AI Gateway またはDatabricksシークレットAPI を使用します。
評価中のトレース
DSPyモデルの評価は、AIシステムの開発における重要なステップです。MLflow Tracing は、各入力に対するプログラムの実行に関する詳細な情報を提供することにより、評価後のプログラムのパフォーマンスを追跡するのに役立ちます。
MLflow の自動トレースが DSPy で有効になっている場合、DSPy の 組み込み評価スイートを実行すると、トレースが自動的に生成されます。次の例は、MLflow で評価トレースとレビュー トレースを実行する方法を示しています。
import dspy
from dspy.evaluate.metrics import answer_exact_match
import mlflow
import os
# Ensure your OPENAI_API_KEY (or other LLM provider keys) is set in your environment
# os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # Uncomment and set if not globally configured
# Enabling tracing for DSPy evaluation
mlflow.dspy.autolog(log_traces_from_eval=True)
# Set up MLflow tracking to Databricks if not already configured
# mlflow.set_tracking_uri("databricks")
# mlflow.set_experiment("/Shared/dspy-eval-demo")
# Define a simple evaluation set
eval_set = [
dspy.Example(
question="How many 'r's are in the word 'strawberry'?", answer="3"
).with_inputs("question"),
dspy.Example(
question="How many 'a's are in the word 'banana'?", answer="3"
).with_inputs("question"),
dspy.Example(
question="How many 'e's are in the word 'elephant'?", answer="2"
).with_inputs("question"),
]
# Define a program
class Counter(dspy.Signature):
question: str = dspy.InputField()
answer: str = dspy.OutputField(
desc="Should only contain a single number as an answer"
)
cot = dspy.ChainOfThought(Counter)
# Evaluate the programs
with mlflow.start_run(run_name="CoT Evaluation"):
evaluator = dspy.evaluate.Evaluate(
devset=eval_set,
return_all_scores=True,
return_outputs=True,
show_progress=True,
)
aggregated_score, outputs, all_scores = evaluator(cot, metric=answer_exact_match)
# Log the aggregated score
mlflow.log_metric("exact_match", aggregated_score)
# Log the detailed evaluation results as a table
mlflow.log_table(
{
"question": [example.question for example in eval_set],
"answer": [example.answer for example in eval_set],
"output": outputs,
"exact_match": all_scores,
},
artifact_file="eval_results.json",
)
MLflow UI を開いて [CoT 評価] の実行に移動すると、評価結果と、評価中に生成されたトレースの一覧が [ Traces
] タブに表示されます。
これらのステップのトレースを無効にするには、log_traces_from_eval
パラメーターを False
に設定して mlflow.dspy.autolog
関数を呼び出します。
コンパイル時のトレース (最適化)
コンパイル(最適化) は、DSPyのコアコンセプトです。コンパイルを通じて、DSPyはDSPyプログラムのプロンプトと重みを自動的に最適化し、最高のパフォーマンスを実現します。
デフォルトでは、MLflow はウォッチフェイスの追加中にトレースを生成し ません 。これは、ウォッチフェイスの追加によって DSPy モジュールの呼び出しが数百または数千回トリガーされる可能性があるためです。コンパイルのトレースを有効にするには、log_traces_from_compile
パラメーターを True
に設定して mlflow.dspy.autolog
関数を呼び出します。
import dspy
import mlflow
import os
# Ensure your OPENAI_API_KEY (or other LLM provider keys) is set in your environment
# os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # Uncomment and set if not globally configured
# Enable auto-tracing for compilation
mlflow.dspy.autolog(log_traces_from_compile=True)
# Set up MLflow tracking to Databricks if not already configured
# mlflow.set_tracking_uri("databricks")
# mlflow.set_experiment("/Shared/dspy-compile-demo")
# Optimize the DSPy program as usual
tp = dspy.MIPROv2(metric=metric, auto="medium", num_threads=24)
optimized = tp.compile(cot, trainset=trainset, ...)
自動トレースを無効にする
LlamaIndex の自動トレースは、 mlflow.llama_index.autolog(disable=True)
または mlflow.autolog(disable=True)
を呼び出すことでグローバルに無効にできます。