> ## 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의 출력을 받아 분석하고 결과 사전을 반환합니다. Scorer는 필요한 경우 참조용으로 입력 데이터를 사용할 수 있으며, 평가에서 나온 설명이나 추론과 같은 추가 정보도 출력할 수 있습니다.

<Tabs>
  <Tab title="Python">
    Scorer는 `weave.Evaluation` 객체에 평가 중에 전달됩니다. Weave에는 두 가지 유형의 Scorer가 있습니다:

    1. **함수 기반 Scorer:** `@weave.op`로 장식된 간단한 Python 함수입니다.
    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">
    더 고급 평가, 특히 추가 scorer 메타데이터를 추적하거나, 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" 열과 같은 데이터셋 행의 데이터를 사용하도록 하려면 `label` 또는 `target` 키워드 인수를 Scorer 정의에 추가하여 쉽게 사용할 수 있습니다.

    예를 들어 데이터셋에서 "label"이라는 열을 사용하려면 Scorer 함수(또는 `score` 클래스 메서드)의 매개변수 목록이 다음과 같을 것입니다:

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

    weave `Evaluation`가 실행되면, AI 시스템의 출력이 `output` 매개변수로 전달됩니다. `Evaluation`는 또한 자동으로 추가 Scorer 인수 이름을 데이터셋 열과 일치시키려고 시도합니다. Scorer 인수나 데이터셋 열을 사용자 정의하는 것이 불가능한 경우, 열 매핑을 사용할 수 있습니다 - 자세한 내용은 아래를 참조하세요.

    * **Output:** Scorer 함수의 서명에 `output` 매개변수를 포함하여 AI 시스템의 출력에 접근할 수 있습니다.

    ### `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](/ko/tutorial-rag#optional-defining-a-scorer-class)의 구현을 확인하세요.
  </Tab>

  <Tab title="TypeScript">
    평가 중에는 데이터셋의 각 행에 대해 스코러가 계산됩니다. 최종 점수를 제공하기 위해 내부 `summarizeResults` 함수를 사용하여 출력 유형에 따라 집계합니다.

    * 수치형 열에 대해서는 평균이 계산됩니다
    * 불리언 열에 대해서는 개수와 비율이 계산됩니다
    * 다른 열 유형은 무시됩니다

    현재는 사용자 정의 요약을 지원하지 않습니다.
  </Tab>
</Tabs>

### 호출에 스코러 적용하기

Weave 연산에 스코러를 적용하려면 `.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>

사용 정보와 예제는 [Using `preprocess_model_input` to format dataset rows before evaluating](../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/ko/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/ko/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/ko/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/ko/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/ko/guides/evaluation/img/filtered_calls_scorer_name.png)
