Buckets:

hf-doc-build/doc-dev / cookbook /main /en /rag_evaluation.html
rtrm's picture
download
raw
106 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;RAG Evaluation&quot;,&quot;local&quot;:&quot;rag-evaluation&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Evaluating RAG performance&quot;,&quot;local&quot;:&quot;evaluating-rag-performance&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Load your knowledge base&quot;,&quot;local&quot;:&quot;load-your-knowledge-base&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:1}">
<link href="/docs/cookbook/main/en/_app/immutable/assets/0.e3b0c442.css" rel="modulepreload">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/entry/start.96b44205.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/scheduler.65852ee5.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/singletons.a64a46c3.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/paths.f88132ad.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/entry/app.e92a3d99.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/index.aa74147d.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/nodes/0.0809e592.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/each.e59479a4.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/nodes/33.1bdc9a8d.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/DocNotebookDropdown.479f4286.js">
<link rel="modulepreload" href="/docs/cookbook/main/en/_app/immutable/chunks/EditOnGithub.4eda6a96.js"><!-- HEAD_svelte-u9bgzb_START --><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;RAG Evaluation&quot;,&quot;local&quot;:&quot;rag-evaluation&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Evaluating RAG performance&quot;,&quot;local&quot;:&quot;evaluating-rag-performance&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3},{&quot;title&quot;:&quot;Load your knowledge base&quot;,&quot;local&quot;:&quot;load-your-knowledge-base&quot;,&quot;sections&quot;:[],&quot;depth&quot;:3}],&quot;depth&quot;:1}"><!-- HEAD_svelte-u9bgzb_END --> <p></p> <div class="flex space-x-1 absolute z-10 right-0 top-0"> <a href="https://colab.research.google.com/github/huggingface/cookbook/blob/multiagent_assist_improvements/notebooks/en/rag_evaluation.ipynb" target="_blank"><img alt="Open In Colab" class="!m-0" src="https://colab.research.google.com/assets/colab-badge.svg"></a> </div> <h1 class="relative group"><a id="rag-evaluation" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#rag-evaluation"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>RAG Evaluation</span></h1> <p data-svelte-h="svelte-1xlqnsv"><em>Authored by: <a href="https://huggingface.co/m-ric" rel="nofollow">Aymeric Roucher</a></em></p> <p data-svelte-h="svelte-2xiv25">This notebook demonstrates how you can evaluate your RAG (Retrieval Augmented Generation), by building a synthetic evaluation dataset and using LLM-as-a-judge to compute the accuracy of your system.</p> <p data-svelte-h="svelte-1460hpm">For an introduction to RAG, you can check <a href="rag_zephyr_langchain">this other cookbook</a>!</p> <p data-svelte-h="svelte-9eyhtm">RAG systems are complex: here a RAG diagram, where we noted in blue all possibilities for system enhancement:</p> <img src="https://huggingface.co/datasets/huggingface/cookbook-images/resolve/main/RAG_workflow.png" height="700"> <p data-svelte-h="svelte-1wwknqm">Implementing any of these improvements can bring a huge performance boost; but changing anything is useless if you cannot monitor the impact of your changes on the system’s performance!
So let’s see how to evaluate our RAG system.</p> <h3 class="relative group"><a id="evaluating-rag-performance" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#evaluating-rag-performance"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Evaluating RAG performance</span></h3> <p data-svelte-h="svelte-vv8zeo">Since there are so many moving parts to tune with a big impact on performance, benchmarking the RAG system is crucial.</p> <p data-svelte-h="svelte-baonz3">For our evaluation pipeline, we will need:</p> <ol data-svelte-h="svelte-12qpxq2"><li>An evaluation dataset with question - answer couples (QA couples)</li> <li>An evaluator to compute the accuracy of our system on the above evaluation dataset.</li></ol> <p data-svelte-h="svelte-gq3s7j">➡️ It turns out, we can use LLMs to help us all along the way!</p> <ol data-svelte-h="svelte-qbxvp7"><li>The evaluation dataset will be synthetically generated by an LLM 🤖, and questions will be filtered out by other LLMs 🤖</li> <li>An <a href="https://huggingface.co/papers/2306.05685" rel="nofollow">LLM-as-a-judge</a> agent 🤖 will then perform the evaluation on this synthetic dataset.</li></ol> <p data-svelte-h="svelte-15hqrk"><strong>Let’s dig into it and start building our evaluation pipeline!</strong> First, we install the required model dependancies.</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->!pip install -q torch transformers transformers langchain sentence-transformers tqdm openpyxl openai pandas datasets langchain-community ragatouille<!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->%reload_ext autoreload
%autoreload <span class="hljs-number">2</span><!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> tqdm.auto <span class="hljs-keyword">import</span> tqdm
<span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
<span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> <span class="hljs-type">Optional</span>, <span class="hljs-type">List</span>, <span class="hljs-type">Tuple</span>
<span class="hljs-keyword">import</span> json
<span class="hljs-keyword">import</span> datasets
pd.set_option(<span class="hljs-string">&quot;display.max_colwidth&quot;</span>, <span class="hljs-literal">None</span>)<!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> notebook_login
notebook_login()<!-- HTML_TAG_END --></pre></div> <h3 class="relative group"><a id="load-your-knowledge-base" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#load-your-knowledge-base"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Load your knowledge base</span></h3> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->ds = datasets.load_dataset(<span class="hljs-string">&quot;m-ric/huggingface_doc&quot;</span>, split=<span class="hljs-string">&quot;train&quot;</span>)<!-- HTML_TAG_END --></pre></div> <h1 class="relative group"><a id="1-build-a-synthetic-dataset-for-evaluation" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#1-build-a-synthetic-dataset-for-evaluation"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>1. Build a synthetic dataset for evaluation</span></h1> <p data-svelte-h="svelte-1wbiyhw">We first build a synthetic dataset of questions and associated contexts. The method is to get elements from our knowledge base, and ask an LLM to generate questions based on these documents.</p> <p data-svelte-h="svelte-1o0ze03">Then we setup other LLM agents to act as quality filters for the generated QA couples: each of them will act as the filter for a specific flaw.</p> <h3 class="relative group"><a id="11-prepare-source-documents" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#11-prepare-source-documents"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>1.1. Prepare source documents</span></h3> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> langchain.text_splitter <span class="hljs-keyword">import</span> RecursiveCharacterTextSplitter
<span class="hljs-keyword">from</span> langchain.docstore.document <span class="hljs-keyword">import</span> Document <span class="hljs-keyword">as</span> LangchainDocument
langchain_docs = [LangchainDocument(page_content=doc[<span class="hljs-string">&quot;text&quot;</span>], metadata={<span class="hljs-string">&quot;source&quot;</span>: doc[<span class="hljs-string">&quot;source&quot;</span>]}) <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> tqdm(ds)]
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=<span class="hljs-number">2000</span>,
chunk_overlap=<span class="hljs-number">200</span>,
add_start_index=<span class="hljs-literal">True</span>,
separators=[<span class="hljs-string">&quot;\n\n&quot;</span>, <span class="hljs-string">&quot;\n&quot;</span>, <span class="hljs-string">&quot;.&quot;</span>, <span class="hljs-string">&quot; &quot;</span>, <span class="hljs-string">&quot;&quot;</span>],
)
docs_processed = []
<span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> langchain_docs:
docs_processed += text_splitter.split_documents([doc])<!-- HTML_TAG_END --></pre></div> <h3 class="relative group"><a id="12-setup-agents-for-question-generation" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#12-setup-agents-for-question-generation"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>1.2. Setup agents for question generation</span></h3> <p data-svelte-h="svelte-162gsjg">We use <a href="https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1" rel="nofollow">Mixtral</a> for QA couple generation because it it has excellent performance in leaderboards such as <a href="https://huggingface.co/spaces/lmsys/chatbot-arena-leaderboard" rel="nofollow">Chatbot Arena</a>.</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> InferenceClient
repo_id = <span class="hljs-string">&quot;mistralai/Mixtral-8x7B-Instruct-v0.1&quot;</span>
llm_client = InferenceClient(
model=repo_id,
timeout=<span class="hljs-number">120</span>,
)
<span class="hljs-keyword">def</span> <span class="hljs-title function_">call_llm</span>(<span class="hljs-params">inference_client: InferenceClient, prompt: <span class="hljs-built_in">str</span></span>):
response = inference_client.post(
json={
<span class="hljs-string">&quot;inputs&quot;</span>: prompt,
<span class="hljs-string">&quot;parameters&quot;</span>: {<span class="hljs-string">&quot;max_new_tokens&quot;</span>: <span class="hljs-number">1000</span>},
<span class="hljs-string">&quot;task&quot;</span>: <span class="hljs-string">&quot;text-generation&quot;</span>,
},
)
<span class="hljs-keyword">return</span> json.loads(response.decode())[<span class="hljs-number">0</span>][<span class="hljs-string">&quot;generated_text&quot;</span>]
call_llm(llm_client, <span class="hljs-string">&quot;This is a test context&quot;</span>)<!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->QA_generation_prompt = <span class="hljs-string">&quot;&quot;&quot;
Your task is to write a factoid question and an answer given a context.
Your factoid question should be answerable with a specific, concise piece of factual information from the context.
Your factoid question should be formulated in the same style as questions users could ask in a search engine.
This means that your factoid question MUST NOT mention something like &quot;according to the passage&quot; or &quot;context&quot;.
Provide your answer as follows:
Output:::
Factoid question: (your factoid question)
Answer: (your answer to the factoid question)
Now here is the context.
Context: {context}\n
Output:::&quot;&quot;&quot;</span><!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1v7z1mr">Now let’s generate our QA couples.
For this example, we generate only 10 QA couples and will load the rest from the Hub.</p> <p data-svelte-h="svelte-jsmlwo">But for your specific knowledge base, given that you want to get at least ~100 test samples, and accounting for the fact that we will filter out around half of these with our critique agents later on, you should generate much more, in the &gt;200 samples.</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">import</span> random
N_GENERATIONS = <span class="hljs-number">10</span> <span class="hljs-comment"># We intentionally generate only 10 QA couples here for cost and time considerations</span>
<span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Generating <span class="hljs-subst">{N_GENERATIONS}</span> QA couples...&quot;</span>)
outputs = []
<span class="hljs-keyword">for</span> sampled_context <span class="hljs-keyword">in</span> tqdm(random.sample(docs_processed, N_GENERATIONS)):
<span class="hljs-comment"># Generate QA couple</span>
output_QA_couple = call_llm(llm_client, QA_generation_prompt.<span class="hljs-built_in">format</span>(context=sampled_context.page_content))
<span class="hljs-keyword">try</span>:
question = output_QA_couple.split(<span class="hljs-string">&quot;Factoid question: &quot;</span>)[-<span class="hljs-number">1</span>].split(<span class="hljs-string">&quot;Answer: &quot;</span>)[<span class="hljs-number">0</span>]
answer = output_QA_couple.split(<span class="hljs-string">&quot;Answer: &quot;</span>)[-<span class="hljs-number">1</span>]
<span class="hljs-keyword">assert</span> <span class="hljs-built_in">len</span>(answer) &lt; <span class="hljs-number">300</span>, <span class="hljs-string">&quot;Answer is too long&quot;</span>
outputs.append(
{
<span class="hljs-string">&quot;context&quot;</span>: sampled_context.page_content,
<span class="hljs-string">&quot;question&quot;</span>: question,
<span class="hljs-string">&quot;answer&quot;</span>: answer,
<span class="hljs-string">&quot;source_doc&quot;</span>: sampled_context.metadata[<span class="hljs-string">&quot;source&quot;</span>],
}
)
<span class="hljs-keyword">except</span>:
<span class="hljs-keyword">continue</span><!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->display(pd.DataFrame(outputs).head(<span class="hljs-number">1</span>))<!-- HTML_TAG_END --></pre></div> <h3 class="relative group"><a id="13-setup-critique-agents" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#13-setup-critique-agents"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>1.3. Setup critique agents</span></h3> <p data-svelte-h="svelte-xa68th">The questions generated by the previous agent can have many flaws: we should do a quality check before validating these questions.</p> <p data-svelte-h="svelte-1rn1tpr">We thus build critique agents that will rate each question on several criteria, given in <a href="https://huggingface.co/papers/2312.10003" rel="nofollow">this paper</a>:</p> <ul data-svelte-h="svelte-mge22a"><li><strong>Groundedness:</strong> can the question be answered from the given context?</li> <li><strong>Relevance:</strong> is the question relevant to users? For instance, <code>&quot;What is the date when transformers 4.29.1 was released?&quot;</code> is not relevant for ML practicioners.</li></ul> <p data-svelte-h="svelte-1a9sdbs">One last failure case we’ve noticed is when a function is tailored for the particular setting where the question was generated, but undecipherable by itself, like <code>&quot;What is the name of the function used in this guide?&quot;</code>.
We also build a critique agent for this criteria:</p> <ul data-svelte-h="svelte-17ofou1"><li><strong>Stand-alone</strong>: is the question understandable free of any context, for someone with domain knowledge/Internet access? The opposite of this would be <code>What is the function used in this article?</code> for a question generated from a specific blog article.</li></ul> <p data-svelte-h="svelte-1bu41t1">We systematically score functions with all these agents, and whenever the score is too low for any one of the agents, we eliminate the question from our eval dataset.</p> <p data-svelte-h="svelte-v7jbl8">💡 <strong><em>When asking the agents to output a score, we first ask them to produce its rationale. This will help us verify scores, but most importantly, asking it to first output rationale gives the model more tokens to think and elaborate an answer before summarizing it into a single score token.</em></strong></p> <p data-svelte-h="svelte-1kwgyx1">We now build and run these critique agents.</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->question_groundedness_critique_prompt = <span class="hljs-string">&quot;&quot;&quot;
You will be given a context and a question.
Your task is to provide a &#x27;total rating&#x27; scoring how well one can answer the given question unambiguously with the given context.
Give your answer on a scale of 1 to 5, where 1 means that the question is not answerable at all given the context, and 5 means that the question is clearly and unambiguously answerable with the context.
Provide your answer as follows:
Answer:::
Evaluation: (your rationale for the rating, as a text)
Total rating: (your rating, as a number between 1 and 5)
You MUST provide values for &#x27;Evaluation:&#x27; and &#x27;Total rating:&#x27; in your answer.
Now here are the question and context.
Question: {question}\n
Context: {context}\n
Answer::: &quot;&quot;&quot;</span>
question_relevance_critique_prompt = <span class="hljs-string">&quot;&quot;&quot;
You will be given a question.
Your task is to provide a &#x27;total rating&#x27; representing how useful this question can be to machine learning developers building NLP applications with the Hugging Face ecosystem.
Give your answer on a scale of 1 to 5, where 1 means that the question is not useful at all, and 5 means that the question is extremely useful.
Provide your answer as follows:
Answer:::
Evaluation: (your rationale for the rating, as a text)
Total rating: (your rating, as a number between 1 and 5)
You MUST provide values for &#x27;Evaluation:&#x27; and &#x27;Total rating:&#x27; in your answer.
Now here is the question.
Question: {question}\n
Answer::: &quot;&quot;&quot;</span>
question_standalone_critique_prompt = <span class="hljs-string">&quot;&quot;&quot;
You will be given a question.
Your task is to provide a &#x27;total rating&#x27; representing how context-independant this question is.
Give your answer on a scale of 1 to 5, where 1 means that the question depends on additional information to be understood, and 5 means that the question makes sense by itself.
For instance, if the question refers to a particular setting, like &#x27;in the context&#x27; or &#x27;in the document&#x27;, the rating must be 1.
The questions can contain obscure technical nouns or acronyms like Gradio, Hub, Hugging Face or Space and still be a 5: it must simply be clear to an operator with access to documentation what the question is about.
For instance, &quot;What is the name of the checkpoint from which the ViT model is imported?&quot; should receive a 1, since there is an implicit mention of a context, thus the question is not independant from the context.
Provide your answer as follows:
Answer:::
Evaluation: (your rationale for the rating, as a text)
Total rating: (your rating, as a number between 1 and 5)
You MUST provide values for &#x27;Evaluation:&#x27; and &#x27;Total rating:&#x27; in your answer.
Now here is the question.
Question: {question}\n
Answer::: &quot;&quot;&quot;</span><!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Generating critique for each QA couple...&quot;</span>)
<span class="hljs-keyword">for</span> output <span class="hljs-keyword">in</span> tqdm(outputs):
evaluations = {
<span class="hljs-string">&quot;groundedness&quot;</span>: call_llm(
llm_client,
question_groundedness_critique_prompt.<span class="hljs-built_in">format</span>(context=output[<span class="hljs-string">&quot;context&quot;</span>], question=output[<span class="hljs-string">&quot;question&quot;</span>]),
),
<span class="hljs-string">&quot;relevance&quot;</span>: call_llm(
llm_client,
question_relevance_critique_prompt.<span class="hljs-built_in">format</span>(question=output[<span class="hljs-string">&quot;question&quot;</span>]),
),
<span class="hljs-string">&quot;standalone&quot;</span>: call_llm(
llm_client,
question_standalone_critique_prompt.<span class="hljs-built_in">format</span>(question=output[<span class="hljs-string">&quot;question&quot;</span>]),
),
}
<span class="hljs-keyword">try</span>:
<span class="hljs-keyword">for</span> criterion, evaluation <span class="hljs-keyword">in</span> evaluations.items():
score, <span class="hljs-built_in">eval</span> = (
<span class="hljs-built_in">int</span>(evaluation.split(<span class="hljs-string">&quot;Total rating: &quot;</span>)[-<span class="hljs-number">1</span>].strip()),
evaluation.split(<span class="hljs-string">&quot;Total rating: &quot;</span>)[-<span class="hljs-number">2</span>].split(<span class="hljs-string">&quot;Evaluation: &quot;</span>)[<span class="hljs-number">1</span>],
)
output.update(
{
<span class="hljs-string">f&quot;<span class="hljs-subst">{criterion}</span>_score&quot;</span>: score,
<span class="hljs-string">f&quot;<span class="hljs-subst">{criterion}</span>_eval&quot;</span>: <span class="hljs-built_in">eval</span>,
}
)
<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
<span class="hljs-keyword">continue</span><!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-yms2wp">Now let us filter out bad questions based on our critique agent scores:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
<span class="hljs-meta">&gt;&gt;&gt; </span>pd.set_option(<span class="hljs-string">&quot;display.max_colwidth&quot;</span>, <span class="hljs-literal">None</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>generated_questions = pd.DataFrame.from_dict(outputs)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Evaluation dataset before filtering:&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>display(
<span class="hljs-meta">... </span> generated_questions[
<span class="hljs-meta">... </span> [
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;question&quot;</span>,
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;answer&quot;</span>,
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;groundedness_score&quot;</span>,
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;relevance_score&quot;</span>,
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;standalone_score&quot;</span>,
<span class="hljs-meta">... </span> ]
<span class="hljs-meta">... </span> ]
<span class="hljs-meta">... </span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>generated_questions = generated_questions.loc[
<span class="hljs-meta">... </span> (generated_questions[<span class="hljs-string">&quot;groundedness_score&quot;</span>] &gt;= <span class="hljs-number">4</span>)
<span class="hljs-meta">... </span> &amp; (generated_questions[<span class="hljs-string">&quot;relevance_score&quot;</span>] &gt;= <span class="hljs-number">4</span>)
<span class="hljs-meta">... </span> &amp; (generated_questions[<span class="hljs-string">&quot;standalone_score&quot;</span>] &gt;= <span class="hljs-number">4</span>)
<span class="hljs-meta">... </span>]
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;============================================&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Final evaluation dataset:&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>display(
<span class="hljs-meta">... </span> generated_questions[
<span class="hljs-meta">... </span> [
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;question&quot;</span>,
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;answer&quot;</span>,
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;groundedness_score&quot;</span>,
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;relevance_score&quot;</span>,
<span class="hljs-meta">... </span> <span class="hljs-string">&quot;standalone_score&quot;</span>,
<span class="hljs-meta">... </span> ]
<span class="hljs-meta">... </span> ]
<span class="hljs-meta">... </span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>eval_dataset = datasets.Dataset.from_pandas(generated_questions, split=<span class="hljs-string">&quot;train&quot;</span>, preserve_index=<span class="hljs-literal">False</span>)<!-- HTML_TAG_END --></pre></div> <pre data-svelte-h="svelte-1k8l62p">Evaluation dataset before filtering:
</pre> <p data-svelte-h="svelte-1asqnia">Now our synthetic evaluation dataset is complete! We can evaluate different RAG systems on this evaluation dataset.</p> <p data-svelte-h="svelte-alkdir">We have generated only a few QA couples here to reduce time and cost. But let’s kick start the next part by loading a pre-generated dataset:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->eval_dataset = datasets.load_dataset(<span class="hljs-string">&quot;m-ric/huggingface_doc_qa_eval&quot;</span>, split=<span class="hljs-string">&quot;train&quot;</span>)<!-- HTML_TAG_END --></pre></div> <h1 class="relative group"><a id="2-build-our-rag-system" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#2-build-our-rag-system"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>2. Build our RAG System</span></h1> <h3 class="relative group"><a id="21-preprocessing-documents-to-build-our-vector-database" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#21-preprocessing-documents-to-build-our-vector-database"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>2.1. Preprocessing documents to build our vector database</span></h3> <ul data-svelte-h="svelte-1fnij86"><li>In this part, <strong>we split the documents from our knowledge base into smaller chunks</strong>: these will be the snippets that are picked by the Retriever, to then be ingested by the Reader LLM as supporting elements for its answer.</li> <li>The goal is to build semantically relevant snippets: not too small to be sufficient for supporting an answer, and not too large too avoid diluting individual ideas.</li></ul> <p data-svelte-h="svelte-53zzzq">Many options exist for text splitting:</p> <ul data-svelte-h="svelte-1g19xro"><li>split every <code>n</code> words / characters, but this has the risk of cutting in half paragraphs or even sentences</li> <li>split after <code>n</code> words / character, but only on sentence boundaries</li> <li><strong>recursive split</strong> tries to preserve even more of the document structure, by processing it tree-like way, splitting first on the largest units (chapters) then recursively splitting on smaller units (paragraphs, sentences).</li></ul> <p data-svelte-h="svelte-1ns6yk3">To learn more about chunking, I recommend you read <a href="https://github.com/FullStackRetrieval-com/RetrievalTutorials/blob/main/tutorials/LevelsOfTextSplitting/5_Levels_Of_Text_Splitting.ipynb" rel="nofollow">this great notebook</a> by Greg Kamradt.</p> <p data-svelte-h="svelte-1hitev5"><a href="https://huggingface.co/spaces/m-ric/chunk_visualizer" rel="nofollow">This space</a> lets you visualize how different splitting options affect the chunks you get.</p> <blockquote data-svelte-h="svelte-w4wn00"><p>In the following, we use Langchain’s <code>RecursiveCharacterTextSplitter</code>.</p></blockquote> <p data-svelte-h="svelte-1toh8cv">💡 <em>To measure chunk length in our Text Splitter, our length function will not be the count of characters, but the count of tokens in the tokenized text: indeed, for subsequent embedder that processes token, measuring length in tokens is more relevant and empirically performs better.</em></p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> langchain.docstore.document <span class="hljs-keyword">import</span> Document <span class="hljs-keyword">as</span> LangchainDocument
RAW_KNOWLEDGE_BASE = [
LangchainDocument(page_content=doc[<span class="hljs-string">&quot;text&quot;</span>], metadata={<span class="hljs-string">&quot;source&quot;</span>: doc[<span class="hljs-string">&quot;source&quot;</span>]}) <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> tqdm(ds)
]<!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> langchain.text_splitter <span class="hljs-keyword">import</span> RecursiveCharacterTextSplitter
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer
<span class="hljs-keyword">def</span> <span class="hljs-title function_">split_documents</span>(<span class="hljs-params">
chunk_size: <span class="hljs-built_in">int</span>,
knowledge_base: <span class="hljs-type">List</span>[LangchainDocument],
tokenizer_name: <span class="hljs-built_in">str</span>,
</span>) -&gt; <span class="hljs-type">List</span>[LangchainDocument]:
<span class="hljs-string">&quot;&quot;&quot;
Split documents into chunks of size `chunk_size` characters and return a list of documents.
&quot;&quot;&quot;</span>
text_splitter = RecursiveCharacterTextSplitter.from_huggingface_tokenizer(
AutoTokenizer.from_pretrained(tokenizer_name),
chunk_size=chunk_size,
chunk_overlap=<span class="hljs-built_in">int</span>(chunk_size / <span class="hljs-number">10</span>),
add_start_index=<span class="hljs-literal">True</span>,
strip_whitespace=<span class="hljs-literal">True</span>,
separators=[<span class="hljs-string">&quot;\n\n&quot;</span>, <span class="hljs-string">&quot;\n&quot;</span>, <span class="hljs-string">&quot;.&quot;</span>, <span class="hljs-string">&quot; &quot;</span>, <span class="hljs-string">&quot;&quot;</span>],
)
docs_processed = []
<span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> knowledge_base:
docs_processed += text_splitter.split_documents([doc])
<span class="hljs-comment"># Remove duplicates</span>
unique_texts = {}
docs_processed_unique = []
<span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> docs_processed:
<span class="hljs-keyword">if</span> doc.page_content <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> unique_texts:
unique_texts[doc.page_content] = <span class="hljs-literal">True</span>
docs_processed_unique.append(doc)
<span class="hljs-keyword">return</span> docs_processed_unique<!-- HTML_TAG_END --></pre></div> <h3 class="relative group"><a id="22-retriever---embeddings-" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#22-retriever---embeddings-"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>2.2. Retriever - embeddings 🗂️</span></h3> <p data-svelte-h="svelte-xymbek">The <strong>retriever acts like an internal search engine</strong>: given the user query, it returns the most relevant documents from your knowledge base.</p> <blockquote data-svelte-h="svelte-1k8ukvt"><p>For the knowledge base, we use Langchain vector databases since <strong>it offers a convenient <a href="https://github.com/facebookresearch/faiss" rel="nofollow">FAISS</a> index and allows us to keep document metadata throughout the processing</strong>.</p></blockquote> <p data-svelte-h="svelte-1hqptzf">🛠️ <strong>Options included:</strong></p> <ul data-svelte-h="svelte-1w0jpt6"><li>Tune the chunking method:<ul><li>Size of the chunks</li> <li>Method: split on different separators, use <a href="https://python.langchain.com/docs/modules/data_connection/document_transformers/semantic-chunker" rel="nofollow">semantic chunking</a></li></ul></li> <li>Change the embedding model</li></ul> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> langchain.vectorstores <span class="hljs-keyword">import</span> FAISS
<span class="hljs-keyword">from</span> langchain_community.embeddings <span class="hljs-keyword">import</span> HuggingFaceEmbeddings
<span class="hljs-keyword">from</span> langchain_community.vectorstores.utils <span class="hljs-keyword">import</span> DistanceStrategy
<span class="hljs-keyword">import</span> os
<span class="hljs-keyword">def</span> <span class="hljs-title function_">load_embeddings</span>(<span class="hljs-params">
langchain_docs: <span class="hljs-type">List</span>[LangchainDocument],
chunk_size: <span class="hljs-built_in">int</span>,
embedding_model_name: <span class="hljs-type">Optional</span>[<span class="hljs-built_in">str</span>] = <span class="hljs-string">&quot;thenlper/gte-small&quot;</span>,
</span>) -&gt; FAISS:
<span class="hljs-string">&quot;&quot;&quot;
Creates a FAISS index from the given embedding model and documents. Loads the index directly if it already exists.
Args:
langchain_docs: list of documents
chunk_size: size of the chunks to split the documents into
embedding_model_name: name of the embedding model to use
Returns:
FAISS index
&quot;&quot;&quot;</span>
<span class="hljs-comment"># load embedding_model</span>
embedding_model = HuggingFaceEmbeddings(
model_name=embedding_model_name,
multi_process=<span class="hljs-literal">True</span>,
model_kwargs={<span class="hljs-string">&quot;device&quot;</span>: <span class="hljs-string">&quot;cuda&quot;</span>},
encode_kwargs={<span class="hljs-string">&quot;normalize_embeddings&quot;</span>: <span class="hljs-literal">True</span>}, <span class="hljs-comment"># set True to compute cosine similarity</span>
)
<span class="hljs-comment"># Check if embeddings already exist on disk</span>
index_name = <span class="hljs-string">f&quot;index_chunk:<span class="hljs-subst">{chunk_size}</span>_embeddings:<span class="hljs-subst">{embedding_model_name.replace(<span class="hljs-string">&#x27;/&#x27;</span>, <span class="hljs-string">&#x27;~&#x27;</span>)}</span>&quot;</span>
index_folder_path = <span class="hljs-string">f&quot;./data/indexes/<span class="hljs-subst">{index_name}</span>/&quot;</span>
<span class="hljs-keyword">if</span> os.path.isdir(index_folder_path):
<span class="hljs-keyword">return</span> FAISS.load_local(
index_folder_path,
embedding_model,
distance_strategy=DistanceStrategy.COSINE,
)
<span class="hljs-keyword">else</span>:
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Index not found, generating it...&quot;</span>)
docs_processed = split_documents(
chunk_size,
langchain_docs,
embedding_model_name,
)
knowledge_index = FAISS.from_documents(
docs_processed, embedding_model, distance_strategy=DistanceStrategy.COSINE
)
knowledge_index.save_local(index_folder_path)
<span class="hljs-keyword">return</span> knowledge_index<!-- HTML_TAG_END --></pre></div> <h3 class="relative group"><a id="23-reader---llm-" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#23-reader---llm-"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>2.3. Reader - LLM 💬</span></h3> <p data-svelte-h="svelte-1m0x0qs">In this part, the <strong>LLM Reader reads the retrieved documents to formulate its answer.</strong></p> <p data-svelte-h="svelte-1e3sl85">🛠️ Here we tried the following options to improve results:</p> <ul data-svelte-h="svelte-1scj3jf"><li>Switch reranking on/off</li> <li>Change the reader model</li></ul> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->RAG_PROMPT_TEMPLATE = <span class="hljs-string">&quot;&quot;&quot;
&lt;|system|&gt;
Using the information contained in the context,
give a comprehensive answer to the question.
Respond only to the question asked, response should be concise and relevant to the question.
Provide the number of the source document when relevant.
If the answer cannot be deduced from the context, do not give an answer.&lt;/s&gt;
&lt;|user|&gt;
Context:
{context}
---
Now here is the question you need to answer.
Question: {question}
&lt;/s&gt;
&lt;|assistant|&gt;
&quot;&quot;&quot;</span><!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> langchain_community.llms <span class="hljs-keyword">import</span> HuggingFaceHub
repo_id = <span class="hljs-string">&quot;HuggingFaceH4/zephyr-7b-beta&quot;</span>
READER_MODEL_NAME = <span class="hljs-string">&quot;zephyr-7b-beta&quot;</span>
HF_API_TOKEN = <span class="hljs-string">&quot;&quot;</span>
READER_LLM = HuggingFaceHub(
repo_id=repo_id,
task=<span class="hljs-string">&quot;text-generation&quot;</span>,
huggingfacehub_api_token=HF_API_TOKEN,
model_kwargs={
<span class="hljs-string">&quot;max_new_tokens&quot;</span>: <span class="hljs-number">512</span>,
<span class="hljs-string">&quot;top_k&quot;</span>: <span class="hljs-number">30</span>,
<span class="hljs-string">&quot;temperature&quot;</span>: <span class="hljs-number">0.1</span>,
<span class="hljs-string">&quot;repetition_penalty&quot;</span>: <span class="hljs-number">1.03</span>,
},
)<!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> ragatouille <span class="hljs-keyword">import</span> RAGPretrainedModel
<span class="hljs-keyword">from</span> langchain_core.vectorstores <span class="hljs-keyword">import</span> VectorStore
<span class="hljs-keyword">from</span> langchain_core.language_models.llms <span class="hljs-keyword">import</span> LLM
<span class="hljs-keyword">def</span> <span class="hljs-title function_">answer_with_rag</span>(<span class="hljs-params">
question: <span class="hljs-built_in">str</span>,
llm: LLM,
knowledge_index: VectorStore,
reranker: <span class="hljs-type">Optional</span>[RAGPretrainedModel] = <span class="hljs-literal">None</span>,
num_retrieved_docs: <span class="hljs-built_in">int</span> = <span class="hljs-number">30</span>,
num_docs_final: <span class="hljs-built_in">int</span> = <span class="hljs-number">7</span>,
</span>) -&gt; <span class="hljs-type">Tuple</span>[<span class="hljs-built_in">str</span>, <span class="hljs-type">List</span>[LangchainDocument]]:
<span class="hljs-string">&quot;&quot;&quot;Answer a question using RAG with the given knowledge index.&quot;&quot;&quot;</span>
<span class="hljs-comment"># Gather documents with retriever</span>
relevant_docs = knowledge_index.similarity_search(query=question, k=num_retrieved_docs)
relevant_docs = [doc.page_content <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> relevant_docs] <span class="hljs-comment"># keep only the text</span>
<span class="hljs-comment"># Optionally rerank results</span>
<span class="hljs-keyword">if</span> reranker:
relevant_docs = reranker.rerank(question, relevant_docs, k=num_docs_final)
relevant_docs = [doc[<span class="hljs-string">&quot;content&quot;</span>] <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> relevant_docs]
relevant_docs = relevant_docs[:num_docs_final]
<span class="hljs-comment"># Build the final prompt</span>
context = <span class="hljs-string">&quot;\nExtracted documents:\n&quot;</span>
context += <span class="hljs-string">&quot;&quot;</span>.join([<span class="hljs-string">f&quot;Document <span class="hljs-subst">{<span class="hljs-built_in">str</span>(i)}</span>:::\n&quot;</span> + doc <span class="hljs-keyword">for</span> i, doc <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(relevant_docs)])
final_prompt = RAG_PROMPT_TEMPLATE.<span class="hljs-built_in">format</span>(question=question, context=context)
<span class="hljs-comment"># Redact an answer</span>
answer = llm(final_prompt)
<span class="hljs-keyword">return</span> answer, relevant_docs<!-- HTML_TAG_END --></pre></div> <h1 class="relative group"><a id="3-benchmarking-the-rag-system" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#3-benchmarking-the-rag-system"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>3. Benchmarking the RAG system</span></h1> <p data-svelte-h="svelte-z2wcut">The RAG system and the evaluation datasets are now ready. The last step is to judge the RAG system’s output on this evlauation dataset.</p> <p data-svelte-h="svelte-1tiikby">To this end, <strong>we setup a judge agent</strong>. ⚖️🤖</p> <p data-svelte-h="svelte-13s04hx">Out of <a href="https://docs.ragas.io/en/latest/concepts/metrics/index.html" rel="nofollow">the different RAG evaluation metrics</a>, we choose to focus only on faithfulness since it the best end-to-end metric of our system’s performance.</p> <blockquote data-svelte-h="svelte-jkfwyy"><p>We use GPT4 as a judge for its empirically good performance, but you could try with other models such as <a href="https://huggingface.co/kaist-ai/prometheus-13b-v1.0" rel="nofollow">kaist-ai/prometheus-13b-v1.0</a> or <a href="https://huggingface.co/BAAI/JudgeLM-33B-v1.0" rel="nofollow">BAAI/JudgeLM-33B-v1.0</a>.</p></blockquote> <p data-svelte-h="svelte-qutlt3">💡 <em>In the evaluation prompt, we give a detailed description each metric on the scale 1-5, as is done in <a href="https://huggingface.co/kaist-ai/prometheus-13b-v1.0" rel="nofollow">Prometheus’s prompt template</a>: this helps the model ground its metric precisely. If instead you give the judge LLM a vague scale to work with, the outputs will not be consistent enough between different examples.</em></p> <p data-svelte-h="svelte-1sle7mx">💡 <em>Again, prompting the LLM to output rationale before giving its final score gives it more tokens to help it formalize and elaborate a judgement.</em></p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> langchain_core.language_models <span class="hljs-keyword">import</span> BaseChatModel
<span class="hljs-keyword">def</span> <span class="hljs-title function_">run_rag_tests</span>(<span class="hljs-params">
eval_dataset: datasets.Dataset,
llm,
knowledge_index: VectorStore,
output_file: <span class="hljs-built_in">str</span>,
reranker: <span class="hljs-type">Optional</span>[RAGPretrainedModel] = <span class="hljs-literal">None</span>,
verbose: <span class="hljs-type">Optional</span>[<span class="hljs-built_in">bool</span>] = <span class="hljs-literal">True</span>,
test_settings: <span class="hljs-type">Optional</span>[<span class="hljs-built_in">str</span>] = <span class="hljs-literal">None</span>, <span class="hljs-comment"># To document the test settings used</span>
</span>):
<span class="hljs-string">&quot;&quot;&quot;Runs RAG tests on the given dataset and saves the results to the given output file.&quot;&quot;&quot;</span>
<span class="hljs-keyword">try</span>: <span class="hljs-comment"># load previous generations if they exist</span>
<span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(output_file, <span class="hljs-string">&quot;r&quot;</span>) <span class="hljs-keyword">as</span> f:
outputs = json.load(f)
<span class="hljs-keyword">except</span>:
outputs = []
<span class="hljs-keyword">for</span> example <span class="hljs-keyword">in</span> tqdm(eval_dataset):
question = example[<span class="hljs-string">&quot;question&quot;</span>]
<span class="hljs-keyword">if</span> question <span class="hljs-keyword">in</span> [output[<span class="hljs-string">&quot;question&quot;</span>] <span class="hljs-keyword">for</span> output <span class="hljs-keyword">in</span> outputs]:
<span class="hljs-keyword">continue</span>
answer, relevant_docs = answer_with_rag(question, llm, knowledge_index, reranker=reranker)
<span class="hljs-keyword">if</span> verbose:
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;=======================================================&quot;</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Question: <span class="hljs-subst">{question}</span>&quot;</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Answer: <span class="hljs-subst">{answer}</span>&quot;</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">f&#x27;True answer: <span class="hljs-subst">{example[<span class="hljs-string">&quot;answer&quot;</span>]}</span>&#x27;</span>)
result = {
<span class="hljs-string">&quot;question&quot;</span>: question,
<span class="hljs-string">&quot;true_answer&quot;</span>: example[<span class="hljs-string">&quot;answer&quot;</span>],
<span class="hljs-string">&quot;source_doc&quot;</span>: example[<span class="hljs-string">&quot;source_doc&quot;</span>],
<span class="hljs-string">&quot;generated_answer&quot;</span>: answer,
<span class="hljs-string">&quot;retrieved_docs&quot;</span>: [doc <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> relevant_docs],
}
<span class="hljs-keyword">if</span> test_settings:
result[<span class="hljs-string">&quot;test_settings&quot;</span>] = test_settings
outputs.append(result)
<span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(output_file, <span class="hljs-string">&quot;w&quot;</span>) <span class="hljs-keyword">as</span> f:
json.dump(outputs, f)<!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->EVALUATION_PROMPT = <span class="hljs-string">&quot;&quot;&quot;###Task Description:
An instruction (might include an Input inside it), a response to evaluate, a reference answer that gets a score of 5, and a score rubric representing a evaluation criteria are given.
1. Write a detailed feedback that assess the quality of the response strictly based on the given score rubric, not evaluating in general.
2. After writing a feedback, write a score that is an integer between 1 and 5. You should refer to the score rubric.
3. The output format should look as follows: \&quot;Feedback: {{write a feedback for criteria}} [RESULT] {{an integer number between 1 and 5}}\&quot;
4. Please do not generate any other opening, closing, and explanations. Be sure to include [RESULT] in your output.
###The instruction to evaluate:
{instruction}
###Response to evaluate:
{response}
###Reference Answer (Score 5):
{reference_answer}
###Score Rubrics:
[Is the response correct, accurate, and factual based on the reference answer?]
Score 1: The response is completely incorrect, inaccurate, and/or not factual.
Score 2: The response is mostly incorrect, inaccurate, and/or not factual.
Score 3: The response is somewhat correct, accurate, and/or factual.
Score 4: The response is mostly correct, accurate, and factual.
Score 5: The response is completely correct, accurate, and factual.
###Feedback:&quot;&quot;&quot;</span>
<span class="hljs-keyword">from</span> langchain.prompts.chat <span class="hljs-keyword">import</span> (
ChatPromptTemplate,
HumanMessagePromptTemplate,
)
<span class="hljs-keyword">from</span> langchain.schema <span class="hljs-keyword">import</span> SystemMessage
evaluation_prompt_template = ChatPromptTemplate.from_messages(
[
SystemMessage(content=<span class="hljs-string">&quot;You are a fair evaluator language model.&quot;</span>),
HumanMessagePromptTemplate.from_template(EVALUATION_PROMPT),
]
)<!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> langchain.chat_models <span class="hljs-keyword">import</span> ChatOpenAI
OPENAI_API_KEY = <span class="hljs-string">&quot;&quot;</span>
eval_chat_model = ChatOpenAI(model=<span class="hljs-string">&quot;gpt-4-1106-preview&quot;</span>, temperature=<span class="hljs-number">0</span>, openai_api_key=OPENAI_API_KEY)
evaluator_name = <span class="hljs-string">&quot;GPT4&quot;</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">evaluate_answers</span>(<span class="hljs-params">
answer_path: <span class="hljs-built_in">str</span>,
eval_chat_model,
evaluator_name: <span class="hljs-built_in">str</span>,
evaluation_prompt_template: ChatPromptTemplate,
</span>) -&gt; <span class="hljs-literal">None</span>:
<span class="hljs-string">&quot;&quot;&quot;Evaluates generated answers. Modifies the given answer file in place for better checkpointing.&quot;&quot;&quot;</span>
answers = []
<span class="hljs-keyword">if</span> os.path.isfile(answer_path): <span class="hljs-comment"># load previous generations if they exist</span>
answers = json.load(<span class="hljs-built_in">open</span>(answer_path, <span class="hljs-string">&quot;r&quot;</span>))
<span class="hljs-keyword">for</span> experiment <span class="hljs-keyword">in</span> tqdm(answers):
<span class="hljs-keyword">if</span> <span class="hljs-string">f&quot;eval_score_<span class="hljs-subst">{evaluator_name}</span>&quot;</span> <span class="hljs-keyword">in</span> experiment:
<span class="hljs-keyword">continue</span>
eval_prompt = evaluation_prompt_template.format_messages(
instruction=experiment[<span class="hljs-string">&quot;question&quot;</span>],
response=experiment[<span class="hljs-string">&quot;generated_answer&quot;</span>],
reference_answer=experiment[<span class="hljs-string">&quot;true_answer&quot;</span>],
)
eval_result = eval_chat_model.invoke(eval_prompt)
feedback, score = [item.strip() <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> eval_result.content.split(<span class="hljs-string">&quot;[RESULT]&quot;</span>)]
experiment[<span class="hljs-string">f&quot;eval_score_<span class="hljs-subst">{evaluator_name}</span>&quot;</span>] = score
experiment[<span class="hljs-string">f&quot;eval_feedback_<span class="hljs-subst">{evaluator_name}</span>&quot;</span>] = feedback
<span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(answer_path, <span class="hljs-string">&quot;w&quot;</span>) <span class="hljs-keyword">as</span> f:
json.dump(answers, f)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-ieknxj">🚀 Let’s run the tests and evaluate answers!👇</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(<span class="hljs-string">&quot;./output&quot;</span>):
os.mkdir(<span class="hljs-string">&quot;./output&quot;</span>)
<span class="hljs-keyword">for</span> chunk_size <span class="hljs-keyword">in</span> [<span class="hljs-number">200</span>]: <span class="hljs-comment"># Add other chunk sizes (in tokens) as needed</span>
<span class="hljs-keyword">for</span> embeddings <span class="hljs-keyword">in</span> [<span class="hljs-string">&quot;thenlper/gte-small&quot;</span>]: <span class="hljs-comment"># Add other embeddings as needed</span>
<span class="hljs-keyword">for</span> rerank <span class="hljs-keyword">in</span> [<span class="hljs-literal">True</span>, <span class="hljs-literal">False</span>]:
settings_name = <span class="hljs-string">f&quot;chunk:<span class="hljs-subst">{chunk_size}</span>_embeddings:<span class="hljs-subst">{embeddings.replace(<span class="hljs-string">&#x27;/&#x27;</span>, <span class="hljs-string">&#x27;~&#x27;</span>)}</span>_rerank:<span class="hljs-subst">{rerank}</span>_reader-model:<span class="hljs-subst">{READER_MODEL_NAME}</span>&quot;</span>
output_file_name = <span class="hljs-string">f&quot;./output/rag_<span class="hljs-subst">{settings_name}</span>.json&quot;</span>
<span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Running evaluation for <span class="hljs-subst">{settings_name}</span>:&quot;</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Loading knowledge base embeddings...&quot;</span>)
knowledge_index = load_embeddings(
RAW_KNOWLEDGE_BASE,
chunk_size=chunk_size,
embedding_model_name=embeddings,
)
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Running RAG...&quot;</span>)
reranker = RAGPretrainedModel.from_pretrained(<span class="hljs-string">&quot;colbert-ir/colbertv2.0&quot;</span>) <span class="hljs-keyword">if</span> rerank <span class="hljs-keyword">else</span> <span class="hljs-literal">None</span>
run_rag_tests(
eval_dataset=eval_dataset,
llm=READER_LLM,
knowledge_index=knowledge_index,
output_file=output_file_name,
reranker=reranker,
verbose=<span class="hljs-literal">False</span>,
test_settings=settings_name,
)
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;Running evaluation...&quot;</span>)
evaluate_answers(
output_file_name,
eval_chat_model,
evaluator_name,
evaluation_prompt_template,
)<!-- HTML_TAG_END --></pre></div> <h3 class="relative group"><a id="inspect-results" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#inspect-results"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Inspect results</span></h3> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">import</span> glob
outputs = []
<span class="hljs-keyword">for</span> file <span class="hljs-keyword">in</span> glob.glob(<span class="hljs-string">&quot;./output/*.json&quot;</span>):
output = pd.DataFrame(json.load(<span class="hljs-built_in">open</span>(file, <span class="hljs-string">&quot;r&quot;</span>)))
output[<span class="hljs-string">&quot;settings&quot;</span>] = file
outputs.append(output)
result = pd.concat(outputs)<!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->result[<span class="hljs-string">&quot;eval_score_GPT4&quot;</span>] = result[<span class="hljs-string">&quot;eval_score_GPT4&quot;</span>].apply(<span class="hljs-keyword">lambda</span> x: <span class="hljs-built_in">int</span>(x) <span class="hljs-keyword">if</span> <span class="hljs-built_in">isinstance</span>(x, <span class="hljs-built_in">str</span>) <span class="hljs-keyword">else</span> <span class="hljs-number">1</span>)
result[<span class="hljs-string">&quot;eval_score_GPT4&quot;</span>] = (result[<span class="hljs-string">&quot;eval_score_GPT4&quot;</span>] - <span class="hljs-number">1</span>) / <span class="hljs-number">4</span><!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->average_scores = result.groupby(<span class="hljs-string">&quot;settings&quot;</span>)[<span class="hljs-string">&quot;eval_score_GPT4&quot;</span>].mean()
average_scores.sort_values()<!-- HTML_TAG_END --></pre></div> <h2 class="relative group"><a id="example-results" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#example-results"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Example results</span></h2> <p data-svelte-h="svelte-5h9xp6">Let us load the results that I obtained by tweaking the different options available in this notebook.
For more detail on why these options could work on not, see the notebook on <a href="advanced_rag">advanced_RAG</a>.</p> <p data-svelte-h="svelte-6vrle6">As you can see in the graph below, some tweaks do not bring any improvement, some give huge performance boosts.</p> <p data-svelte-h="svelte-1l99caq">➡️ <strong><em>There is no single good recipe: you should try several different directions when tuning your RAG systems.</em></strong></p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">import</span> plotly.express <span class="hljs-keyword">as</span> px
scores = datasets.load_dataset(<span class="hljs-string">&quot;m-ric/rag_scores_cookbook&quot;</span>, split=<span class="hljs-string">&quot;train&quot;</span>)
scores = pd.Series(scores[<span class="hljs-string">&quot;score&quot;</span>], index=scores[<span class="hljs-string">&quot;settings&quot;</span>])<!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->fig = px.bar(
scores,
color=scores,
labels={
<span class="hljs-string">&quot;value&quot;</span>: <span class="hljs-string">&quot;Accuracy&quot;</span>,
<span class="hljs-string">&quot;settings&quot;</span>: <span class="hljs-string">&quot;Configuration&quot;</span>,
},
color_continuous_scale=<span class="hljs-string">&quot;bluered&quot;</span>,
)
fig.update_layout(
width=<span class="hljs-number">1000</span>,
height=<span class="hljs-number">600</span>,
barmode=<span class="hljs-string">&quot;group&quot;</span>,
yaxis_range=[<span class="hljs-number">0</span>, <span class="hljs-number">100</span>],
title=<span class="hljs-string">&quot;&lt;b&gt;Accuracy of different RAG configurations&lt;/b&gt;&quot;</span>,
xaxis_title=<span class="hljs-string">&quot;RAG settings&quot;</span>,
font=<span class="hljs-built_in">dict</span>(size=<span class="hljs-number">15</span>),
)
fig.layout.yaxis.ticksuffix = <span class="hljs-string">&quot;%&quot;</span>
fig.update_coloraxes(showscale=<span class="hljs-literal">False</span>)
fig.update_traces(texttemplate=<span class="hljs-string">&quot;%{y:.1f}&quot;</span>, textposition=<span class="hljs-string">&quot;outside&quot;</span>)
fig.show()<!-- HTML_TAG_END --></pre></div> <img src="https://huggingface.co/datasets/huggingface/cookbook-images/resolve/main/RAG_settings_accuracy.png" height="500" width="800"> <p data-svelte-h="svelte-i71q2k">As you can see, these had varying impact on performance. In particular, tuning the chunk size is both easy and very impactful.</p> <p data-svelte-h="svelte-5zkqt2">But this is our case: your results could be very different: now that you have a robust evaluation pipeline, you can set on to explore other options! 🗺️</p> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/cookbook/blob/main/notebooks/en/rag_evaluation.md" target="_blank"><span data-svelte-h="svelte-1kd6by1">&lt;</span> <span data-svelte-h="svelte-x0xyl0">&gt;</span> <span data-svelte-h="svelte-1dajgef"><span class="underline ml-1.5">Update</span> on GitHub</span></a> <p></p>
<script>
{
__sveltekit_1l2350x = {
assets: "/docs/cookbook/main/en",
base: "/docs/cookbook/main/en",
env: {}
};
const element = document.currentScript.parentElement;
const data = [null,null];
Promise.all([
import("/docs/cookbook/main/en/_app/immutable/entry/start.96b44205.js"),
import("/docs/cookbook/main/en/_app/immutable/entry/app.e92a3d99.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 33],
data,
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
106 kB
·
Xet hash:
df9ad3665dba342e7084ad47532047922cd0b568aac173e5dcbfb98328f142b6

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.