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

# Scorers

Weaveでは、Scorerを使用してAI出力を評価し、評価メトリクスを返します。Scorerは、AIの出力を取得して分析し、結果の辞書を返します。必要に応じて入力データを参照として使用でき、評価からの説明や推論などの追加情報も出力できます。

<Tabs>
  <Tab title="Python">
    Scorerは`weave.Evaluation`オブジェクトに評価中に渡されます。weaveには2種類のScorerがあります：

    1. **関数ベースのScorer：**でデコレートされたシンプルなPython関数`@weave.op`。
    2. **クラスベースのScorer：**より複雑な評価のために`weave.Scorer`を継承するPythonクラス。

    Scorerは辞書を返す必要があり、複数のメトリクス、ネストされたメトリクス、LLM評価者からの推論についてのテキストなどの非数値の値を返すことができます。
  </Tab>

  <Tab title="TypeScript">
    Scorerは評価中に`weave.Evaluation`オブジェクトに渡される特別なオペレーションです。
  </Tab>
</Tabs>

## 独自のScorerを作成する

<Tip>
  **すぐに使えるScorer**
  このガイドではカスタムScorerの作成方法を示していますが、Weaveには様々な[predefined scorers](./builtin_scorers.mdx)や[local SLM scorers](./weave_local_scorers.mdx)がすぐに使えるように用意されています。以下のようなものがあります：

  * [幻覚検出](./builtin_scorers.mdx#hallucinationfreescorer)
  * [要約の品質](./builtin_scorers.mdx#summarizationscorer)
  * [埋め込み類似性](./builtin_scorers.mdx#embeddingsimilarityscorer)
  * [有害性検出（ローカル）](./weave_local_scorers.md#weavetoxicityscorerv1)
  * [コンテキスト関連性スコアリング（ローカル）](./weave_local_scorers.md#weavecontextrelevancescorerv1)
  * その他多数！
</Tip>

### 関数ベースのScorer

<Tabs>
  <Tab title="Python">
    これらは`@weave.op`でデコレートされ、辞書を返す関数です。以下のような単純な評価に最適です：

    ```python
    import weave

    @weave.op
    def evaluate_uppercase(text: str) -> dict:
        return {"text_is_uppercase": text.isupper()}

    my_eval = weave.Evaluation(
        dataset=[{"text": "HELLO WORLD"}],
        scorers=[evaluate_uppercase]
    )
    ```

    評価が実行されると、`evaluate_uppercase`はテキストがすべて大文字かどうかをチェックします。
  </Tab>

  <Tab title="TypeScript">
    これらは`weave.op`でラップされた関数で、`modelOutput`と任意で`datasetRow`を持つオブジェクトを受け取ります。以下のような単純な評価に最適です：

    ```typescript
    import * as weave from 'weave'

    const evaluateUppercase = weave.op(
        ({modelOutput}) => modelOutput.toUpperCase() === modelOutput,
        {name: 'textIsUppercase'}
    );

    const myEval = new weave.Evaluation({
        dataset: [{text: 'HELLO WORLD'}],
        scorers: [evaluateUppercase],
    })
    ```
  </Tab>
</Tabs>

### クラスベースのScorer

<Tabs>
  <Tab title="Python">
    より高度な評価、特に追加のスコアラーメタデータを追跡する必要がある場合や、LLM評価者に異なるプロンプトを試したり、複数の関数呼び出しを行ったりする場合は、`Scorer`クラスを使用できます。

    **Requirements:**

    1. 以下から継承します：`weave.Scorer`。
    2. `score`メソッドを`@weave.op`でデコレートして定義します。
    3. `score`メソッドは辞書を返す必要があります。

    Example:

    ```python
    import weave
    from openai import OpenAI
    from weave import Scorer

    llm_client = OpenAI()

    #highlight-next-line
    class SummarizationScorer(Scorer):
        model_id: str = "gpt-4o"
        system_prompt: str = "Evaluate whether the summary is good."

        @weave.op
        def some_complicated_preprocessing(self, text: str) -> str:
            processed_text = "Original text: \n" + text + "\n"
            return processed_text

        @weave.op
        def call_llm(self, summary: str, processed_text: str) -> dict:
            res = llm_client.chat.completions.create(
                messages=[
                    {"role": "system", "content": self.system_prompt},
                    {"role": "user", "content": (
                        f"Analyse how good the summary is compared to the original text."
                        f"Summary: {summary}\n{processed_text}"
                    )}])
            return {"summary_quality": res}

        @weave.op
        def score(self, output: str, text: str) -> dict:
            """Score the summary quality.

            Args:
                output: The summary generated by an AI system
                text: The original text being summarized
            """
            processed_text = self.some_complicated_preprocessing(text)
            eval_result = self.call_llm(summary=output, processed_text=processed_text)
            return {"summary_quality": eval_result}

    evaluation = weave.Evaluation(
        dataset=[{"text": "The quick brown fox jumps over the lazy dog."}],
        scorers=[summarization_scorer])
    ```

    このクラスは、要約を元のテキストと比較することで、要約の質を評価します。
  </Tab>

  <Tab title="TypeScript">
    ```plaintext
    This feature is not available in TypeScript yet.  Stay tuned!
    ```
  </Tab>
</Tabs>

## Scorerの仕組み

### Scorerのキーワード引数

<Tabs>
  <Tab title="Python">
    ScorerはAIシステムからの出力とデータセット行からの入力データの両方にアクセスできます。

    * **Input:**Scorerがデータセット行から「label」や「target」列などのデータを使用するようにしたい場合は、Scorerの定義に`label`または`target`キーワード引数を追加することで簡単に利用できるようになります。

    例えば、データセットから「label」という列を使用したい場合、Scorer関数（または`score`クラスメソッド）のパラメータリストは次のようになります：

    ```python
    @weave.op
    def my_custom_scorer(output: str, label: int) -> dict:
        ...
    ```

    weave`Evaluation`が実行されると、AIシステムの出力が`output`パラメータに渡されます。`Evaluation`は自動的に追加のScorer引数名をデータセット列に一致させようとします。Scorer引数やデータセット列のカスタマイズが難しい場合は、列マッピングを使用できます - 詳細は以下をご覧ください。

    * **Output:**AIシステムの出力にアクセスするには、Scorer関数のシグネチャに`output`パラメータを含めてください。

    ### を使用した列名のマッピング`column_map`

    時々、`score`メソッドの引数名がデータセットの列名と一致しないことがあります。これは`column_map`を使用して修正できます。

    クラスベースのScorerを使用している場合は、Scorerクラスを初期化するときに`column_map`属性に辞書を渡します。この辞書は`Scorer`メソッドの引数名をデータセットの列名にマッピングします。順序は：`score`です。`{scorer_keyword_argument: dataset_column_name}`。

    Example:

    ```python
    import weave
    from weave import Scorer

    # A dataset with news articles to be summarised
    dataset = [
        {"news_article": "The news today was great...", "date": "2030-04-20", "source": "Bright Sky Network"},
        ...
    ]

    # Scorer class
    class SummarizationScorer(Scorer):

        @weave.op
        def score(self, output, text) -> dict:
            """
                output: output summary from a LLM summarization system
                text: the text being summarised
            """
            ...  # evaluate the quality of the summary

    # create a scorer with a column mapping the `text` argument to the `news_article` data column
    scorer = SummarizationScorer(column_map={"text" : "news_article"})
    ```

    これで、`text`メソッドの`score`引数は`news_article`データセット列からデータを受け取ります。

    **Notes:**

    * 列をマッピングするもう一つの同等のオプションは、`Scorer`をサブクラス化し、`score`メソッドをオーバーロードして列を明示的にマッピングすることです。

    ```python
    import weave
    from weave import Scorer

    class MySummarizationScorer(SummarizationScorer):

        @weave.op
        def score(self, output: str, news_article: str) -> dict:  # Added type hints
            # overload the score method and map columns manually
            return super().score(output=output, text=news_article)
    ```
  </Tab>

  <Tab title="TypeScript">
    ScorerはAIシステムからの出力とデータセット行の内容の両方にアクセスできます。

    Scorerの定義に`datasetRow`キーワード引数を追加することで、データセット行から関連する列に簡単にアクセスできます。

    ```typescript
    const myScorer = weave.op(
        ({modelOutput, datasetRow}) => {
            return modelOutput * 2 === datasetRow.expectedOutputTimesTwo;
        },
        {name: 'myScorer'}
    );
    ```

    ### を使用した列名のマッピング`columnMapping`

    <Warning>
      TypeScriptでは、この機能は現在個々のScorerではなく`Evaluation`オブジェクトにあります。
    </Warning>

    時々、`datasetRow`キーがScorerの命名スキームと完全に一致しないことがありますが、意味的には似ています。`Evaluation`の`columnMapping`オプションを使用して列をマッピングできます。

    マッピングは常にScorerの視点から行われます。つまり`{scorer_key: dataset_column_name}`です。

    Example:

    ```typescript
    const myScorer = weave.op(
        ({modelOutput, datasetRow}) => {
            return modelOutput * 2 === datasetRow.expectedOutputTimesTwo;
        },
        {name: 'myScorer'}
    );

    const myEval = new weave.Evaluation({
        dataset: [{expected: 2}],
        scorers: [myScorer],
        columnMapping: {expectedOutputTimesTwo: 'expected'}
    });
    ```
  </Tab>
</Tabs>

### Scorerの最終要約

<Tabs>
  <Tab title="Python">
    評価中、Scorerはデータセットの各行に対して計算されます。評価の最終スコアを提供するために、出力の戻り値の型に応じて`auto_summarize`を提供します。

    * 数値列の平均が計算されます
    * ブール列のカウントと割合
    * その他の列タイプは無視されます

    `summarize`メソッドを`Scorer`クラスでオーバーライドして、最終スコアを計算する独自の方法を提供できます。`summarize`関数は以下を期待します：

    * 単一のパラメータ`score_rows`：これは辞書のリストで、各辞書にはデータセットの単一行に対して`score`メソッドから返されたスコアが含まれています。
    * 要約されたスコアを含む辞書を返す必要があります。

    **なぜこれが役立つのか？**

    データセットのスコアの最終値を決定する前に、すべての行をスコアリングする必要がある場合。

    ```python
    class MyBinaryScorer(Scorer):
        """
        Returns True if the full output matches the target, False if not
        """

        @weave.op
        def score(self, output, target):
            return {"match": output == target}

        def summarize(self, score_rows: list) -> dict:
            full_match = all(row["match"] for row in score_rows)
            return {"full_match": full_match}
    ```

    > この例では、デフォルトの`auto_summarize`はTrueのカウントと割合を返していたでしょう。

    詳細を知りたい場合は、[CorrectnessLLMJudge](/ja/tutorial-rag#optional-defining-a-scorer-class)の実装をチェックしてください。
  </Tab>

  <Tab title="TypeScript">
    評価中、スコアラーはデータセットの各行に対して計算されます。最終スコアを提供するために、内部の`summarizeResults`関数を使用して、出力タイプに応じて集計します。

    * 数値列には平均が計算されます
    * ブール列にはカウントと割合が計算されます
    * その他の列タイプは無視されます

    現在、カスタム集計はサポートしていません。
  </Tab>
</Tabs>

### コールにスコアラーを適用する

Weave opsにスコアラーを適用するには、`.call()`メソッドを使用する必要があります。これにより、操作の結果とそのトラッキング情報の両方にアクセスできます。これにより、スコアラーの結果をWeaveのデータベース内の特定のコールに関連付けることができます。

メソッドの使用方法の詳細については、`.call()`ガイドの[Calling Ops](../tracking/tracing#calling-ops#getting-a-handle-to-the-call-object-during-execution)を参照してください。

<Tabs>
  <Tab title="Python">
    基本的な例を以下に示します：

    ```python
    # Get both result and Call object
    result, call = generate_text.call("Say hello")

    # Apply a scorer
    score = await call.apply_scorer(MyScorer())
    ```

    同じコールに複数のスコアラーを適用することもできます：

    ```python
    # Apply multiple scorers in parallel
    await asyncio.gather(
        call.apply_scorer(quality_scorer),
        call.apply_scorer(toxicity_scorer)
    )
    ```

    **Notes:**

    * スコアラーの結果は自動的にWeaveのデータベースに保存されます
    * スコアラーはメイン操作の完了後に非同期で実行されます
    * UIでスコアラーの結果を表示したり、APIを通じてクエリを実行したりできます

    ガードレールやモニターとしてスコアラーを使用する詳細情報（本番環境のベストプラクティスや完全な例を含む）については、[Guardrails and Monitors guide](./guardrails_and_monitors.mdx)を参照してください。
  </Tab>

  <Tab title="TypeScript">
    ```plaintext
    This feature is not available in TypeScript yet. Stay tuned!
    ```
  </Tab>
</Tabs>

### 使用`preprocess_model_input`

評価中にモデルに到達する前にデータセットの例を変更するには、`preprocess_model_input`パラメータを使用できます。

<Important>
  この`preprocess_model_input`関数は、モデルの予測関数に渡される前に入力を変換するだけです。

  スコアラー関数は常に、前処理が適用されていない元のデータセットの例を受け取ります。
</Important>

使用情報と例については、[評価前にデータセット行をフォーマットするための`preprocess_model_input`の使用](../core-types/evaluations.md#using-preprocess_model_input-to-format-dataset-rows-before-evaluating)を参照してください。

## スコア分析

このセクションでは、単一のコール、複数のコール、および特定のスコアラーによってスコアリングされたすべてのコールのスコアを分析する方法を示します。

### 単一のコールのスコアを分析する

#### 単一コールAPI

単一のコールのスコアを取得するには、`get_call`メソッドを使用できます。

```python
client = weave.init("my-project")

# Get a single call
call = client.get_call("call-uuid-here")

# Get the feedback for the call which contains the scores
feedback = list(call.feedback)
```

#### 単一コールUI

![Call Scores Tab](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/evaluation/img/call_scores_tab.png)

個々のコールのスコアは、コール詳細ページの「Scores」タブに表示されます。

### 複数のコールのスコアを分析する

#### 複数コールAPI

複数のコールのスコアを取得するには、`get_calls`メソッドを使用できます。

```python
client = weave.init("my-project")

# Get multiple calls - use whatever filters you want and include feedback
calls = client.get_calls(..., include_feedback=True)

# Iterate over the calls and access the feedback which contains the scores
for call in calls:
    feedback = list(call.feedback)
```

#### 複数コールUI

![Multiple Calls Tab](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/evaluation/img/traces_table_scores.png)

複数のコールのスコアは、トレーステーブルの「Scores」列に表示されます。

### 特定のスコアラーによってスコアリングされたすべてのコールを分析する

#### スコアラー別のすべてのコールAPI

特定のスコアラーによってスコアリングされたすべてのコールを取得するには、`get_calls`メソッドを使用できます。

```python
client = weave.init("my-project")

# To get all the calls scored by any version of a scorer, use the scorer name (typically the class name)
calls = client.get_calls(scored_by=["MyScorer"], include_feedback=True)

# To get all the calls scored by a specific version of a scorer, use the entire ref
# Refs can be obtained from the scorer object or via the UI.
calls = client.get_calls(scored_by=[myScorer.ref.uri()], include_feedback=True)

# Iterate over the calls and access the feedback which contains the scores
for call in calls:
    feedback = list(call.feedback)
```

#### スコアラー別のすべてのコールUI

最後に、スコアラーによってスコアリングされたすべてのコールを表示したい場合は、UIのScorersタブに移動し、「Programmatic Scorer」タブを選択します。スコアラーをクリックしてスコアラー詳細ページを開きます。

![Scorer Details Page](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/evaluation/img/scorer_detail_page.png)

次に、`View Traces`ボタンを`Scores`の下でクリックして、スコアラーによってスコアリングされたすべてのコールを表示します。

![Filtered Calls to Scorer Version](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/evaluation/img/filtered_calls_to_scorer_version.png)

これはデフォルトで選択されたバージョンのスコアラーになります。バージョンフィルターを削除して、スコアラーの任意のバージョンによってスコアリングされたすべてのコールを表示することができます。

![Filtered Calls to Scorer Name](https://mintlify.s3.us-west-1.amazonaws.com/wb-21fd5541-feature-automate-reference-docs-generation/ja/guides/evaluation/img/filtered_calls_scorer_name.png)
