Weave에서 Scorer는 AI 출력을 평가하고 평가 메트릭을 반환하는 데 사용됩니다. Scorer는 AI의 출력을 받아 분석하고 결과 사전을 반환합니다. Scorer는 필요한 경우 참조용으로 입력 데이터를 사용할 수 있으며, 평가에서 나온 설명이나 추론과 같은 추가 정보도 출력할 수 있습니다.
Scorer는 weave.Evaluation 객체에 평가 중에 전달됩니다. Weave에는 두 가지 유형의 Scorer가 있습니다:
  1. 함수 기반 Scorer: @weave.op로 장식된 간단한 Python 함수입니다.
  2. 클래스 기반 Scorer: weave.Scorer를 상속받는 Python 클래스로 더 복잡한 평가에 사용됩니다.
Scorer는 반드시 사전을 반환해야 하며, 여러 메트릭, 중첩된 메트릭, LLM-평가자가 추론에 대해 반환한 텍스트와 같은 비숫자 값을 반환할 수 있습니다.

자신만의 Scorer 만들기

바로 사용 가능한 Scorer 이 가이드에서는 사용자 정의 scorer를 만드는 방법을 보여주지만, Weave에는 다양한 predefined scorerslocal SLM scorers가 포함되어 있어 바로 사용할 수 있습니다. 다음과 같은 기능이 포함됩니다:

함수 기반 Scorer

이것들은 @weave.op로 장식된 함수로 사전을 반환합니다. 다음과 같은 간단한 평가에 적합합니다:
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는 텍스트가 모두 대문자인지 확인합니다.

클래스 기반 Scorer

더 고급 평가, 특히 추가 scorer 메타데이터를 추적하거나, LLM-평가자에 대해 다른 프롬프트를 시도하거나, 여러 함수 호출을 수행해야 할 때는 Scorer 클래스를 사용할 수 있습니다.Requirements:
  1. weave.Scorer에서 상속받습니다.
  2. score 메서드를 @weave.op로 장식하여 정의합니다.
  3. score 메서드는 반드시 사전을 반환해야 합니다.
Example:
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])
이 클래스는 요약이 원본 텍스트와 비교하여 얼마나 좋은지 평가합니다.

Scorer 작동 방식

Scorer 키워드 인수

Scorer는 AI 시스템의 출력과 데이터셋 행의 입력 데이터 모두에 접근할 수 있습니다.
  • Input: Scorer가 “label” 또는 “target” 열과 같은 데이터셋 행의 데이터를 사용하도록 하려면 label 또는 target 키워드 인수를 Scorer 정의에 추가하여 쉽게 사용할 수 있습니다.
예를 들어 데이터셋에서 “label”이라는 열을 사용하려면 Scorer 함수(또는 score 클래스 메서드)의 매개변수 목록이 다음과 같을 것입니다:
@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:
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 메서드를 오버로드하여 열을 명시적으로 매핑하는 것입니다.
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)

Scorer의 최종 요약

평가 중에 Scorer는 데이터셋의 각 행에 대해 계산됩니다. 평가에 대한 최종 점수를 제공하기 위해 출력 유형에 따라 auto_summarize를 제공합니다.
  • 숫자 열에 대해 평균이 계산됩니다
  • 부울 열에 대한 개수 및 비율
  • 다른 열 유형은 무시됩니다
summarize 클래스의 Scorer 메서드를 재정의하고 최종 점수를 계산하는 자신만의 방법을 제공할 수 있습니다. summarize 함수는 다음을 기대합니다:
  • 단일 매개변수 score_rows: 이것은 사전 목록으로, 각 사전에는 데이터셋의 단일 행에 대해 score 메서드가 반환한 점수가 포함되어 있습니다.
  • 요약된 점수가 포함된 사전을 반환해야 합니다.
이것이 유용한 이유는 무엇인가요?데이터셋에 대한 점수의 최종 값을 결정하기 전에 모든 행을 점수화해야 할 때 유용합니다.
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의 구현을 확인하세요.

호출에 스코러 적용하기

Weave 연산에 스코러를 적용하려면 .call() 메서드를 사용해야 합니다. 이 메서드는 연산 결과와 추적 정보 모두에 접근할 수 있게 해줍니다. 이를 통해 스코러 결과를 Weave 데이터베이스의 특정 호출과 연결할 수 있습니다. 메서드 사용 방법에 대한 자세한 정보는 .call() 메서드에 대한 정보는 Calling Ops 가이드를 참조하세요.
다음은 기본 예제입니다:
# Get both result and Call object
result, call = generate_text.call("Say hello")

# Apply a scorer
score = await call.apply_scorer(MyScorer())
동일한 호출에 여러 스코러를 적용할 수도 있습니다:
# 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를 참조하세요.

사용 preprocess_model_input

다음을 사용할 수 있습니다 preprocess_model_input 매개변수를 사용하여 평가 중에 모델에 도달하기 전에 데이터셋 예제를 수정할 수 있습니다. 사용 정보와 예제는 Using preprocess_model_input to format dataset rows before evaluating를 참조하세요.

점수 분석

이 섹션에서는 단일 호출, 여러 호출 및 특정 스코러로 점수가 매겨진 모든 호출에 대한 점수를 분석하는 방법을 보여드립니다.

단일 호출의 점수 분석

단일 호출 API

단일 호출에 대한 호출을 검색하려면 get_call 메서드를 사용할 수 있습니다.
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 개별 호출에 대한 점수는 호출 세부 정보 페이지의 “Scores” 탭 아래에 표시됩니다.

여러 호출의 점수 분석

여러 호출 API

여러 호출에 대한 호출을 검색하려면 get_calls 메서드를 사용할 수 있습니다.
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 여러 호출에 대한 점수는 추적 테이블의 “Scores” 열 아래에 표시됩니다.

특정 스코러로 점수가 매겨진 모든 호출 분석

스코러별 모든 호출 API

특정 스코러로 점수가 매겨진 모든 호출을 검색하려면 get_calls 메서드를 사용할 수 있습니다.
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 다음으로, View Traces 버튼을 클릭하세요 Scores 아래에서 스코러로 점수가 매겨진 모든 호출을 볼 수 있습니다. Filtered Calls to Scorer Version 이는 기본적으로 선택된 스코러 버전으로 설정됩니다. 버전 필터를 제거하여 스코러의 모든 버전으로 점수가 매겨진 모든 호출을 볼 수 있습니다. Filtered Calls to Scorer Name