mcpField
D
dspy

dspy

github.com/kalarislabsその他7344 回インストール4 日前に更新
リポジトリ

dspy について

DSPy でモジュール型の言語モデルプログラムを構築・改善するためのスキルです。宣言的なタスク定義、パイプライン、評価、データ駆動の最適化を扱い、RAG、エージェント、分類器の開発に役立ちます。

主な機能

  1. 01宣言的なタスクシグネチャ
  2. 02再利用可能な予測モジュール
  3. 03推論・ツール利用モジュール
  4. 04データ駆動のプロンプト最適化
  5. 05評価とトレース

活用シーン

  1. 01多段階の QA パイプライン構築
  2. 02例を使ったプロンプト最適化
  3. 03RAG システムや分類器の評価

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/kalarislabs/research-agent-skills --skill dspy

インストール後、Claude Code で/dspyを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
common-patterns.md
examples.md
lm-provider-configuration.md
modules.md
optimizers.md
scripts/
safe_arithmetic.py

詳細

DSPy:宣言的な言語モデルプログラミング

このスキルを使う場面

次のような場合に DSPy を使用します。

  • 複数のコンポーネントとワークフローを含む、複雑な AI システムを構築する
  • 手動でプロンプトを設計する代わりに、宣言的に LM をプログラミングする
  • データ駆動型の手法を使って、プロンプトを自動的に最適化する
  • 保守性と移植性に優れた、モジュール式の AI パイプラインを作成する
  • オプティマイザーを使って、モデルの出力を体系的に改善する
  • 信頼性の高い RAG システム、エージェント、分類器を構築する

インストール

# Stable release
pip install dspy

# Latest development version
pip install git+https://github.com/stanfordnlp/dspy.git

# With specific LM providers
pip install dspy[openai]        # OpenAI
pip install dspy[anthropic]     # Anthropic Claude
pip install dspy[all]           # All providers

クイックスタート

基本的な例:質問応答
import dspy

# Configure your language model
lm = dspy.Claude(model="claude-sonnet-4-5-20250929")
dspy.settings.configure(lm=lm)

# Define a signature (input → output)
class QA(dspy.Signature):
    """Answer questions with short factual answers."""
    question = dspy.InputField()
    answer = dspy.OutputField(desc="often between 1 and 5 words")

# Create a module
qa = dspy.Predict(QA)

# Use it
response = qa(question="What is the capital of France?")
print(response.answer)  # "Paris"
思考の連鎖による推論
import dspy

lm = dspy.Claude(model="claude-sonnet-4-5-20250929")
dspy.settings.configure(lm=lm)

# Use ChainOfThought for better reasoning
class MathProblem(dspy.Signature):
    """Solve math word problems."""
    problem = dspy.InputField()
    answer = dspy.OutputField(desc="numerical answer")

# ChainOfThought generates reasoning steps automatically
cot = dspy.ChainOfThought(MathProblem)

response = cot(problem="If John has 5 apples and gives 2 to Mary, how many does he have?")
print(response.rationale)  # Shows reasoning steps
print(response.answer)     # "3"

コアコンセプト

1. シグネチャ

シグネチャは、AI タスクの構造(入力 → 出力)を定義します。

# Inline signature (simple)
qa = dspy.Predict("question -> answer")

# Class signature (detailed)
class Summarize(dspy.Signature):
    """Summarize text into key points."""
    text = dspy.InputField()
    summary = dspy.OutputField(desc="bullet points, 3-5 items")

summarizer = dspy.ChainOfThought(Summarize)

それぞれの使いどころ:

  • インライン:手早いプロトタイピング、単純なタスク
  • クラス:複雑なタスク、型ヒント、より充実したドキュメント
2. モジュール

モジュールは、入力を出力に変換する再利用可能なコンポーネントです。

dspy.Predict

基本的な予測モジュール:

predictor = dspy.Predict("context, question -> answer")
result = predictor(context="Paris is the capital of France",
                   question="What is the capital?")
dspy.ChainOfThought

回答する前に推論の手順を生成します。

cot = dspy.ChainOfThought("question -> answer")
result = cot(question="Why is the sky blue?")
print(result.rationale)  # Reasoning steps
print(result.answer)     # Final answer
dspy.ReAct

ツールを使ったエージェントのような推論:

from dspy.predict import ReAct

class SearchQA(dspy.Signature):
    """Answer questions using search."""
    question = dspy.InputField()
    answer = dspy.OutputField()

def search_tool(query: str) -> str:
    """Search Wikipedia."""
    # Your search implementation
    return results

react = ReAct(SearchQA, tools=[search_tool])
result = react(question="When was Python created?")
dspy.ProgramOfThought

