Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Japanese Specification for Answer Relevance #1387

Open
1 task done
TakutoIyanagi-littletree opened this issue Sep 30, 2024 · 8 comments
Open
1 task done

Japanese Specification for Answer Relevance #1387

TakutoIyanagi-littletree opened this issue Sep 30, 2024 · 8 comments
Labels
question Further information is requested

Comments

@TakutoIyanagi-littletree
  • I have checked the documentation and related resources and couldn't resolve my bug.

Your Question
I would like to use Answer Relevance for RAG evaluation in Japanese.
However, when I run it, the question is generated in English.
Is it possible to specify Japanese as the language in Answer Relevance?

Code Examples

import openai
from ragas.experimental.metrics._faithfulness import FaithfulnessExperimental
from ragas.metrics.base import get_segmenter
from ragas.llms import llm_factory
from ragas import evaluate
from datasets import Dataset
from ragas.metrics import (
    answer_relevancy,
)

# Ragasの評価用LLMの設定
LLM_NAME = "gpt-4o-mini"
ragas_llm = llm_factory(model=LLM_NAME)

dataset = Dataset.from_dict(
    {
        "question": questions,
        "answer": answers,
        "contexts": contexts,
        "ground_truth": ground_truths,
    }
) 

score = evaluate(
    dataset,
    llm=ragas_llm,
    metrics=[
        answer_relevancy,
        ],
                 )
print(score)
score.to_pandas()
@TakutoIyanagi-littletree TakutoIyanagi-littletree added the question Further information is requested label Sep 30, 2024
Copy link

dosubot bot commented Sep 30, 2024

Yes, it is possible to specify Japanese as the language in Answer Relevance for RAG evaluation. The ResponseRelevancy class in the ragas framework includes a method called adapt that allows the metric to be adapted to different languages, including Japanese. This method ensures that the question generation prompt and other relevant components are adjusted to work with the specified language [1][2].

To configure it, you need to adapt the ResponseRelevancy metric to Japanese. Here is an example of how you can modify your code:

import openai
from ragas.experimental.metrics._faithfulness import FaithfulnessExperimental
from ragas.metrics.base import get_segmenter
from ragas.llms import llm_factory
from ragas import evaluate
from datasets import Dataset
from ragas.metrics import (
    ResponseRelevancy,
)

# Ragasの評価用LLMの設定
LLM_NAME = "gpt-4o-mini"
ragas_llm = llm_factory(model=LLM_NAME)

# Adapt the ResponseRelevancy metric to Japanese
answer_relevancy = ResponseRelevancy()
answer_relevancy.adapt(language="japanese")

dataset = Dataset.from_dict(
    {
        "question": questions,
        "answer": answers,
        "contexts": contexts,
        "ground_truth": ground_truths,
    }
) 

score = evaluate(
    dataset,
    llm=ragas_llm,
    metrics=[
        answer_relevancy,
    ],
)
print(score)
score.to_pandas()

This should ensure that the questions are generated in Japanese.

To continue talking to Dosu, mention @dosu.

@TakutoIyanagi-littletree
Copy link
Author

The following error occurred.
ImportError: cannot import name 'ResponseRelevancy' from 'ragas.metrics' (/usr/local/lib/python3.10/dist-packages/ragas/metrics/init.py)

Copy link

dosubot bot commented Sep 30, 2024

To resolve the ImportError: cannot import name 'ResponseRelevancy' from 'ragas.metrics', you should ensure that the ResponseRelevancy class is correctly imported from its actual location. The ResponseRelevancy class is defined in the src/ragas/metrics/_answer_relevance.py file.

Here is the correct way to import the ResponseRelevancy class:

from ragas.metrics._answer_relevance import ResponseRelevancy

Update your code to use this import statement:

import openai
from ragas.experimental.metrics._faithfulness import FaithfulnessExperimental
from ragas.metrics.base import get_segmenter
from ragas.llms import llm_factory
from ragas import evaluate
from datasets import Dataset
from ragas.metrics._answer_relevance import ResponseRelevancy

# Ragasの評価用LLMの設定
LLM_NAME = "gpt-4o-mini"
ragas_llm = llm_factory(model=LLM_NAME)

# Adapt the ResponseRelevancy metric to Japanese
answer_relevancy = ResponseRelevancy()
answer_relevancy.adapt(language="japanese")

dataset = Dataset.from_dict(
    {
        "question": questions,
        "answer": answers,
        "contexts": contexts,
        "ground_truth": ground_truths,
    }
) 

score = evaluate(
    dataset,
    llm=ragas_llm,
    metrics=[
        answer_relevancy,
    ],
)
print(score)
score.to_pandas()

This should resolve the import error and allow you to adapt the ResponseRelevancy metric to Japanese [1].

To continue talking to Dosu, mention @dosu.

@TakutoIyanagi-littletree
Copy link
Author

