AI Prompt Engineering · レッスン

シグネチャとモジュールの定義

シグネチャの構文、ChainOfThought、ReAct、カスタムDSPyモジュールを学びます。

レッスン 2/413 ステップ

「シグネチャとモジュールの定義」はCoddyKit上の無料AI Prompt Engineeringレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Prompt Engineering学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Prompt Engineeringコースには全4レッスンが含まれています。

シグネチャは型付きの契約

DSPyのシグネチャは、推論ステップの入力と出力を宣言するPythonクラスです。LLM呼び出しにおける、型付き関数の契約だと考えてください。

docstringがタスクの説明になります。フィールドのアノテーションは、DSPyに何を生成すべきかを伝えます。実際のプロンプトテキストを記述する必要はありません。DSPyがこの宣言から導出します。

基本的なシグネチャの定義

最小限のシグネチャでは、dspy.Signatureを継承し、フィールドにInputFieldまたはOutputFieldのアノテーションを付けます。クラスのdocstringがタスクの指示になります。

import dspy

class QASignature(dspy.Signature):
    """Answer the question based on the given context."""
    context: str = dspy.InputField(desc='Relevant background text')
    question: str = dspy.InputField(desc='The question to answer')
    answer: str = dspy.OutputField(desc='A concise answer')

# Inspect what DSPy sees
print(QASignature.instructions)  # The docstring
print(list(QASignature.input_fields.keys()))   # ['context', 'question']
print(list(QASignature.output_fields.keys()))  # ['answer']

複数の出力フィールド

シグネチャには複数の出力フィールドを定義できます。DSPyは、1回の呼び出しでそれらすべてを生成するようモデルにプロンプトを出します。構造化された情報を抽出する場合に便利です。

import dspy

class EntityExtraction(dspy.Signature):
    """Extract named entities from the text."""
    text: str = dspy.InputField()
    people: list[str] = dspy.OutputField(desc='List of person names mentioned')
    organizations: list[str] = dspy.OutputField(desc='List of organization names')
    locations: list[str] = dspy.OutputField(desc='List of place names')

extractor = dspy.Predict(EntityExtraction)
result = extractor(text='Elon Musk founded SpaceX in Hawthorne, California.')
print(result.people, result.organizations, result.locations)

Predictモジュール

dspy.Predictは最も単純なモジュールです。シグネチャを受け取り、モデルに出力を直接生成するよう指示します。推論のための補助構造は追加せず、シグネチャに対応した構造化プロンプトだけを使用します。

タスクが単純で、明示的な推論ステップを必要としない場合はPredictを使用してください。

import dspy

class Classify(dspy.Signature):
    """Classify the sentiment of the review."""
    review: str = dspy.InputField()
    sentiment: str = dspy.OutputField(desc='positive, negative, or neutral')

# Predict wraps the signature with a direct prompt
classifier = dspy.Predict(Classify)
result = classifier(review='The food was amazing and the service was excellent!')
print(result.sentiment)  # positive

ChainOfThoughtモジュール

dspy.ChainOfThoughtは、シグネチャに中間のreasoningフィールドを追加します。モデルはまず推論を書き出し、その後で最終的な回答を生成します。

自分でChain-of-Thoughtのプロンプト指示を記述しなくても、複数ステップの問題に対する正解率が安定して向上します。

import dspy

class MathSolver(dspy.Signature):
    """Solve the math problem."""
    problem: str = dspy.InputField()
    answer: str = dspy.OutputField(desc='The numerical answer')

# ChainOfThought adds a 'reasoning' step automatically
solver = dspy.ChainOfThought(MathSolver)
result = solver(problem='If a train travels 60 mph for 2.5 hours, how far does it go?')
print(result.reasoning)  # Step-by-step reasoning
print(result.answer)     # 150 miles

ReActモジュール

dspy.ReActはReason + Actのループを実装します。モデルは推論ステップとツール呼び出しを交互に行うため、検索、計算、データ取得が必要なエージェントに適しています。

ツール(docstringを持つPython関数)のリストを渡すと、DSPyがその組み合わせを自動的に処理します。

import dspy

def search_web(query: str) -> str:
    """Search the web and return relevant results."""
    # In production, call a real search API
    return f'Search results for: {query}'

def calculate(expression: str) -> str:
    """Evaluate a mathematical expression."""
    return str(eval(expression))

class ResearchQA(dspy.Signature):
    """Answer the question using web search and calculation as needed."""
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

agent = dspy.ReAct(ResearchQA, tools=[search_web, calculate])
result = agent(question='What is 15% of 847?')
print(result.answer)

モジュールを組み合わせたプログラムの構築

本当の力を発揮するのは、モジュールを複数ステップのプログラムへ組み合わせたときです。dspy.Moduleを継承し、__init__でサブモジュールを定義して、forward()を実装してそれらを接続します。

import dspy

