DSPyの入門 ①
はじめに
プロンプトの自動最適化の方法として、DSPyが話題になっていたので入門してみました。
最適化の主要コンポーネントのオプティマイザは、ボリュームが大きいので別でまとめます。
DSPyとは
DSPy (Declarative Self-improving Language Programs) は、大規模言語モデル(LLM)を用いたアプリケーションのプロンプトや重みを、アルゴリズムによって自動的に最適化するためのフレームワークです。
スタンフォード大学の研究者らによって開発され、従来の「手動でのプロンプトエンジニアリング」を「プログラマブルなシステム構築」へと進化させることを目的としています。
1. プロンプトから宣言的なプログラミングへ
従来のLLM開発では、特定のモデル(例:GPT-4)に合わせて「プロンプトの文字列」を微調整する作業が中心でした。しかし、モデルを変更したりデータを更新したりするたびに、プロンプトを書き直す必要がありました。
DSPyは、「プログラムのロジック」と「プロンプトの表現(およびモデルの重み)」を分離します。開発者はタスクの構造を定義するだけで、最適なプロンプトはDSPyが自動的に生成・最適化します。
2. 主要コンポーネント
DSPyは主に以下の要素で構成されています。
① Signatures(シグネチャ)
タスクの「入力」と「出力」の仕様を宣言的に定義します。
- 例:
input: question -> output: answer - 開発者は具体的な指示文(「あなたは親切なアシスタントです...」など)を書く必要はなく、入出力の型を定義するだけで済みます。
② Modules(モジュール)
シグネチャを使用して、具体的な推論ステップを構築します。
-
dspy.ChainOfThought(思考の連鎖)やdspy.ReAct(思考と行動のループ)など、標準的な推論手法が再利用可能なコンポーネントとして提供されています。 - これらを組み合わせることで、複雑なパイプラインを構築できます。
③ Adapters(アダプター)
Adapterは、Module / Signature と LM(Language Model)の間に入る「通訳レイヤ(入力/出力の変換機構)」です。DSPy側の構造化された入出力を、LM が理解できるリクエスト形式へ変換し、LMの応答を Signatureの出力フィールドへパース(復元)します。
④ Optimizers(オプティマイザ)
DSPyの核心となる機能です。プログラム、少量のトレーニングデータ、および評価指標(Metric)を入力として受け取り、以下の自動最適化を行います。
- 最も効果的なプロンプト(例:Few-shotの例示の選択)の生成。
- モデルの重みのファインチューニング。
- モデルを変更(例:GPT-4からLlama 3へ)しても、オプティマイザを再実行するだけで、そのモデルに最適なプロンプトが再生成されます。
基本的な使い方
環境
Python: 3.12.7
DSPy: 3.1.3
uv: 0.8.17
LLMの呼び出し
DSPy で LLM を実行するときは、LM(Language Model)を使用します。LM は、DSPy における LLM の統一インターフェースです。
内部では、さまざまな LLM 呼び出しを抽象化するライブラリである LiteLLM を利用しています。これにより、複数のプロバイダのモデルを同一の API で扱えます。
コード例
import os
import dspy
from dotenv import load_dotenv
# .env から環境変数を読み込む
load_dotenv()
def main() -> None:
# LM(Language Model)を設定して DSPy に登録する # noqa: RUF003
lm = dspy.LM("gemini/gemini-2.5-flash", api_key=os.getenv("GOOGLE_API_KEY"))
dspy.configure(lm=lm)
response = lm("こんにちは! 今日の調子はどうですか?")
print("Direct call response:")
print(response)
print()
if __name__ == "__main__":
main()
キャッシュ
DSPyは、同じLLMリクエストを繰り返し実行する際に、API呼び出しをスキップしてキャッシュから結果を返します。
これは、LMの呼び出しのcacheパラメタにあり、デフォルトがTrueになっています。
lm = dspy.LM(
"gemini/gemini-2.5-flash",
api_key=os.getenv("GOOGLE_API_KEY"),
cache=True, # キャッシュの設定(default: True)
)
DSPyのキャッシュは、メモリキャッシュとディスクキャッシュで構成されていて、Macであれば ~/.dspy_cache/ 配下にキャッシュDBが作られます。
キャッシュのコードは、このあたりで定義されています。
キャッシュのキーは、リクエストのプロンプトやパラメタなどからsha256でハッシュを取られているため、プロンプトが更新された場合などは、LLMへの呼び出しが再度実行される構成となっています。
Signatures(シグネチャ)
シグネチャは、LLMの入出力の宣言です。DSPyでは、プロンプトの全てを指示するのではなくシグネチャという構造化されたコンポーネントを使うことで、再利用性や最適化を実現しています。
インライン形式
DSPy では、シグネチャ(入出力の型定義に相当するもの)を文字列で定義できます。
dspy.Predict("question -> answer")
この例では、question を入力パラメータ、answer を出力フィールドとして宣言しています。
(呼び出し例)
import os
import dspy
from dotenv import load_dotenv
load_dotenv()
def main() -> None:
lm = dspy.LM("gemini/gemini-2.5-flash", api_key=os.getenv("GOOGLE_API_KEY"))
dspy.configure(lm=lm)
qa_simple = dspy.Predict("question -> answer")
result = qa_simple(question="Pythonのとはどういうプログラム言語ですか?")
print(result.answer)
if __name__ == "__main__":
main()
上記のコードでは、LLM(lm)を 直接呼び出すのではなく、dspy.Predict を使ってモジュール化して呼び出しています。
• 呼び出し時は、シグネチャで定義した入力名 question をキーワード引数として渡します
• 実行結果は、シグネチャで定義した出力名 answer に格納され、result.answer で参照できます
インラインのシグネチャのフォーマットはデータの型を指定することも出来ます。
qa_simple = dspy.Predict("question: str -> answer: int")
result = qa_simple(question="100 * 100 = ?")
# 数値で取得できる
複雑なデータ形式になる場合は、後述のクラス形式を使うべきだと思いますが、対応するフォーマットなどは次のとおりになります。
基本のルール
| ルール | 説明 |
|---|---|
| 区切り |
-> で入力と出力を分ける(必ず1つ) |
| 左側 | 入力フィールド(InputField) |
| 右側 | 出力フィールド(OutputField) |
| 複数フィールド | カンマ , で区切る |
| 型の指定 |
フィールド名: 型 で指定。省略すると str
|
書き方の例
| シグネチャ文字列 | 入力 | 出力 | 備考 |
|---|---|---|---|
"question -> answer" |
question (str) | answer (str) | 最もシンプルな形 |
"question, context -> answer" |
question (str), context (str) | answer (str) | 入力が複数 |
"question -> answer, confidence: float" |
question (str) | answer (str), confidence (float) | 出力が複数+型指定 |
"query -> keywords: list[str]" |
query (str) | keywords (list[str]) | ジェネリクス型 |
"x: int, y: int -> result: int" |
x (int), y (int) | result (int) | 入出力ともに型指定 |
"problem -> steps: list[str], final_answer" |
problem (str) | steps (list[str]), final_answer (str) | 混在(型指定あり+なし) |
指示文(instructions)の付け方
# 第2引数で指示文を渡せる
dspy.Predict("question -> answer", "簡潔に1文で答えてください。")
# 省略すると自動生成される
# → "Given the fields `question`, produce the fields `answer`."
クラス形式
インライン形式("question -> answer")は手軽ですが、入力・出力が増えてくると「何を渡して、何が返るのか」が曖昧になりがちです。
そこで使うのが クラス形式(dspy.Signature) です。
Signatureクラスを使うと、入出力を型付きの契約で明示でき、モジュールの再利用性・保守性が上がります。
import os
import dspy
from dotenv import load_dotenv
load_dotenv()
class QuestionAnswer(dspy.Signature):
"""コンテキストを参考に質問に回答する。"""
context: str = dspy.InputField(desc="回答の根拠となる情報。ここに書かれた事実は真とみなす")
question: str = dspy.InputField(desc="ユーザーからの質問")
answer: str = dspy.OutputField(desc="コンテキストに基づいた簡潔な回答")
reason: str = dspy.OutputField(desc="判断の理由")
def main() -> None:
lm = dspy.LM("gemini/gemini-2.5-flash", api_key=os.getenv("GOOGLE_API_KEY"))
dspy.configure(lm=lm)
qa_simple = dspy.Predict(QuestionAnswer)
result = qa_simple(
context="昨日の東京の天気は晴れでした。大阪の天気は雨でした。",
question="昨日の東京の天気はどうでしたか?",
)
print(f"answer: {result.answer}")
print(f"reason: {result.reason}")
if __name__ == "__main__":
main()
インプットとアウトプットは、それぞれ「InputField」「OutputField」として定義されます。
クラスのdocstringや、descパラメタはプロンプトに含まれます。
実行されるプロンプト
print(dspy.inspect_history(n=1))
で直近のプロンプトを確認すると次のようになっており、Signatureクラスを使ってプロンプトが構成されていることがわかります。
[2026-02-09T07:53:41.913144]
System message:
Your input fields are:
1. `context` (str): 回答の根拠となる情報。ここに書かれた事実は真とみなす
2. `question` (str): ユーザーからの質問
Your output fields are:
1. `answer` (str): コンテキストに基づいた簡潔な回答
2. `reason` (str): 判断の理由
All interactions will be structured in the following way, with the appropriate values filled in.
[[ ## context ## ]]
{context}
[[ ## question ## ]]
{question}
[[ ## answer ## ]]
{answer}
[[ ## reason ## ]]
{reason}
[[ ## completed ## ]]
In adhering to this structure, your objective is:
コンテキストを参考に質問に回答する。
User message:
[[ ## context ## ]]
昨日の東京の天気は晴れでした。大阪の天気は雨でした。
[[ ## question ## ]]
昨日の東京の天気はどうでしたか?
Respond with the corresponding output fields, starting with the field `[[ ## answer ## ]]`, then `[[ ## reason ## ]]`, and then ending with the marker for `[[ ## completed ## ]]`.
Response:
[[ ## answer ## ]]
昨日の東京の天気は晴れでした。
[[ ## reason ## ]]
コンテキストに「昨日の東京の天気は晴れでした」と明記されているため。
[[ ## completed ## ]]
Modules(モジュール)
Modules(モジュール)は、Signature(入出力の宣言)に対して 「どうやって解くか」 を実装する部品です。
DSPyでは、Predict / ChainOfThought / ReAct などの 推論・実行パターン(prompting technique) を、再利用可能なモジュールとして提供しています。
Predict
Predict は、DSPy における 最も基本的な推論モジュールです。
Signature(シグネチャ)で定義した入出力に従って、LLM を1回呼び出し、構造化された出力オブジェクトとして返します。
qa = dspy.Predict("question -> answer")
result = qa(question="日本の首都は?")
print(result.answer)
サンプルコード
import os
import dspy
from dotenv import load_dotenv
load_dotenv()
def main() -> None:
lm = dspy.LM("gemini/gemini-2.5-flash", api_key=os.getenv("GOOGLE_API_KEY"))
dspy.configure(lm=lm)
qa = dspy.Predict("question -> answer")
result = qa(question="日本の首都は?")
print(result.answer)
if __name__ == "__main__":
main()
ChainOfThought
ChainOfThought は、ステップバイステップで推論してから出力を作るモジュールです。
Signature(文字列/クラス)を受け取り、内部で推論用フィールド(rationale)を扱います。
Predictとの違いは、記載のとおり、プロンプトに推論用のフィールドが追加される点です。
次の実行プロンプトを見ると [[ ## reasoning ## ]] というフィールドが追加されていることがわかります。逆に差分としてはこれだけのようです。
ChainOfThoughtを使った場合の、実行プロンプト
System message:
Your input fields are:
1. `question` (str):
Your output fields are:
1. `reasoning` (str):
2. `answer` (str):
All interactions will be structured in the following way, with the appropriate values filled in.
[[ ## question ## ]]
{question}
[[ ## reasoning ## ]]
{reasoning}
[[ ## answer ## ]]
{answer}
[[ ## completed ## ]]
In adhering to this structure, your objective is:
Given the fields `question`, produce the fields `answer`.
User message:
[[ ## question ## ]]
A君は1000円持っています。A君は1つ50円のりんごを3つ買いました。A君はいくら残りますか?
Respond with the corresponding output fields, starting with the field `[[ ## reasoning ## ]]`, then `[[ ## answer ## ]]`, and then ending with the marker for `[[ ## completed ## ]]`.
Response:
[[ ## reasoning ## ]]
まず、A君がリンゴを買うのに使った金額を計算します。
リンゴ1つの値段は50円で、3つ買いました。
50円 × 3個 = 150円
次に、A君が持っていたお金から使った金額を引きます。
1000円 - 150円 = 850円
これがA君に残る金額です。
[[ ## answer ## ]]
850円
[[ ## completed ## ]]
サンプルコード
import os
import dspy
from dotenv import load_dotenv
load_dotenv()
def main() -> None:
lm = dspy.LM("gemini/gemini-2.5-flash", api_key=os.getenv("GOOGLE_API_KEY"))
dspy.configure(lm=lm)
qa = dspy.ChainOfThought("question -> answer")
result = qa(
question="A君は1000円持っています。A君は1つ50円のりんごを3つ買いました。A君はいくら残りますか?"
)
print(result.answer)
print(dspy.inspect_history(n=1))
if __name__ == "__main__":
main()
ReAct
ReAct は Reasoning and Acting(推論し、必要なら行動=ツール呼び出しを行い、その観測結果を踏まえて再度推論する)というエージェント的ループを、DSPyのモジュールとして提供するものです。与えたツール一覧の中から、LLM が「使うべきツール」を選び、複数回の試行を通じて解に到達します。
次のサンプルでは、簡単な計算のツールを使わせてReAct上で使用させています。
サンプルコード
import os
import dspy
from dotenv import load_dotenv
load_dotenv()
def multiply(a: int, b: int) -> int:
"""2つの整数を掛け算して返す。"""
return a * b
class CalcSig(dspy.Signature):
question: str = dspy.InputField(desc="ユーザーの質問")
result: str = dspy.OutputField(desc="最終回答")
def main() -> None:
lm = dspy.LM("gemini/gemini-2.5-flash", api_key=os.getenv("GOOGLE_API_KEY"))
dspy.configure(lm=lm)
agent = dspy.ReAct(signature=CalcSig, tools=[multiply], max_iters=5)
out = agent(question="17 と 23 を掛けると?")
print(out.result)
if __name__ == "__main__":
main()
こちらの実行プロンプトのログは次の通りです。
実行ログ
System message:
Your input fields are:
1. `question` (str): ユーザーの質問
2. `trajectory` (str):
Your output fields are:
1. `reasoning` (str):
2. `result` (str): 最終回答
All interactions will be structured in the following way, with the appropriate values filled in.
[[ ## question ## ]]
{question}
[[ ## trajectory ## ]]
{trajectory}
[[ ## reasoning ## ]]
{reasoning}
[[ ## result ## ]]
{result}
[[ ## completed ## ]]
In adhering to this structure, your objective is:
Given the fields `question`, produce the fields `result`.
User message:
[[ ## question ## ]]
17 と 23 を掛けると?
[[ ## trajectory ## ]]
[[ ## thought_0 ## ]]
ユーザーは17と23の掛け算を求めています。`multiply`ツールを使って計算します。
[[ ## tool_name_0 ## ]]
multiply
[[ ## tool_args_0 ## ]]
{"a": 17, "b": 23}
[[ ## observation_0 ## ]]
391
[[ ## thought_1 ## ]]
掛け算の結果が391と得られました。これでユーザーの質問に答えられるので、タスクを完了します。
[[ ## tool_name_1 ## ]]
finish
[[ ## tool_args_1 ## ]]
{}
[[ ## observation_1 ## ]]
Completed.
Respond with the corresponding output fields, starting with the field `[[ ## reasoning ## ]]`, then `[[ ## result ## ]]`, and then ending with the marker for `[[ ## completed ## ]]`.
Response:
[[ ## reasoning ## ]]
ユーザーは17と23の積を求めています。すでに計算が実行され、結果は391と判明しています。この結果を最終回答として提示します。
[[ ## result ## ]]
17 と 23 を掛けると 391 になります。
[[ ## completed ## ]]
[[ ## thought_0 ## ]]
ユーザーは17と23の掛け算を求めています。`multiply`ツールを使って計算します。
...
[[ ## thought_1 ## ]]
掛け算の結果が391と得られました。これでユーザーの質問に答えられるので、タスクを完了します。
のように、toolを使って結果を元にもう一度推論した結果を返していることがわかります。
Adaptors(アダプター)
アダプターは、入出力の変換を担います。
Signatureの構造をModuleの形式に合わせてシステムプロンプトを構成したり、LLMからの応答を指定の構造にパースしています。
import dspy
dspy.configure(
lm=dspy.LM("openai/gpt-4o-mini"),
adapter=dspy.ChatAdapter(), # 何も指定しない場合、ChatAdapterが使われる
)
predict = dspy.Predict("question -> answer")
result = predict(question="What is the capital of France?")
ChatAdapter
ChatAdapter は、Signature・few-shot・履歴を マルチターンの chat messages(system/user/assistant の配列)に整形する、最も標準的なアダプターです。 
lm = dspy.LM("gemini/gemini-2.5-flash", api_key=os.getenv("GOOGLE_API_KEY"))
dspy.configure(lm=lm, adapter=dspy.ChatAdapter())
qa_simple = dspy.Predict("question: str -> answer: int")
result = qa_simple(question="100 * 100 = ?")
ChatAdapterを使うと、上記のようなシグネチャに対して、[[ ## <field_name> ## ]]という形式のSystem messageを生成します。実際のRequestをResponseは次のような形になります。
System message:
Your input fields are:
1. `question` (str):
Your output fields are:
1. `answer` (int):
All interactions will be structured in the following way, with the appropriate values filled in.
[[ ## question ## ]]
{question}
[[ ## answer ## ]]
{answer} # note: the value you produce must be a single int value
[[ ## completed ## ]]
In adhering to this structure, your objective is:
Given the fields `question`, produce the fields `answer`.
User message:
[[ ## question ## ]]
100 * 100 = ?
Respond with the corresponding output fields, starting with the field `[[ ## answer ## ]]` (must be formatted as a valid Python int), and then ending with the marker for `[[ ## completed ## ]]`.
Response:
[[ ## answer ## ]]
10000
[[ ## completed ## ]]
JSONAdapter
JSONAdapter は、LM が 構造化出力(例:response_format)に対応している 場合に強いアダプターです。
JSONAdapterを使うと、システムプロンプトで構造化を指示するプロンプトが生成されます。
OutputもJSON形式で出力されていることがわかります。
System message:
Your input fields are:
1. `question` (str):
Your output fields are:
1. `answer` (int):
All interactions will be structured in the following way, with the appropriate values filled in.
Inputs will have the following structure:
[[ ## question ## ]]
{question}
Outputs will be a JSON object with the following fields.
{
"answer": "{answer} # note: the value you produce must be a single int value"
}
In adhering to this structure, your objective is:
Given the fields `question`, produce the fields `answer`.
User message:
[[ ## question ## ]]
100 * 100 = ?
Respond with a JSON object in the following order of fields: `answer` (must be formatted as a valid Python int).
Response:
{"answer": 10000}
TwoStepAdapter
TwoStepAdapter は、「メインLMの生テキスト出力」を、そのままパースしにいかず、別の小さめ LM(extraction_model)で 抽出(extraction して構造化する二段構えのアダプターです。 
内部実装的には、抽出段で ChatAdapter を使って、completion(生テキスト)から Signature の出力フィールドを再構成します。
TwoStepAdapterを使う場合は、推論用のLLMモデルと抽出用のLLMモデルを2つ指定します。
lm = dspy.LM("gemini/gemini-3-pro-preview", api_key=os.getenv("GOOGLE_API_KEY"))
extract_lm = dspy.LM("gemini/gemini-2.0-flash", api_key=os.getenv("GOOGLE_API_KEY"))
dspy.configure(lm=lm, adapter=dspy.TwoStepAdapter(extraction_model=extract_lm))
qa_simple = dspy.Predict("question: str -> summary: str, details: str")
result = qa_simple(question="Pythonのプログラミングについて特徴を日本語で解説してください")
出力構造が複雑な場合に有効そうなモデルですが、あまり使い道はないかもしれません。
触ってみた感想
普段は LangChain などを使って実験的なコードを書くことが多いのですが、DSPy は「プロンプトを書かなくてよい」という体験が直感的に良く、シグネチャもインラインでサクッと書ける点が魅力だと感じました。
一方で、DSPy はオプティマイザと組み合わせてこそ真価が出るフレームワークだと思うので、現時点ではそこまで踏み込んだ評価はできていません。ただ、「とりあえずモデルを試したい」「ざっくり精度感を素早く把握したい」といった用途には相性が良さそうです。
また、キャッシュ機構や、あらかじめ用意されたモジュール群(Predict / ChainOfThought / ReAct など)の存在も、試行錯誤の回転数を上げるうえで非常に便利だと感じています。
その一方で、複雑で作り込んだフローや、入り組んだプロンプト設計にどこまで対応できるのかはまだ未知数です。いずれは実際のプロダクトにも組み込み、実運用の中で手触りや限界を確かめてみたいと思います。
Discussion