> ## 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.

# Builtin scorers

<Tabs>
  <Tab title="Python">
    **설치**

    Weave의 사전 정의된 평가기(scorers)를 사용하려면 추가 종속성을 설치해야 합니다:

    ```bash
    pip install weave[scorers]
    ```

    **LLM-evaluators**2025년 2월 업데이트: LLM을 활용하는 사전 정의된 평가기는 이제 litellm과 자동으로 통합됩니다.
    더 이상 LLM 클라이언트를 전달할 필요가 없으며, 다음만 설정하면 됩니다 `model_id`.
    지원되는 모델 확인 [here](https://docs.litellm.ai/docs/providers).

    ## `HallucinationFreeScorer`

    이 평가기는 AI 시스템의 출력에 입력 데이터를 기반으로 한 환각(hallucinations)이 포함되어 있는지 확인합니다.

    ```python
    from weave.scorers import HallucinationFreeScorer

    scorer = HallucinationFreeScorer()
    ```

    **Customization:**

    * 평가기의 `system_prompt` 및 `user_prompt` 필드를 사용자 정의하여 귀하에게 "환각"이 무엇을 의미하는지 정의하세요.

    **Notes:**

    * 이 `score` 메서드는 `context`라는 이름의 입력 열을 예상합니다. 데이터셋이 다른 이름을 사용하는 경우, `column_map` 속성을 사용하여 `context`을 데이터셋 열에 매핑하세요.

    여기에 평가 맥락에서의 예시가 있습니다:

    ```python
    import asyncio
    import weave
    from weave.scorers import HallucinationFreeScorer

    # Initialize scorer with a column mapping if needed.
    hallucination_scorer = HallucinationFreeScorer(
        model_id="openai/gpt-4o", # or any other model supported by litellm
        column_map={"context": "input", "output": "other_col"}
    )

    # Create dataset
    dataset = [
        {"input": "John likes various types of cheese."},
        {"input": "Pepe likes various types of cheese."},
    ]

    @weave.op
    def model(input: str) -> str:
        return "The person's favorite cheese is cheddar."

    # Run evaluation
    evaluation = weave.Evaluation(
        dataset=dataset,
        scorers=[hallucination_scorer],
    )
    result = asyncio.run(evaluation.evaluate(model))
    print(result)
    # Example output:
    # {'HallucinationFreeScorer': {'has_hallucination': {'true_count': 2, 'true_fraction': 1.0}}, 'model_latency': {'mean': ...}}
    ```

    ***

    ## `SummarizationScorer`

    LLM을 사용하여 요약본을 원본 텍스트와 비교하고 요약의 품질을 평가합니다.

    ```python
    from weave.scorers import SummarizationScorer

    scorer = SummarizationScorer(
        model_id="openai/gpt-4o"  # or any other model supported by litellm
    )
    ```

    **작동 방식:**

    이 평가기는 두 가지 방식으로 요약을 평가합니다:

    1. **엔티티 밀도:** 요약에서 언급된 고유 엔티티(이름, 장소 또는 사물과 같은)의 비율을 요약의 총 단어 수로 나누어 요약의 "정보 밀도"를 추정합니다. LLM을 사용하여 엔티티를 추출합니다. Chain of Density 논문에서 엔티티 밀도가 사용되는 방식과 유사합니다, [https://arxiv.org/abs/2309.04269](https://arxiv.org/abs/2309.04269)
    2. **품질 등급:** LLM 평가자가 요약을 `poor`, `ok`, 또는 `excellent`로 등급을 매깁니다. 이러한 등급은 집계 성능 평가를 위해 점수(불량은 0.0, 양호는 0.5, 우수는 1.0)로 매핑됩니다.

    **Customization:**

    * 평가 과정을 조정하려면 `summarization_evaluation_system_prompt` 및 `summarization_evaluation_prompt`를 조정하세요.

    **Notes:**

    * 이 평가기는 내부적으로 litellm을 사용합니다.
    * 이 `score` 메서드는 원본 텍스트(요약되는 텍스트)가 `input` 열에 있을 것으로 예상합니다. 데이터셋이 다른 이름을 사용하는 경우 `column_map`를 사용하세요.

    여기에 평가 맥락에서의 사용 예시가 있습니다:

    ```python
    import asyncio
    import weave
    from weave.scorers import SummarizationScorer

    class SummarizationModel(weave.Model):
        @weave.op()
        async def predict(self, input: str) -> str:
            return "This is a summary of the input text."

    # Initialize scorer
    summarization_scorer = SummarizationScorer(
        model_id="openai/gpt-4o"  # or any other model supported by litellm
    )
    # Create dataset
    dataset = [
        {"input": "The quick brown fox jumps over the lazy dog."},
        {"input": "Artificial Intelligence is revolutionizing various industries."}
    ]
    # Run evaluation
    evaluation = weave.Evaluation(dataset=dataset, scorers=[summarization_scorer])
    results = asyncio.run(evaluation.evaluate(SummarizationModel()))
    print(results)
    # Example output:
    # {'SummarizationScorer': {'is_entity_dense': {'true_count': 0, 'true_fraction': 0.0}, 'summarization_eval_score': {'mean': 0.0}, 'entity_density': {'mean': 0.0}}, 'model_latency': {'mean': ...}}
    ```

    ***

    ## `OpenAIModerationScorer`

    이 `OpenAIModerationScorer`는 OpenAI의 Moderation API를 사용하여 AI 시스템의 출력에 혐오 발언이나 노골적인 자료와 같은 허용되지 않는 콘텐츠가 포함되어 있는지 확인합니다.

    ```python
    from weave.scorers import OpenAIModerationScorer

    scorer = OpenAIModerationScorer()
    ```

    **작동 방식:**

    * AI의 출력을 OpenAI Moderation 엔드포인트로 보내고 콘텐츠가 플래그 지정되었는지 여부를 나타내는 구조화된 응답을 반환합니다.

    **Notes:**
    다음은 평가 맥락에서의 예시입니다:

    ```python
    import asyncio
    import weave
    from weave.scorers import OpenAIModerationScorer

    class MyModel(weave.Model):
        @weave.op
        async def predict(self, input: str) -> str:
            return input

    # Initialize scorer
    moderation_scorer = OpenAIModerationScorer()

    # Create dataset
    dataset = [
        {"input": "I love puppies and kittens!"},
        {"input": "I hate everyone and want to hurt them."}
    ]

    # Run evaluation
    evaluation = weave.Evaluation(dataset=dataset, scorers=[moderation_scorer])
    results = asyncio.run(evaluation.evaluate(MyModel()))
    print(results)
    # Example output:
    # {'OpenAIModerationScorer': {'flagged': {'true_count': 1, 'true_fraction': 0.5}, 'categories': {'violence': {'true_count': 1, 'true_fraction': 1.0}}}, 'model_latency': {'mean': ...}}
    ```

    ***

    ## `EmbeddingSimilarityScorer`

    이 `EmbeddingSimilarityScorer`는 AI 시스템의 출력과 데이터셋의 대상 텍스트 간의 임베딩 코사인 유사도를 계산합니다. AI의 출력이 참조 텍스트와 얼마나 유사한지 측정하는 데 유용합니다.

    ```python
    from weave.scorers import EmbeddingSimilarityScorer

    similarity_scorer = EmbeddingSimilarityScorer(
        model_id="openai/text-embedding-3-small",  # or any other model supported by litellm
        threshold=0.4  # the cosine similarity threshold
    )
    ```

    Note: You can use `column_map`를 사용하여 `target` 열을 다른 이름에 매핑합니다.

    **Parameters:**

    * `threshold` (float): 두 텍스트가 유사하다고 간주하는 데 필요한 최소 코사인 유사도 점수(-1에서 1 사이)(기본값은 `0.5`).

    다음은 평가 맥락에서의 사용 예시입니다:

    ```python
    import asyncio
    import weave
    from weave.scorers import EmbeddingSimilarityScorer

    # Initialize scorer
    similarity_scorer = EmbeddingSimilarityScorer(
        model_id="openai/text-embedding-3-small",  # or any other model supported by litellm
        threshold=0.7
    )
    # Create dataset
    dataset = [
        {
            "input": "He's name is John",
            "target": "John likes various types of cheese.",
        },
        {
            "input": "He's name is Pepe.",
            "target": "Pepe likes various types of cheese.",
        },
    ]
    # Define model
    @weave.op
    def model(input: str) -> str:
        return "John likes various types of cheese."

    # Run evaluation
    evaluation = weave.Evaluation(
        dataset=dataset,
        scorers=[similarity_scorer],
    )
    result = asyncio.run(evaluation.evaluate(model))
    print(result)
    # Example output:
    # {'EmbeddingSimilarityScorer': {'is_similar': {'true_count': 1, 'true_fraction': 0.5}, 'similarity_score': {'mean': 0.844851403}}, 'model_latency': {'mean': ...}}
    ```

    ***

    ## `ValidJSONScorer`

    이 `ValidJSONScorer`는 AI 시스템의 출력이 유효한 JSON인지 확인합니다. 이 평가기는 출력이 JSON 형식이어야 하고 그 유효성을 확인해야 할 때 유용합니다.

    ```python
    from weave.scorers import ValidJSONScorer

    json_scorer = ValidJSONScorer()
    ```

    다음은 평가 맥락에서의 예시입니다:

    ```python
    import asyncio
    import weave
    from weave.scorers import ValidJSONScorer

    class JSONModel(weave.Model):
        @weave.op()
        async def predict(self, input: str) -> str:
            # This is a placeholder.
            # In a real scenario, this would generate JSON.
            return '{"key": "value"}'

    model = JSONModel()
    json_scorer = ValidJSONScorer()

    dataset = [
        {"input": "Generate a JSON object with a key and value"},
        {"input": "Create an invalid JSON"}
    ]

    evaluation = weave.Evaluation(dataset=dataset, scorers=[json_scorer])
    results = asyncio.run(evaluation.evaluate(model))
    print(results)
    # Example output:
    # {'ValidJSONScorer': {'json_valid': {'true_count': 2, 'true_fraction': 1.0}}, 'model_latency': {'mean': ...}}
    ```

    ***

    ## `ValidXMLScorer`

    이 `ValidXMLScorer`는 AI 시스템의 출력이 유효한 XML인지 확인합니다. XML 형식의 출력을 기대할 때 유용합니다.

    ```python
    from weave.scorers import ValidXMLScorer

    xml_scorer = ValidXMLScorer()
    ```

    다음은 평가 맥락에서의 예시입니다:

    ```python
    import asyncio
    import weave
    from weave.scorers import ValidXMLScorer

    class XMLModel(weave.Model):
        @weave.op()
        async def predict(self, input: str) -> str:
            # This is a placeholder. In a real scenario, this would generate XML.
            return '<root><element>value</element></root>'

    model = XMLModel()
    xml_scorer = ValidXMLScorer()

    dataset = [
        {"input": "Generate a valid XML with a root element"},
        {"input": "Create an invalid XML"}
    ]

    evaluation = weave.Evaluation(dataset=dataset, scorers=[xml_scorer])
    results = asyncio.run(evaluation.evaluate(model))
    print(results)
    # Example output:
    # {'ValidXMLScorer': {'xml_valid': {'true_count': 2, 'true_fraction': 1.0}}, 'model_latency': {'mean': ...}}
    ```

    ***

    ## `PydanticScorer`

    이 `PydanticScorer`는 AI 시스템의 출력을 Pydantic 모델과 비교하여 지정된 스키마나 데이터 구조를 준수하는지 확인합니다.

    ```python
    from weave.scorers import PydanticScorer
    from pydantic import BaseModel

    class FinancialReport(BaseModel):
        revenue: int
        year: str

    pydantic_scorer = PydanticScorer(model=FinancialReport)
    ```

    ***

    ## RAGAS - `ContextEntityRecallScorer`

    이 `ContextEntityRecallScorer`는 AI 시스템의 출력과 제공된 컨텍스트에서 엔티티를 추출한 다음 리콜 점수를 계산하여 컨텍스트 리콜을 추정합니다. 이는 [RAGAS](https://github.com/explodinggradients/ragas) 평가 라이브러리를 기반으로 합니다.

    ```python
    from weave.scorers import ContextEntityRecallScorer

    entity_recall_scorer = ContextEntityRecallScorer(
        model_id="openai/gpt-4o"
    )
    ```

    **작동 방식:**

    * LLM을 사용하여 출력과 컨텍스트에서 고유 엔티티를 추출하고 리콜을 계산합니다.
    * **Recall**은 컨텍스트에서 중요한 엔티티 중 출력에 포함된 비율을 나타냅니다.
    * 리콜 점수가 포함된 사전을 반환합니다.

    **Notes:**

    * 데이터셋에 `context` 열이 있을 것으로 예상합니다. 열 이름이 다른 경우 `column_map` 속성을 사용하세요.

    ***

    ## RAGAS - `ContextRelevancyScorer`

    이 `ContextRelevancyScorer`는 제공된 컨텍스트가 AI 시스템의 출력과 얼마나 관련이 있는지 평가합니다. 이는 [RAGAS](https://github.com/explodinggradients/ragas) 평가 라이브러리를 기반으로 합니다.

    ```python
    from weave.scorers import ContextRelevancyScorer

    relevancy_scorer = ContextRelevancyScorer(
        model_id="openai/gpt-4o",  # or any other model supported by litellm
        relevancy_prompt="""
    Given the following question and context, rate the relevancy of the context to the question on a scale from 0 to 1.

    Question: {question}
    Context: {context}
    Relevancy Score (0-1):
    """
    )
    ```

    **작동 방식:**

    * LLM을 사용하여 출력에 대한 컨텍스트의 관련성을 0에서 1까지의 척도로 평가합니다.
    * 다음이 포함된 사전을 반환합니다 `relevancy_score`.

    **Notes:**

    * 데이터셋에 `context` 열이 있을 것으로 예상합니다. 다른 이름이 사용되는 경우 `column_map`를 사용하세요.
    * 관련성 평가 방법을 정의하려면 `relevancy_prompt`를 사용자 정의하세요.

    다음은 평가 맥락에서의 사용 예시입니다:

    ```python
    import asyncio
    from textwrap import dedent
    import weave
    from weave.scorers import ContextEntityRecallScorer, ContextRelevancyScorer

    class RAGModel(weave.Model):
        @weave.op()
        async def predict(self, question: str) -> str:
            "Retrieve relevant context"
            return "Paris is the capital of France."

    # Define prompts
    relevancy_prompt: str = dedent("""
        Given the following question and context, rate the relevancy of the context to the question on a scale from 0 to 1.

        Question: {question}
        Context: {context}
        Relevancy Score (0-1):
        """)
    # Initialize scorers
    entity_recall_scorer = ContextEntityRecallScorer()
    relevancy_scorer = ContextRelevancyScorer(relevancy_prompt=relevancy_prompt)
    # Create dataset
    dataset = [
        {
            "question": "What is the capital of France?",
            "context": "Paris is the capital city of France."
        },
        {
            "question": "Who wrote Romeo and Juliet?",
            "context": "William Shakespeare wrote many famous plays."
        }
    ]
    # Run evaluation
    evaluation = weave.Evaluation(
        dataset=dataset,
        scorers=[entity_recall_scorer, relevancy_scorer]
    )
    results = asyncio.run(evaluation.evaluate(RAGModel()))
    print(results)
    # Example output:
    # {'ContextEntityRecallScorer': {'recall': {'mean': ...}}, 
    # 'ContextRelevancyScorer': {'relevancy_score': {'mean': ...}}, 
    # 'model_latency': {'mean': ...}}
    ```
  </Tab>

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

**Note:** 내장 평가기는 OpenAI 모델(예: `openai/gpt-4o`, `openai/text-embedding-3-small`)을 사용하여 보정되었습니다. 다른 제공업체를 실험하고 싶다면 간단히 `model_id`를 업데이트하면 됩니다. 예를 들어, Anthropic 모델을 사용하려면:

```python
from weave.scorers import SummarizationScorer

# Switch to Anthropic's Claude model
summarization_scorer = SummarizationScorer(
    model_id="anthropic/claude-3-5-sonnet-20240620"
)
```
