Documentation Index
Fetch the complete documentation index at: https://translations.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
Weave는 환각 감지, 요약 품질과 같이 AI 애플리케이션을 평가하기 위한 여러 미리 정의된 스코어러를 제공합니다. 이를 활용하면 평가를 빠르게 정의하고 애플리케이션 출력에 점수를 매길 수 있습니다.
로컬 스코어러는 현재 Weave Python SDK에서만 사용할 수 있습니다. Weave TypeScript SDK에서는 아직 지원되지 않습니다.TypeScript에서 Weave 스코어러를 사용하려면 함수 기반 스코어러를 참고하세요.
Weave의 사전 정의된 스코어러를 사용하려면 몇 가지 추가 의존성을 설치해야 합니다.
pip install weave[scorers]
LLM-evaluators
2025년 2월 업데이트: LLM을 활용하는 사전 정의된 스코어러가 이제 자동으로 litellm과 통합됩니다.
더 이상 LLM 클라이언트를 넘겨줄 필요 없이 model_id만 설정하면 됩니다.
지원되는 모델 목록은 여기에서 확인하세요.
이 스코어러는 입력 데이터와 비교하여 AI 시스템의 출력 결과에 환각(hallucination)이 포함되어 있는지 확인합니다.
from weave.scorers import HallucinationFreeScorer
scorer = HallucinationFreeScorer()
사용자 정의:
system_prompt와 user_prompt 필드를 커스터마이즈하여 무엇을 “hallucination”으로 간주할지 직접 정의할 수 있습니다.
참고 사항:
score 메서드는 context라는 이름의 입력 컬럼을 사용한다고 가정합니다. 데이터셋에서 다른 이름을 사용하고 있다면, column_map 속성을 사용하여 context를 해당 데이터셋 컬럼에 매핑하십시오.
다음은 평가 과정에서의 예시입니다:
import asyncio
import weave
from weave.scorers import HallucinationFreeScorer
# 필요한 경우 열 매핑을 사용하여 scorer를 초기화합니다.
hallucination_scorer = HallucinationFreeScorer(
model_id="openai/gpt-4o", # 또는 litellm이 지원하는 다른 모델
column_map={"context": "input", "output": "other_col"}
)
# 데이터셋 생성
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."
# 평가 실행
evaluation = weave.Evaluation(
dataset=dataset,
scorers=[hallucination_scorer],
)
result = asyncio.run(evaluation.evaluate(model))
print(result)
# 출력 예시:
# {'HallucinationFreeScorer': {'has_hallucination': {'true_count': 2, 'true_fraction': 1.0}}, 'model_latency': {'mean': ...}}
LLM을 사용해 원본 텍스트와 요약을 비교하여 요약의 품질을 평가합니다.
from weave.scorers import SummarizationScorer
scorer = SummarizationScorer(
model_id="openai/gpt-4o" # 또는 litellm이 지원하는 다른 모델
)
작동 방식:
이 스코어러는 요약을 두 가지 방식으로 평가합니다.
- 엔터티 밀도(Entity Density): 요약에 언급된 고유 엔터티(이름, 장소, 사물 등)의 비율을 요약의 전체 단어 수와 비교하여 요약의 “정보 밀도”를 추정합니다. 엔터티 추출에는 LLM을 사용합니다. Chain of Density 논문(https://arxiv.org/abs/2309.04269)에서 정의한 엔터티 밀도 개념과 유사합니다.
- 품질 등급(Quality Grading): LLM 평가자가 요약을
poor, ok, excellent로 등급을 매깁니다. 그런 다음 이 등급을 성능 집계 평가를 위해 점수로 매핑합니다 (poor는 0.0, ok는 0.5, excellent는 1.0).
커스터마이징:
- 평가 과정을 조정하려면
summarization_evaluation_system_prompt와 summarization_evaluation_prompt를 수정하십시오.
참고 사항:
- 이 스코어러는 내부적으로 litellm을 사용합니다.
score 메서드는 원본 텍스트(요약 대상 텍스트)가 input 열에 존재한다고 가정합니다. 데이터셋에서 다른 이름을 사용한다면 column_map을 사용하십시오.
다음은 평가 컨텍스트에서의 사용 예시입니다:
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."
# 스코어러 초기화
summarization_scorer = SummarizationScorer(
model_id="openai/gpt-4o" # 또는 litellm이 지원하는 다른 모델
)
# 데이터셋 생성
dataset = [
{"input": "The quick brown fox jumps over the lazy dog."},
{"input": "Artificial Intelligence is revolutionizing various industries."}
]
# 평가 실행
evaluation = weave.Evaluation(dataset=dataset, scorers=[summarization_scorer])
results = asyncio.run(evaluation.evaluate(SummarizationModel()))
print(results)
# 출력 예시:
# {'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는 OpenAI의 Moderation API를 사용하여 AI 시스템의 출력 결과에 혐오 발언이나 노골적인(선정적인) 내용 등 허용되지 않는 콘텐츠가 포함되어 있는지 확인합니다.
from weave.scorers import OpenAIModerationScorer
scorer = OpenAIModerationScorer()
작동 방식:
- AI 출력을 OpenAI Moderation 엔드포인트로 전송하고, 콘텐츠가 플래그 처리되었는지 여부를 나타내는 구조화된 응답을 반환합니다.
참고 사항:
다음은 평가 맥락에서의 예시입니다:
import asyncio
import weave
from weave.scorers import OpenAIModerationScorer
class MyModel(weave.Model):
@weave.op
async def predict(self, input: str) -> str:
return input
# scorer 초기화
moderation_scorer = OpenAIModerationScorer()
# 데이터셋 생성
dataset = [
{"input": "I love puppies and kittens!"},
{"input": "I hate everyone and want to hurt them."}
]
# 평가 실행
evaluation = weave.Evaluation(dataset=dataset, scorers=[moderation_scorer])
results = asyncio.run(evaluation.evaluate(MyModel()))
print(results)
# 출력 예시:
# {'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 출력이 참조 텍스트와 얼마나 유사한지 측정할 수 있습니다.
from weave.scorers import EmbeddingSimilarityScorer
similarity_scorer = EmbeddingSimilarityScorer(
model_id="openai/text-embedding-3-small", # litellm이 지원하는 다른 모델도 사용 가능
threshold=0.4 # 코사인 유사도 임계값
)
매개변수:
threshold (float): 두 텍스트를 유사하다고 판단하는 데 필요한 최소 코사인 유사도 점수(-1에서 1 사이)입니다(기본값은 0.5).
사용 예:
다음 예시는 평가에서 EmbeddingSimilarityScorer를 사용하는 방법을 보여줍니다:
import asyncio
import weave
from weave.scorers import EmbeddingSimilarityScorer
# 스코어러 초기화
similarity_scorer = EmbeddingSimilarityScorer(
model_id="openai/text-embedding-3-small", # 또는 litellm이 지원하는 다른 모델
threshold=0.7
)
# 데이터셋 생성
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.",
},
]
# 모델 정의
@weave.op
def model(input: str) -> str:
return "John likes various types of cheese."
# 평가 실행
evaluation = weave.Evaluation(
dataset=dataset,
scorers=[similarity_scorer],
)
result = asyncio.run(evaluation.evaluate(model))
print(result)
# 출력 예시:
# {'EmbeddingSimilarityScorer': {'is_similar': {'true_count': 1, 'true_fraction': 0.5}, 'similarity_score': {'mean': 0.844851403}}, 'model_latency': {'mean': ...}}
ValidJSONScorer는 AI 시스템의 출력이 유효한 JSON 형식인지 확인합니다. 이 스코어러는 출력이 JSON 형식일 것으로 예상되고 그 유효성을 검증해야 할 때 유용합니다.
from weave.scorers import ValidJSONScorer
json_scorer = ValidJSONScorer()
다음은 평가 상황에서의 예시입니다:
import asyncio
import weave
from weave.scorers import ValidJSONScorer
class JSONModel(weave.Model):
@weave.op()
async def predict(self, input: str) -> str:
# 이것은 플레이스홀더입니다.
# 실제 시나리오에서는 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)
# 출력 예시:
# {'ValidJSONScorer': {'json_valid': {'true_count': 2, 'true_fraction': 1.0}}, 'model_latency': {'mean': ...}}
ValidXMLScorer는 AI 시스템의 출력이 유효한 XML인지 확인합니다. XML 형식의 출력을 기대할 때 유용합니다.
from weave.scorers import ValidXMLScorer
xml_scorer = ValidXMLScorer()
평가 맥락에서의 예시는 다음과 같습니다:
import asyncio
import weave
from weave.scorers import ValidXMLScorer
class XMLModel(weave.Model):
@weave.op()
async def predict(self, input: str) -> str:
# 이것은 플레이스홀더입니다. 실제 시나리오에서는 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)
# 출력 예시:
# {'ValidXMLScorer': {'xml_valid': {'true_count': 2, 'true_fraction': 1.0}}, 'model_latency': {'mean': ...}}
PydanticScorer는 AI 시스템이 생성한 결과가 Pydantic 모델이 정의한 스키마나 데이터 구조를 준수하는지 검증합니다.
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 평가 라이브러리를 기반으로 합니다.
from weave.scorers import ContextEntityRecallScorer
entity_recall_scorer = ContextEntityRecallScorer(
model_id="openai/gpt-4o"
)
동작 방식:
- LLM을 사용해 출력과 컨텍스트로부터 고유 엔티티를 추출하고 Recall을 계산합니다.
- Recall은 컨텍스트에 있는 중요한 엔티티 중 출력에 반영된 비율을 나타냅니다.
- Recall 점수를 포함한 딕셔너리를 반환합니다.
참고 사항:
RAGAS - ContextRelevancyScorer
ContextRelevancyScorer는 제공된 컨텍스트가 AI 시스템의 출력과 얼마나 관련성이 높은지 평가합니다. 이는 RAGAS 평가 라이브러리를 기반으로 합니다.
from weave.scorers import ContextRelevancyScorer
relevancy_scorer = ContextRelevancyScorer(
model_id="openai/gpt-4o", # 또는 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를 포함한 딕셔너리를 반환합니다.
참고:
- 데이터셋에
context 열이 있어야 합니다. 열 이름이 다르다면 column_map 속성을 사용하세요.
- 관련성을 어떻게 평가할지 정의하려면
relevancy_prompt를 사용자 정의하세요.
다음은 평가 과정에서의 사용 예시입니다.
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."
# 프롬프트 정의
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):
""")
# 스코어러 초기화
entity_recall_scorer = ContextEntityRecallScorer()
relevancy_scorer = ContextRelevancyScorer(relevancy_prompt=relevancy_prompt)
# 데이터셋 생성
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."
}
]
# 평가 실행
evaluation = weave.Evaluation(
dataset=dataset,
scorers=[entity_recall_scorer, relevancy_scorer]
)
results = asyncio.run(evaluation.evaluate(RAGModel()))
print(results)
# 출력 예시:
# {'ContextEntityRecallScorer': {'recall': {'mean': ...}},
# 'ContextRelevancyScorer': {'relevancy_score': {'mean': ...}},
# 'model_latency': {'mean': ...}}
참고: 기본 제공 스코어러는 openai/gpt-4o, openai/text-embedding-3-small 같은 OpenAI 모델을 사용하여 보정되었습니다. 다른 제공업체의 모델을 사용해 보고 싶다면 model_id 필드를 다른 모델로 변경하면 됩니다. 예를 들어 Anthropic 모델을 사용하려면 다음과 같이 설정할 수 있습니다:
from weave.scorers import SummarizationScorer
# Anthropic의 Claude 모델로 전환
summarization_scorer = SummarizationScorer(
model_id="anthropic/claude-3-5-sonnet-20240620"
)