메트릭에서 프롬프트 수정하기

메트릭에서 프롬프트 수정하기

LLM을 사용하는 Ragas의 모든 메트릭은 점수를 만드는 데 필요한 중간 결과를 생성할 때 하나 이상의 프롬프트를 사용해요. LLM 기반 메트릭을 쓸 때 이 프롬프트를 하이퍼파라미터처럼 다룰 수 있어요. 도메인과 사용 사례에 맞게 최적화된 프롬프트는 LLM 기반 메트릭의 정확도를 10~20%까지 높여줄 수 있어요. 최적의 프롬프트는 사용하는 LLM에 따라 달라지기 때문에, 각 메트릭을 구동하는 프롬프트를 조정해 보고 싶을 거예요.

Quick start : 단순한 커스텀 메트릭이 필요하다면 DiscreteMetric 이나 NumericMetric 을 고려해 보세요. 이들은 커스텀 프롬프트를 직접 받아요. 예시는 Discrete Metrics 문서에서 확인할 수 있어요.

이 가이드는 BasePrompt 클래스를 사용하는 기존 컬렉션 메트릭(예: Faithfulness, FactualCorrectness)에서 프롬프트를 수정하는 방법을 다뤄요. 계속 진행하기 전에 Prompt Object 문서를 이해하고 있는지 확인해 주세요.

출처: 문서

본문

메트릭의 프롬프트 이해하기

프롬프트 커스터마이징을 지원하는 메트릭에서 Ragas는 메트릭 인스턴스를 통해 내부 프롬프트 객체에 접근할 수 있게 해줘요. Faithfulness 메트릭에서 프롬프트에 접근하는 방법을 볼게요.

from ragas.metrics.collections import Faithfulness
from openai import AsyncOpenAI
from ragas.llms import llm_factory

# Setup dependencies
client = AsyncOpenAI()
llm = llm_factory("gpt-4o-mini", client=client)

# Create metric instance
scorer = Faithfulness(llm=llm)

# Faithfulness has two prompts:
# 1. statement_generator_prompt - breaks response into atomic statements
# 2. nli_statement_prompt - evaluates each statement against context
print(scorer.statement_generator_prompt)
print(scorer.nli_statement_prompt)

프롬프트 문자열 생성 및 확인

LLM으로 전송될 프롬프트를 확인해 볼게요.

from ragas.metrics.collections.faithfulness.util import StatementGeneratorInput

# Create sample input
sample_input = StatementGeneratorInput(
    question="What is the Eiffel Tower?",
    answer="The Eiffel Tower is located in Paris."
)

# Generate the prompt string
prompt_string = scorer.statement_generator_prompt.to_string(sample_input)
print(prompt_string)

프롬프트 수정하기

Ragas의 최신 메트릭은 모듈형 BasePrompt 클래스를 사용해요. 프롬프트를 커스터마이징하는 방법은 다음과 같아요.

  • 프롬프트 접근하기 : 프롬프트는 메트릭 인스턴스의 속성으로 사용할 수 있어요
  • 프롬프트 클래스 수정하기 : instruction이나 examples를 커스터마이징하려면 프롬프트를 확장하거나 서브클래싱해요
  • 메트릭 업데이트하기 : 커스텀 프롬프트를 메트릭의 속성에 할당해요

예시: FactualCorrectness 프롬프트 커스터마이징

FactualCorrectness 는 내부적으로 두 개의 프롬프트를 사용해요.

  • prompt - 텍스트를 claim으로 분해하는 ClaimDecompositionPrompt
  • nli_prompt - context를 기준으로 claim을 검증하는 NLIStatementPrompt

둘 중 하나 또는 둘 다 커스터마이징할 수 있어요.

from ragas.metrics.collections import FactualCorrectness
from ragas.metrics.collections.factual_correctness.util import (
    ClaimDecompositionPrompt,
    NLIStatementPrompt,
)