推論のためのコードを生成して実行します。

pot = dspy.ProgramOfThought("question -> answer")
result = pot(question="What is 15% of 240?")
# Generates: answer = 240 * 0.15
3. オプティマイザー

オプティマイザーは、トレーニングデータを使ってモジュールを自動的に改善します。

BootstrapFewShot

例から学習します。

from dspy.teleprompt import BootstrapFewShot

# Training data
trainset = [
    dspy.Example(question="What is 2+2?", answer="4").with_inputs("question"),
    dspy.Example(question="What is 3+5?", answer="8").with_inputs("question"),
]

# Define metric
def validate_answer(example, pred, trace=None):
    return example.answer == pred.answer

# Optimize
optimizer = BootstrapFewShot(metric=validate_answer, max_bootstrapped_demos=3)
optimized_qa = optimizer.compile(qa, trainset=trainset)

# Now optimized_qa performs better!
MIPRO(最重要プロンプト最適化)

プロンプトを反復的に改善します。

from dspy.teleprompt import MIPRO

optimizer = MIPRO(
    metric=validate_answer,
    num_candidates=10,
    init_temperature=1.0
)

optimized_cot = optimizer.compile(
    cot,
    trainset=trainset,
    num_trials=100
)
BootstrapFinetune

モデルのファインチューニング用データセットを作成します。

from dspy.teleprompt import BootstrapFinetune

optimizer = BootstrapFinetune(metric=validate_answer)
optimized_module = optimizer.compile(qa, trainset=trainset)

# Exports training data for fine-tuning
4. 複雑なシステムの構築
マルチステージパイプライン
import dspy

class MultiHopQA(dspy.Module):
    def __init__(self):
        super().__init__()
        self.retrieve = dspy.Retrieve(k=3)
        self.generate_query = dspy.ChainOfThought("question -> search_query")
        self.generate_answer = dspy.ChainOfThought("context, question -> answer")

    def forward(self, question):
        # Stage 1: Generate search query
        search_query = self.generate_query(question=question).search_query

        # Stage 2: Retrieve context
        passages = self.retrieve(search_query).passages
        context = "\n".join(passages)

        # Stage 3: Generate answer
        answer = self.generate_answer(context=context, question=question).answer
        return dspy.Prediction(answer=answer, context=context)

# Use the pipeline
qa_system = MultiHopQA()
result = qa_system(question="Who wrote the book that inspired the movie Blade Runner?")
最適化を組み込んだ RAG システム
import dspy
from dspy.retrieve.chromadb_rm import ChromadbRM

# Configure retriever
retriever = ChromadbRM(
    collection_name="documents",
    persist_directory="./chroma_db"
)

class RAG(dspy.Module):
    def __init__(self, num_passages=3):
        super().__init__()
        self.retrieve = dspy.Retrieve(k=num_passages)
        self.generate = dspy.ChainOfThought("context, question -> answer")

    def forward(self, question):
        context = self.retrieve(question).passages
        return self.generate(context=context, question=question)

# Create and optimize
rag = RAG()

# Optimize with training data
from dspy.teleprompt import BootstrapFewShot

optimizer = BootstrapFewShot(metric=validate_answer)
optimized_rag = optimizer.compile(rag, trainset=trainset)

LM プロバイダーの設定

詳細、コード例、パラメーター表については、references/lm-provider-configuration.md を参照してください。この手順が該当する場合は、内容を確認してください。

よく使われるパターン

詳細、コード例、パラメーター表については、references/common-patterns.md を参照してください。この手順が該当する場合は、内容を確認してください。

評価とメトリクス

カスタムメトリクス
def exact_match(example, pred, trace=None):
    """Exact match metric."""
    return example.answer.lower() == pred.answer.lower()

def f1_score(example, pred, trace=None):
    """F1 score for text overlap."""
    pred_tokens = set(pred.answer.lower().split())
    gold_tokens = set(example.answer.lower().split())

    if not pred_tokens:
        return 0.0

    precision = len(pred_tokens & gold_tokens) / len(pred_tokens)
    recall = len(pred_tokens & gold_tokens) / len(gold_tokens)

    if precision + recall == 0:
        return 0.0

    return 2 * (precision * recall) / (precision + recall)
評価
from dspy.evaluate import Evaluate

# Create evaluator
evaluator = Evaluate(
    devset=testset,
    metric=exact_match,
    num_threads=4,
    display_progress=True
)

# Evaluate model
score = evaluator(qa_system)
print(f"Accuracy: {score}")

# Compare optimized vs unoptimized
score_before = evaluator(qa)
score_after = evaluator(optimized_qa)
print(f"Improvement: {score_after - score_before:.2%}")

