|
| 1 | +# An answer evaluation is added to evaluate the quality of the answer generated by the entire RAG pipeline. |
| 2 | +# In this example, we evaluate the relevance and faithfulness of the answer to the question and the expected output. |
| 3 | + |
| 4 | +from typing import Annotated, TypedDict |
| 5 | + |
| 6 | +from dotenv import load_dotenv |
| 7 | +from langchain_openai import ChatOpenAI |
| 8 | +from langfuse import Evaluation, get_client |
| 9 | +from langfuse.experiment import ExperimentItem |
| 10 | +from main import rag_bot |
| 11 | + |
| 12 | +load_dotenv() |
| 13 | +langfuse = get_client() |
| 14 | + |
| 15 | + |
| 16 | +def rag_task(*, item: ExperimentItem, **kwargs): |
| 17 | + """Task function that runs the full RAG pipeline.""" |
| 18 | + question = item.input["question"] # type: ignore |
| 19 | + result = rag_bot(question) |
| 20 | + |
| 21 | + return {"answer": result["answer"], "documents": result["documents"]} |
| 22 | + |
| 23 | + |
| 24 | +# Answer Relevance Evaluation |
| 25 | +class AnswerRelevanceGrade(TypedDict): |
| 26 | + explanation: Annotated[str, ..., "Explain your reasoning for the score"] |
| 27 | + score: Annotated[int, ..., "Rate the relevance of the answer to the question of 0 or 1"] |
| 28 | + |
| 29 | + |
| 30 | +answer_relevance_llm = ChatOpenAI(model="gpt-4o", temperature=0).with_structured_output( |
| 31 | + AnswerRelevanceGrade, method="json_schema", strict=True |
| 32 | +) |
| 33 | + |
| 34 | +answer_relevance_instructions = """You are evaluating the relevance of an answer to a question. |
| 35 | +You will be given a QUESTION, an ANSWER, and an EXPECTED OUTPUT. |
| 36 | +
|
| 37 | +Here is the grade criteria to follow: |
| 38 | +(1) The ANSWER should directly address the QUESTION |
| 39 | +(2) The ANSWER should be similar in scope to the EXPECTED OUTPUT |
| 40 | +(3) The ANSWER should not contain significant irrelevant information |
| 41 | +(4) It's acceptable if the ANSWER provides additional helpful context as long as it addresses the core question |
| 42 | +
|
| 43 | +You should return a score of 0 or 1, where: |
| 44 | +- 0: The answer is irrelevant or doesn't address the question |
| 45 | +- 1: The answer is relevant and addresses the question |
| 46 | +""" |
| 47 | + |
| 48 | + |
| 49 | +def answer_relevance_evaluator(*, input, output, expected_output, metadata, **kwargs): |
| 50 | + """Evaluates how relevant the generated answer is to the question.""" |
| 51 | + result = answer_relevance_llm.invoke( |
| 52 | + answer_relevance_instructions |
| 53 | + + "\n\nQUESTION: " |
| 54 | + + input["question"] |
| 55 | + + "\n\nANSWER: " |
| 56 | + + output["answer"] |
| 57 | + + "\n\nEXPECTED OUTPUT: " |
| 58 | + + expected_output["answer"] |
| 59 | + ) |
| 60 | + |
| 61 | + return Evaluation(name="answer_relevance", value=result["score"], comment=result.get("explanation", "")) |
| 62 | + |
| 63 | + |
| 64 | +# Faithfulness Evaluation |
| 65 | +class FaithfulnessGrade(TypedDict): |
| 66 | + explanation: Annotated[str, ..., "Explain your reasoning for the score"] |
| 67 | + score: Annotated[int, ..., "Rate the faithfulness of the answer to the source documents of 0 or 1"] |
| 68 | + |
| 69 | + |
| 70 | +faithfulness_llm = ChatOpenAI(model="gpt-4o", temperature=0).with_structured_output( |
| 71 | + FaithfulnessGrade, method="json_schema", strict=True |
| 72 | +) |
| 73 | + |
| 74 | +faithfulness_instructions = """You are evaluating the faithfulness of an answer to the source documents. |
| 75 | +You will be given an ANSWER and the FACTS (source documents) that were used to generate it. |
| 76 | +
|
| 77 | +Here is the grade criteria to follow: |
| 78 | +(1) The ANSWER should only contain information that can be verified from the FACTS |
| 79 | +(2) The ANSWER should not hallucinate or make up information not present in the FACTS |
| 80 | +(3) The ANSWER should not contradict information in the FACTS |
| 81 | +(4) It's acceptable for the ANSWER to say "I don't know" if the FACTS don't contain the information |
| 82 | +
|
| 83 | +You should return a score of 0 or 1, where: |
| 84 | +- 1: The answer is fully grounded in the source facts |
| 85 | +- 0: The answer contains hallucinations or unverified claims |
| 86 | +
|
| 87 | +Explain your reasoning for the score.""" |
| 88 | + |
| 89 | + |
| 90 | +def faithfulness_evaluator(*, input, output, expected_output, metadata, **kwargs): |
| 91 | + """Evaluates how faithful the generated answer is to the source facts.""" |
| 92 | + result = faithfulness_llm.invoke( |
| 93 | + faithfulness_instructions |
| 94 | + + "\n\nANSWER: " |
| 95 | + + output["answer"] |
| 96 | + + "\n\FACTS: " |
| 97 | + + "\n\n".join(doc.page_content for doc in output["documents"]) |
| 98 | + ) |
| 99 | + |
| 100 | + return Evaluation(name="faithfulness", value=result["score"], comment=result.get("explanation", "")) |
| 101 | + |
| 102 | + |
| 103 | +if __name__ == "__main__": |
| 104 | + print("Fetching dataset") |
| 105 | + dataset = langfuse.get_dataset(name="rag_bot_evals") |
| 106 | + |
| 107 | + print("Running answer evaluation experiment") |
| 108 | + dataset.run_experiment( |
| 109 | + name="Answer Quality: Relevance and Faithfulness", |
| 110 | + task=rag_task, |
| 111 | + evaluators=[answer_relevance_evaluator, faithfulness_evaluator], |
| 112 | + ) |
| 113 | + |
| 114 | + print("Experiment run successfully") |
| 115 | + langfuse.flush() |
0 commit comments