メインコンテンツへスキップ
DSPy は、特にパイプライン内で LM が 1 回以上使用される場合に有効な、LM のプロンプトや重みをアルゴリズムで最適化するためのフレームワークです。Weave は DSPy のモジュールや関数を通じて行われる呼び出しを自動的にトレースしてログに記録します。

トレース

言語モデルアプリケーションのトレースを、開発中と本番環境の両方で一元的な場所に保存しておくことは重要です。これらのトレースはデバッグに役立つだけでなく、アプリケーションの改善に役立つデータセットとしても利用できます。 Weave は DSPy のトレースを自動的に取得します。記録を開始するには、weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>") を呼び出し、通常どおりライブラリを使用してください。
import os
import dspy
import weave

os.environ["OPENAI_API_KEY"] = "<YOUR-OPENAI-API-KEY>"

weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>")

lm = dspy.LM('openai/gpt-4o-mini')
dspy.configure(lm=lm)
classify = dspy.Predict("sentence -> sentiment")
classify(sentence="it's a charming and often affecting journey.")
dspy_trace.png Weave は DSPy プログラム内のすべての LM 呼び出しを記録し、入力・出力・メタデータに関する詳細を提供します。

自分の DSPy Module と Signature を追跡する

Module は、プロンプト手法を抽象化した DSPy プログラム向けの、学習可能なパラメータを持つ構成要素です。Signature は、DSPy Module の入出力の挙動を宣言的に指定する仕様です。Weave は、DSPy プログラム内のすべての組み込みおよびカスタムの Signature と Module を自動的に追跡します。
import os
import dspy
import weave

os.environ["OPENAI_API_KEY"] = "<YOUR-OPENAI-API-KEY>"

weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>")

class Outline(dspy.Signature):
    """Outline a thorough overview of a topic."""

    topic: str = dspy.InputField()
    title: str = dspy.OutputField()
    sections: list[str] = dspy.OutputField()
    section_subheadings: dict[str, list[str]] = dspy.OutputField(
        desc="mapping from section headings to subheadings"
    )


class DraftSection(dspy.Signature):
    """Draft a top-level section of an article."""

    topic: str = dspy.InputField()
    section_heading: str = dspy.InputField()
    section_subheadings: list[str] = dspy.InputField()
    content: str = dspy.OutputField(desc="markdown-formatted section")


class DraftArticle(dspy.Module):
    def __init__(self):
        self.build_outline = dspy.ChainOfThought(Outline)
        self.draft_section = dspy.ChainOfThought(DraftSection)

    def forward(self, topic):
        outline = self.build_outline(topic=topic)
        sections = []
        for heading, subheadings in outline.section_subheadings.items():
            section, subheadings = (
                f"## {heading}",
                [f"### {subheading}" for subheading in subheadings],
            )
            section = self.draft_section(
                topic=outline.title,
                section_heading=section,
                section_subheadings=subheadings,
            )
            sections.append(section.content)
        return dspy.Prediction(title=outline.title, sections=sections)


draft_article = DraftArticle()
article = draft_article(topic="World Cup 2002")
Weave における DSPy カスタムモジュールのトレース(モジュール実行フローとトレースの詳細)

DSPy プログラムの最適化と評価

Weave は、DSPy の optimizer および Evaluation 呼び出しに対するトレースも自動的に取得し、開発用データセット上で DSPy プログラムの性能を改善・評価するために活用できます。
import os
import dspy
import weave

os.environ["OPENAI_API_KEY"] = "<YOUR-OPENAI-API-KEY>"
weave.init(project_name="<YOUR-WANDB-PROJECT-NAME>")

def accuracy_metric(answer, output, trace=None):
    predicted_answer = output["answer"].lower()
    return answer["answer"].lower() == predicted_answer

module = dspy.ChainOfThought("question -> answer: str, explanation: str")
optimizer = dspy.BootstrapFewShot(metric=accuracy_metric)
optimized_module = optimizer.compile(
    module, trainset=SAMPLE_EVAL_DATASET, valset=SAMPLE_EVAL_DATASET
)
最適化プロセスとパフォーマンス向上を示す Weave 内の DSPy オプティマイザーのトレース