> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-serverless-sft-revamp.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 評価 パイプライン の構築

> thoughtful mini-thought Annex Weave Models と Evaluations を使用して評価 パイプライン を構築する方法について学びます

export const GitHubLink = ({url}) => <a href={url} target="_blank" rel="noopener noreferrer" className="github-source-link">
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
      <path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z" />
    </svg>
    GitHub source
  </a>;

export const ColabLink = ({url}) => <a href={url} target="_blank" rel="noopener noreferrer" className="colab-link">
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
      <path d="M14.25.18l.9.2.73.26.59.3.45.32.34.34.25.34.16.33.1.3.04.26.02.2-.01.13V8.5l-.05.63-.13.55-.21.46-.26.38-.3.31-.33.25-.35.19-.35.14-.33.1-.3.07-.26.04-.21.02H8.77l-.69.05-.59.14-.5.22-.41.27-.33.32-.27.35-.2.36-.15.37-.1.35-.07.32-.04.27-.02.21v3.06H3.17l-.21-.03-.28-.07-.32-.12-.35-.18-.36-.26-.36-.36-.35-.46-.32-.59-.28-.73-.21-.88-.14-1.05-.05-1.23.06-1.22.16-1.04.24-.87.32-.71.36-.57.4-.44.42-.33.42-.24.4-.16.36-.1.32-.05.24-.01h.16l.06.01h8.16v-.83H6.18l-.01-2.75-.02-.37.05-.34.11-.31.17-.28.25-.26.31-.23.38-.2.44-.18.51-.15.58-.12.64-.1.71-.06.77-.04.84-.02 1.27.05zm-6.3 1.98l-.23.33-.08.41.08.41.23.34.33.22.41.09.41-.09.33-.22.23-.34.08-.41-.08-.41-.23-.33-.33-.22-.41-.09-.41.09zm13.09 3.95l.28.06.32.12.35.18.36.27.36.35.35.47.32.59.28.73.21.88.14 1.04.05 1.23-.06 1.23-.16 1.04-.24.86-.32.71-.36.57-.4.45-.42.33-.42.24-.4.16-.36.09-.32.05-.24.02-.16-.01h-8.22v.82h5.84l.01 2.76.02.36-.05.34-.11.31-.17.29-.25.25-.31.24-.38.2-.44.17-.51.15-.58.13-.64.09-.71.07-.77.04-.84.01-1.27-.04-1.07-.14-.9-.2-.73-.25-.59-.3-.45-.33-.34-.34-.25-.34-.16-.33-.1-.3-.04-.25-.02-.2.01-.13v-5.34l.05-.64.13-.54.21-.46.26-.38.3-.32.33-.24.35-.2.35-.14.33-.1.3-.06.26-.04.21-.02.13-.01h5.84l.69-.05.59-.14.5-.21.41-.28.33-.32.27-.35.2-.36.15-.36.1-.35.07-.32.04-.28.02-.21V6.07h2.09l.14.01.21.03zm-6.47 14.25l-.23.33-.08.41.08.41.23.33.33.23.41.08.41-.08.33-.23.23-.33.08-.41-.08-.41-.23-.33-.33-.23-.41-.08-.41.08z" />
    </svg>
    Try in Colab
  </a>;

<div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
  <ColabLink url="https://colab.research.google.com/github/wandb/docs/blob/main/weave/cookbooks/source/build_an_evaluation_pipeline.ipynb" />

  <GitHubLink url="https://github.com/wandb/docs/blob/main/weave/cookbooks/source/build_an_evaluation_pipeline.ipynb" />
</div>

Evaluations （評価）は、アプリケーションに変更を加えた後、一連の例題に対してテストを行うことで、反復的な改善を可能にします。 Weave は、 [`Model`](/weave/guides/core-types/models) クラスと [`Evaluation`](/weave/guides/core-types/evaluations) クラスを使用して、評価のトラッキングを第一級の機能としてサポートしています。これらの API は最小限の前提で設計されており、幅広いユースケースに対して柔軟に対応できます。

