이 노트북은 대화형입니다. 로컬에서 실행하거나 아래 링크를 사용할 수 있습니다:
가드레일로서의 Scorer
score 메서드를 가진 특수한 클래스입니다. 간단한 규칙부터 판사 역할을 하는 복잡한 LLM까지 다양할 수 있습니다.
이 노트북에서는 Scorer를 가드레일로 활용하여 LLM이 유해하거나 부적절한 콘텐츠를 생성하지 못하도록 하는 방법을 살펴보겠습니다.
잘못된 코드 신고
복사
AI에게 묻기
%pip install weave --quiet
python
"""
Weave에서 가드레일을 구현하는 방법을 보여주는 예제입니다.
이 예제는 잠재적으로 유해하거나 부정적인 응답을 방지하는
간단한 콘텐츠 안전 검사기를 보여줍니다.
"""
import weave
# 프로젝트 이름을 지정하여 Weave 초기화
weave.init("content-safety-guardrails")
class ContentSafetyScorer(weave.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:
"""
콘텐츠 안전 가드레일을 적용하여 사용자 입력을 처리합니다.
안전한 경우 응답을 반환하고, 안전하지 않은 경우 대체 메시지를 반환합니다.
"""
# 안전 스코어러 초기화
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("콘텐츠 안전 가드레일 테스트:\n")
for prompt in test_prompts:
print(f"Input: '{prompt}'")
response = await process_with_guardrail(prompt)
print(f"Response: {response}\n")