Ragas: Evaluation Framework for RAG and LLM Applications

repository·main·Indexed 12 days ago

https://github.com/vibrantlabsai/ragas

A toolkit for evaluating and optimizing Large Language Model (LLM) applications using objective metrics, intelligent test generation, and data-driven insights. It provides tools for RAG system evaluation, LLM benchmarking, prompt evaluation, and workflow evaluation, including a DiscreteMetric for custom aspect evaluators and a plugin architecture for custom storage backends via BaseBackend.

Tokens
204.3K
Snippets
575
Records
719
Agent score
92%

What's inside Ragas

  1. Introduction to Ragas

    main

    Ragas is a library designed to replace manual "vibe checks" with systematic evaluation loops for Large Language Model (LLM) applications. It enables developers to move from qualitative assessments to quantitative, repeatable evaluations using LLM-driven metrics and systematic experimentation.

    Core Workflow

    1. Experiments: Use an experiments-first approach to evaluate changes consistently. Make changes to your application, run evaluations, observe results, and iterate.
    2. Metrics: Utilize built-in Ragas metrics or create custom metrics tailored to your specific use case using simple decorators.
    3. Integration: Integrate with existing LLM frameworks like LangChain and LlamaIndex, leveraging built-in dataset management and result tracking.
  2. Explore Ragas API Reference categories

    main

    The Ragas API is organized into four primary functional areas:

    1. Core Components: Low-level interfaces for managing the evaluation lifecycle, including Prompt management, LLMs, Embeddings, Tokenizers, RunConfig, Executor, and Cache mechanisms.
    2. Evaluation: The high-level API for scoring RAG applications, covering Schemas (data structures), Metrics (implementations), and the primary evaluate() function.
    3. Testset Generation: Tools for creating synthetic evaluation data, including Schemas, Graph management, Transforms, Synthesizers, and the Generation API.
    4. Integrations: APIs for connecting Ragas with external tools and services.
  3. Explore available Ragas evaluation metrics

    main

    Ragas provides a diverse set of evaluation metrics categorized by application type and task. Metrics can be LLM-based (using one or more LLM calls to derive a score) or custom-written. Use the following categories to select the appropriate metrics for your use case:

    Retrieval Augmented Generation (RAG)

    Focuses on the quality of retrieved context and the faithfulness of the generated response.

    • Context Precision
    • Context Recall
    • Context Entities Recall
    • Noise Sensitivity
    • Response Relevancy
    • Faithfulness
    • Multimodal Faithfulness
    • Multimodal Relevance

    Nvidia Metrics

    • Answer Accuracy
    • Context Relevance
    • Response Groundedness

    Agents or Tool Use Cases

    Designed for evaluating agentic workflows and tool interactions.

    • Topic adherence
    • Tool call Accuracy
    • Tool Call F1
    • Agent Goal Accuracy

    Natural Language Comparison

    Used for comparing text outputs using semantic or traditional string-based methods.

    • Factual Correctness
    • Semantic Similarity
    • Non LLM String Similarity (includes BLEU Score, CHRF Score, ROUGE Score, String Presence, and Exact Match)

    SQL

    • Execution based Datacompy Score
    • SQL query Equivalence

    General Purpose

    Flexible scoring methods for various criteria.

    • Aspect critic
    • Simple Criteria Scoring
    • Rubrics based scoring
    • Instance specific rubrics scoring

    Other Tasks

    • Summarization
  4. What is Aspect Critique and how to use DiscreteMetric

    main

    Aspect Critique is a binary evaluation method used to assess submissions against specific predefined aspects (e.g., harmlessness, correctness, coherence). It uses LLM-based evaluation to determine if a submission aligns with a defined aspect, returning a discrete value from a set of allowed responses.

    To implement this, use the DiscreteMetric class. You must provide a name, a list of allowed_values, a prompt containing the evaluation criteria, and an llm instance.

    Key Configuration:

    • allowed_values: A list of strings that the LLM is permitted to return (e.g., ["safe", "unsafe"]).
    • prompt: A template string that includes the {response} placeholder. The prompt should explicitly instruct the LLM to only use the values provided in allowed_values.
    • strictness: A parameter used for self-consistency checks. An ideal range for maintaining consistent predictions is typically between 2 and 4.
    from ragas.metrics import DiscreteMetric
    
    # Example initialization
    metric = DiscreteMetric(
        name="aspect_name",
        allowed_values=["value1", "value2"],
        prompt="Evaluate based on criteria. Response: {response}. Answer with only 'value1' or 'value2'.",
        llm=llm
    )
  5. What is a Prompt Object in Ragas

    main

    In Ragas, a Prompt Object is a structured way to define instructions, context, and data schemas for tasks like metric calculation or synthetic data generation. Ragas allows users to modify or replace default prompts with custom ones using this object structure.

    A Prompt Object consists of four key components:

    1. instruction: A natural language directive describing the task.
    2. examples: A list of few-shot examples (input/output pairs) to improve LLM performance.
    3. input_model: A Pydantic model defining the expected structure of the input data.
    4. output_model: A Pydantic model defining the expected structure of the LLM's response.

    Using these components ensures that inputs are validated and outputs are parsed correctly into structured data.

  6. What is an Evaluation Dataset in Ragas

    main

    An EvaluationDataset is a homogeneous collection of data samples designed to assess the performance of an AI application. In Ragas, it is represented by the EvaluationDataset class.

    Structure

    • Samples: A collection of SingleTurnSample or MultiTurnSample instances. Each sample represents a unique interaction.
    • Consistency: To maintain evaluation consistency, all samples within a single EvaluationDataset must be of the same type (either all single-turn or all multi-turn).
  7. How Single-turn and Multi-turn metrics work in Ragas

    main

    Ragas distinguishes between metrics based on the interaction depth they evaluate:

    1. Single-turn metrics: Evaluate a single interaction between a user and the AI. These inherit from SingleTurnMetric and are scored using the single_turn_ascore method. They require a SingleTurnSample object.
    2. Multi-turn metrics: Evaluate performance across multiple turns of interaction. These inherit from MultiTurnMetric and are scored using the multi_turn_ascore method. They require a MultiTurnSample object.

    Single-turn usage example:

    from ragas.metrics import FactualCorrectness
    
    scorer = FactualCorrectness()
    await scorer.single_turn_ascore(sample) # sample is a SingleTurnSample

    Multi-turn usage example:

    from ragas.metrics import AgentGoalAccuracy
    from ragas import MultiTurnSample
    
    scorer = AgentGoalAccuracy()
    await scorer.multi_turn_ascore(sample) # sample is a MultiTurnSample
    from ragas.metrics import AgentGoalAccuracy
    from ragas import MultiTurnSample
    
    scorer = AgentGoalAccuracy()
    await scorer.multi_turn_ascore(sample)
  8. How Datasets are used for evaluation

    main
    Datasets are the foundation of the evaluation process. You can create and manage datasets to provide the necessary inputs for testing your AI applications. The framework supports various dataset structures and storage backends to help you maintain consistent test data for your evaluation workflows.
  9. Define custom evaluation metrics using AspectCritic and RubricsScore

    main

    When evaluating autonomous agents, it is recommended to use metrics that focus on binary decisions or discrete classification scores rather than ambiguous continuous scales. Ragas provides two primary ways to implement this:

    1. AspectCritic: Evaluates whether a submission follows specific user-defined criteria (e.g., brand tone or request completeness) using LLM judgments to return a binary outcome (1 or 0).
    2. RubricsScore: Assesses responses against a detailed, user-defined rubric to assign scores based on specific qualitative descriptions.

    Both metrics require an llm (wrapped via LangchainLLMWrapper) to perform the evaluation.

    from ragas.metrics import AspectCritic, RubricsScore
    from ragas.dataset_schema import SingleTurnSample, MultiTurnSample, EvaluationDataset
    from ragas import evaluate
    
    # Example: Using RubricsScore for recommendation quality
    rubrics = {
        "score-1_description": (
            "The item requested by the customer is not present in the menu and no recommendations were made."
        ),
        "score0_description": (
            "Either the item requested by the customer is present in the menu, or the conversation does not include any food or menu inquiry (e.g., booking, cancellation). This score applies regardless of whether any recommendation was provided."
        ),
        "score1_description": (
            "The item requested by the customer is not present in the menu and a recommendation was provided."
        ),
    }
    
    recommendations = RubricsScore(rubrics=rubrics, llm=evaluator_llm, name="Recommendations")
    
    # Example: Using AspectCritic for binary compliance (e.g., Request Completeness)
    request_completeness = AspectCritic(
        name="Request Completeness",
        llm=evaluator_llm,
        definition=(
            "Return 1 The agent completely fulfills all the user requests with no omissions. "
            "otherwise, return 0."
        ),
    )
    
    # Example: Using AspectCritic for Brand Voice
    brand_tone = AspectCritic(
        name="Brand Voice Metric",
        llm=evaluator_llm,
        definition="Return 1 if the AI's communication is friendly, approachable, helpful, clear, and concise; otherwise, return 0.",
    )
  10. How Answer Relevancy is calculated

    main

    The AnswerRelevancy metric uses a reverse-engineering approach to determine if an answer addresses a question:

    1. Question Generation: An LLM generates $N$ artificial questions (default is 3) based solely on the response. These questions represent what information is contained in the answer.
    2. Similarity Calculation: The metric computes the cosine similarity between the embedding of the original user_input ($E_o$) and the embedding of each generated question ($E_{g_i}$).
    3. Averaging: The final score is the average of these cosine similarity scores:

    $$\text{Answer Relevancy} = \frac{1}{N} \sum_{i=1}^{N} \text{cosine similarity}(E_{g_i}, E_o)$$

    If the answer is highly relevant, the original question can be easily reconstructed from the answer, resulting in high similarity scores.

  11. Use custom callbacks for observability in Ragas

    main
    Ragas provides a callbacks parameter in the evaluate function, which allows you to hook into the evaluation process using various observability tools. You can use tracers supported by LangChain (such as WandbTracer or OpikTracer) or implement your own custom callback handler by inheriting from LangChain's BaseCallbackHandler.