메인 콘텐츠로 건너뛰기
이것은 인터랙티브 노트북입니다. 로컬에서 실행하거나 아래 링크를 사용할 수 있습니다:

Scorers as Guardrails

Weave Scorers는 call의 성능을 평가할 수 있는 score 메소드를 가진 특수 클래스입니다. 아주 간단한 규칙부터 복잡한 LLM-as-a-judge 방식까지 다양하게 활용될 수 있습니다. 이 노트북에서는 LLM이 유해하거나 부적절한 콘텐츠를 생성하지 않도록 방지하는 가드레일(guardrails)로 Scorers를 사용하는 방법을 살펴보겠습니다.
%pip install weave --quiet
python
"""
Weave에서 가드레일을 구현하는 방법을 보여주는 예시입니다.
이 예시는 잠재적으로 유해하거나 부정적인 응답을 방지하는 간단한 콘텐츠 안전 검사기를 보여줍니다.
"""

import weave

# 설명적인 프로젝트 이름으로 Weave 초기화
weave.init("content-safety-guardrails")

class ContentSafetyScorer(weave.Scorer):
    """지정된 문구의 포함 여부에 따라 콘텐츠 안전성을 평가하는 scorer입니다."""

    unsafe_phrases: list[str]
    case_sensitive: bool = False

    @weave.op
    def score(self, output: str) -> bool:
        """
        안전하지 않은 문구의 포함 여부에 따라 출력물의 안전성을 평가합니다.

        Args:
            output: 평가할 텍스트 출력물

        Returns:
            bool: 출력이 안전하면 True, 안전하지 않으면 False
        """
        normalized_output = output if self.case_sensitive else output.lower()

        for phrase in self.unsafe_phrases:
            normalized_phrase = phrase if self.case_sensitive else phrase.lower()
            if normalized_phrase in normalized_output:
                return False
        return True

@weave.op
def generate_response(prompt: str) -> str:
    """LLM 응답 생성을 시뮬레이션합니다."""
    if "test" in prompt.lower():
        return "I'm sorry, I cannot process that request."
    elif "help" in prompt.lower():
        return "I'd be happy to help you with that!"
    else:
        return "Here's what you requested: " + prompt

async def process_with_guardrail(prompt: str) -> str:
    """
    콘텐츠 안전 가드레일을 사용하여 사용자 입력을 처리합니다.
    안전한 경우 응답을 반환하고, 안전하지 않은 경우 대체 메시지를 반환합니다.
    """
    # 안전 scorer 초기화
    safety_scorer = ContentSafetyScorer(
        name="Content Safety Checker",
        unsafe_phrases=["sorry", "cannot", "unable", "won't", "will not"],
    )

    # 응답 생성 및 Call 오브젝트 획득
    response, call = generate_response.call(prompt)

    # 안전성 스코어링 적용
    evaluation = await call.apply_scorer(safety_scorer)

    # 안전성 체크 결과에 따라 응답 또는 대체 메시지 반환
    if evaluation.result:
        return response
    else:
        return "I cannot provide that response."
python
"""가드레일 시스템 사용 예시입니다."""
test_prompts = [
    "Please help me with my homework",
    "Can you run a test for me?",
    "Tell me a joke",
]

print("Testing content safety guardrails:\n")

for prompt in test_prompts:
    print(f"Input: '{prompt}'")
    response = await process_with_guardrail(prompt)
    print(f"Response: {response}\n")