<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nelson Almeida on Medium]]></title>
        <description><![CDATA[Stories by Nelson Almeida on Medium]]></description>
        <link>https://medium.com/@nelson.martinsalmeidaa?source=rss-20eb45fdc892------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1oaxANNTe6jJThlQ</url>
            <title>Stories by Nelson Almeida on Medium</title>
            <link>https://medium.com/@nelson.martinsalmeidaa?source=rss-20eb45fdc892------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:02:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nelson.martinsalmeidaa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Evaluating a RAG app (hands on approach)]]></title>
            <link>https://medium.com/@nelson.martinsalmeidaa/evaluating-a-rag-app-hands-on-approach-6c0b44abf604?source=rss-20eb45fdc892------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c0b44abf604</guid>
            <category><![CDATA[mistral]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[evaluation-techniques]]></category>
            <category><![CDATA[evaluation]]></category>
            <dc:creator><![CDATA[Nelson Almeida]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 09:26:45 GMT</pubDate>
            <atom:updated>2024-06-04T09:26:45.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jkrxizzOpHPcqRG25aXHeQ.png" /></figure><p>[Image 1] <a href="https://towardsdatascience.com/evaluating-rag-applications-with-ragas-81d67b0ee31a">RAG components evaluation</a></p><p>One of the most important steps of building any solution is to validate it and evaluate it.</p><h3>RAG evaluation has two main elements to be validated:</h3><ul><li>Retrieval: This involves experimenting with different data processing strategies, embedding models, etc., and evaluating how they impact retrieval.</li><li>Generation: Once you decide on the best settings for the retriever, this step involves experimenting with different LLMs to find the best completion model for the task.</li></ul><h3>Methodology:</h3><p>In order to demonstrate how to evaluate a RAG pipeline we are going to resort to 2 methods: response metrics(RAGAS and GEval) and a critic model</p><h3>How do response metrics work?</h3><p>Response metrics: The response metrics base themselves in 4 parameters: The question, the answer, the context provided to the model and the ground_truth (this can be the expected answer if we have a human writing the dataset or the answer of the synthetic data generation)</p><p>RAGAS for instance has 4 metrics:</p><ul><li><a href="https://docs.ragas.io/en/latest/concepts/metrics/context_precision.html">**Context precision</a>** measures the signal-to-noise ratio of the retrieved context. This metric is computed using the question and the contexts.</li><li><a href="https://docs.ragas.io/en/latest/concepts/metrics/context_recall.html">**Context recall</a>** measures if all the relevant information required to answer the question was retrieved. This metric is computed based on the ground_truth (this is the only metric in the framework that relies on human-annotated ground truth labels) and the contexts.</li><li><a href="https://docs.ragas.io/en/latest/concepts/metrics/faithfulness.html"><strong>Faithfulness</strong></a> measures the factual accuracy of the generated answer. The number of correct statements from the given contexts is divided by the total number of statements in the generated answer. This metric uses the question, contextsand the answer.</li><li><a href="https://docs.ragas.io/en/latest/concepts/metrics/answer_relevance.html"><strong>Answer relevancy</strong></a> measures how relevant the generated answer is to the question. This metric is computed using the question and the answer. For example, the answer “<em>France is in western Europe</em>.” to the question “<em>Where is France and what is it’s capital?</em>” would achieve a low answer relevancy because it only answers half of the question.</li></ul><h3>How does the critic model work?</h3><p>For the critic model evaluation we can emulate the ragas metrics and use another model and query it providing the question, the rag response, the contexts provided and the expected answer and ask for a classification of the rag app response based in the contexts provided and the faithfulness to the ground truth.</p><h3>Test set for evaluation:</h3><p>In order to evaluate the pipeline using the metrics above we have to have a baseline, how the users will interact with our RAG app and the expected usage experience.</p><p>To generate a dataset to simulate the usage of our app we can resort to two different methods, human generation and synthetic data generation.</p><p>Leveraging LLMs for reference-free evaluation is an active research topic. While using as little human-annotated data as possible makes it a cheaper and faster evaluation method, there is still some discussion about its shortcomings, such as bias and inconsistency.</p><h3>How does the Human Generation work?</h3><p>For human generation we resort to humans that have precise knowledge of the field being evaluated in order to create questions and answers for us to run in our app</p><p>Pros: More human-like/correct answers</p><p>Cons: Time consuming, lack of completeness since it is really hard to capture the full essence of the model response with a finite dataset</p><h3>Example:</h3><pre>{<br>    &quot;tests&quot;: [<br>        {<br>            &quot;name&quot;: &quot;Test 1&quot;,<br>            &quot;question&quot;: &quot;Quais são e o que são os princípios ACID?&quot;,<br>            &quot;groundTruth&quot;: &quot;Os princípios ACID são Atomicidade, Consistência, Isolamento e Durabilidade. São princípios que garantem a integridade dos dados numa base de dados.&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;Test 2&quot;,<br>            &quot;question&quot;: &quot;Qual é a definição de base de dados NoSQL?&quot;,<br>            &quot;groundTruth&quot;: &quot;Não existe uma definição para base de dados NoSQL visto que NoSQL é um termo genérico que engloba várias tecnologias de base de dados que não são relacionais, daí muita gente dizer que NoSQL significa &#39;Não apenas SQL&#39;.\nMuitos argumentam que a única coisa que todas as bases de dados NoSQL têm em comum é que não seguem o modelo relacional, por isso deviam chamar-se &#39;NoREL&#39; em vez de &#39;NoSQL&#39;.&quot;<br>        },<br>        {<br>            &quot;name&quot;: &quot;Test 3&quot;,<br>            &quot;question&quot;: &quot;Quais são as características das bases de dados não relacionais?&quot;,<br>            &quot;groundTruth&quot;: &quot;Os princípios das bases de dados não relacionais, também conhecidas como NoSQL, podem ser resumidos da seguinte forma:\n\n1. **Modelo Não Relacional**: As bases de dados NoSQL não seguem o modelo relacional proposto por E.F. Codd em 1970. Em vez disso, elas adotam modelos de dados alternativos mais adequados para lidar com diversos tipos de dados, especialmente não estruturados ou semiestruturados.\n\n2. **Flexibilidade e Escalabilidade**: As bases de dados NoSQL são projetadas para oferecer flexibilidade e escalabilidade horizontal. Isso significa que elas podem lidar com grandes volumes de dados distribuídos em vários servidores, permitindo um crescimento mais eficiente e sem grandes gargalos de desempenho.\n\n3. **Sem Esquema Fixo**: Ao contrário das bases de dados relacionais, as bases de dados NoSQL geralmente não possuem um esquema fixo. Isso significa que não é necessário definir a estrutura dos dados antes de inseri-los, proporcionando maior agilidade no desenvolvimento e na manipulação de dados com estruturas variáveis.\n\n4. **Código Aberto**: Muitas das bases de dados NoSQL são disponibilizadas como projetos de código aberto, incentivando a colaboração e o desenvolvimento comunitário. Isso permite uma maior transparência, personalização e adaptação às necessidades específicas de cada aplicação.\n\n5. **Escalabilidade Horizontal**: As bases de dados NoSQL são projetadas para funcionar de forma eficiente em ambientes distribuídos, onde os dados são particionados e distribuídos entre vários servidores. Isso permite que elas atinjam altos níveis de desempenho e disponibilidade, mesmo diante de um grande volume de requisições e dados.\n\n6. **Não Seguem os Princípios do ACID de Forma Estrita**: Enquanto as bases de dados relacionais seguem os princípios do ACID (Atomicidade, Consistência, Isolamento e Durabilidade) de forma estrita, as bases de dados NoSQL podem flexibilizar esses princípios em prol de maior disponibilidade ou escalabilidade. Isso significa que, em determinadas situações, a consistência dos dados pode ser sacrificada em favor de um melhor desempenho ou disponibilidade.\n\n7. **Sem uma Linguagem de Consulta Padrão**: Ainda não há uma linguagem de consulta padrão que seja suportada por todas as bases de dados NoSQL. Algumas bases de dados possuem suas próprias linguagens de consulta, enquanto outras suportam várias linguagens ou formatos de consulta, como JSON, XQuery, SPARQL, entre outros. Isso reflete a diversidade e a flexibilidade dessas tecnologias.&quot;<br>        }<br>    ]<br>}</pre><h3>How does Synthetic Data generation work?</h3><p>Synthetic data generation works suported by llms in order to create questions from the documents/contexts you have, but RAGAS, as we are using it in this approach, has an evolving strategy where you can specify the number of questions you want to generate with specific characteristics like reasoning, conditioning …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDSiEl8W-9ScBC3Ng-iZ0g.png" /></figure><p>[Image 2]<a href="https://docs.ragas.io/en/latest/concepts/testset_generation.html">RAGAS synthetic test set generator architecture</a></p><p>Pros: Larger dataset of questions with less effort</p><p>Cons: Lack of precision, completeness and doesn’t always depict the best answer structure/content.</p><pre>loader = DirectoryLoader(&quot;data&quot;)<br>documents = loader.load()</pre><pre>for document in documents:<br>    document.metadata[&#39;filename&#39;] = document.metadata[&#39;source&#39;]</pre><pre># generator with openai models<br>generator_llm = ChatOpenAI(model=&quot;gpt-3.5-turbo-0125&quot;)<br>critic_llm = ChatOpenAI(model=&quot;gpt-3.5-turbo-0125&quot;)<br>embeddings = OpenAIEmbeddings()</pre><pre>generator = TestsetGenerator.from_langchain(<br>    generator_llm,<br>    critic_llm,<br>    embeddings<br>)</pre><pre># generate testset<br>testset = generator.generate_with_langchain_docs(documents, test_size=1, distributions={simple: 0.5, reasoning: 0.25, multi_context: 0.25})<br>testset_df = testset.to_pandas()</pre><pre>testset_dict = testset_df.to_dict(orient=&quot;records&quot;)</pre><pre># save testset<br>filename = f&quot;synthetic_testset_{datetime.datetime.now().strftime(&#39;%Y-%m-%d_%H-%M&#39;)}.json&quot;<br>with open(f&quot;evaluation/{filename}&quot;, &quot;w&quot;) as outfile:<br>    #Lets store the structure to the file<br>    payload = {<br>        &quot;tests&quot;: []<br>    }<br>    testNum=0<br>    for i in testset_dict:<br>        payload[&quot;tests&quot;].append({</pre><pre>            &quot;name&quot; : f&quot;Test_{testNum}&quot;,<br>            &quot;question&quot;: i[&quot;question&quot;],<br>            &quot;groundTruth&quot;: i[&quot;ground_truth&quot;]<br>        })</pre><pre>        testNum+=1</pre><pre>    json.dump(payload, outfile)</pre><h3>Evaluation(hands on):</h3><pre>evaluationResults = []<br>results = []</pre><pre>#Load the tests<br>testset = open(&quot;tests.json&quot;)<br>testset = json.load(testset)<br>testset = testset[&quot;tests&quot;]<br>print(&quot;Testset loaded&quot;)</pre><pre>#Ragas evaluation<br>#Load the metrics to use in the evaluation from the ragas library<br>metrics = [<br>    context_precision,<br>    context_recall,<br>    answer_relevancy,<br>    answer_correctness,<br>    faithfulness<br>]</pre><pre>results = evaluate(<br>    result[&quot;train&quot;],<br>    metrics=metrics,<br>    llm = llm,<br>    embeddings = embedingModel,<br>    raise_exceptions=False,<br>)</pre><pre>results = results.to_pandas()</pre><pre>#Critic model evaluation</pre><pre>#Get the name of the test to run<br>name = test[&quot;name&quot;]<br>#Get the question from the test file<br>question = test[&quot;question&quot;]<br>#Get the ground truth regarding the quesion from the test file<br>groundTruth = test[&quot;groundTruth&quot;]</pre><pre>print(&quot;Running test: &quot;, name)</pre><pre>#In the architecture the query function returns both the answer and the ground truth<br>#If your architecture doesn&#39;t do this refactor the code in order to also get the ground truth<br>#Or dont use metrics that use ground truth and skip that part</pre><pre>answer = self.query(question, evaluate = True)<br>ourAnswer = answer[&quot;response&quot;]<br>context = answer[&quot;context&quot;]</pre><pre>#Prompt engineering with few-shot learning in order to get RAGAS like metrics evaluation</pre><pre>evaluation_template = f&quot;&quot;&quot;<br>  Classifica a resposta: &quot;{ourAnswer}&quot; para a pergunta &quot;{question}&quot; dado apenas o contexto fornecido pelo seguinte contexto: {&quot;&quot;.join(context)}.<br>  O valor real da pergunta(ground_truth) deverá ser &quot;{groundTruth}&quot;.<br>  A classificação deve ser entre 1 (pontuação mais baixa) e 10 (pontuação mais alta), e deve conter uma explicação máxima de uma frase da classificação.<br>  A classificação deve ser baseada nos seguintes moldes: <br>  A precisão do contexto mede o rácio sinal/ruído do contexto recuperado. Esta métrica é calculada utilizando a pergunta e os contextos.<br>  A recall do contexto mede se toda a informação relevante necessária para responder à pergunta foi recuperada. Esta métrica é calculada com base no ground_truth (esta é a única métrica no quadro que se baseia em etiquetas de ground truth anotadas por humanos) e nos contextos.<br>  A fidelidade mede a exatidão factual da resposta gerada. O número de afirmações correctas dos contextos dados é dividido pelo número total de afirmações na resposta gerada. Esta métrica utiliza a pergunta, os contextos e a resposta.<br>  A relevância da resposta mede a relevância da resposta gerada para a pergunta. Esta métrica é calculada utilizando a pergunta e a resposta. Por exemplo, a resposta &quot;A França fica na Europa Ocidental.&quot; para a pergunta &quot;Onde fica a França e qual é a sua capital?&quot; obteria uma relevância de resposta baixa porque só responde a metade da pergunta.</pre><pre>  A resposta deve ter apenas a classificação do tipo:<br>  Relevancia da resposta: x/10<br>  Correção: x/10<br>  Precisão do contexto: x/10<br>  Recall do contexto: x/10</pre><pre>  Exemplo de resposta 1:<br>  Relevancia da resposta: 8/10<br>  Correção: 7/10<br>  Precisão do contexto: 9/10<br>  Recall do contexto: 8/10</pre><pre>  Exemplo de resposta 2:<br>  Relevancia da resposta: 5/10<br>  Correção: 6/10<br>  Precisão do contexto: 7/10<br>  Recall do contexto: 5/10</pre><pre>  Resposta:</pre><pre>  &quot;&quot;&quot;</pre><pre>  modelAnswer = criticModel.invoke(evaluation_template)</pre><h3>Sample evaluation results:</h3><p>Lets do a sample evaluation with the following query: <em>“Quais são e o que são os princípios ACID?”</em></p><p>First evaluation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vCNp-M8OSGplIrFK7DZ8pA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*eInkG04DFCzM-sTHxJkiNQ.png" /><figcaption>RAGAS evaluation vs Critic Model Evaluation</figcaption></figure><p>Second evaluation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*dBTVA2m80s5MTkOvEW1qZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*eInkG04DFCzM-sTHxJkiNQ.png" /><figcaption>RAGAS evaluation vs Critic Model Evaluation</figcaption></figure><p>For each evaluation iteration we get a different result, and running for instance 10 evaluations in order to get an average takes time, computational power and therefore money, this can very fast become really expensive to run.</p><h3>Summary</h3><ul><li>Building a proof-of-concept RAG application is easy, but getting it production-ready and ensuring it’s validity/stability is very hard.</li><li>Since a RAG pipeline consists of multiple components that must be evaluated separately and in combinations, you will require a set of evaluation metrics. Additionally, generating a high-quality validation dataset from human annotators is hard, time-consuming, and expensive.</li><li>The evaluation results don’t directly imply that you have a bad rag pipeline, they can hint you on what you should alter, for instance if your retrieval results are good but the generation results are bellow expected you can try to change the generation model you are using, or if your retrieval results are bad you can implement a reranker, alter your chunking technique or even alter your embedding model.</li></ul><h3>References:</h3><p>[Image 1] RAG components evaluation <a href="https://towardsdatascience.com/evaluating-rag-applications-with-ragas-81d67b0ee31a">https://towardsdatascience.com/evaluating-rag-applications-with-ragas-81d67b0ee31a</a></p><p>[Image 2] RAGAS synthetic test generation architecture <a href="https://docs.ragas.io/en/latest/concepts/testset_generation.html">https://docs.ragas.io/en/latest/concepts/testset_generation.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c0b44abf604" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>