Tutorial 2

Simple RAG evaluation

The system is no longer a single prompt. A query hits a document corpus, the retrieved text is handed to an LLM, and the answer is judged against grading notes rather than one gold string.

The system Retrieve, then generate

A query and a corpus both enter the retriever. The LLM only sees what came back.

QueryDocument corpusstored stringsRetrieverLLM + promptAnswer
The short version. The class diagram and the method pipeline below are the same path, opened up.

The classes Who holds what

The corpus lives in two places. ExampleRAG owns the strings. The retriever gets its own copy when it is fitted.

retrieverBaseRetrieverdocuments: list of stringsfit(documents)get_top_k(query, k)stores the list, does not score itSimpleKeywordRetriever_count_keyword_matches(query, document) → intget_top_k(query, k)whole-word overlap, then sortreturns (index, score) pairsExampleRAGdocuments: list of stringsretriever: BaseRetrieverllm_clientis_fitted: booladd_documents(documents)retrieve_documents(query, top_k)generate_response(query, top_k)query(question, top_k)add_documents extends self.documentsthen calls retriever.fit on the full listdefault_rag_client builds both objectsand loads the five DOCUMENTS strings
Hollow arrow: SimpleKeywordRetriever is a BaseRetriever. Diamond: ExampleRAG has a retriever.

The pipeline Store, then query

Documents are plain strings. Scoring is a word count, not an embedding. The LLM only runs inside generate_response.

1. StoreDOCUMENTSadd_documentsExampleRAGself.documentsretriever.fitretriever.documents2. query calls both, and generate_response retrieves againquery(question)retrieve_documentsget_top_k_count_keyword_matchesgenerate_responsecalls againretrieve_documentsprompt + contextLLM → answer
query retrieves for the trace, then generate_response retrieves again and is the only step that calls the LLM. Smoke-test with python -m ragas_examples.rag_eval.rag.
MethodWhat it doesWhat it returns
add_documentsAppends strings onto ExampleRAG.documents, then retriever.fit replaces the retriever's list with that full corpus.nothing
_count_keyword_matchesLowercases and splits both sides. Counts query words that appear as whole words in the document.an int
get_top_kScores every stored document and sorts by that count.(index, score) pairs
retrieve_documentsTurns those pairs into document dicts and drops any score of 0.content, score, document id
generate_responseRetrieves, fills the prompt with the query and those documents, then calls llm_client.chat.completions.the answer string
queryRuns retrieval, then generate_response, and writes a trace log.answer, run id, log path
A score of 0 is a miss. retrieve_documents keeps a document only when at least one query word is in it. If nothing matches, generate_response never calls the LLM and returns that it could not find a relevant document.

The dataset query + grading notes

There is no single expected sentence. Each row lists the points a good answer must contain.

samples = [
    {"query": "What is Ragas 0.3?",
     "grading_notes": "- Ragas 0.3 is a library for evaluating LLM applications."},
    {"query": "How to install Ragas?",
     "grading_notes": "- install from source\n- install from pip using ragas[examples]"},
    {"query": "What are the main features of Ragas?",
     "grading_notes": "organised around experiments, datasets, and metrics."},
]

Grading notes are a rubric, which is why the next step cannot be string equality. “How to install Ragas?” passes if the answer mentions both source install and ragas[examples], whatever the surrounding prose looks like.

The metric LLM judge

DiscreteMetric is a prompt. You pass an evaluator LLM when you score.

my_metric = DiscreteMetric(
    name="correctness",
    prompt=(
        "Check if the response contains points mentioned from the grading notes "
        "and return 'pass' or 'fail'.\n"
        "Response: {response} Grading Notes: {grading_notes}"
    ),
    allowed_values=["pass", "fail"],
)

Placeholders in the metric prompt (response, grading_notes) are filled by the keyword arguments to score. allowed_values still limits the judge to pass and fail.

The experiment Keep the retrieval log

The score says whether the answer was good. The log says what the retriever actually returned.

@experiment()
async def run_experiment(row):
    response = rag_client.query(row["query"])
    score = my_metric.score(
        llm=llm,
        response=response.get("answer", " "),
        grading_notes=row["grading_notes"],
    )
    return {
        **row,
        "response": response.get("answer", ""),
        "score": score.value,
        "log_file": response.get("logs", " "),
    }

Key takeaways

  • End to end: python -m ragas_examples.rag_eval.evals. Results land in experiments/experiment_name.csv.
  • score needs an llm argument. The judge is a separate call from the RAG model.
  • Store log_file beside the score so a fail can be traced to a bad retrieval or a bad generation.