The following error occurred.

ImportError: cannot import name 'ResponseRelevancy' from 'ragas.metrics._answer_relevance' (/usr/local/lib/python3.10/dist-packages/ragas/metrics/_answer_relevance.py)

Copy link

dosubot bot commented Sep 30, 2024

To resolve the ImportError: cannot import name 'ResponseRelevancy' from 'ragas.metrics._answer_relevance', ensure that the ResponseRelevancy class is correctly defined and available for import in the ragas.metrics._answer_relevance module.

Here is the corrected version of the ragas.metrics._answer_relevance module with a single definition of the ResponseRelevancy class:

from __future__ import annotations

import logging
import typing as t
from dataclasses import dataclass, field

import numpy as np
from langchain_core.pydantic_v1 import BaseModel

from ragas.dataset_schema import SingleTurnSample
from ragas.llms.output_parser import RagasoutputParser, get_json_format_instructions
from ragas.llms.prompt import Prompt
from ragas.metrics.base import (
    MetricType,
    MetricWithEmbeddings,
    MetricWithLLM,
    SingleTurnMetric,
)

logger = logging.getLogger(__name__)

if t.TYPE_CHECKING:
    from langchain_core.callbacks import Callbacks

    from ragas.llms.prompt import PromptValue

class ResponseRelevanceClassification(BaseModel):
    question: str
    noncommittal: int

_output_instructions = get_json_format_instructions(
    pydantic_object=ResponseRelevanceClassification
)
_output_parser = RagasoutputParser(pydantic_object=ResponseRelevanceClassification)

@dataclass
class ResponseRelevancy(MetricWithLLM, MetricWithEmbeddings, SingleTurnMetric):
    """
    Scores the relevancy of the answer according to the given question.
    Answers with incomplete, redundant or unnecessary information is penalized.
    Score can range from 0 to 1 with 1 being the best.

    Attributes
    ----------
    name: string
        The name of the metrics
    strictness: int
        Here indicates the number questions generated per answer.
        Ideal range between 3 to 5.
    embeddings: Embedding
        The langchain wrapper of Embedding object.
        E.g. HuggingFaceEmbeddings('BAAI/bge-base-en')
    """

    name: str = "answer_relevancy"  # type: ignore
    _required_columns: t.Dict[MetricType, t.Set[str]] = field(
        default_factory=lambda: {
            MetricType.SINGLE_TURN: {
                "user_input",
                "response",
                "retrieved_contexts",
            }
        }
    )
    question_generation: Prompt = field(default_factory=lambda: QUESTION_GEN)
    strictness: int = 3

    def calculate_similarity(
        self: t.Self, question: str, generated_questions: list[str]
    ):
        assert self.embeddings is not None
        question_vec = np.asarray(self.embeddings.embed_query(question)).reshape(1, -1)
        gen_question_vec = np.asarray(
            self.embeddings.embed_documents(generated_questions)
        ).reshape(len(generated_questions), -1)
        norm = np.linalg.norm(gen_question_vec, axis=1) * np.linalg.norm(
            question_vec, axis=1
        )
        return (
            np.dot(gen_question_vec, question_vec.T).reshape(
                -1,
            )
            / norm
        )

    def _calculate_score(
        self, answers: t.Sequence[ResponseRelevanceClassification], row: t.Dict
    ) -> float:
        question = row["user_input"]
        gen_questions = [answer.question for answer in answers]
        committal = np.any([answer.noncommittal for answer in answers])
        if all(q == "" for q in gen_questions):
            logger.warning(
                "Invalid JSON response. Expected dictionary with key 'question'"
            )
            score = np.nan
        else:
            cosine_sim = self.calculate_similarity(question, gen_questions)
            score = cosine_sim.mean() * int(not committal)

        return score

    def _create_question_gen_prompt(self, row: t.Dict) -> PromptValue:
        ans, ctx = row["response"], row["retrieved_contexts"]
        return self.question_generation.format(answer=ans, context="\n".join(ctx))

    async def _single_turn_ascore(
        self, sample: SingleTurnSample, callbacks: Callbacks
    ) -> float:
        row = sample.dict()
        return await self._ascore(row, callbacks)

    async def _ascore(self, row: t.Dict, callbacks: Callbacks) -> float:
        assert self.llm is not None, "LLM is not set"

        prompt = self._create_question_gen_prompt(row)
        result = await self.llm.generate(
            prompt,
            n=self.strictness,
            callbacks=callbacks,
        )

        answers = [
            await _output_parser.aparse(result.text, prompt, self.llm)
            for result in result.generations[0]
        ]
        if any(answer is None for answer in answers):
            return np.nan

        answers = [answer for answer in answers if answer is not None]
        return self._calculate_score(answers, row)

    def adapt(self, language: str, cache_dir: str | None = None) -> None:
        assert self.llm is not None, "LLM is not set"

        logger.info(f"Adapting AnswerRelevancy metric to {language}")
        self.question_generation = self.question_generation.adapt(
            language, self.llm, cache_dir
        )

    def save(self, cache_dir: str | None = None) -> None:
        self.question_generation.save(cache_dir)