# Create a custom claim decomposition prompt by subclassing
class CustomClaimDecompositionPrompt(ClaimDecompositionPrompt):
    instruction = """You are an expert at breaking down complex statements into atomic claims.
Break down the input text into clear, verifiable claims.
Only output valid JSON with a "claims" array."""

# Optionally customize the NLI prompt too
class CustomNLIPrompt(NLIStatementPrompt):
    instruction = """Carefully evaluate if each statement is supported by the context.
Be strict in your verification - only mark as supported if directly stated."""

# Create metric instance and replace prompts
scorer = FactualCorrectness(llm=llm)
scorer.prompt = CustomClaimDecompositionPrompt()
scorer.nli_prompt = CustomNLIPrompt()

# Now the metric will use the custom prompts
result = await scorer.ascore(
    response="The Eiffel Tower is in Paris and was built in 1889.",
    reference="The Eiffel Tower is located in Paris. It was completed in 1889."
)

예시: Faithfulness examples 커스터마이징

Few-shot 예시는 LLM 출력에 큰 영향을 줄 수 있어요. 이를 수정하는 방법은 다음과 같아요.

from ragas.metrics.collections import Faithfulness
from ragas.metrics.collections.faithfulness.util import (
    NLIStatementInput,
    NLIStatementOutput,
    NLIStatementPrompt,
    StatementFaithfulnessAnswer,
)

# Create custom prompt with domain-specific examples
class DomainSpecificNLIPrompt(NLIStatementPrompt):
    examples = [
        (
            NLIStatementInput(
                context="Machine learning is a field within artificial intelligence that enables systems to learn from data.",
                statements=[
                    "Machine learning is a subset of AI.",
                    "Machine learning uses statistical techniques.",
                ],
            ),
            NLIStatementOutput(
                statements=[
                    StatementFaithfulnessAnswer(
                        statement="Machine learning is a subset of AI.",
                        reason="The context states ML is 'a field within artificial intelligence', supporting this claim.",
                        verdict=1
                    ),
                    StatementFaithfulnessAnswer(
                        statement="Machine learning uses statistical techniques.",
                        reason="The context doesn't mention statistical techniques.",
                        verdict=0
                    ),
                ]
            ),
        ),
    ]

# Update the metric with custom prompt
scorer = Faithfulness(llm=llm)
scorer.nli_statement_prompt = DomainSpecificNLIPrompt()

# Now evaluate with domain-specific prompts
result = await scorer.ascore(
    user_input="How do neural networks work?",
    response="Neural networks are inspired by biological neurons.",
    retrieved_contexts=["Artificial neural networks are computing systems loosely inspired by biological neural networks."]
)

프롬프트를 다른 언어로 적용하기

adapt 메서드를 사용하면 프롬프트를 다른 언어로 적용할 수 있어요.

from ragas.metrics.collections import Faithfulness

scorer = Faithfulness(llm=llm)

# Adapt the statement generator prompt to Spanish
adapted_prompt = await scorer.statement_generator_prompt.adapt(
    target_language="spanish",
    llm=llm,
    adapt_instruction=False  # Keep instruction in English, only translate examples
)

# Replace the prompt with the adapted version
scorer.statement_generator_prompt = adapted_prompt

# Now use the metric with Spanish examples
result = await scorer.ascore(
    user_input="¿Dónde nació Einstein?",
    response="Einstein nació en Alemania.",
    retrieved_contexts=["Albert Einstein nació en Alemania..."]
)

커스터마이징 검증하기

프롬프트 커스터마이징이 제대로 동작하는지 확인하는 방법은 다음과 같아요.

from ragas.metrics.collections.faithfulness.util import NLIStatementInput

# Create sample input to test the prompt
sample_input = NLIStatementInput(
    context="Paris is the capital and most populous city of France.",
    statements=["The capital of France is Paris.", "Paris is in Germany."]
)

# Generate and view the full prompt string
full_prompt = scorer.nli_statement_prompt.to_string(sample_input)
print("Full Prompt:")
print(full_prompt)

더 알아보기 (Learn more)