页面简介
In this guide, we will learn how to develop and productionize a retrieval augmented generation (RAG) based LLM application, with a focus on scale and evaluation.
正文摘录
HomeBlogBlog DetailBuilding RAG-based LLM Applications for ProductionBy Goku Mohandas and Philipp Moritz | October 25, 2023Check out our updated RAG blogFor the most up-to-date content on how to run the best RAG pipelines with Ray, read our updated blog. [ GitHub | Notebook | Anyscale Endpoints | Ray Docs] · 55 min readNote: Check out the new evaluation reports and cost analysis with mixtral-8x7b-instruct-v0.1 and our data flywheel workflow to continuously improve our RAG applications.In this guide, we will learn how to:💻 Develop a retrieval augmented generation (RAG) based LLM application from scratch.🚀 Scale the major workloads (load, chunk, embed, index, serve, etc.) across multiple workers with different compute resources.✅ Evaluate different configurations of our application to optimize for both per-component (ex. retrieval_score) and overall performance (quality_score).🔀 Implement a hybrid agent routing approach b/w OSS and closed LLMs to create the most performant and cost effective application.📦 Serve the application in a highly scalable and available manner.💡 Learn how methods like fine-tuning, prompt engineering, lexical search, reranking, data flywheel, etc. impact our application's performance.LinkOverviewLarge language models (LLMs) have undoubtedly changed the way we interact with information. However, they come with their fair share of limitations as to what we can ask of them. Base LLMs (ex. Llama-2-70b, gpt-4, etc.) are only aware of the information that they've been trained on and will fall short when we require them to know information beyond that. Retrieval augmented generation (RAG) based LLM applications address this exact issue and extend the utility of LLMs to our specific data sources. image1In this guide, we're going to build a RAG-based LLM application where we will incorporate external data sources to augment our LLM’s capabilities. Specifically, we will be building an assistant that can answer questions about Ray — a Python framework for productionizing and scaling ML workloads. The goal here is to make it easier for developers to adopt Ray, but also, as we'll see in this guide, to help improve our Ray documentation itself and provide a foundation for other LLM applications. We’ll also share challenges we faced along the way and how we overcame them.Note: We have generalized this entire guide so that it can easily be extended to build RAG-based LLM applications on top of your own data.image2Pass the query to the embedding model to semantically represent it as an embedded query vector.Pass the embedded query vector to our vector DB.Retrieve the top-k relevant contexts – measured by distance between the query embedding and all the embedded chunks in our knowledge base.Pass the query text and retrieved context text to our LLM.The LLM will generate a response using the provided content.Besides just building our LLM application, we’re also going to be focused on scaling and serving it in production. Unlike traditional machine learning, or even supervised deep learning, scale is a bottleneck for LLM applications from the very beginning. Large datasets, models, compute intensive workloads, serving requirements, etc. We’ll develop our application to be able to handle any scale as the world around us continues to grow.We’re also going to be focused on evaluation and performance. Our application involves many moving pieces: embedding models, chunking logic, the LLM itself, etc. and so it's important that we experiment with different configurations to optimize for the best quality responses. However, it's non-trivial to evaluate and quantitatively compare different configurations for a generative task. We’re going to break down evaluation of individual parts of our application (retrieval given query, generation given source), also assess the overall performance (end-to-end generation) and share findings towards an optimized configuration.Note: We'll be experimenting with different LLMs (OpenAI, Llama, etc.) in this guide. You will need OpenAI credentials to access ChatGPT models and Anyscale Endpoints (public and private endpoints available) to serve + fine-tune OSS LLMs.LinkVector DB creationBefore we can start building our RAG application, we need to first create our vector DB that will contain our processed data sources.image3LinkLoad dataWe’re going to start by loading the Ray documentation from the website to a local directory:1export EFS_DIR=/desired/output/directory 2wget -e robots=off --recursive --no-clobber --page-requisites \ 3 --html-extension --convert-links --restrict-file-names=windows \ 4 --domains docs.ray.io --no-parent --accept=html \ 5 -P $EFS_DIR https://docs.ray.io/en/master/We’re going to then load our docs contents into a Ray Dataset so that we can perform operations at scale on them (ex. embed, index, etc.). With large data sources, models and application serving needs, scale is a day-1 priority for LLM applications. We want to build our applications in such a way that they can scale as our needs grow without us having to change our code later.1# Ray dataset 2DOCS_DIR = Path(EFS_DIR, "docs.ray.io/en/master/") 3ds = ray.data.from_items([{"path": path} for path in DOCS_DIR.rglob("*.html") 4if not path.is_dir()]) 5print(f"{ds.count()} documents")LinkSectionsNow that we have a dataset of all the paths to the html files, we're going to develop some functions that can appropriately extract the content from these files. We want to do this in a generalized manner so that we can perform this extraction across all of our docs pages (and so you can use it for your own data sources). Our process is to first identify the sections in our html page and then extract the text in between them. We save all of this into a list of dictionaries that map the text within a section to a specific url with a section anchor id.image51sample_html_fp = Path(EFS_DIR, "docs.ray.io/en/master/rllib/rllib-env.html") 2extract_sections({"path": sample_html_fp})[0] 3{'source': 'https://docs.ray.io/en/master/rllib/rllib-env.html#environments', 'text': '\nEnvironments#\nRLlib works with several different types of environments, including Farama-Foundation Gymnasium, user-defined, multi-agent, and also batched environments.\nTip\nNot all environments work with all algorithms. Check out the algorithm overview for more information.\n'}We can apply this extraction process (extract_section) in parallel to all the file paths in our dataset with just one line using Ray Data’s flat_map.1# Extract sections 2sections_ds = ds.flat_map(extract_sections) 3sections = sections_ds.take_all() 4print (len(sections)) 5LinkChunk dataWe now have a list of sections (with text and source of each section) but we shouldn't directly use this as context to our RAG application just yet. The text lengths of each section are all varied and many are quite large chunks. image7If we were to use these large sections, then we'd be inserting a lot of noisy/unwanted context and because all LLMs have a maximum context length, we wouldn't be able to fit too much other relevant context. So instead, we're going to split the text within each section into smaller chunks. Intuitively, smaller chunks will encapsulate single/few concepts and will be less noisy compared to larger chunks. We're going to choose some typical text splitting values (ex. chunk_size=300) to create our chunks for now but we'll be experimenting with a wider range of values later.1from langchain.document_loaders import ReadTheDocsLoader 2from langchain.text_splitter import RecursiveCharacterTextSplitter 3 4# Text splitter 5chunk_size = 300 6chunk_overlap = 50 7text_splitter = RecursiveCharacterTextSplitter( 8 separators=["\n\n", "\n", " ", ""], 9 chunk_size=chunk_size, 10 chunk_overlap=chunk_overlap, 11 length_function=len, 12) 13 14# Chunk a sample section 15sample_section = sections_ds.take(1)[0] 16chunks = text_splitter.create_documents( 17 texts=[sample_section["text"]], 18 metadatas=[{"source": sample_section["source"]}]) 19print (chunks[0]) 20page_content='ray.tune.TuneConfig.search_alg#\nTuneConfig.search_alg: Optional[Union[ray.tune.search.searcher.Searcher, ray.tune.search.search_algorithm.SearchAlgorithm]] = None#' metadata={'source': 'https://docs.ray.io/en/master/tune/api/doc/ray.tune.TuneConfig.search_alg.html#ray-tune-tuneconfig-search-alg'}While chunking our dataset is relatively fast, let’s wrap the chunking logic into a function so that we can apply the workload at scale so that chunking remains just as fast as our data sources grow:1def chunk_section(section, chunk_size, chunk_overlap): 2 text_splitter = RecursiveCharacterTextSplitter( 3 separators=["\n\n", "\n", " ", ""], 4 chunk_size=chunk_size, 5 chunk_overlap=chunk_overlap, 6 length_function=len) 7 chunks = text_splitter.create_documents( 8 texts=[sample_section["text"]], 9 metadatas=[{"source": sample_section["source"]}]) 10 return [{"text": chunk.page_content, "source": chunk.metadata["source"]} for chunk in chunks] 11 12# Scale chunking 13chunks_ds = sections_ds.flat_map(partial( 14 chunk_section, 15 chunk_size=chunk_size, 16 chunk_overlap=chunk_overlap)) 17print(f"{chunks_ds.count()} chunks") 18chunks_ds.show(1) 195727 chunks{'text': 'ray.tune.TuneConfig.search_alg#\nTuneConfig.search_alg: Optional[Union[ray.tune.search.searcher.Searcher, ray.tune.search.search_algorithm.SearchAlgorithm]] = None#', 'source': 'https://docs.ray.io/en/master/tune/api/doc/ray.tune.TuneConfig.search_alg.html#ray-tune-tuneconfig-search-alg'}LinkEmbed dataNow that we've created small chunks from our sections, we need a way to identify the most relevant ones for a given query. A very effective and quick method is to embed our data using a pretrained model and use the same model to embed the query. We can then compute the distance between all of the chunk embeddings and our query embedding to determine the top-k chunks. There are many different pretrained models to choose from to embed our data but the most popular ones can be di