class RetrieveAndAnswer(dspy.Module):
    def __init__(self):
        super().__init__()
        self.retrieve = dspy.Retrieve(k=3)  # Retrieves top-3 passages
        self.generate = dspy.ChainOfThought('context, question -> answer')

    def forward(self, question):
        passages = self.retrieve(question).passages
        context = '\n'.join(passages)
        return self.generate(context=context, question=question)

# This is a complete RAG pipeline in ~10 lines
rag = RetrieveAndAnswer()
result = rag(question='What are the main causes of climate change?')
print(result.answer)

インラインシグネチャの省略記法

単純なケースでは、DSPyはインライン文字列によるシグネチャを受け付けます。'input1, input2 -> output1, output2'のように記述でき、完全なクラスを定義せずにすばやくプロトタイプを作成できます。

import dspy

# Full class signature
class Translate(dspy.Signature):
    """Translate text to French."""
    text: str = dspy.InputField()
    translation: str = dspy.OutputField()

# Equivalent inline shorthand
translator_v1 = dspy.Predict(Translate)
translator_v2 = dspy.Predict('text -> translation')  # Less metadata

# Both work the same way
result = translator_v1(text='Hello world')
print(result.translation)

フィールドの説明が重要な理由

InputFieldとOutputFieldのdescパラメーターは、生成されるプロンプトに含まれます。適切な説明によって、モデルを正確に導けます。

descは、フィールド名とともにプロンプトに表示される、フィールド単位のドキュメントだと考えてください。

import dspy

class Summarize(dspy.Signature):
    """Summarize the article for a busy executive."""
    article: str = dspy.InputField(
        desc='The full article text to summarize'
    )
    summary: str = dspy.OutputField(
        desc='3-5 bullet points highlighting key decisions and numbers'
    )
    confidence: float = dspy.OutputField(
        desc='Your confidence in the summary accuracy from 0.0 to 1.0'
    )

summarizer = dspy.Predict(Summarize)
# DSPy constructs a prompt using all the desc values automatically

プログラムの保存と読み込み

最適化後は、毎回最適化を再実行する必要がないよう、コンパイル済みのプログラムを保存します。DSPyは最適化された状態をJSONファイルにシリアライズします。

import dspy

class QA(dspy.Signature):
    """Answer questions accurately."""
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

program = dspy.ChainOfThought(QA)

# After optimization, save the compiled state
program.save('optimized_qa.json')

# Load it later without re-running optimization
loaded_program = dspy.ChainOfThought(QA)
loaded_program.load('optimized_qa.json')

result = loaded_program(question='What is the speed of light?')
print(result.answer)

出力制約のためのAssertions

DSPyのAssertionsを使うと、出力に対する制約を宣言できます。モデルが制約に違反した場合、DSPyが修正フィードバックを付けて自動的に再試行するため、手動で再試行ロジックを実装する必要はありません。

import dspy

class ShortAnswer(dspy.Signature):
    """Answer in at most 10 words."""
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

class ConstrainedQA(dspy.Module):
    def __init__(self):
        super().__init__()
        self.predict = dspy.Predict(ShortAnswer)

    def forward(self, question):
        result = self.predict(question=question)
        # Assert: answer must be at most 10 words
        dspy.Assert(
            len(result.answer.split()) <= 10,
            'The answer must be 10 words or fewer.'
        )
        return result

理解度チェック:ChainOfThought

同じシグネチャを使用した場合、dspy.Predictと比べてdspy.ChainOfThoughtは何を追加しますか。

まとめ:シグネチャとモジュール

DSPyのシグネチャは、LLMのステップで何を行うべきか(入力、出力、docstringによる指示)を記述する型付きクラス宣言です。Predict、ChainOfThought、ReActなどのモジュールは、シグネチャを中心に異なる推論戦略を実装します。複数のモジュールをdspy.Moduleのサブクラス内で組み合わせることで、複数ステップのパイプラインを構築できます。フィールドのdesc値は自動生成されたプロンプト内でモデルを導き、Assertionsは自動再試行によって出力制約を適用します。

無料で開始

AI チューターと学ぶ AI Prompt Engineering — 無料

ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。

コース
53
レッスン
199

よくある質問

「シグネチャとモジュールの定義」レッスンは無料ですか?

はい。「シグネチャとモジュールの定義」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Prompt Engineeringコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Prompt Engineeringコースには全4レッスンが含まれています。

「シグネチャとモジュールの定義」で何を学びますか?

シグネチャの構文、ChainOfThought、ReAct、カスタムDSPyモジュールを学びます。 ブラウザで直接実行するハンズオンコードでAI Prompt Engineeringを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Prompt Engineeringを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Prompt Engineeringは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。

「シグネチャとモジュールの定義」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Prompt Engineeringレッスンでコードを書いて実行できますか?

はい。すべてのAI Prompt Engineeringレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. DSPy Framework入門
  2. シグネチャとモジュールの定義
  3. プロンプトのコンパイルと最適化
  4. DSPyパイプラインの評価
← AI Prompt Engineeringに戻る