<img src="https://mintcdn.com/wb-21fd5541-serverless-sft-revamp/TaOfeZ6YiMh7Ljor/images/evals-hero.png?fit=max&auto=format&n=TaOfeZ6YiMh7Ljor&q=85&s=bcf5f7b307290e76d1201f968b0fcd6b" alt="Evals hero" width="4100" height="2160" data-path="images/evals-hero.png" />

## 学習内容:

このガイドでは、以下の方法について説明します。

* `Model` のセットアップ
* LLM の応答をテストするためのデータセットの作成
* モデルの出力と期待される出力を比較するためのスコアリング関数の定義
* スコアリング関数と組み込みのスコアラーを使用して、モデルをデータセットに対してテストする評価の実行
* Weave UI での評価結果の確認

## Prerequisites

* A [W\&B account](https://wandb.ai/signup)
* Python 3.8+ or Node.js 18+
* Required packages installed:
  * **Python**: `pip install weave openai`
  * **TypeScript**: `npm install weave openai`
* An [OpenAI API key](https://platform.openai.com/api-keys) set as an environment variable

## 必要なライブラリと関数のインポート

スクリプトに以下のライブラリをインポートします。

<Tabs>
  <Tab title="Python">
    ```python lines theme={null}
    import json
    import openai
    import asyncio
    import weave
    from weave.scorers import MultiTaskBinaryClassificationF1
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines theme={null}
    import * as weave from 'weave';
    import OpenAI from 'openai';
    ```
  </Tab>
</Tabs>

## `Model` の構築

Weave において、 [`Models` はオブジェクト](/weave/guides/core-types/models) であり、モデルやエージェントの振る舞い（ロジック、プロンプト、パラメータ）と、バージョン管理されたメタデータ（パラメータ、コード、マイクロ設定）の両方をキャプチャします。これにより、信頼性の高いトラッキング、比較、評価、および反復が可能になります。

`Model` をインスタンス化すると、 Weave は自動的にその設定と振る舞いをキャプチャし、変更があった場合にはバージョンを更新します。これにより、反復作業を進めながら、時間の経過に伴うパフォーマンスの推移を追跡できます。

`Model` は、 `Model` クラスを継承し、1つの例を受け取って応答を返す `predict` 関数の定義を実装することで宣言されます。

以下の例のモデルは、 OpenAI を使用して、送信された文章からエイリアンのフルーツの名前、色、味を抽出します。

<Tabs>
  <Tab title="Python">
    ```python lines {1,5} theme={null}
    class ExtractFruitsModel(weave.Model):
        model_name: str
        prompt_template: str

        @weave.op()
        async def predict(self, sentence: str) -> dict:
            client = openai.AsyncClient()

            response = await client.chat.completions.create(
                model=self.model_name,
                messages=[
                    {"role": "user", "content": self.prompt_template.format(sentence=sentence)}
                ],
            )
            result = response.choices[0].message.content
            if result is None:
                raise ValueError("No response from model")
            parsed = json.loads(result)
            return parsed
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines {9} theme={null}
    // 注意: weave.Model はまだ TypeScript でサポートされていません。
    // 代わりに、モデルのような関数を weave.op でラップしてください。

    import * as weave from 'weave';
    import OpenAI from 'openai';

    const openaiClient = new OpenAI();

    const model = weave.op(async function myModel({datasetRow}) {
      const prompt = `Extract fields ("fruit": <str>, "color": <str>, "flavor") from the following text, as json: ${datasetRow.sentence}`;
      const response = await openaiClient.chat.completions.create({
        model: 'gpt-3.5-turbo',
        messages: [{ role: 'user', content: prompt }],
        response_format: { type: 'json_object' }
      });
      return JSON.parse(response.choices[0].message.content);
    });
    ```
  </Tab>
</Tabs>

`ExtractFruitsModel` クラスは `weave.Model` を継承（サブクラス化）しているため、 Weave はインスタンス化されたオブジェクトを追跡できます。 `@weave.op` は predict 関数をデコレートし、その入力と出力を記録します。

次のように `Model` オブジェクトをインスタンス化できます。

<Tabs>
  <Tab title="Python">
    ```python lines theme={null}
    # チーム名とプロジェクト名を設定します
    weave.init('<team-name>/eval_pipeline_quickstart')

    model = ExtractFruitsModel(
        model_name='gpt-3.5-turbo-1106',
        prompt_template='Extract fields ("fruit": <str>, "color": <str>, "flavor": <str>) from the following text, as json: {sentence}'
    )

    sentence = "There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy."

    print(asyncio.run(model.predict(sentence)))
    # Jupyter Notebook の場合は、以下を実行してください:
    # await model.predict(sentence)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    await weave.init('eval_pipeline_quickstart');

    const sentence = "There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy.";

    const result = await model({ datasetRow: { sentence } });

    console.log(result);
    ```
  </Tab>
</Tabs>

## データセットの作成

次に、モデルを評価するためのデータセットが必要です。 [`Dataset` は、 Weave オブジェクトとして保存された例題のコレクション](/weave/guides/core-types/datasets) です。

以下の例のデータセットでは、3つの入力文の例とそれに対する正解（ `labels` ）を定義し、スコアリング関数が読み取れるように JSON テーブル形式でフォーマットします。

この例ではコード内で例題のリストを作成していますが、実行中のアプリケーションから1つずつログを記録することも可能です。

<Tabs>
  <Tab title="Python">
    ```python lines theme={null}
    sentences = ["There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy.",
    "Pounits are a bright green color and are more savory than sweet.",
    "Finally, there are fruits called glowls, which have a very sour and bitter taste which is acidic and caustic, and a pale orange tinge to them."]
    labels = [
        {'fruit': 'neoskizzles', 'color': 'purple', 'flavor': 'candy'},
        {'fruit': 'pounits', 'color': 'bright green', 'flavor': 'savory'},
        {'fruit': 'glowls', 'color': 'pale orange', 'flavor': 'sour and bitter'}
    ]
    examples = [
        {'id': '0', 'sentence': sentences[0], 'target': labels[0]},
        {'id': '1', 'sentence': sentences[1], 'target': labels[1]},
        {'id': '2', 'sentence': sentences[2], 'target': labels[2]}
    ]
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const sentences = [
      "There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy.",
      "Pounits are a bright green color and are more savory than sweet.",
      "Finally, there are fruits called glowls, which have a very sour and bitter taste which is acidic and caustic, and a pale orange tinge to them."
    ];
    const labels = [
      { fruit: 'neoskizzles', color: 'purple', flavor: 'candy' },
      { fruit: 'pounits', color: 'bright green', flavor: 'savory' },
      { fruit: 'glowls', color: 'pale orange', flavor: 'sour and bitter' }
    ];
    const examples = sentences.map((sentence, i) => ({
      id: i.toString(),
      sentence,
      target: labels[i]
    }));
    ```
  </Tab>
</Tabs>

次に、 `weave.Dataset()` クラスを使用してデータセットを作成し、パブリッシュします。

<Tabs>
  <Tab title="Python">
    ```python lines {2} theme={null}
    weave.init('eval_pipeline_quickstart')
    dataset = weave.Dataset(name='fruits', rows=examples)
    weave.publish(dataset)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines {3-6} theme={null}
    import * as weave from 'weave';
    await weave.init('eval_pipeline_quickstart');
    const dataset = new weave.Dataset({
      name: 'fruits',
      rows: examples
    });
    await dataset.save();
    ```
  </Tab>
</Tabs>

## カスタムスコアリング関数の定義

Weave の評価を使用する場合、 Weave は `output` と比較するための `target` を想定します。以下のスコアリング関数は、2つの辞書（ `target` と `output` ）を受け取り、出力がターゲットと一致するかどうかを示すブール値の辞書を返します。 `@weave.op()` デコレータにより、 Weave はスコアリング関数の実行を追跡できるようになります。

<Tabs>
  <Tab title="Python">
    ```python lines theme={null}
    @weave.op()
    def fruit_name_score(target: dict, output: dict) -> dict:
        return {'correct': target['fruit'] == output['fruit']}
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import * as weave from 'weave';

    const fruitNameScorer = weave.op(
      function fruitNameScore({target, output}) {
        return { correct: target.fruit === output.fruit };
      }
    );
    ```
  </Tab>
</Tabs>

独自のスコアリング関数を作成する方法については、 [Scorers](/weave/guides/evaluation/scorers) ガイドで詳細を確認してください。

アプリケーションによっては、カスタムの `Scorer` クラスを作成したい場合があるでしょう。例えば、特定のパラメータ（チャットモデルやプロンプトなど）、特定の行のスコアリング、および集計スコアの計算を備えた標準化された `LLMJudge` クラスを作成できます。詳細については、次章の [RAG アプリケーションのモデルベース評価](/weave/tutorial-rag#optional-defining-a-scorer-class) にある Scorer クラスの定義に関するチュートリアルを参照してください。

## 組み込みスコアラーの使用と評価の実行

カスタムスコアリング関数に加えて、 [Weave の組み込みスコアラー](/weave/guides/evaluation/builtin_scorers) も使用できます。以下の評価では、 `weave.Evaluation()` は前のセクションで定義した `fruit_name_score` 関数と、 [F1 スコア](https://en.wikipedia.org/wiki/F-score) を計算する組み込みの `MultiTaskBinaryClassificationF1` スコアラーを使用します。

以下の例では、2つのスコアリング関数を使用して `fruits` データセットに対して `ExtractFruitsModel` の評価を実行し、その結果を Weave に記録します。

<Tabs>
  <Tab title="Python">
    ```python lines {3-10} theme={null}
    weave.init('eval_pipeline_quickstart')

    evaluation = weave.Evaluation(
        name='fruit_eval',
        dataset=dataset, 
        scorers=[
            MultiTaskBinaryClassificationF1(class_names=["fruit", "color", "flavor"]), 
            fruit_name_score
        ],
    )
    print(asyncio.run(evaluation.evaluate(model)))
    # Jupyter Notebook の場合は、以下を実行してください:
    # await evaluation.evaluate(model)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines {5-9} theme={null}
    import * as weave from 'weave';

    await weave.init('eval_pipeline_quickstart');

    const evaluation = new weave.Evaluation({
      name: 'fruit_eval',
      dataset: dataset,
      scorers: [fruitNameScorer],
    });
    const results = await evaluation.evaluate(model);
    console.log(results);
    ```
  </Tab>
</Tabs>

<Note>
  Python スクリプトから実行する場合は、 `asyncio.run` を使用する必要があります。ただし、 Jupyter Notebook から実行する場合は、直接 `await` を使用できます。
</Note>

### 完全な例

<Accordion title="1つのスクリプトにまとめた完全な評価パイプライン:">
  <Tabs>
    <Tab title="Python">
      ```python lines theme={null}
      import json
      import asyncio
      import openai
      import weave
      from weave.scorers import MultiTaskBinaryClassificationF1

      # Weave を一度初期化します
      weave.init('eval_pipeline_quickstart')

      # 1. Model の定義
      class ExtractFruitsModel(weave.Model):
          model_name: str
          prompt_template: str

          @weave.op()
          async def predict(self, sentence: str) -> dict:
              client = openai.AsyncClient()
              response = await client.chat.completions.create(
                  model=self.model_name,
                  messages=[{"role": "user", "content": self.prompt_template.format(sentence=sentence)}],
              )
              result = response.choices[0].message.content
              if result is None:
                  raise ValueError("No response from model")
              return json.loads(result)

      # 2. モデルのインスタンス化
      model = ExtractFruitsModel(
          model_name='gpt-3.5-turbo-1106',
          prompt_template='Extract fields ("fruit": <str>, "color": <str>, "flavor": <str>) from the following text, as json: {sentence}'
      )

      # 3. データセットの作成
      sentences = ["There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy.",
      "Pounits are a bright green color and are more savory than sweet.",
      "Finally, there are fruits called glowls, which have a very sour and bitter taste which is acidic and caustic, and a pale orange tinge to them."]
      labels = [
          {'fruit': 'neoskizzles', 'color': 'purple', 'flavor': 'candy'},
          {'fruit': 'pounits', 'color': 'bright green', 'flavor': 'savory'},
          {'fruit': 'glowls', 'color': 'pale orange', 'flavor': 'sour and bitter'}
      ]
      examples = [
          {'id': '0', 'sentence': sentences[0], 'target': labels[0]},
          {'id': '1', 'sentence': sentences[1], 'target': labels[1]},
          {'id': '2', 'sentence': sentences[2], 'target': labels[2]}
      ]

      dataset = weave.Dataset(name='fruits', rows=examples)
      weave.publish(dataset)

      # 4. スコアリング関数の定義
      @weave.op()
      def fruit_name_score(target: dict, output: dict) -> dict:
          return {'correct': target['fruit'] == output['fruit']}

      # 5. 評価の実行
      evaluation = weave.Evaluation(
          name='fruit_eval',
          dataset=dataset,
          scorers=[
              MultiTaskBinaryClassificationF1(class_names=["fruit", "color", "flavor"]),
              fruit_name_score
          ],
      )
      print(asyncio.run(evaluation.evaluate(model)))
      ```
    </Tab>

    <Tab title="TypeScript">
      ```typescript lines theme={null}
      import * as weave from 'weave';
      import OpenAI from 'openai';

      // Weave を一度初期化します
      await weave.init('eval_pipeline_quickstart');

      // 1. Model の定義
      // 注意: weave.Model はまだ TypeScript でサポートされていません。
      // 代わりに、モデルのような関数を weave.op でラップしてください。
      const openaiClient = new OpenAI();

      const model = weave.op(async function myModel({datasetRow}) {
        const prompt = `Extract fields ("fruit": <str>, "color": <str>, "flavor": <str>) from the following text, as json: ${datasetRow.sentence}`;
        const response = await openaiClient.chat.completions.create({
          model: 'gpt-3.5-turbo',
          messages: [{ role: 'user', content: prompt }],
          response_format: { type: 'json_object' }
        });
        return JSON.parse(response.choices[0].message.content);
      });

      // 2. データセットの作成
      const sentences = [
        "There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy.",
        "Pounits are a bright green color and are more savory than sweet.",
        "Finally, there are fruits called glowls, which have a very sour and bitter taste which is acidic and caustic, and a pale orange tinge to them."
      ];
      const labels = [
        { fruit: 'neoskizzles', color: 'purple', flavor: 'candy' },
        { fruit: 'pounits', color: 'bright green', flavor: 'savory' },
        { fruit: 'glowls', color: 'pale orange', flavor: 'sour and bitter' }
      ];
      const examples = sentences.map((sentence, i) => ({
        id: i.toString(),
        sentence,
        target: labels[i]
      }));

      const dataset = new weave.Dataset({
        name: 'fruits',
        rows: examples
      });
      await dataset.save();

      // 3. スコアリング関数の定義
      const fruitNameScorer = weave.op(
        function fruitNameScore({target, output}) {
          return { correct: target.fruit === output.fruit };
        }
      );

      // 4. 評価の実行
      const evaluation = new weave.Evaluation({
        name: 'fruit_eval',
        dataset: dataset,
        scorers: [fruitNameScorer],
      });
      const results = await evaluation.evaluate(model);
      console.log(results);
      ```
    </Tab>
  </Tabs>
</Accordion>

## 評価結果の確認

Weave は、各予測とスコアのトレースを自動的にキャプチャします。評価によって出力されたリンクをクリックして、 Weave UI で結果を確認してください。

<img src="https://mintcdn.com/wb-21fd5541-serverless-sft-revamp/TaOfeZ6YiMh7Ljor/images/evals-hero.png?fit=max&auto=format&n=TaOfeZ6YiMh7Ljor&q=85&s=bcf5f7b307290e76d1201f968b0fcd6b" alt="Evaluation results" width="4100" height="2160" data-path="images/evals-hero.png" />

## Weave 評価の詳細

* スコアラーの [構築と使用方法](/weave/guides/evaluation/scorers) についての詳細。
* Weave の [組み込みスコアリング関数](/weave/guides/evaluation/builtin_scorers) の確認。
* LLM を評価者として使用する [モデルベース評価](/weave/guides/evaluation/scorers#model-based-evaluation) について。

## 次のステップ

[RAG アプリケーションの構築](/weave/tutorial-rag) を通じて、検索拡張生成（Retrieval-Augmented Generation）の評価について学びましょう。