class AnswerRelevancy(ResponseRelevancy):
    async def _ascore(self, row: t.Dict, callbacks: Callbacks) -> float:
        return await super()._ascore(row, callbacks)

answer_relevancy = AnswerRelevancy()
QUESTION_GEN = Prompt(
    name="question_generation",
    instruction="""Generate a question for the given answer and Identify if answer is noncommittal. Give noncommittal as 1 if the answer is noncommittal and 0 if the answer is committal. A noncommittal answer is one that is evasive, vague, or ambiguous. For example, "I don't know" or "I'm not sure" are noncommittal answers""",
    output_format_instruction=_output_instructions,
    examples=[
        {
            "answer": """Albert Einstein was born in Germany.""",
            "context": """Albert Einstein was a German-born theoretical physicist who is widely held to be one of the greatest and most influential scientists of all time""",
            "output": ResponseRelevanceClassification.parse_obj(
                {
                    "question": "Where was Albert Einstein born?",
                    "noncommittal": 0,
                }
            ).dict(),
        },
        {
            "answer": """It can change its skin color based on the temperature of its environment.""",
            "context": """A recent scientific study has discovered a new species of frog in the Amazon rainforest that has the unique ability to change its skin color based on the temperature of its environment.""",
            "output": ResponseRelevanceClassification.parse_obj(
                {
                    "question": "What unique ability does the newly discovered species of frog have?",
                    "noncommittal": 0,
                }
            ).dict(),
        },
        {
            "answer": """Everest""",
            "context": """The tallest mountain on Earth, measured from sea level, is a renowned peak located in the Himalayas.""",
            "output": ResponseRelevanceClassification.parse_obj(
                {
                    "question": "What is the tallest mountain on Earth?",
                    "noncommittal": 0,
                }
            ).dict(),
        },
        {
            "answer": """I don't know about the  groundbreaking feature of the smartphone invented in 2023 as am unaware of information beyond 2022. """,
            "context": """In 2023, a groundbreaking invention was announced: a smartphone with a battery life of one month, revolutionizing the way people use mobile technology.""",
            "output": ResponseRelevanceClassification.parse_obj(
                {
                    "question": "What was the groundbreaking feature of the smartphone invented in 2023?",
                    "noncommittal": 1,
                }
            ).dict(),
        },
    ],
    input_keys=["answer", "context"],
    output_key="output",
    output_type="json",
)

Ensure that you have this corrected version of the module and then try importing ResponseRelevancy again. This should resolve the ImportError [1].

To continue talking to Dosu, mention @dosu.

@TakutoIyanagi-littletree
Copy link
Author

Is the ResponseRelevancy feature still not included in Ragas version 0.1.20 installed via pip?

Copy link

dosubot bot commented Sep 30, 2024

Yes, the ResponseRelevancy feature is included in Ragas version 0.1.20 installed via pip [1].

To continue talking to Dosu, mention @dosu.

@TakutoIyanagi-littletree
Copy link
Author

To resolve the ImportError: cannot import name 'ResponseRelevancy' from 'ragas.metrics', you should ensure that the ResponseRelevancy class is correctly imported from its actual location. The ResponseRelevancy class is defined in the src/ragas/metrics/_answer_relevance.py file.

Here is the correct way to import the ResponseRelevancy class:

from ragas.metrics._answer_relevance import ResponseRelevancy

Update your code to use this import statement:

import openai
from ragas.experimental.metrics._faithfulness import FaithfulnessExperimental
from ragas.metrics.base import get_segmenter
from ragas.llms import llm_factory
from ragas import evaluate
from datasets import Dataset
from ragas.metrics._answer_relevance import ResponseRelevancy

# Ragasの評価用LLMの設定
LLM_NAME = "gpt-4o-mini"
ragas_llm = llm_factory(model=LLM_NAME)

# Adapt the ResponseRelevancy metric to Japanese
answer_relevancy = ResponseRelevancy()
answer_relevancy.adapt(language="japanese")

dataset = Dataset.from_dict(
    {
        "question": questions,
        "answer": answers,
        "contexts": contexts,
        "ground_truth": ground_truths,
    }
) 

score = evaluate(
    dataset,
    llm=ragas_llm,
    metrics=[
        answer_relevancy,
    ],
)
print(score)
score.to_pandas()

This should resolve the import error and allow you to adapt the ResponseRelevancy metric to Japanese [1].

To continue talking to Dosu, mention @dosu.

The following error occurred.

NotImplementedError: adapt() is not implemented for answer_relevancy metric

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant