Skip to content

Commit

Permalink
Implemented requested changes
Browse files Browse the repository at this point in the history
  • Loading branch information
sahusiddharth committed Aug 13, 2024
1 parent 99e4848 commit dfe069f
Showing 1 changed file with 3 additions and 100 deletions.
103 changes: 3 additions & 100 deletions src/ragas/metrics/_noise_sensitivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from ragas.llms.output_parser import RagasoutputParser, get_json_format_instructions
from ragas.llms.prompt import Prompt
from ragas.metrics._faithfulness import LONG_FORM_ANSWER_PROMPT, NLI_STATEMENTS_MESSAGE
from ragas.metrics.base import EvaluationMode, MetricWithLLM, ensembler, get_segmenter

if t.TYPE_CHECKING:
Expand Down Expand Up @@ -42,48 +43,10 @@ def dicts(self) -> t.List[t.Dict]:
return self.dict()["__root__"]


_statements_output_instructions = get_json_format_instructions(StatementsAnswers)
# _statements_output_instructions = get_json_format_instructions(StatementsAnswers)
_statements_output_parser = RagasoutputParser(pydantic_object=StatementsAnswers)


LONG_FORM_ANSWER_PROMPT = Prompt(
name="long_form_answer",
output_format_instruction=_statements_output_instructions,
instruction="Given a question, an answer, and sentences from the answer analyze the complexity of each sentence given under 'sentences' and break down each sentence into one or more fully understandable statements while also ensuring no pronouns are used in each statement. Format the outputs in JSON.",
examples=[
{
"question": "Who was Albert Einstein and what is he best known for?",
"answer": "He was a German-born theoretical physicist, widely acknowledged to be one of the greatest and most influential physicists of all time. He was best known for developing the theory of relativity, he also made important contributions to the development of the theory of quantum mechanics.",
"sentences": """
0:He was a German-born theoretical physicist, widely acknowledged to be one of the greatest and most influential physicists of all time.
1:He was best known for developing the theory of relativity, he also made important contributions to the development of the theory of quantum mechanics.
""",
"analysis": StatementsAnswers.parse_obj(
[
{
"sentence_index": 0,
"simpler_statements": [
"Albert Einstein was a German-born theoretical physicist.",
"Albert Einstein is recognized as one of the greatest and most influential physicists of all time.",
],
},
{
"sentence_index": 1,
"simpler_statements": [
"Albert Einstein was best known for developing the theory of relativity.",
"Albert Einstein also made important contributions to the development of the theory of quantum mechanics.",
],
},
]
).dicts(),
}
],
input_keys=["question", "answer", "sentences"],
output_key="analysis",
language="english",
)


class StatementFaithfulnessAnswer(BaseModel):
statement: str = Field(..., description="the original statement, word-by-word")
reason: str = Field(..., description="the reason of the verdict")
Expand All @@ -104,64 +67,6 @@ def dicts(self) -> t.List[t.Dict]:
pydantic_object=StatementFaithfulnessAnswers
)

NLI_STATEMENTS_MESSAGE = Prompt(
name="nli_statements",
instruction="Your task is to judge the faithfulness of a series of statements based on a given context. For each statement you must return verdict as 1 if the statement can be directly inferred based on the context or 0 if the statement can not be directly inferred based on the context.",
output_format_instruction=_faithfulness_output_instructions,
examples=[
{
"context": """John is a student at XYZ University. He is pursuing a degree in Computer Science. He is enrolled in several courses this semester, including Data Structures, Algorithms, and Database Management. John is a diligent student and spends a significant amount of time studying and completing assignments. He often stays late in the library to work on his projects.""",
"statements": [
"John is majoring in Biology.",
"John is taking a course on Artificial Intelligence.",
"John is a dedicated student.",
"John has a part-time job.",
],
"answer": StatementFaithfulnessAnswers.parse_obj(
[
{
"statement": "John is majoring in Biology.",
"reason": "John's major is explicitly mentioned as Computer Science. There is no information suggesting he is majoring in Biology.",
"verdict": 0,
},
{
"statement": "John is taking a course on Artificial Intelligence.",
"reason": "The context mentions the courses John is currently enrolled in, and Artificial Intelligence is not mentioned. Therefore, it cannot be deduced that John is taking a course on AI.",
"verdict": 0,
},
{
"statement": "John is a dedicated student.",
"reason": "The context states that he spends a significant amount of time studying and completing assignments. Additionally, it mentions that he often stays late in the library to work on his projects, which implies dedication.",
"verdict": 1,
},
{
"statement": "John has a part-time job.",
"reason": "There is no information given in the context about John having a part-time job.",
"verdict": 0,
},
]
).dicts(),
},
{
"context": """Photosynthesis is a process used by plants, algae, and certain bacteria to convert light energy into chemical energy.""",
"statements": ["Albert Einstein was a genius."],
"answer": StatementFaithfulnessAnswers.parse_obj(
[
{
"statement": "Albert Einstein was a genius.",
"reason": "The context and statement are unrelated",
"verdict": 0,
}
]
).dicts(),
},
],
input_keys=["context", "statements"],
output_key="answer",
output_type="json",
language="english",
) # noqa: E501


@dataclass
class NoiseSensitivity(MetricWithLLM):
Expand Down Expand Up @@ -199,11 +104,9 @@ def __post_init__(self):
def _create_nli_prompt(self, contexts: str, statements: t.List[str]) -> PromptValue:
assert self.llm is not None, "llm must be set to compute score"

# check if the statements are support in the contexts
contexts_str: str = "\n".join(contexts)
statements_str: str = json.dumps(statements)
prompt_value = self.nli_statements_message.format(
context=contexts_str, statements=statements_str
context=contexts, statements=statements_str
)
return prompt_value

Expand Down

0 comments on commit dfe069f

Please sign in to comment.