Notebooks
G
Groq
Benchmarking Rag

Benchmarking Rag

managed-by-terraformtutorialsbenchmarking-rag-langchain04-raggroq-api-cookbook

Benchmarking a RAG Pipeline with Llama3 and LangChain

Retrieval Augmented Generation (RAG) pipelines are one of the most popular use cases of Generative AI and Large Language Models (LLMs). Evaluating these pipelines is crucial for understanding their performance, limitations, and potential for improvement.

This notebook demonstrates how to benchmark a RAG pipeline using Llama3-8B as the retrieval model and Llama3-70B as both the dataset generator and the evaluation judge.

This tutorial will walk you through how to:

  1. Set up the environment and dependencies.
  2. Load and index the data into the vectorstore.
  3. Set up the RAG pipeline.
  4. Generate evaluation dataset.
  5. Evaluate the RAG pipeline.
  6. Display and save the evaluation metrics.

For the fastest LLM inference speed in the world, we use Llama3-8B and Llama3-70B powered by Groq. You can create a developer account for free at https://console.groq.com/ and generate a free API key to follow this tutorial!

1. Set up the Environment and Dependencies

In this section, we install and import the necessary libraries required for our benchmarking task.

[1]
[2]

Set Up Environment Variables

To use Groq, you need to make sure that GROQ_API_KEY is specified as an environment variable.

[19]

Instantiate LLM and Embeddings Model

We then instantiate the ChatGroq class to use Llama3 through Groq and HuggingFaceEmbeddings to use the embeddings model.

NOTE: The BBAI/bge-small-en-v1.5 HuggingFace embeddings model will download the model locally on your computer. The model is ~135MB.

You can swap out any of the Chat and Embeddings models with any of Langchain's Chat Model integrations and Embeddings Model integrations.