ベストプラクティス

1. シンプルに始めて、反復する
# Start with Predict
qa = dspy.Predict("question -> answer")

# Add reasoning if needed
qa = dspy.ChainOfThought("question -> answer")

# Add optimization when you have data
optimized_qa = optimizer.compile(qa, trainset=data)
2. 説明的なシグネチャを使う
# ❌ Bad: Vague
class Task(dspy.Signature):
    input = dspy.InputField()
    output = dspy.OutputField()

# ✅ Good: Descriptive
class SummarizeArticle(dspy.Signature):
    """Summarize news articles into 3-5 key points."""
    article = dspy.InputField(desc="full article text")
    summary = dspy.OutputField(desc="bullet points, 3-5 items")
3. 代表的なデータで最適化する
# Create diverse training examples
trainset = [
    dspy.Example(question="factual", answer="...).with_inputs("question"),
    dspy.Example(question="reasoning", answer="...").with_inputs("question"),
    dspy.Example(question="calculation", answer="...").with_inputs("question"),
]

# Use validation set for metric
def metric(example, pred, trace=None):
    return example.answer in pred.answer
4. 最適化したモデルを保存して読み込む
# Save
optimized_qa.save("models/qa_v1.json")

# Load
loaded_qa = dspy.ChainOfThought("question -> answer")
loaded_qa.load("models/qa_v1.json")
5. 監視してデバッグする
# Enable tracing
dspy.settings.configure(lm=lm, trace=[])

# Run prediction
result = qa(question="...")

# Inspect trace
for call in dspy.settings.trace:
    print(f"Prompt: {call['prompt']}")
    print(f"Response: {call['response']}")

他のアプローチとの比較

機能手動プロンプト設計LangChainDSPy
プロンプトエンジニアリング手動手動自動
最適化試行錯誤なしデータ駆動型
モジュール性低中高
型安全性なし限定的あり(シグネチャ)
移植性低中高
学習曲線低中中〜高

DSPy を選ぶ場面:

  • トレーニングデータがある、または生成できる
  • プロンプトを体系的に改善する必要がある
  • 複雑なマルチステージシステムを構築している
  • さまざまな LM にわたって最適化したい

代替手段を選ぶ場面:

  • 手早くプロトタイプを作る場合(手動プロンプト設計)
  • 既存のツールを使った単純なチェーンの場合(LangChain)
  • カスタムの最適化ロジックが必要な場合

リソース

関連項目

  • references/modules.md - モジュールの詳細ガイド(Predict、ChainOfThought、ReAct、ProgramOfThought)
  • references/optimizers.md - 最適化アルゴリズム(BootstrapFewShot、MIPRO、BootstrapFinetune)
  • references/examples.md - 実例(RAG、エージェント、分類器)

エージェントの運用手順

  1. 環境を確認します。 フレームワークのバージョン、モデルプロバイダー、API キー、レート制限を確認します。
  2. 入力を明確にします。 データまたはユーザーから、形式、識別子、パラメーターを確認します。結果を左右する値は推測せず、質問してください。
  3. まず小規模に実行します。 既知の入力で単一の呼び出しまたはチェーンをテストし、生の出力を確認します。
  4. 上記の指示と参考情報を使用して、タスク全体を実行します。
  5. 結果を検証します。 小規模なラベル付きデータセットで評価し、構造化出力をスキーマと照合して、プロンプトと応答をログに記録します。
  6. 報告します。 実行した内容(バージョン、コマンド、パラメーター)、確認した内容、未確認の事項を明示します。
このような場合対応
出力が想定されたスキーマと一致しない検証と再試行を追加し、スキーマを厳密にするか、プロンプトを簡素化します。
この手順に記載された関数、フラグ、エンドポイントがインストール済みのバージョンにないインストール済みバージョンのドキュメント(help()、--help、公式ドキュメント)を確認して対応し、ユーザーに伝えます。API を捏造してはいけません。
必須の入力、識別子、パラメーターが曖昧であるユーザーに確認するか、実行前に仮定を明示します。

誠実性に関するルール

  • 結果、パラメーター、識別子、引用、統計を捏造してはいけません。実行または検証できない場合は、その旨を明確に伝えます。
  • ユーザーの同意なしに、個人情報や機密データを外部 API に送信してはいけません。
  • ここに記載されたバージョン固有の詳細は古くなっている可能性があるため、インストール済みバージョンの公式ドキュメントで確認します。
  • 費用が発生する操作、共有 GPU やクラウドのクォータを消費する操作、個人データや患者データに触れる操作、取り消せない操作を行う前に確認します。

コメント