[4]
/Users/skapadia/Desktop/sk/repos/llama-recipes/env/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
/Users/skapadia/Desktop/sk/repos/llama-recipes/env/lib/python3.12/site-packages/huggingface_hub/file_download.py:1132: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.
  warnings.warn(
/Users/skapadia/Desktop/sk/repos/llama-recipes/env/lib/python3.12/site-packages/huggingface_hub/file_download.py:1132: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.
  warnings.warn(

2. Load and Index Data into the Vectorstore

We will be using one of Paul Graham's essays as the data to query for the RAG pipeline.

[5]
--2024-06-06 11:50:27--  https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.108.133, 185.199.109.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 75042 (73K) [text/plain]
Saving to: ‘data/paul_graham/paul_graham_essay.txt’

data/paul_graham/pa 100%[===================>]  73.28K  --.-KB/s    in 0.02s   

2024-06-06 11:50:27 (3.87 MB/s) - ‘data/paul_graham/paul_graham_essay.txt’ saved [75042/75042]

Load Data, Split into Chunks, and Index into Vectorstore

We are using Langchain's DirectoryLoader to load the data from the directory we just downloaded it to.

To split the data, we are using the RecursiveCharacterTextSplitter to recursively split the data by characters.

Finally, we are using ChromaDB as our vectorstore provider through Langchain's Chroma class.

Again, all of this is swappable based on your needs through Langchain's integrations and modules:

[6]
Documents indexed: 27
[7]
[Document(page_content="Asterix comics begin by zooming in on a tiny corner of Roman Gaul that turns out not to be controlled by the Romans. You can do something similar on a map of New York City: if you zoom in on the Upper East Side, there's a tiny corner that's not rich, or at least wasn't in 1993. It's called Yorkville, and that was my new home. Now I was a New York artist — in the strictly technical sense of making paintings and living in New York.\n\nI was nervous about money, because I could sense that Interleaf was on the way down. Freelance Lisp hacking work was very rare, and I didn't want to have to program in another language, which in those days would have meant C++ if I was lucky. So with my unerring nose for financial opportunity, I decided to write another book on Lisp. This would be a popular book, the sort of book that could be used as a textbook. I imagined myself living frugally off the royalties and spending all my time painting. (The painting on the cover of this book, ANSI Common Lisp, is one that I painted around this time.)\n\nThe best thing about New York for me was the presence of Idelle and Julian Weber. Idelle Weber was a painter, one of the early photorealists, and I'd taken her painting class at Harvard. I've never known a teacher more beloved by her students. Large numbers of former students kept in touch with her, including me. After I moved to New York I became her de facto studio assistant.\n\nShe liked to paint on big, square canvases, 4 to 5 feet on a side. One day in late 1994 as I was stretching one of these monsters there was something on the radio about a famous fund manager. He wasn't that much older than me, and was super rich. The thought suddenly occurred to me: why don't I become rich? Then I'll be able to work on whatever I want.\n\nMeanwhile I'd been hearing more and more about this new thing called the World Wide Web. Robert Morris showed it to me when I visited him in Cambridge, where he was now in grad school at Harvard. It seemed to me that the web would be a big deal. I'd seen what graphical user interfaces had done for the popularity of microcomputers. It seemed like the web would do the same for the internet.\n\nIf I wanted to get rich, here was the next train leaving the station. I was right about that part. What I got wrong was the idea. I decided we should start a company to put art galleries online. I can't honestly say, after reading so many Y Combinator applications, that this was the worst startup idea ever, but it was up there. Art galleries didn't want to be online, and still don't, not the fancy ones. That's not how they sell. I wrote some software to generate web sites for galleries, and Robert wrote some to resize images and set up an http server to serve the pages. Then we tried to sign up galleries. To call this a difficult sale would be an understatement. It was difficult to give away. A few galleries let us make sites for them for free, but none paid us.", metadata={'source': 'data/paul_graham/paul_graham_essay.txt'}),
, Document(page_content='I had to ban myself from writing essays during most of this time, or I\'d never have finished. In late 2015 I spent 3 months writing essays, and when I went back to working on Bel I could barely understand the code. Not so much because it was badly written as because the problem is so convoluted. When you\'re working on an interpreter written in itself, it\'s hard to keep track of what\'s happening at what level, and errors can be practically encrypted by the time you get them.\n\nSo I said no more essays till Bel was done. But I told few people about Bel while I was working on it. So for years it must have seemed that I was doing nothing, when in fact I was working harder than I\'d ever worked on anything. Occasionally after wrestling for hours with some gruesome bug I\'d check Twitter or HN and see someone asking "Does Paul Graham still code?"\n\nWorking on Bel was hard but satisfying. I worked on it so intensively that at any given time I had a decent chunk of the code in my head and could write more there. I remember taking the boys to the coast on a sunny day in 2015 and figuring out how to deal with some problem involving continuations while I watched them play in the tide pools. It felt like I was doing life right. I remember that because I was slightly dismayed at how novel it felt. The good news is that I had more moments like this over the next few years.\n\nIn the summer of 2016 we moved to England. We wanted our kids to see what it was like living in another country, and since I was a British citizen by birth, that seemed the obvious choice. We only meant to stay for a year, but we liked it so much that we still live there. So most of Bel was written in England.\n\nIn the fall of 2019, Bel was finally finished. Like McCarthy\'s original Lisp, it\'s a spec rather than an implementation, although like McCarthy\'s Lisp it\'s a spec expressed as code.\n\nNow that I could write essays again, I wrote a bunch about topics I\'d had stacked up. I kept writing essays through 2020, but I also started to think about other things I could work on. How should I choose what to do? Well, how had I chosen what to work on in the past? I wrote an essay for myself to answer that question, and I was surprised how long and messy the answer turned out to be. If this surprised me, who\'d lived it, then I thought perhaps it would be interesting to other people, and encouraging to those with similarly messy lives. So I wrote a more detailed version for others to read, and this is the last sentence of it.\n\n\n\n\n\n\n\n\n\nNotes\n\n[1] My experience skipped a step in the evolution of computers: time-sharing machines with interactive OSes. I went straight from batch processing to microcomputers, which made microcomputers seem all the more exciting.', metadata={'source': 'data/paul_graham/paul_graham_essay.txt'}),
, Document(page_content='What I Worked On\n\nFebruary 2021\n\nBefore college the two main things I worked on, outside of school, were writing and programming. I didn\'t write essays. I wrote what beginning writers were supposed to write then, and probably still are: short stories. My stories were awful. They had hardly any plot, just characters with strong feelings, which I imagined made them deep.\n\nThe first programs I tried writing were on the IBM 1401 that our school district used for what was then called "data processing." This was in 9th grade, so I was 13 or 14. The school district\'s 1401 happened to be in the basement of our junior high school, and my friend Rich Draves and I got permission to use it. It was like a mini Bond villain\'s lair down there, with all these alien-looking machines — CPU, disk drives, printer, card reader — sitting up on a raised floor under bright fluorescent lights.\n\nThe language we used was an early version of Fortran. You had to type programs on punch cards, then stack them in the card reader and press a button to load the program into memory and run it. The result would ordinarily be to print something on the spectacularly loud printer.\n\nI was puzzled by the 1401. I couldn\'t figure out what to do with it. And in retrospect there\'s not much I could have done with it. The only form of input to programs was data stored on punched cards, and I didn\'t have any data stored on punched cards. The only other option was to do things that didn\'t rely on any input, like calculate approximations of pi, but I didn\'t know enough math to do anything interesting of that type. So I\'m not surprised I can\'t remember any programs I wrote, because they can\'t have done much. My clearest memory is of the moment I learned it was possible for programs not to terminate, when one of mine didn\'t. On a machine without time-sharing, this was a social as well as a technical error, as the data center manager\'s expression made clear.\n\nWith microcomputers, everything changed. Now you could have a computer sitting right in front of you, on a desk, that could respond to your keystrokes as it was running instead of just churning through a stack of punch cards and then stopping. [1]\n\nThe first of my friends to get a microcomputer built it himself. It was sold as a kit by Heathkit. I remember vividly how impressed and envious I felt watching him sitting in front of it, typing programs right into the computer.\n\nComputers were expensive in those days and it took me years of nagging before I convinced my father to buy one, a TRS-80, in about 1980. The gold standard then was the Apple II, but a TRS-80 was good enough. This was when I really started programming. I wrote simple games, a program to predict how high my model rockets would fly, and a word processor that my father used to write at least one book. There was only room in memory for about 2 pages of text, so he\'d write 2 pages at a time and then print them out, but it was a lot better than a typewriter.', metadata={'source': 'data/paul_graham/paul_graham_essay.txt'}),
, Document(page_content='At this stage I had a negative net worth, because the thousand dollars or so I had in the bank was more than counterbalanced by what I owed the government in taxes. (Had I diligently set aside the proper proportion of the money I\'d made consulting for Interleaf? No, I had not.) So although Robert had his graduate student stipend, I needed that seed funding to live on.\n\nWe originally hoped to launch in September, but we got more ambitious about the software as we worked on it. Eventually we managed to build a WYSIWYG site builder, in the sense that as you were creating pages, they looked exactly like the static ones that would be generated later, except that instead of leading to static pages, the links all referred to closures stored in a hash table on the server.\n\nIt helped to have studied art, because the main goal of an online store builder is to make users look legit, and the key to looking legit is high production values. If you get page layouts and fonts and colors right, you can make a guy running a store out of his bedroom look more legit than a big company.\n\n(If you\'re curious why my site looks so old-fashioned, it\'s because it\'s still made with this software. It may look clunky today, but in 1996 it was the last word in slick.)\n\nIn September, Robert rebelled. "We\'ve been working on this for a month," he said, "and it\'s still not done." This is funny in retrospect, because he would still be working on it almost 3 years later. But I decided it might be prudent to recruit more programmers, and I asked Robert who else in grad school with him was really good. He recommended Trevor Blackwell, which surprised me at first, because at that point I knew Trevor mainly for his plan to reduce everything in his life to a stack of notecards, which he carried around with him. But Rtm was right, as usual. Trevor turned out to be a frighteningly effective hacker.\n\nIt was a lot of fun working with Robert and Trevor. They\'re the two most independent-minded people I know, and in completely different ways. If you could see inside Rtm\'s brain it would look like a colonial New England church, and if you could see inside Trevor\'s it would look like the worst excesses of Austrian Rococo.\n\nWe opened for business, with 6 stores, in January 1996. It was just as well we waited a few months, because although we worried we were late, we were actually almost fatally early. There was a lot of talk in the press then about ecommerce, but not many people actually wanted online stores. [8]', metadata={'source': 'data/paul_graham/paul_graham_essay.txt'})]

3. Set Up the RAG Pipeline

Now that we have the vectorstore with the documents indexed, we can create the RAG pipeline.

[8]

Let's test our RAG pipeline!

[9]
"According to the provided context, Paul Graham grew up in a family that encouraged his interest in computers. He started writing programs in 9th grade (around 13-14 years old) using an IBM 1401 computer with an early version of Fortran. He and his friend Rich Draves got permission to use the computer in the basement of their junior high school. He tried to write programs, but was puzzled by the 1401 and couldn't figure out what to do with it."

4. Generate Evaluation Dataset

To evaluate our RAG pipeline, we need to generate a dataset with questions that are relevant to our data.

Groq supports providing output JSON by using the json_mode feature. We will use json_mode to generate formatted questions for each document from our data.

We create the qa_chain that takes in a chunk of text and returns 3 questions in JSON format.

[10]

We can generate the questions using the qa_chain in batches using Langchain's abatch method.

[11]
[12]
From document: 
What I Worked On

February 2021

Before college the two main things I worked on, outside of school, were writing and programming. I didn't write essays. I wrote what beginning writers were supposed to write then, and probably still are: short stories. My stories were awful. They had hardly any plot, just characters with strong feelings, which I imagined made them deep.

The first programs I tried writing were on the IBM 1401 that our school district used for what was then called "data processing." This was in 9th grade, so I was 13 or 14. The school district's 1401 happened to be in the basement of our junior high school, and my friend Rich Draves and I got permission to use it. It was like a mini Bond villain's lair down there, with all these alien-looking machines — CPU, disk drives, printer, card reader — sitting up on a raised floor under bright fluorescent lights.

The language we used was an early version of Fortran. You had to type programs on punch cards, then stack them in the card reader and press a button to load the program into memory and run it. The result would ordinarily be to print something on the spectacularly loud printer.

I was puzzled by the 1401. I couldn't figure out what to do with it. And in retrospect there's not much I could have done with it. The only form of input to programs was data stored on punched cards, and I didn't have any data stored on punched cards. The only other option was to do things that didn't rely on any input, like calculate approximations of pi, but I didn't know enough math to do anything interesting of that type. So I'm not surprised I can't remember any programs I wrote, because they can't have done much. My clearest memory is of the moment I learned it was possible for programs not to terminate, when one of mine didn't. On a machine without time-sharing, this was a social as well as a technical error, as the data center manager's expression made clear.

With microcomputers, everything changed. Now you could have a computer sitting right in front of you, on a desk, that could respond to your keystrokes as it was running instead of just churning through a stack of punch cards and then stopping. [1]

The first of my friends to get a microcomputer built it himself. It was sold as a kit by Heathkit. I remember vividly how impressed and envious I felt watching him sitting in front of it, typing programs right into the computer.

Computers were expensive in those days and it took me years of nagging before I convinced my father to buy one, a TRS-80, in about 1980. The gold standard then was the Apple II, but a TRS-80 was good enough. This was when I really started programming. I wrote simple games, a program to predict how high my model rockets would fly, and a word processor that my father used to write at least one book. There was only room in memory for about 2 pages of text, so he'd write 2 pages at a time and then print them out, but it was a lot better than a typewriter.

Questions generated:
1: What were the two main things the author worked on outside of school before college?
2: What was the name of the computer system that the author and his friend Rich Draves used in 9th grade?
3: What was the name of the microcomputer that the author's father bought for him in about 1980?

5. Evaluate the RAG Pipeline

Now let's create a pipeline to evaluate our RAG pipeline on our generated set of questions. To get an evaluation, we need to provide the question, document that the question was generated from, and an answer from the RAG pipeline. We pass all this into our benchmark_llm and use json_mode to return a score as well as an evaluation of the answer.

[13]

Lets test a question and context/answer pair in our newly created benchmark_chain.

[14]
Question: What is the problem with Hacker News (HN) when you both write essays and run a forum?
Answer: According to the given context, when you both write essays and run a forum, a bizarre edge case occurs. When you write essays, people post highly imaginative misinterpretations of them on the forum. Individually, these phenomena are tedious but bearable. However, when combined, they become disastrous.
---------------------
Score: 10
Explanation: The answer accurately summarizes the problem that occurs when you both write essays and run a forum on Hacker News, which is a bizarre edge case where people post misinterpretations of your essays and you have to respond to them, and the combination of these two phenomena becomes disastrous.
---------------------

We can create a function that takes in a list of questions and their corresponding document chunks to run our whole evaluation pipeline.

[15]
[16]
Running RAG pipeline for 15 questions
Time taken: 8.43082308769226
Evaluating RAG pipeline...
Time taken: 10.45450210571289

6. Display and Save the Evaluation Metrics

Let's now display some statistics of our newly created evaluations. For simplicity, we are printing out the results but in production, you should consider using an analytics/evaluations platform.

[17]
Average Score: 9.333333333333334
Standard Deviation of Score: 2.581988897471611
Lowest Score: 0 Count: 1
Highest Score: 10 Count: 14
Evals lower than 5
--------------------------
1. Score: 0
Question: What was the topic the author chose for their dissertation, which they wrote in a short span of 5 weeks?
Answer: The author does not mention writing a dissertation in this context. The text does not mention a dissertation or a specific topic for a dissertation.
Explanation: The answer is incorrect because the text does mention the topic of the dissertation, which is applications of continuations.

Our RAG pipeline did very well! The pipeline answered most of the questions accurately apart from just one, in which it scored 0. Based on the answer and explanation we can infer that the pipeline might not have retrieved the right documents from the vectorstore. To improve the pipeline we can try switching the embeddings model and/or increase the k parameter from our retriever to return more number of documents from the vectorstore.

Let's save the evaluations in the evaluations.csv file.

[18]
Evaluations saved to evaluations.csv

Conclusion

In this notebook, we demonstrated how to set up and evaluate a Retrieval Augmented Generation (RAG) pipeline using Llama3 models powered by Groq and LangChain. The goal of this notebook was to provide an easy-to-follow guide on setting up and evaluating a simple RAG pipeline. We now have valuable metrics and insights that we can use to further optimize and improve our RAG pipeline.

It's important to note that this is just one approach to evaluating your pipeline. In practice, you should consider using dedicated frameworks such as RAGAs to obtain a variety of detailed evaluation metrics to improve your RAG pipeline.