import{s as Ua,a as Hs,n as ra,o as ja}from"../chunks/scheduler.1f027d5a.js";import{S as wa,i as ca,e as A,s as n,c as p,h as Ta,a as i,d as e,b as a,f as Ma,g as M,j as o,k as ht,l as fa,m as s,n as U,t as r,o as j,p as w}from"../chunks/index.6117a65d.js";import{C as Ja}from"../chunks/CopyLLMTxtMenu.610b106b.js";import{D as ya,C as c}from"../chunks/DocNotebookDropdown.4ae0d470.js";import{H as T,E as ua}from"../chunks/MermaidChart.svelte_svelte_type_style_lang.bd18ae98.js";function ma(qs){let f,gt,Ft,It,J,vt,y,Et,u,Kt,m,Gs='<em>作者: <a href="https://huggingface.co/m-ric" rel="nofollow">Aymeric Roucher</a></em>',Vt,d,Ps="这个 notebook 主要讲述了你怎么构建一个高级的 RAG，用于回答一个关于特定知识库的问题（这里，是 HuggingFace 文档），使用 LangChain。",Nt,R,Ws='对于 RAG 的介绍，你可以查看<a href="rag_zephyr_langch">这个教程</a>',Xt,C,zs="RAG 系统是复杂的，它有许多组块:这里画一个简单的 RAG 图表，其中用蓝色标注了所有系统增强的可能性。",kt,h,Zs,Qt,b,Ls="<p>💡 可以看到，这个架构中有许多步骤可以调整：正确调整系统将带来显著的性能提升。</p>",xt,F,Ss="在这个 notebook 中，我们将研究许多这些蓝色标注的部分，看看如何调整你的 RAG 系统以获得最佳性能。",Ht,B,Ds="<strong>让我们深入研究模型架构吧！</strong> 首先，安装所需的模型依赖项。",qt,g,Gt,I,Pt,v,Wt,E,zt,K,Zt,V,Lt,N,St,X,Ys="<strong>检索器的作用类似于内部搜索引擎</strong>：给定用户查询，它从你的知识库中返回几个相关的片段。",Dt,k,_s="这些片段随后将被输入到阅读器模型中，以帮助其生成答案。",Yt,Q,Os="所以 <strong>我们的目标在这里是，给定一个用户问题，从我们的知识库中找到最多的片段来回答这个问题。</strong>",_t,x,$s="这是一个宽泛的目标，它留下了一些问题。我们应该检索多少片段？这个参数将被命名为<code>top_k</code>。",Ot,H,ln="这些片段应该有多长？这被称为 <code>chunk size</code> （片段大小）。没有一刀切的答案，但这里有一些要点：",$t,q,tn='<li>🔀 你的 <code>chunk size</code> 允许从一段片段到另一段片段有所不同。</li> <li>由于你的检索中总会存在一些噪音，增加 <code>top_k</code> 可以提高你检索到的片段中包含相关元素的概率。🎯 射更多的箭增加了你命中目标的概率。</li> <li>同时，你检索到的文档的总长度不应过高：例如，对于大多数当前模型来说，16k 个 token 可能会因为<a href="https://huggingface.co/papers/2307.03172" rel="nofollow">中间丢失现象</a>而在信息中淹没你的阅读器模型。🎯 只给你的阅读器模型提供最相关的见解，而不是一堆书！</li>',le,G,en="<p>在这个 notebook 中，我们使用 Langchain 库，因为 <strong>它为向量数据库提供了大量的选项，并允许我们在整个处理过程中保留文档的元数据</strong>。</p>",te,P,ee,W,sn="<li>在这一部分，<strong>我们将知识库中的文档拆分成更小的片段</strong>，这些片段将是喂给阅读器 LLM 生成答案的片段。</li> <li>目标是准备一组<strong>语义上相关的片段</strong>。因此，它们的大小应该适配确切的想法：太小会截断想法，太大则会稀释它们。</li>",se,z,nn='💡 <em>对于文本拆分存在许多选项：按单词拆分，按句子边界拆分，递归拆分以树状方式处理文档以保留结构信息… 要了解更多关于拆分的信息，我建议你阅读<a href="https://github.com/FullStackRetrieval-com/RetrievalTutorials/blob/main/5_Levels_Of_Text_Splitting.ipynb" rel="nofollow">这个很棒的 notebook</a>，这是由 Greg Kamradt 编写的。</em>',ne,Z,an="<li><p><strong>递归拆分</strong>使用给定的一组分隔符逐步将文本分解为更小的部分，这些分隔符按从最重要到最不重要的顺序排序。如果第一次拆分没有给出正确大小或形状的片段，该方法会使用不同的分隔符在新的片段上重复自身。例如，使用分隔符列表<code>[&quot;\\n\\n&quot;, &quot;\\n&quot;, &quot;.&quot;, &quot;&quot;]</code>：</p> <ul><li>该方法首先在出现双行中断<code>&quot;\\n\\n&quot;</code>的任何地方拆分文档。</li> <li>结果文档将在简单的行中断<code>&quot;\\n&quot;</code>处再次拆分，然后在句子结尾<code>&quot;.&quot;</code>处拆分。</li> <li>最后，如果有些片段仍然太大，它们将在超过最大大小时拆分。</li></ul></li> <li><p>使用这种方法，整体结构得到了很好的保留，代价是片段大小会有轻微的变化。</p></li>",ae,L,An='<p><a href="https://huggingface.co/spaces/A-Roucher/chunk_visualizer" rel="nofollow">这个空间</a>让你可视化不同的拆分选项如何影响你得到的片段。</p>',Ae,S,on="🔬 让我们用片段大小做一些实验，从任意大小开始，看看拆分是如何工作的。我们使用 Langchain 的 <code>RecursiveCharacterTextSplitter</code> 实现递归拆分。",ie,D,pn="<li>参数 <code>chunk_size</code> 控制单个片段的长度：这个长度默认计算为片段中的字符数。</li> <li>参数 <code>chunk_overlap</code> 允许相邻片段彼此有一些重叠。这减少了想法被两个相邻片段之间的拆分切割成两半的概率。我们武断地将这个设置为片段大小的1/10，你可以尝试不同的值！</li>",oe,Y,pe,_,Mn="我们还必须记住，当我们嵌入文档时，我们将使用一个接受特定最大序列长度 <code>max_seq_length</code> 的嵌入模型。",Me,O,Un="因此，我们应该确保我们的片段大小低于这个限制，因为任何更长的片段在处理之前都会被截断，从而失去相关性。",Ue,$,re,ll,rn=`Model's maximum sequence length: 512
`,je,tl,jn="👀 可以看到，<strong>片段长度与我们的 512 个 token 的限制不匹配</strong>，并且有些文档超出了限制，因此它们的一部分将在截断中丢失！",we,el,wn=`<li>因此，我们应该更改 <code>RecursiveCharacterTextSplitter</code> 类，以计算 token 数量而不是字符数量。</li> <li>然后，我们可以选择一个特定的片段大小，这里我们会选择低于 512 的阈值：
<ul><li>较小的文档可能允许拆分更专注于特定想法的内容。</li> <li>但太小的片段会拆分句子，从而再次失去意义：适当的调整是一个平衡的问题。</li></ul></li>`,ce,sl,Te,bt,cn,fe,nl,Tn="➡️ 现在分块长度分布看起来好多了!",Je,al,ye,Al,fn='我们希望为我们知识库的所有片段计算嵌入向量：要了解更多关于句子嵌入的信息，我们建议阅读<a href="https://osanseviero.github.io/hackerllama/blog/posts/sentence_embeddings/" rel="nofollow">这个指南</a>。',ue,il,me,ol,Jn="一旦所有片段都被嵌入，我们就将它们存储到一个向量数据库中。当用户输入一个查询时，它会被之前使用的同一模型嵌入，并且相似性搜索会返回向量数据库中最接近的文档。",de,pl,yn="因此，技术挑战在于，给定一个查询向量，快速找到向量数据库中这个向量的最近邻。为此，我们需要选择两件事：一个距离度量，以及一个搜索算法，以便在成千上万的记录数据库中快速找到最近邻。",Re,Ml,Ce,Ul,un='最近邻搜索算法有很多选择：我们选择 Facebook 的 <a href="https://github.com/facebookresearch/faiss" rel="nofollow">FAISS</a>，因为 FAISS 对于大多数用例来说性能足够好，而且它广为人知，因此被广泛实现。',he,rl,be,jl,mn='关于距离度量，你可以在<a href="https://osanseviero.github.io/hackerllama/blog/posts/sentence_embeddings/#distance-between-embeddings" rel="nofollow">这里</a>找到一个很好的指南。简而言之：',Fe,wl,dn="<li><strong>余弦相似度</strong>计算两个向量之间的相似性，作为它们相对角度的余弦值：它允许我们比较向量的方向，而不考虑它们的幅度。使用它需要对所有向量进行归一化，将它们重新缩放到单位范数。</li> <li><strong>点积</strong>考虑幅度，有时会有不希望的效果，即增加向量的长度会使它与所有其他向量更相似。</li> <li><strong>欧氏距离</strong>是向量末端之间的距离。</li>",Be,cl,Rn='你可以尝试<a href="https://developers.google.com/machine-learning/clustering/similarity/check-your-understanding" rel="nofollow">这个小测</a>来检查你对这些概念的理解。但是一旦向量被归一化，<a href="https://platform.openai.com/docs/guides/embeddings/which-distance-function-should-i-use" rel="nofollow">选择特定的距离度量并不重要</a>。',ge,Tl,Cn="我们的特定模型与余弦相似度配合得很好，所以我们选择这个距离度量，并在嵌入模型中以及 FAISS 索引的 <code>distance_strategy</code> 参数中设置它。使用余弦相似度，我们需要归一化我们的嵌入向量。",Ie,fl,hn="🚨👇 下面的单元格需要在 A10G 上运行几分钟！",ve,Jl,Ee,yl,bn="👀 为了可视化搜索最接近的文档，我们使用 PaCMAP 将我们的嵌入向量从 384 维降至 2 维。",Ke,ul,Fn='💡 <em>我们选择 PaCMAP 而不是其他技术，如 t-SNE 或 UMAP，因为<a href="https://www.nature.com/articles/s42003-022-03628-x#Abs1" rel="nofollow">它效率高（保留局部和全局结构），对初始化参数鲁棒且速度快</a>。</em>',Ve,ml,Ne,dl,Xe,Rl,ke,Cl,Bn,Qe,hl,gn="➡️ 在上面的图表中，你可以看到知识库文档的空间表示。由于向量嵌入代表了文档的含义，它们在意义上的接近应该在它们的嵌入的接近程度上反映出来。",xe,bl,In="用户查询的嵌入也被显示出来：我们想要找到意义最接近的 <code>k</code> 个文档，因此我们选择最接近的 <code>k</code> 个向量。",He,Fl,vn="在 LangChain 向量数据库实现中，这个搜索操作是由方法 <code>vector_database.similarity_search(query)</code> 执行的。",qe,Bl,En="这里是结果：",Ge,gl,Pe,Il,Kn=`Starting retrieval for user_query='How to create a pipeline object?'...

==================================Top document==================================
\`\`\`

## Available Pipelines:
==================================Metadata==================================
&#123;'source': 'huggingface/diffusers/blob/main/docs/source/en/api/pipelines/deepfloyd_if.md', 'start_index': 16887}
`,We,vl,ze,El,Vn="在这一部分，<strong>LLM 阅读器读取检索到的上下文以形成其答案。</strong>",Ze,Kl,Nn="实际上有多个可以调整的子步骤：",Le,Vl,Xn="<li>检索到的文档内容被聚合并放入“上下文”中，这其中有许多处理选项，如<em>提示压缩</em>。</li> <li>上下文和用户查询被聚合并形成一个提示(prompt)，然后交给 LLM 生成其答案。</li>",Se,Nl,De,Xl,kn="在选择阅读器模型时，有几个方面很重要：",Ye,kl,Qn="<li>阅读器模型的 <code>max_seq_length</code> 必须适应我们的提示(prompt)，其中包括检索器调用输出的上下文：上下文包括 5 个每份 512 个 token 的文档，所以我们至少需要 4k 个 token 的上下文长度。</li> <li>阅读器模型</li>",_e,Ql,xn='在这个例子中，我们选择了 <a href="https://huggingface.co/HuggingFaceH4/zephyr-7b-beta" rel="nofollow"><code>HuggingFaceH4/zephyr-7b-beta</code></a>，这是一个小而强大的模型。',Oe,xl,Hn='由于每周都会发布许多模型，你可能想要用最新最好的模型替换这个模型。跟踪开源 LLM 的最佳方式是查看 <a href="https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard" rel="nofollow">Open-source LLM leaderboard</a>。',$e,Hl,qn="为了加速推理，我们将加载模型的量化版本：",ls,ql,ts,Gl,es,Pl,ss,Wl,Gn="下面的 RAG 提示模板是我们将要提供给阅读器 LLM 的内容：需要将其格式化为阅读器 LLM 的聊天模板,这点非常重要。",ns,zl,Pn="我们向其提供我们的上下文和用户的问题。",as,Zl,As,Ll,Wn=`<|system|>
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.
<|user|>
Context:
&#123;context}
---
Now here is the question you need to answer.

Question: &#123;question}
<|assistant|>
`,is,Sl,zn="让我们在之前检索的文档上测试我们的阅读器!",os,Dl,ps,Yl,Zn=`To create a pipeline object, follow these steps:

1. Define the inputs and outputs of your pipeline. These could be strings, dictionaries, or any other format that best suits your use case.

2. Inherit the \`Pipeline\` class from the \`transformers\` module and implement the following methods:

   - \`preprocess\`: This method takes the raw inputs and returns a preprocessed dictionary that can be passed to the model.

   - \`_forward\`: This method performs the actual inference using the model and returns the output tensor.

   - \`postprocess\`: This method takes the output tensor and returns the final output in the desired format.

   - \`_sanitize_parameters\`: This method is used to sanitize the input parameters before passing them to the model.

3. Load the necessary components, such as the model and scheduler, into the pipeline object.

4. Instantiate the pipeline object and return it.

Here's an example implementation based on the given context:

\`\`\`python
from transformers import Pipeline
import torch
from diffusers import StableDiffusionPipeline

class MyPipeline(Pipeline):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.pipe = StableDiffusionPipeline.from_pretrained("my_model")

    def preprocess(self, inputs):
        # Preprocess the inputs as needed
        return &#123;"input_ids":...}

    def _forward(self, inputs):
        # Run the forward pass of the model
        return self.pipe(**inputs).images[0]

    def postprocess(self, outputs):
        # Postprocess the outputs as needed
        return outputs["sample"]

    def _sanitize_parameters(self, params):
        # Sanitize the input parameters
        return params

my_pipeline = MyPipeline()
result = my_pipeline("My input string")
print(result)
\`\`\`

Note that this implementation assumes that the model and scheduler are already loaded into memory. If they need to be loaded dynamically, you can modify the \`__init__\` method accordingly.
`,Ms,_l,Us,Ol,Ln="对于 RAG 来说，通常更好的选择会最终检索出比你想要的更多的文档，然后在保留 <code>top_k</code> 之前，使用更强大的检索模型对结果进行重新排序。",rs,$l,Sn='为此，<a href="https://arxiv.org/abs/2112.01488" rel="nofollow">Colbertv2</a>是一个很好的选择：它不是像我们传统的嵌入模型那样的双向编码器，而是一个交叉编码器，它计算查询 token 与每个文档 token 之间更细致的交互。',js,lt,Dn='由于有了 <a href="https://github.com/bclavie/RAGatouille" rel="nofollow">RAGatouille 库</a>，它的使用变得非常简单。',ws,tt,cs,et,Ts,st,fs,nt,Yn="让我们看看我们的 RAG 流水线是怎么回答用户的询问的。",Js,at,ys,At,_n=`=> Retrieving documents...
`,us,it,ms,ot,On=`==================================Answer==================================
To create a pipeline object, follow these steps:

1. Import the \`pipeline\` function from the \`transformers\` module:

   \`\`\`python
   from transformers import pipeline
   \`\`\`

2. Choose the task you want to perform, such as object detection, sentiment analysis, or image generation, and pass it as an argument to the \`pipeline\` function:

   - For object detection:

     \`\`\`python
     >>> object_detector = pipeline('object-detection')
     >>> object_detector(image)
     [&#123;'score': 0.9982201457023621,
       'label':'remote',
       'box': &#123;'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}},
     ...]
     \`\`\`

   - For sentiment analysis:

     \`\`\`python
     >>> classifier = pipeline("sentiment-analysis")
     >>> classifier("This is a great product!")
     &#123;'labels': ['POSITIVE'],'scores': tensor([0.9999], device='cpu', dtype=torch.float32)}
     \`\`\`

   - For image generation:

     \`\`\`python
     >>> image = pipeline(
    ... "stained glass of darth vader, backlight, centered composition, masterpiece, photorealistic, 8k"
    ... ).images[0]
     >>> image
     PILImage mode RGB size 7680x4320 at 0 DPI
     \`\`\`

Note that the exact syntax may vary depending on the specific pipeline being used. Refer to the documentation for more details on how to use each pipeline.

In general, the process involves importing the necessary modules, selecting the desired pipeline task, and passing it to the \`pipeline\` function along with any required arguments. The resulting pipeline object can then be used to perform the selected task on input data.
==================================Source docs==================================
Document 0------------------------------------------------------------
# Allocate a pipeline for object detection
>>> object_detector = pipeline('object-detection')
>>> object_detector(image)
[&#123;'score': 0.9982201457023621,
  'label': 'remote',
  'box': &#123;'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}},
 &#123;'score': 0.9960021376609802,
  'label': 'remote',
  'box': &#123;'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}},
 &#123;'score': 0.9954745173454285,
  'label': 'couch',
  'box': &#123;'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}},
 &#123;'score': 0.9988006353378296,
  'label': 'cat',
  'box': &#123;'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}},
 &#123;'score': 0.9986783862113953,
  'label': 'cat',
  'box': &#123;'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}]
Document 1------------------------------------------------------------
# Allocate a pipeline for object detection
>>> object_detector = pipeline('object_detection')
>>> object_detector(image)
[&#123;'score': 0.9982201457023621,
  'label': 'remote',
  'box': &#123;'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}},
 &#123;'score': 0.9960021376609802,
  'label': 'remote',
  'box': &#123;'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}},
 &#123;'score': 0.9954745173454285,
  'label': 'couch',
  'box': &#123;'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}},
 &#123;'score': 0.9988006353378296,
  'label': 'cat',
  'box': &#123;'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}},
 &#123;'score': 0.9986783862113953,
  'label': 'cat',
  'box': &#123;'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}]
Document 2------------------------------------------------------------
Start by creating an instance of [\`pipeline\`] and specifying a task you want to use it for. In this guide, you'll use the [\`pipeline\`] for sentiment analysis as an example:

\`\`\`py
>>> from transformers import pipeline

>>> classifier = pipeline("sentiment-analysis")
Document 3------------------------------------------------------------
\`\`\`

## Add the pipeline to 🤗 Transformers

If you want to contribute your pipeline to 🤗 Transformers, you will need to add a new module in the \`pipelines\` submodule
with the code of your pipeline, then add it to the list of tasks defined in \`pipelines/__init__.py\`.

Then you will need to add tests. Create a new file \`tests/test_pipelines_MY_PIPELINE.py\` with examples of the other tests.

The \`run_pipeline_test\` function will be very generic and run on small random models on every possible
architecture as defined by \`model_mapping\` and \`tf_model_mapping\`.

This is very important to test future compatibility, meaning if someone adds a new model for
\`XXXForQuestionAnswering\` then the pipeline test will attempt to run on it. Because the models are random it's
impossible to check for actual values, that's why there is a helper \`ANY\` that will simply attempt to match the
output of the pipeline TYPE.

You also *need* to implement 2 (ideally 4) tests.

- \`test_small_model_pt\` : Define 1 small model for this pipeline (doesn't matter if the results don't make sense)
  and test the pipeline outputs. The results should be the same as \`test_small_model_tf\`.
- \`test_small_model_tf\` : Define 1 small model for this pipeline (doesn't matter if the results don't make sense)
  and test the pipeline outputs. The results should be the same as \`test_small_model_pt\`.
- \`test_large_model_pt\` (\`optional\`): Tests the pipeline on a real pipeline where the results are supposed to
  make sense. These tests are slow and should be marked as such. Here the goal is to showcase the pipeline and to make
  sure there is no drift in future releases.
- \`test_large_model_tf\` (\`optional\`): Tests the pipeline on a real pipeline where the results are supposed to
  make sense. These tests are slow and should be marked as such. Here the goal is to showcase the pipeline and to make
  sure there is no drift in future releases.
Document 4------------------------------------------------------------
\`\`\`

2. Pass a prompt to the pipeline to generate an image:

\`\`\`py
image = pipeline(
	"stained glass of darth vader, backlight, centered composition, masterpiece, photorealistic, 8k"
).images[0]
image
`,ds,pt,$n="✅ 现在我们已经拥有了一个完整且性能出色的 RAG 系统。今天的教程就到这里！恭喜你坚持到了最后 🥳",Rs,Mt,Cs,Ut,la="这并不是旅程的终点！你可以尝试许多步骤来改进你的 RAG 系统。我们建议以迭代的方式进行：对系统进行小的更改，看看哪些可以提升性能。",hs,rt,bs,jt,ta="<li>💬 “你不能改进你没有衡量的模型性能”，甘地说过… 或者至少 Llama2 告诉我他这么说过。无论如何，你绝对应该从衡量性能开始：这意味着构建一个小的评估数据集，然后在评估数据集上监控你的 RAG 系统的性能。</li>",Fs,wt,Bs,ct,ea="🛠️ <strong>你可以使用这些选项来调整结果：</strong>",gs,Tt,sa='<li><p>调整分块方法：</p> <ul><li>片段的大小</li> <li>方法：使用不同的分隔符进行拆分，使用<a href="https://python.langchain.com/docs/modules/data_connection/document_transformers/semantic-chunker" rel="nofollow">语义分块</a>…</li></ul></li> <li><p>更改嵌入模型</p></li>',Is,ft,na="👷‍♀️ <strong>还可以考虑以下事项：</strong>",vs,Jt,aa="<li>尝试另一种分块方法，如语义分块</li> <li>更改使用的索引（这里使用的是 FAISS）</li> <li>查询扩展：以略微不同的方式重新构建用户查询以检索更多文档。</li>",Es,yt,Ks,ut,Aa="🛠️ <strong>这里你可以尝试以下选项来改善结果：</strong>",Vs,mt,ia="<li>调整提示</li> <li>开启/关闭重排序</li> <li>选择一个更强大的阅读器模型</li>",Ns,dt,oa="💡 <strong>这里有许多选项可以考虑以进一步改善结果：</strong>",Xs,Rt,pa=`<li>压缩检索到的上下文，只保留与回答查询最相关的部分。</li> <li>扩展 RAG 系统，使其更加用户友好：
<ul><li>引用来源</li> <li>使其能够进行对话</li></ul></li>`,ks,Ct,Qs,Bt,xs;return J=new ya({props:{classNames:"absolute z-10 right-0 top-0",options:[{label:"Google Colab",value:"https://colab.research.google.com/github/huggingface/cookbook/blob/main/notebooks/zh-CN/advanced_rag.ipynb"}]}}),y=new Ja({props:{containerStyle:"float: right; margin-left: 10px; display: inline-flex; position: relative; z-index: 10;"}}),u=new T({props:{title:"使用 LangChain 在 HuggingFace 文档上构建高级 RAG",local:"使用-langchain-在-huggingface-文档上构建高级-rag",headingTag:"h1"}}),g=new c({props:{code:"IXBpcCUyMGluc3RhbGwlMjAtcSUyMHRvcmNoJTIwdHJhbnNmb3JtZXJzJTIwdHJhbnNmb3JtZXJzJTIwYWNjZWxlcmF0ZSUyMGJpdHNhbmRieXRlcyUyMGxhbmdjaGFpbiUyMHNlbnRlbmNlLXRyYW5zZm9ybWVycyUyMGZhaXNzLWdwdSUyMG9wZW5weXhsJTIwcGFjbWFwJTIwZGF0YXNldHMlMjBsYW5nY2hhaW4tY29tbXVuaXR5JTIwcmFnYXRvdWlsbGU=",highlighted:"!pip install -q torch transformers transformers accelerate bitsandbytes langchain sentence-transformers faiss-gpu openpyxl pacmap datasets langchain-community ragatouille",wrap:!1}}),I=new c({props:{code:"JTI1cmVsb2FkX2V4dCUyMGRvdGVudiUwQSUyNWRvdGVudg==",highlighted:`%reload_ext dotenv
%dotenv`,wrap:!1}}),v=new c({props:{code:"ZnJvbSUyMHRxZG0ubm90ZWJvb2slMjBpbXBvcnQlMjB0cWRtJTBBaW1wb3J0JTIwcGFuZGFzJTIwYXMlMjBwZCUwQWZyb20lMjB0eXBpbmclMjBpbXBvcnQlMjBPcHRpb25hbCUyQyUyMExpc3QlMkMlMjBUdXBsZSUwQWZyb20lMjBkYXRhc2V0cyUyMGltcG9ydCUyMERhdGFzZXQlMEFpbXBvcnQlMjBtYXRwbG90bGliLnB5cGxvdCUyMGFzJTIwcGx0JTBBJTBBcGQuc2V0X29wdGlvbiglMEElMjAlMjAlMjAlMjAlMjJkaXNwbGF5Lm1heF9jb2x3aWR0aCUyMiUyQyUyME5vbmUlMEEpJTIwJTIwJTIzJTIwdGhpcyUyMHdpbGwlMjBiZSUyMGhlbHBmdWwlMjB3aGVuJTIwdmlzdWFsaXppbmclMjByZXRyaWV2ZXIlMjBvdXRwdXRz",highlighted:`<span class="hljs-keyword">from</span> tqdm.notebook <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">from</span> datasets <span class="hljs-keyword">import</span> Dataset
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt

pd.set_option(
    <span class="hljs-string">&quot;display.max_colwidth&quot;</span>, <span class="hljs-literal">None</span>
)  <span class="hljs-comment"># this will be helpful when visualizing retriever outputs</span>`,wrap:!1}}),E=new T({props:{title:"加载你的知识基础",local:"加载你的知识基础",headingTag:"h3"}}),K=new c({props:{code:"aW1wb3J0JTIwZGF0YXNldHMlMEElMEFkcyUyMCUzRCUyMGRhdGFzZXRzLmxvYWRfZGF0YXNldCglMjJtLXJpYyUyRmh1Z2dpbmdmYWNlX2RvYyUyMiUyQyUyMHNwbGl0JTNEJTIydHJhaW4lMjIp",highlighted:`<span class="hljs-keyword">import</span> datasets

ds = datasets.load_dataset(<span class="hljs-string">&quot;m-ric/huggingface_doc&quot;</span>, split=<span class="hljs-string">&quot;train&quot;</span>)`,wrap:!1}}),V=new c({props:{code:"ZnJvbSUyMGxhbmdjaGFpbi5kb2NzdG9yZS5kb2N1bWVudCUyMGltcG9ydCUyMERvY3VtZW50JTIwYXMlMjBMYW5nY2hhaW5Eb2N1bWVudCUwQSUwQVJBV19LTk9XTEVER0VfQkFTRSUyMCUzRCUyMCU1QiUwQSUyMCUyMCUyMCUyMExhbmdjaGFpbkRvY3VtZW50KHBhZ2VfY29udGVudCUzRGRvYyU1QiUyMnRleHQlMjIlNUQlMkMlMjBtZXRhZGF0YSUzRCU3QiUyMnNvdXJjZSUyMiUzQSUyMGRvYyU1QiUyMnNvdXJjZSUyMiU1RCU3RCklMEElMjAlMjAlMjAlMjBmb3IlMjBkb2MlMjBpbiUyMHRxZG0oZHMpJTBBJTVE",highlighted:`<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)
]`,wrap:!1}}),N=new T({props:{title:"1. 检索器- 嵌入 🗂️",local:"1-检索器--嵌入-",headingTag:"h1"}}),P=new T({props:{title:"1.1 将文档拆分为片段(chuncks)",local:"11-将文档拆分为片段chuncks",headingTag:"h3"}}),Y=new c({props:{code:"ZnJvbSUyMGxhbmdjaGFpbi50ZXh0X3NwbGl0dGVyJTIwaW1wb3J0JTIwUmVjdXJzaXZlQ2hhcmFjdGVyVGV4dFNwbGl0dGVyJTBBJTBBJTIzJTIwV2UlMjB1c2UlMjBhJTIwaGllcmFyY2hpY2FsJTIwbGlzdCUyMG9mJTIwc2VwYXJhdG9ycyUyMHNwZWNpZmljYWxseSUyMHRhaWxvcmVkJTIwZm9yJTIwc3BsaXR0aW5nJTIwTWFya2Rvd24lMjBkb2N1bWVudHMlMEElMjMlMjBUaGlzJTIwbGlzdCUyMGlzJTIwdGFrZW4lMjBmcm9tJTIwTGFuZ0NoYWluJ3MlMjBNYXJrZG93blRleHRTcGxpdHRlciUyMGNsYXNzLiUwQU1BUktET1dOX1NFUEFSQVRPUlMlMjAlM0QlMjAlNUIlMEElMjAlMjAlMjAlMjAlMjIlNUNuJTIzJTdCMSUyQzYlN0QlMjAlMjIlMkMlMEElMjAlMjAlMjAlMjAlMjIlNjAlNjAlNjAlNUNuJTIyJTJDJTBBJTIwJTIwJTIwJTIwJTIyJTVDbiU1QyU1QyolNUMlNUMqJTVDJTVDKiUyQiU1Q24lMjIlMkMlMEElMjAlMjAlMjAlMjAlMjIlNUNuLS0tJTJCJTVDbiUyMiUyQyUwQSUyMCUyMCUyMCUyMCUyMiU1Q25fX18lMkIlNUNuJTIyJTJDJTBBJTIwJTIwJTIwJTIwJTIyJTVDbiU1Q24lMjIlMkMlMEElMjAlMjAlMj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V19LTk9XTEVER0VfQkFTRSUzQSUwQSUyMCUyMCUyMCUyMGRvY3NfcHJvY2Vzc2VkJTIwJTJCJTNEJTIwdGV4dF9zcGxpdHRlci5zcGxpdF9kb2N1bWVudHMoJTVCZG9jJTVEKQ==",highlighted:`<span class="hljs-keyword">from</span> langchain.text_splitter <span class="hljs-keyword">import</span> RecursiveCharacterTextSplitter

<span class="hljs-comment"># We use a hierarchical list of separators specifically tailored for splitting Markdown documents</span>
<span class="hljs-comment"># This list is taken from LangChain&#x27;s MarkdownTextSplitter class.</span>
MARKDOWN_SEPARATORS = [
    <span class="hljs-string">&quot;\\n#{1,6} &quot;</span>,
    <span class="hljs-string">&quot;\`\`\`\\n&quot;</span>,
    <span class="hljs-string">&quot;\\n\\\\*\\\\*\\\\*+\\n&quot;</span>,
    <span class="hljs-string">&quot;\\n---+\\n&quot;</span>,
    <span class="hljs-string">&quot;\\n___+\\n&quot;</span>,
    <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>,
]

text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=<span class="hljs-number">1000</span>,  <span class="hljs-comment"># the maximum number of characters in a chunk: we selected this value arbitrarily</span>
    chunk_overlap=<span class="hljs-number">100</span>,  <span class="hljs-comment"># the number of characters to overlap between chunks</span>
    add_start_index=<span class="hljs-literal">True</span>,  <span class="hljs-comment"># If \`True\`, includes chunk&#x27;s start index in metadata</span>
    strip_whitespace=<span class="hljs-literal">True</span>,  <span class="hljs-comment"># If \`True\`, strips whitespace from the start and end of every document</span>
    separators=MARKDOWN_SEPARATORS,
)

docs_processed = []
<span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> RAW_KNOWLEDGE_BASE:
    docs_processed += text_splitter.split_documents([doc])`,wrap:!1}}),$=new c({props:{code:"ZnJvbSUyMHNlbnRlbmNlX3RyYW5zZm9ybWVycyUyM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wZG9jdW1lbnQlMjBsZW5ndGhzJTIwaW4lMjB0aGUlMjBrbm93bGVkZ2UlMjBiYXNlJTIwKGluJTIwY291bnQlMjBvZiUyMHRva2VucyklMjIpJTBBcGx0LnNob3coKQ==",highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> sentence_transformers <span class="hljs-keyword">import</span> SentenceTransformer

<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-comment"># To get the value of the max sequence_length, we will query the underlying \`SentenceTransformer\` object used in the RecursiveCharacterTextSplitter.</span>
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(
<span class="hljs-meta">... </span>    <span class="hljs-string">f&quot;Model&#x27;s maximum sequence length: <span class="hljs-subst">{SentenceTransformer(<span class="hljs-string">&#x27;thenlper/gte-small&#x27;</span>).max_seq_length}</span>&quot;</span>
<span class="hljs-meta">... </span>)

<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer

<span class="hljs-meta">&gt;&gt;&gt; </span>tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">&quot;thenlper/gte-small&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>lengths = [<span class="hljs-built_in">len</span>(tokenizer.encode(doc.page_content)) <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> tqdm(docs_processed)]

<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-comment"># Plot the distribution of document lengths, counted as the number of tokens</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>fig = pd.Series(lengths).hist()
<span class="hljs-meta">&gt;&gt;&gt; </span>plt.title(<span class="hljs-string">&quot;Distribution of document lengths in the knowledge base (in count of tokens)&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>plt.show()`,wrap:!1}}),sl=new c({props:{code:"ZnJvbSUyMGxhbmdjaGFpbi50ZXh0X3NwbGl0dGVyJTIwaW1wb3J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3VtZW50JTIwbGVuZ3RocyUyMGluJTIwdGhlJTIwa25vd2xlZGdlJTIwYmFzZSUyMChpbiUyMGNvdW50JTIwb2YlMjB0b2tlbnMpJTIyKSUwQXBsdC5zaG93KCk=",highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> langchain.text_splitter <span class="hljs-keyword">import</span> RecursiveCharacterTextSplitter
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer

<span class="hljs-meta">&gt;&gt;&gt; </span>EMBEDDING_MODEL_NAME = <span class="hljs-string">&quot;thenlper/gte-small&quot;</span>


<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">split_documents</span>(<span class="hljs-params">
<span class="hljs-meta">... </span>    chunk_size: <span class="hljs-built_in">int</span>,
<span class="hljs-meta">... </span>    knowledge_base: <span class="hljs-type">List</span>[LangchainDocument],
<span class="hljs-meta">... </span>    tokenizer_name: <span class="hljs-type">Optional</span>[<span class="hljs-built_in">str</span>] = EMBEDDING_MODEL_NAME,
<span class="hljs-meta">... </span></span>) -&gt; <span class="hljs-type">List</span>[LangchainDocument]:
<span class="hljs-meta">... </span>    <span class="hljs-string">&quot;&quot;&quot;
<span class="hljs-meta">... </span>    Split documents into chunks of maximum size \`chunk_size\` tokens and return a list of documents.
<span class="hljs-meta">... </span>    &quot;&quot;&quot;</span>
<span class="hljs-meta">... </span>    text_splitter = RecursiveCharacterTextSplitter.from_huggingface_tokenizer(
<span class="hljs-meta">... </span>        AutoTokenizer.from_pretrained(tokenizer_name),
<span class="hljs-meta">... </span>        chunk_size=chunk_size,
<span class="hljs-meta">... </span>        chunk_overlap=<span class="hljs-built_in">int</span>(chunk_size / <span class="hljs-number">10</span>),
<span class="hljs-meta">... </span>        add_start_index=<span class="hljs-literal">True</span>,
<span class="hljs-meta">... </span>        strip_whitespace=<span class="hljs-literal">True</span>,
<span class="hljs-meta">... </span>        separators=MARKDOWN_SEPARATORS,
<span class="hljs-meta">... </span>    )

<span class="hljs-meta">... </span>    docs_processed = []
<span class="hljs-meta">... </span>    <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> knowledge_base:
<span class="hljs-meta">... </span>        docs_processed += text_splitter.split_documents([doc])

<span class="hljs-meta">... </span>    <span class="hljs-comment"># Remove duplicates</span>
<span class="hljs-meta">... </span>    unique_texts = {}
<span class="hljs-meta">... </span>    docs_processed_unique = []
<span class="hljs-meta">... </span>    <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> docs_processed:
<span class="hljs-meta">... </span>        <span class="hljs-keyword">if</span> doc.page_content <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> unique_texts:
<span class="hljs-meta">... </span>            unique_texts[doc.page_content] = <span class="hljs-literal">True</span>
<span class="hljs-meta">... </span>            docs_processed_unique.append(doc)

<span class="hljs-meta">... </span>    <span class="hljs-keyword">return</span> docs_processed_unique


<span class="hljs-meta">&gt;&gt;&gt; </span>docs_processed = split_documents(
<span class="hljs-meta">... </span>    <span class="hljs-number">512</span>,  <span class="hljs-comment"># We choose a chunk size adapted to our model</span>
<span class="hljs-meta">... </span>    RAW_KNOWLEDGE_BASE,
<span class="hljs-meta">... </span>    tokenizer_name=EMBEDDING_MODEL_NAME,
<span class="hljs-meta">... </span>)

<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-comment"># Let&#x27;s visualize the chunk sizes we would have in tokens from a common model</span>
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer

<span class="hljs-meta">&gt;&gt;&gt; </span>tokenizer = AutoTokenizer.from_pretrained(EMBEDDING_MODEL_NAME)
<span class="hljs-meta">&gt;&gt;&gt; </span>lengths = [<span class="hljs-built_in">len</span>(tokenizer.encode(doc.page_content)) <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> tqdm(docs_processed)]
<span class="hljs-meta">&gt;&gt;&gt; </span>fig = pd.Series(lengths).hist()
<span class="hljs-meta">&gt;&gt;&gt; </span>plt.title(<span class="hljs-string">&quot;Distribution of document lengths in the knowledge base (in count of tokens)&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>plt.show()`,wrap:!1}}),al=new T({props:{title:"1.2 构建向量数据库",local:"12-构建向量数据库",headingTag:"h3"}}),il=new T({props:{title:"检索的工作原理",local:"检索的工作原理",headingTag:"h4"}}),Ml=new T({props:{title:"最近邻搜索算法",local:"最近邻搜索算法",headingTag:"h5"}}),rl=new T({props:{title:"距离度量",local:"距离度量",headingTag:"h5"}}),Jl=new c({props:{code:"ZnJvbSUyMGxhbmdjaGFpbi52ZWN0b3JzdG9yZXMlMjBpbXBvcnQlMjBGQUlTUyUwQWZyb20lMjBsYW5nY2hhaW5fY29tbXVuaXR5LmVtYmVkZGluZ3MlMjBpbXBvcnQlMjBIdWdnaW5nRmFjZUVtYmVkZGluZ3MlMEFmcm9tJTIwbGFuZ2NoYWluX2NvbW11bml0eS52ZWN0b3JzdG9yZXMudXRpbHMlMjBpbXBvcnQlMjBEaXN0YW5jZVN0cmF0ZWd5JTBBJTBBZW1iZWRkaW5nX21vZGVsJTIwJTNEJTIwSHVnZ2luZ0ZhY2VFbWJlZGRpbmdzKCUwQSUyMCUyMCUyMCUyMG1vZGVsX25hbWUlM0RFTUJFRERJTkdfTU9ERUxfTkFNRSUyQyUwQSUyMCUyMCUyMCUyMG11bHRpX3Byb2Nlc3MlM0RUcnVlJTJDJTBBJTIwJTIwJTIwJTIwbW9kZWxfa3dhcmdzJTNEJTdCJTIyZGV2aWNlJTIyJTNBJTIwJTIyY3VkYSUyMiU3RCUyQyUwQSUyMCUyMCUyMCUyMGVuY29kZV9rd2FyZ3MlM0QlN0IlMjJub3JtYWxpemVfZW1iZWRkaW5ncyUyMiUzQSUyMFRydWUlN0QlMkMlMjAlMjAlMjMlMjBzZXQlMjBUcnVlJTIwZm9yJTIwY29zaW5lJTIwc2ltaWxhcml0eSUwQSklMEElMEFLTk9XTEVER0VfVkVDVE9SX0RBVEFCQVNFJTIwJTNEJTIwRkFJU1MuZnJvbV9kb2N1bWVudHMoJTBBJTIwJTIwJTIwJTIwZG9jc19wcm9jZXNzZWQlMkMlMjBlbWJlZGRpbmdfbW9kZWwlMkMlMjBkaXN0YW5jZV9zdHJhdGVneSUzRERpc3RhbmNlU3RyYXRlZ3kuQ09TSU5FJTBBKQ==",highlighted:`<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

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 for cosine similarity</span>
)

KNOWLEDGE_VECTOR_DATABASE = FAISS.from_documents(
    docs_processed, embedding_model, distance_strategy=DistanceStrategy.COSINE
)`,wrap:!1}}),ml=new c({props:{code:"JTIzJTIwZW1iZWQlMjBhJTIwdXNlciUyMHF1ZXJ5JTIwaW4lMjB0aGUlMjBzYW1lJTIwc3BhY2UlMEF1c2VyX3F1ZXJ5JTIwJTNEJTIwJTIySG93JTIwdG8lMjBjcmVhdGUlMjBhJTIwcGlwZWxpbmUlMjBvYmplY3QlM0YlMjIlMEFxdWVyeV92ZWN0b3IlMjAlM0QlMjBlbWJlZGRpbmdfbW9kZWwuZW1iZWRfcXVlcnkodXNlcl9xdWVyeSk=",highlighted:`<span class="hljs-comment"># embed a user query in the same space</span>
user_query = <span class="hljs-string">&quot;How to create a pipeline object?&quot;</span>
query_vector = embedding_model.embed_query(user_query)`,wrap:!1}}),dl=new c({props:{code:"aW1wb3J0JTIwcGFjbWFwJTBBaW1wb3J0JTIwbnVtcHklMjBhcyUyMG5wJTBBaW1wb3J0JTIwcGxvdGx5LmV4cHJlc3MlMjBhcyUyMHB4JTBBJTBBZW1iZWRkaW5nX3Byb2plY3RvciUyMCUzRCUyMHBhY21hcC5QYUNNQVAoJTBBJTIwJTIwJTIwJTIwbl9jb21wb25lbnRzJTNEMiUyQyUyMG5fbmVpZ2hib3JzJTNETm9uZSUyQyUyME1OX3JhdGlvJTNEMC41JTJDJTIwRlBfcmF0aW8lM0QyLjAlMkMlMjByYW5kb21fc3RhdGUlM0QxJTBBKSUwQSUwQWVtYmVkZGluZ3NfMmQlMjAlM0QlMjAlNUIlMEElMjAlMjAlMjAlMjBsaXN0KEtOT1dMRURHRV9WRUNUT1JfREFUQUJBU0UuaW5kZXgucmVjb25zdHJ1Y3RfbihpZHglMkMlMjAxKSU1QjAlNUQpJTBBJTIwJTIwJTIwJTIwZm9yJTIwaWR4JTIwaW4lMjByYW5nZShsZW4oZG9jc19wcm9jZXNzZWQpKSUwQSU1RCUyMCUyQiUyMCU1QnF1ZXJ5X3ZlY3RvciU1RCUwQSUwQSUyMyUyMGZpdCUyMHRoZSUyMGRhdGElMjAoVGhlJTIwaW5kZXglMjBvZiUyMHRyYW5zZm9ybWVkJTIwZGF0YSUyMGNvcnJlc3BvbmRzJTIwdG8lMjB0aGUlMjBpbmRleCUyMG9mJTIwdGhlJTIwb3JpZ2luYWwlMjBkYXRhKSUwQWRvY3VtZW50c19wcm9qZWN0ZWQlMjAlM0QlMjBlbWJlZGRpbmdfcHJvamVjdG9yLmZpdF90cmFuc2Zvcm0obnAuYXJyYXkoZW1iZWRkaW5nc18yZCklMkMlMjBpbml0JTNEJTIycGNhJTIyKQ==",highlighted:`<span class="hljs-keyword">import</span> pacmap
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> plotly.express <span class="hljs-keyword">as</span> px

embedding_projector = pacmap.PaCMAP(
    n_components=<span class="hljs-number">2</span>, n_neighbors=<span class="hljs-literal">None</span>, MN_ratio=<span class="hljs-number">0.5</span>, FP_ratio=<span class="hljs-number">2.0</span>, random_state=<span class="hljs-number">1</span>
)

embeddings_2d = [
    <span class="hljs-built_in">list</span>(KNOWLEDGE_VECTOR_DATABASE.index.reconstruct_n(idx, <span class="hljs-number">1</span>)[<span class="hljs-number">0</span>])
    <span class="hljs-keyword">for</span> idx <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(docs_processed))
] + [query_vector]

<span class="hljs-comment"># fit the data (The index of transformed data corresponds to the index of the original data)</span>
documents_projected = embedding_projector.fit_transform(np.array(embeddings_2d), init=<span class="hljs-string">&quot;pca&quot;</span>)`,wrap:!1}}),Rl=new c({props:{code:"ZGYlMjAlM0QlMjBwZC5EYXRhRnJhbWUuZnJvbV9kaWN0KCUwQSUyMCUyMCUyMCUyMCU1QiUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCU3QiUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMnglMjIlM0ElMjBkb2N1bWVudHNfcHJvamVjdGVkJTVCaSUyQyUyMDAlNUQlMkMlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjJ5JTIyJTNBJTIwZG9jdW1lbnRzX3Byb2plY3RlZCU1QmklMkMlMjAxJTVEJTJDJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIyc291cmNlJTIyJTNBJTIwZG9jc19wcm9jZXNzZWQlNUJpJTVELm1ldGFkYXRhJTVCJTIyc291cmNlJTIyJTVELnNwbGl0KCUyMiUyRiUyMiklNUIxJTVEJTJDJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIw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0JTNEJTIyJTNDYiUzRUNodW5rJTIwc291cmNlJTNDJTJGYiUzRSUyMiUyQyUwQSUyMCUyMCUyMCUyMHRpdGxlJTNEJTIyJTNDYiUzRTJEJTIwUHJvamVjdGlvbiUyMG9mJTIwQ2h1bmslMjBFbWJlZGRpbmdzJTIwdmlhJTIwUGFDTUFQJTNDJTJGYiUzRSUyMiUyQyUwQSklMEFmaWcuc2hvdygp",highlighted:`df = pd.DataFrame.from_dict(
    [
        {
            <span class="hljs-string">&quot;x&quot;</span>: documents_projected[i, <span class="hljs-number">0</span>],
            <span class="hljs-string">&quot;y&quot;</span>: documents_projected[i, <span class="hljs-number">1</span>],
            <span class="hljs-string">&quot;source&quot;</span>: docs_processed[i].metadata[<span class="hljs-string">&quot;source&quot;</span>].split(<span class="hljs-string">&quot;/&quot;</span>)[<span class="hljs-number">1</span>],
            <span class="hljs-string">&quot;extract&quot;</span>: docs_processed[i].page_content[:<span class="hljs-number">100</span>] + <span class="hljs-string">&quot;...&quot;</span>,
            <span class="hljs-string">&quot;symbol&quot;</span>: <span class="hljs-string">&quot;circle&quot;</span>,
            <span class="hljs-string">&quot;size_col&quot;</span>: <span class="hljs-number">4</span>,
        }
        <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(docs_processed))
    ]
    + [
        {
            <span class="hljs-string">&quot;x&quot;</span>: documents_projected[-<span class="hljs-number">1</span>, <span class="hljs-number">0</span>],
            <span class="hljs-string">&quot;y&quot;</span>: documents_projected[-<span class="hljs-number">1</span>, <span class="hljs-number">1</span>],
            <span class="hljs-string">&quot;source&quot;</span>: <span class="hljs-string">&quot;User query&quot;</span>,
            <span class="hljs-string">&quot;extract&quot;</span>: user_query,
            <span class="hljs-string">&quot;size_col&quot;</span>: <span class="hljs-number">100</span>,
            <span class="hljs-string">&quot;symbol&quot;</span>: <span class="hljs-string">&quot;star&quot;</span>,
        }
    ]
)

<span class="hljs-comment"># visualize the embedding</span>
fig = px.scatter(
    df,
    x=<span class="hljs-string">&quot;x&quot;</span>,
    y=<span class="hljs-string">&quot;y&quot;</span>,
    color=<span class="hljs-string">&quot;source&quot;</span>,
    hover_data=<span class="hljs-string">&quot;extract&quot;</span>,
    size=<span class="hljs-string">&quot;size_col&quot;</span>,
    symbol=<span class="hljs-string">&quot;symbol&quot;</span>,
    color_discrete_map={<span class="hljs-string">&quot;User query&quot;</span>: <span class="hljs-string">&quot;black&quot;</span>},
    width=<span class="hljs-number">1000</span>,
    height=<span class="hljs-number">700</span>,
)
fig.update_traces(
    marker=<span class="hljs-built_in">dict</span>(opacity=<span class="hljs-number">1</span>, line=<span class="hljs-built_in">dict</span>(width=<span class="hljs-number">0</span>, color=<span class="hljs-string">&quot;DarkSlateGrey&quot;</span>)), selector=<span class="hljs-built_in">dict</span>(mode=<span class="hljs-string">&quot;markers&quot;</span>)
)
fig.update_layout(
    legend_title_text=<span class="hljs-string">&quot;&lt;b&gt;Chunk source&lt;/b&gt;&quot;</span>,
    title=<span class="hljs-string">&quot;&lt;b&gt;2D Projection of Chunk Embeddings via PaCMAP&lt;/b&gt;&quot;</span>,
)
fig.show()`,wrap:!1}}),gl=new c({props:{code:"cHJpbnQoZiUyMiU1Q25TdGFydGluZyUyMHJldHJpZXZhbCUyMGZvciUyMCU3QnVzZXJfcXVlcnklM0QlN0QuLi4lMjIpJTBBcmV0cmlldmVkX2RvY3MlMjAlM0QlMjBLTk9XTEVER0VfVkVDVE9SX0RBVEFCQVNFLnNpbWlsYXJpdHlfc2VhcmNoKHF1ZXJ5JTNEdXNlcl9xdWVyeSUyQyUyMGslM0Q1KSUwQXByaW50KCUyMiU1Q24lM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0QlM0RUb3AlMjBkb2N1bWVudCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUyMiklMEFwcmludChyZXRyaWV2ZWRfZG9jcyU1QjAlNUQucGFnZV9jb250ZW50KSUwQXByaW50KCUyMiUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRE1ldGFkYXRhJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTIyKSUwQXByaW50KHJldHJpZXZlZF9kb2NzJTVCMCU1RC5tZXRhZGF0YSk=",highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;\\nStarting retrieval for <span class="hljs-subst">{user_query=}</span>...&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>retrieved_docs = KNOWLEDGE_VECTOR_DATABASE.similarity_search(query=user_query, k=<span class="hljs-number">5</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;\\n==================================Top document==================================&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(retrieved_docs[<span class="hljs-number">0</span>].page_content)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;==================================Metadata==================================&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(retrieved_docs[<span class="hljs-number">0</span>].metadata)`,wrap:!1}}),vl=new T({props:{title:"2. 阅读器- LLM 💬",local:"2-阅读器--llm-",headingTag:"h1"}}),Nl=new T({props:{title:"2.1. 阅读器模型",local:"21-阅读器模型",headingTag:"h3"}}),ql=new c({props:{code:"ZnJvbSUyMHRyYW5zZm9ybWVycyUyMGltcG9ydCUyMHBpcGVsaW5lJTBBaW1wb3J0JTIwdG9yY2glMEFmcm9tJTIwdHJhbnNmb3JtZXJzJTIwaW1wb3J0JTIwQXV0b1Rva2VuaXplciUyQyUyMEF1dG9Nb2RlbEZvckNhdXNhbExNJTJDJTIwQml0c0FuZEJ5dGVzQ29uZmlnJTBBJTBBUkVBREVSX01PREVMX05BTUUlMjAlM0QlMjAlMjJIdWdnaW5nRmFjZUg0JTJGemVwaHlyLTdiLWJldGElMjIlMEElMEFibmJfY29uZmlnJTIwJTNEJTIwQml0c0FuZEJ5dGVzQ29uZmlnKCUwQSUyMCUyMCUyMCUyMGxvYWRfaW5fNGJpdCUzRFRydWUlMkMlMEElMjAlMjAlMjAlMjBibmJfNGJpdF91c2VfZG91YmxlX3F1YW50JTNEVHJ1ZSUyQyUwQSUyMCUyMCUyMCUyMGJuYl80Yml0X3F1YW50X3R5cGUlM0QlMjJuZjQlMjIlMkMlMEElMjAlMjAlMjAlMjBibmJfNGJpdF9jb21wdXRlX2R0eXBlJTNEdG9yY2guYmZsb2F0MTYlMkMlMEEpJTBBbW9kZWwlMjAlM0QlMjBBdXRvTW9kZWxGb3JDYXVzYWxMTS5mcm9tX3ByZXRyYWluZWQoUkVBREVSX01PREVMX05BTUUlMkMlMjBxdWFudGl6YXRpb25fY29uZmlnJTNEYm5iX2NvbmZpZyklMEF0b2tlbml6ZXIlMjAlM0QlMjBBdXRvVG9rZW5pemVyLmZyb21fcHJldHJhaW5lZChSRUFERVJfTU9ERUxfTkFNRSklMEElMEFSRUFERVJfTExNJTIwJTNEJTIwcGlwZWxpbmUoJTBBJTIwJTIwJTIwJTIwbW9kZWwlM0Rtb2RlbCUyQyUwQSUyMCUyMCUyMCUyMHRva2VuaXplciUzRHRva2VuaXplciUyQyUwQSUyMCUyMCUyMCUyMHRhc2slM0QlMjJ0ZXh0LWdlbmVyYXRpb24lMjIlMkMlMEElMjAlMjAlMjAlMjBkb19zYW1wbGUlM0RUcnVlJTJDJTBBJTIwJTIwJTIwJTIwdGVtcGVyYXR1cmUlM0QwLjIlMkMlMEElMjAlMjAlMjAlMjByZXBldGl0aW9uX3BlbmFsdHklM0QxLjElMkMlMEElMjAlMjAlMjAlMjByZXR1cm5fZnVsbF90ZXh0JTNERmFsc2UlMkMlMEElMjAlMjAlMjAlMjBtYXhfbmV3X3Rva2VucyUzRDUwMCUyQyUwQSk=",highlighted:`<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> pipeline
<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig

READER_MODEL_NAME = <span class="hljs-string">&quot;HuggingFaceH4/zephyr-7b-beta&quot;</span>

bnb_config = BitsAndBytesConfig(
    load_in_4bit=<span class="hljs-literal">True</span>,
    bnb_4bit_use_double_quant=<span class="hljs-literal">True</span>,
    bnb_4bit_quant_type=<span class="hljs-string">&quot;nf4&quot;</span>,
    bnb_4bit_compute_dtype=torch.bfloat16,
)
model = AutoModelForCausalLM.from_pretrained(READER_MODEL_NAME, quantization_config=bnb_config)
tokenizer = AutoTokenizer.from_pretrained(READER_MODEL_NAME)

READER_LLM = pipeline(
    model=model,
    tokenizer=tokenizer,
    task=<span class="hljs-string">&quot;text-generation&quot;</span>,
    do_sample=<span class="hljs-literal">True</span>,
    temperature=<span class="hljs-number">0.2</span>,
    repetition_penalty=<span class="hljs-number">1.1</span>,
    return_full_text=<span class="hljs-literal">False</span>,
    max_new_tokens=<span class="hljs-number">500</span>,
)`,wrap:!1}}),Gl=new c({props:{code:"UkVBREVSX0xMTSglMjJXaGF0JTIwaXMlMjA0JTJCNCUzRiUyMEFuc3dlciUzQSUyMik=",highlighted:'READER_LLM(<span class="hljs-string">&quot;What is 4+4? Answer:&quot;</span>)',wrap:!1}}),Pl=new T({props:{title:"2.2. 提示(Prompt)",local:"22-提示prompt",headingTag:"h3"}}),Zl=new c({props:{code:"cHJvbXB0X2luX2NoYXRfZm9ybWF0JTIwJTNEJTIwJTVCJTBBJTIwJTIwJTIwJTIwJTdCJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIycm9sZSUyMiUzQSUyMCUyMnN5c3RlbSUyMiUyQyUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMmNvbnRlbnQlMjIlM0ElMjAlMjIlMjIlMjJVc2luZyUyMHRoZSUyMGluZm9ybWF0aW9uJTIwY29udGFpbmVkJTIwaW4lMjB0aGUlMjBjb250ZXh0JTJDJTBBZ2l2ZSUyMGElMjBjb21wcmVoZW5zaXZlJTIwYW5zd2VyJTIwdG8lMjB0aGUlMjBxdWVzdGlvbi4lMEFSZXNwb25kJTIwb25seSUyMHRvJTIwdGhlJTIwcXVlc3Rpb24lMjBhc2tlZCUyQyUyMHJlc3BvbnNlJTIwc2hvdWxkJTIwYmUlMjBjb25jaXNlJTIwYW5kJTIwcmVsZXZhbnQlMjB0byUyMHRoZSUyMHF1ZXN0aW9uLiUwQVByb3ZpZGUlMjB0aGUlMjBudW1iZXIlMjBvZiUyMHRoZSUyMHNvdXJjZSUyMGRvY3VtZW50JTIwd2hlbiUyMHJlbGV2YW50LiUwQUlmJTIwdGhlJTIwYW5zd2VyJTIwY2Fubm90JTIwYmUlMjBkZWR1Y2VkJTIwZnJvbSUyMHRoZSUyMGNvbnRleHQlMkMlMjBkbyUyMG5vdCUyMGdpdmUlMjBhbiUyMGFuc3dlci4lMjIlMjIlMjIlMkMlMEElMjAlMjAlMjAlMjAlN0QlMkMlMEElMjAlMjAlMjAlMjAlN0IlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjJyb2xlJTIyJTNBJTIwJTIydXNlciUyMiUyQyUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMmNvbnRlbnQlMjIlM0ElMjAlMjIlMjIlMjJDb250ZXh0JTNBJTBBJTdCY29udGV4dCU3RCUwQS0tLSUwQU5vdyUyMGhlcmUlMjBpcyUyMHRoZSUyMHF1ZXN0aW9uJTIweW91JTIwbmVlZCUyMHRvJTIwYW5zd2VyLiUwQSUwQVF1ZXN0aW9uJTNBJTIwJTdCcXVlc3Rpb24lN0QlMjIlMjIlMjIlMkMlMEElMjAlMjAlMjAlMjAlN0QlMkMlMEElNUQlMEFSQUdfUFJPTVBUX1RFTVBMQVRFJTIwJTNEJTIwdG9rZW5pemVyLmFwcGx5X2NoYXRfdGVtcGxhdGUoJTBBJTIwJTIwJTIwJTIwcHJvbXB0X2luX2NoYXRfZm9ybWF0JTJDJTIwdG9rZW5pemUlM0RGYWxzZSUyQyUyMGFkZF9nZW5lcmF0aW9uX3Byb21wdCUzRFRydWUlMEEpJTBBcHJpbnQoUkFHX1BST01QVF9URU1QTEFURSk=",highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>prompt_in_chat_format = [
<span class="hljs-meta">... </span>    {
<span class="hljs-meta">... </span>        <span class="hljs-string">&quot;role&quot;</span>: <span class="hljs-string">&quot;system&quot;</span>,
<span class="hljs-meta">... </span>        <span class="hljs-string">&quot;content&quot;</span>: <span class="hljs-string">&quot;&quot;&quot;Using the information contained in the context,
<span class="hljs-meta">... </span>give a comprehensive answer to the question.
<span class="hljs-meta">... </span>Respond only to the question asked, response should be concise and relevant to the question.
<span class="hljs-meta">... </span>Provide the number of the source document when relevant.
<span class="hljs-meta">... </span>If the answer cannot be deduced from the context, do not give an answer.&quot;&quot;&quot;</span>,
<span class="hljs-meta">... </span>    },
<span class="hljs-meta">... </span>    {
<span class="hljs-meta">... </span>        <span class="hljs-string">&quot;role&quot;</span>: <span class="hljs-string">&quot;user&quot;</span>,
<span class="hljs-meta">... </span>        <span class="hljs-string">&quot;content&quot;</span>: <span class="hljs-string">&quot;&quot;&quot;Context:
<span class="hljs-meta">... </span>{context}
<span class="hljs-meta">... </span>---
<span class="hljs-meta">... </span>Now here is the question you need to answer.

<span class="hljs-meta">... </span>Question: {question}&quot;&quot;&quot;</span>,
<span class="hljs-meta">... </span>    },
<span class="hljs-meta">... </span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>RAG_PROMPT_TEMPLATE = tokenizer.apply_chat_template(
<span class="hljs-meta">... </span>    prompt_in_chat_format, tokenize=<span class="hljs-literal">False</span>, add_generation_prompt=<span class="hljs-literal">True</span>
<span class="hljs-meta">... </span>)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(RAG_PROMPT_TEMPLATE)`,wrap:!1}}),Dl=new c({props:{code:"cmV0cmlldmVkX2RvY3NfdGV4dCUyMCUzRCUyMCU1QiUwQSUyMCUyMCUyMCUyMGRvYy5wYWdlX2NvbnRlbnQlMjBmb3IlMjBkb2MlMjBpbiUyMHJldHJpZXZlZF9kb2NzJTBBJTVEJTIwJTIwJTIzJTIwd2UlMjBvbmx5JTIwbmVlZCUyMHRoZSUyMHRleHQlMjBvZiUyMHRoZSUyMGRvY3VtZW50cyUwQWNvbnRleHQlMjAlM0QlMjAlMjIlNUNuRXh0cmFjdGVkJTIwZG9jdW1lbnRzJTNBJTVDbiUyMiUwQWNvbnRleHQlMjAlMkIlM0QlMjAlMjIlMjIuam9pbiglNUJmJTIyRG9jdW1lbnQlMjAlN0JzdHIoaSklN0QlM0ElM0ElM0ElNUNuJTIyJTIwJTJCJTIwZG9jJTIwZm9yJTIwaSUyQyUyMGRvYyUyMGluJTIwZW51bWVyYXRlKHJldHJpZXZlZF9kb2NzX3RleHQpJTVEKSUwQSUwQWZpbmFsX3Byb21wdCUyMCUzRCUyMFJBR19QUk9NUFRfVEVNUExBVEUuZm9ybWF0KCUwQSUyMCUyMCUyMCUyMHF1ZXN0aW9uJTNEJTIySG93JTIwdG8lMjBjcmVhdGUlMjBhJTIwcGlwZWxpbmUlMjBvYmplY3QlM0YlMjIlMkMlMjBjb250ZXh0JTNEY29udGV4dCUwQSklMEElMEElMjMlMjBSZWRhY3QlMjBhbiUyMGFuc3dlciUwQWFuc3dlciUyMCUzRCUyMFJFQURFUl9MTE0oZmluYWxfcHJvbXB0KSU1QjAlNUQlNUIlMjJnZW5lcmF0ZWRfdGV4dCUyMiU1RCUwQXByaW50KGFuc3dlcik=",highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>retrieved_docs_text = [
<span class="hljs-meta">... </span>    doc.page_content <span class="hljs-keyword">for</span> doc <span class="hljs-keyword">in</span> retrieved_docs
<span class="hljs-meta">... </span>]  <span class="hljs-comment"># we only need the text of the documents</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>context = <span class="hljs-string">&quot;\\nExtracted documents:\\n&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </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>(retrieved_docs_text)])

<span class="hljs-meta">&gt;&gt;&gt; </span>final_prompt = RAG_PROMPT_TEMPLATE.<span class="hljs-built_in">format</span>(
<span class="hljs-meta">... </span>    question=<span class="hljs-string">&quot;How to create a pipeline object?&quot;</span>, context=context
<span class="hljs-meta">... </span>)

<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-comment"># Redact an answer</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>answer = READER_LLM(final_prompt)[<span class="hljs-number">0</span>][<span class="hljs-string">&quot;generated_text&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(answer)`,wrap:!1}}),_l=new T({props:{title:"2.3. 重排序(rerank)",local:"23-重排序rerank",headingTag:"h3"}}),tt=new c({props:{code:"ZnJvbSUyMHJhZ2F0b3VpbGxlJTIwaW1wb3J0JTIwUkFHUHJldHJhaW5lZE1vZGVsJTBBJTBBUkVSQU5LRVIlMjAlM0QlMjBSQUdQcmV0cmFpbmVkTW9kZWwuZnJvbV9wcmV0cmFpbmVkKCUyMmNvbGJlcnQtaXIlMkZjb2xiZXJ0djIuMCUyMik=",highlighted:`<span class="hljs-keyword">from</span> ragatouille <span class="hljs-keyword">import</span> RAGPretrainedModel

RERANKER = RAGPretrainedModel.from_pretrained(<span class="hljs-string">&quot;colbert-ir/colbertv2.0&quot;</span>)`,wrap:!1}}),et=new T({props:{title:"3. 集成所有组件",local:"3-集成所有组件",headingTag:"h1"}}),st=new c({props:{code:"ZnJvbSUyMHRyYW5zZm9ybWVycyUyMGltcG9ydCUyMFBpcGVsaW5lJTBBJTBBJTBBZGVmJTIwYW5zd2VyX3dpdGhfcmFnKCUwQSUyMCUyMCUyMCUyMHF1ZXN0aW9uJTNBJTIwc3RyJTJDJTBBJTIwJTIwJTIwJTIwbGxtJTNBJTIwUGlwZWxpbmUlMkMlMEElMjAlMjAlMjAlMjBrbm93bGVkZ2VfaW5kZXglM0ElMjBGQUlTUyUyQyUwQSUyMCUyMCUyMCUyMHJlcmFua2VyJTNBJTIwT3B0aW9uYWwlNUJSQUdQcmV0cmFpbmVkTW9kZWwlNUQlMjAlM0QlMjBOb25lJTJDJTBBJTIwJTIwJTIwJTIwbnVtX3JldHJpZXZlZF9kb2NzJTNBJTIwaW50JTIwJTNEJTIwMzAlMkMlMEElMjAlMjAlMjAlMjBudW1fZG9jc19maW5hbCUzQSUyMGludCUyMCUzRCUyMDUlMkMlMEEpJTIwLSUzRSUyMFR1cGxlJTVCc3RyJTJDJTIwTGlzdCU1QkxhbmdjaGFpbkRvY3VtZW50JTVEJTVEJTNBJTBBJTIwJTIwJTIwJTIwJTIzJTIwR2F0aGVyJTIwZG9jdW1lbnRzJTIwd2l0aCUyMHJldHJpZXZlciUwQSUyMCUyMCUyMCUy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wJTIwJTIwJTIwY29udGV4dCUyMCUzRCUyMCUyMiU1Q25FeHRyYWN0ZWQlMjBkb2N1bWVudHMlM0ElNUNuJTIyJTBBJTIwJTIwJTIwJTIwY29udGV4dCUyMCUyQiUzRCUyMCUyMiUyMi5qb2luKCU1QmYlMjJEb2N1bWVudCUyMCU3QnN0cihpKSU3RCUzQSUzQSUzQSU1Q24lMjIlMjAlMkIlMjBkb2MlMjBmb3IlMjBpJTJDJTIwZG9jJTIwaW4lMjBlbnVtZXJhdGUocmVsZXZhbnRfZG9jcyklNUQpJTBBJTBBJTIwJTIwJTIwJTIwZmluYWxfcHJvbXB0JTIwJTNEJTIwUkFHX1BST01QVF9URU1QTEFURS5mb3JtYXQocXVlc3Rpb24lM0RxdWVzdGlvbiUyQyUyMGNvbnRleHQlM0Rjb250ZXh0KSUwQSUwQSUyMCUyMCUyMCUyMCUyMyUyMFJlZGFjdCUyMGFuJTIwYW5zd2VyJTBBJTIwJTIwJTIwJTIwcHJpbnQoJTIyJTNEJTNFJTIwR2VuZXJhdGluZyUyMGFuc3dlci4uLiUyMiklMEElMjAlMjAlMjAlMjBhbnN3ZXIlMjAlM0QlMjBsbG0oZmluYWxfcHJvbXB0KSU1QjAlNUQlNUIlMjJnZW5lcmF0ZWRfdGV4dCUyMiU1RCUwQSUwQSUyMCUyMCUyMCUyMHJldHVybiUyMGFuc3dlciUyQyUyMHJlbGV2YW50X2RvY3M=",highlighted:`<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> Pipeline


<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: Pipeline,
    knowledge_index: FAISS,
    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">5</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-comment"># Gather documents with retriever</span>
    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;=&gt; Retrieving documents...&quot;</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:
        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;=&gt; Reranking documents...&quot;</span>)
        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>
    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;=&gt; Generating answer...&quot;</span>)
    answer = llm(final_prompt)[<span class="hljs-number">0</span>][<span class="hljs-string">&quot;generated_text&quot;</span>]

    <span class="hljs-keyword">return</span> answer, relevant_docs`,wrap:!1}}),at=new c({props:{code:"cXVlc3Rpb24lMjAlM0QlMjAlMjJob3clMjB0byUyMGNyZWF0ZSUyMGElMjBwaXBlbGluZSUyMG9iamVjdCUzRiUyMiUwQSUwQWFuc3dlciUyQyUyMHJlbGV2YW50X2RvY3MlMjAlM0QlMjBhbnN3ZXJfd2l0aF9yYWcoJTBBJTIwJTIwJTIwJTIwcXVlc3Rpb24lMkMlMjBSRUFERVJfTExNJTJDJTIwS05PV0xFREdFX1ZFQ1RPUl9EQVRBQkFTRSUyQyUyMHJlcmFua2VyJTNEUkVSQU5LRVIlMEEp",highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span>question = <span class="hljs-string">&quot;how to create a pipeline object?&quot;</span>

<span class="hljs-meta">&gt;&gt;&gt; </span>answer, relevant_docs = answer_with_rag(
<span class="hljs-meta">... </span>    question, READER_LLM, KNOWLEDGE_VECTOR_DATABASE, reranker=RERANKER
<span class="hljs-meta">... </span>)`,wrap:!1}}),it=new c({props:{code:"cHJpbnQoJTIyJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEQW5zd2VyJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTIyKSUwQXByaW50KGYlMjIlN0JhbnN3ZXIlN0QlMjIpJTBBcHJpbnQoJTIyJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEJTNEU291cmNlJTIwZG9jcyUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUzRCUyMiklMEFmb3IlMjBpJTJDJTIwZG9jJTIwaW4lMjBlbnVtZXJhdGUocmVsZXZhbnRfZG9jcyklM0ElMEElMjAlMjAlMjAlMjBwcmludChmJTIyRG9jdW1lbnQlMjAlN0JpJTdELS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tJTIyKSUwQSUyMCUyMCUyMCUyMHByaW50KGRvYyk=",highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;==================================Answer==================================&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;<span class="hljs-subst">{answer}</span>&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;==================================Source docs==================================&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">for</span> i, doc <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(relevant_docs):
<span class="hljs-meta">... </span>    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Document <span class="hljs-subst">{i}</span>------------------------------------------------------------&quot;</span>)
<span class="hljs-meta">... </span>    <span class="hljs-built_in">print</span>(doc)`,wrap:!1}}),Mt=new T({props:{title:"进一步探索 🗺️",local:"进一步探索-",headingTag:"h1"}}),rt=new T({props:{title:"设置评估流水线",local:"设置评估流水线",headingTag:"h3"}}),wt=new T({props:{title:"改进检索器",local:"改进检索器",headingTag:"h3"}}),yt=new T({props:{title:"改进阅读器",local:"改进阅读器",headingTag:"h3"}}),Ct=new ua({props:{source:"https://github.com/huggingface/cookbook/blob/main/notebooks/zh-CN/advanced_rag.md"}}),{c(){f=A("meta"),gt=n(),Ft=A("p"),It=n(),p(J.$$.fragment),vt=n(),p(y.$$.fragment),Et=n(),p(u.$$.fragment),Kt=n(),m=A("p"),m.innerHTML=Gs,Vt=n(),d=A("p"),d.textContent=Ps,Nt=n(),R=A("p"),R.innerHTML=Ws,Xt=n(),C=A("p"),C.textContent=zs,kt=n(),h=A("img"),Qt=n(),b=A("blockquote"),b.innerHTML=Ls,xt=n(),F=A("p"),F.textContent=Ss,Ht=n(),B=A("p"),B.innerHTML=Ds,qt=n(),p(g.$$.fragment),Gt=n(),p(I.$$.fragment),Pt=n(),p(v.$$.fragment),Wt=n(),p(E.$$.fragment),zt=n(),p(K.$$.fragment),Zt=n(),p(V.$$.fragment),Lt=n(),p(N.$$.fragment),St=n(),X=A("p"),X.innerHTML=Ys,Dt=n(),k=A("p"),k.textContent=_s,Yt=n(),Q=A("p"),Q.innerHTML=Os,_t=n(),x=A("p"),x.innerHTML=$s,Ot=n(),H=A("p"),H.innerHTML=ln,$t=n(),q=A("ul"),q.innerHTML=tn,le=n(),G=A("blockquote"),G.innerHTML=en,te=n(),p(P.$$.fragment),ee=n(),W=A("ul"),W.innerHTML=sn,se=n(),z=A("p"),z.innerHTML=nn,ne=n(),Z=A("ul"),Z.innerHTML=an,ae=n(),L=A("blockquote"),L.innerHTML=An,Ae=n(),S=A("p"),S.innerHTML=on,ie=n(),D=A("ul"),D.innerHTML=pn,oe=n(),p(Y.$$.fragment),pe=n(),_=A("p"),_.innerHTML=Mn,Me=n(),O=A("p"),O.textContent=Un,Ue=n(),p($.$$.fragment),re=n(),ll=A("pre"),ll.textContent=rn,je=n(),tl=A("p"),tl.innerHTML=jn,we=n(),el=A("ul"),el.innerHTML=wn,ce=n(),p(sl.$$.fragment),Te=n(),bt=A("img"),fe=n(),nl=A("p"),nl.textContent=Tn,Je=n(),p(al.$$.fragment),ye=n(),Al=A("p"),Al.innerHTML=fn,ue=n(),p(il.$$.fragment),me=n(),ol=A("p"),ol.textContent=Jn,de=n(),pl=A("p"),pl.textContent=yn,Re=n(),p(Ml.$$.fragment),Ce=n(),Ul=A("p"),Ul.innerHTML=un,he=n(),p(rl.$$.fragment),be=n(),jl=A("p"),jl.innerHTML=mn,Fe=n(),wl=A("ul"),wl.innerHTML=dn,Be=n(),cl=A("p"),cl.innerHTML=Rn,ge=n(),Tl=A("p"),Tl.innerHTML=Cn,Ie=n(),fl=A("p"),fl.textContent=hn,ve=n(),p(Jl.$$.fragment),Ee=n(),yl=A("p"),yl.textContent=bn,Ke=n(),ul=A("p"),ul.innerHTML=Fn,Ve=n(),p(ml.$$.fragment),Ne=n(),p(dl.$$.fragment),Xe=n(),p(Rl.$$.fragment),ke=n(),Cl=A("img"),Qe=n(),hl=A("p"),hl.textContent=gn,xe=n(),bl=A("p"),bl.innerHTML=In,He=n(),Fl=A("p"),Fl.innerHTML=vn,qe=n(),Bl=A("p"),Bl.textContent=En,Ge=n(),p(gl.$$.fragment),Pe=n(),Il=A("pre"),Il.textContent=Kn,We=n(),p(vl.$$.fragment),ze=n(),El=A("p"),El.innerHTML=Vn,Ze=n(),Kl=A("p"),Kl.textContent=Nn,Le=n(),Vl=A("ol"),Vl.innerHTML=Xn,Se=n(),p(Nl.$$.fragment),De=n(),Xl=A("p"),Xl.textContent=kn,Ye=n(),kl=A("ul"),kl.innerHTML=Qn,_e=n(),Ql=A("p"),Ql.innerHTML=xn,Oe=n(),xl=A("p"),xl.innerHTML=Hn,$e=n(),Hl=A("p"),Hl.textContent=qn,ls=n(),p(ql.$$.fragment),ts=n(),p(Gl.$$.fragment),es=n(),p(Pl.$$.fragment),ss=n(),Wl=A("p"),Wl.textContent=Gn,ns=n(),zl=A("p"),zl.textContent=Pn,as=n(),p(Zl.$$.fragment),As=n(),Ll=A("pre"),Ll.textContent=Wn,is=n(),Sl=A("p"),Sl.textContent=zn,os=n(),p(Dl.$$.fragment),ps=n(),Yl=A("pre"),Yl.textContent=Zn,Ms=n(),p(_l.$$.fragment),Us=n(),Ol=A("p"),Ol.innerHTML=Ln,rs=n(),$l=A("p"),$l.innerHTML=Sn,js=n(),lt=A("p"),lt.innerHTML=Dn,ws=n(),p(tt.$$.fragment),cs=n(),p(et.$$.fragment),Ts=n(),p(st.$$.fragment),fs=n(),nt=A("p"),nt.textContent=Yn,Js=n(),p(at.$$.fragment),ys=n(),At=A("pre"),At.textContent=_n,us=n(),p(it.$$.fragment),ms=n(),ot=A("pre"),ot.textContent=On,ds=n(),pt=A("p"),pt.textContent=$n,Rs=n(),p(Mt.$$.fragment),Cs=n(),Ut=A("p"),Ut.textContent=la,hs=n(),p(rt.$$.fragment),bs=n(),jt=A("ul"),jt.innerHTML=ta,Fs=n(),p(wt.$$.fragment),Bs=n(),ct=A("p"),ct.innerHTML=ea,gs=n(),Tt=A("ul"),Tt.innerHTML=sa,Is=n(),ft=A("p"),ft.innerHTML=na,vs=n(),Jt=A("ul"),Jt.innerHTML=aa,Es=n(),p(yt.$$.fragment),Ks=n(),ut=A("p"),ut.innerHTML=Aa,Vs=n(),mt=A("ul"),mt.innerHTML=ia,Ns=n(),dt=A("p"),dt.innerHTML=oa,Xs=n(),Rt=A("ul"),Rt.innerHTML=pa,ks=n(),p(Ct.$$.fragment),Qs=n(),Bt=A("p"),this.h()},l(l){const t=Ta("svelte-u9bgzb",document.head);f=i(t,"META",{name:!0,content:!0}),t.forEach(e),gt=a(l),Ft=i(l,"P",{}),Ma(Ft).forEach(e),It=a(l),M(J.$$.fragment,l),vt=a(l),M(y.$$.fragment,l),Et=a(l),M(u.$$.fragment,l),Kt=a(l),m=i(l,"P",{"data-svelte-h":!0}),o(m)!=="svelte-1ouqjzx"&&(m.innerHTML=Gs),Vt=a(l),d=i(l,"P",{"data-svelte-h":!0}),o(d)!=="svelte-1y8o57u"&&(d.textContent=Ps),Nt=a(l),R=i(l,"P",{"data-svelte-h":!0}),o(R)!=="svelte-cgsx28"&&(R.innerHTML=Ws),Xt=a(l),C=i(l,"P",{"data-svelte-h":!0}),o(C)!=="svelte-45g62z"&&(C.textContent=zs),kt=a(l),h=i(l,"IMG",{src:!0,height:!0}),Qt=a(l),b=i(l,"BLOCKQUOTE",{"data-svelte-h":!0}),o(b)!=="svelte-oiyp3w"&&(b.innerHTML=Ls),xt=a(l),F=i(l,"P",{"data-svelte-h":!0}),o(F)!=="svelte-1c77kj2"&&(F.textContent=Ss),Ht=a(l),B=i(l,"P",{"data-svelte-h":!0}),o(B)!=="svelte-16f9kjd"&&(B.innerHTML=Ds),qt=a(l),M(g.$$.fragment,l),Gt=a(l),M(I.$$.fragment,l),Pt=a(l),M(v.$$.fragment,l),Wt=a(l),M(E.$$.fragment,l),zt=a(l),M(K.$$.fragment,l),Zt=a(l),M(V.$$.fragment,l),Lt=a(l),M(N.$$.fragment,l),St=a(l),X=i(l,"P",{"data-svelte-h":!0}),o(X)!=="svelte-ql0xxw"&&(X.innerHTML=Ys),Dt=a(l),k=i(l,"P",{"data-svelte-h":!0}),o(k)!=="svelte-79k71u"&&(k.textContent=_s),Yt=a(l),Q=i(l,"P",{"data-svelte-h":!0}),o(Q)!=="svelte-gfu2zq"&&(Q.innerHTML=Os),_t=a(l),x=i(l,"P",{"data-svelte-h":!0}),o(x)!=="svelte-c8pzbv"&&(x.innerHTML=$s),Ot=a(l),H=i(l,"P",{"data-svelte-h":!0}),o(H)!=="svelte-1ylwvta"&&(H.innerHTML=ln),$t=a(l),q=i(l,"UL",{"data-svelte-h":!0}),o(q)!=="svelte-1ynnvg9"&&(q.innerHTML=tn),le=a(l),G=i(l,"BLOCKQUOTE",{"data-svelte-h":!0}),o(G)!=="svelte-1jq112o"&&(G.innerHTML=en),te=a(l),M(P.$$.fragment,l),ee=a(l),W=i(l,"UL",{"data-svelte-h":!0}),o(W)!=="svelte-18g8ey5"&&(W.innerHTML=sn),se=a(l),z=i(l,"P",{"data-svelte-h":!0}),o(z)!=="svelte-uaz899"&&(z.innerHTML=nn),ne=a(l),Z=i(l,"UL",{"data-svelte-h":!0}),o(Z)!=="svelte-1j9j687"&&(Z.innerHTML=an),ae=a(l),L=i(l,"BLOCKQUOTE",{"data-svelte-h":!0}),o(L)!=="svelte-nls6mz"&&(L.innerHTML=An),Ae=a(l),S=i(l,"P",{"data-svelte-h":!0}),o(S)!=="svelte-164rw2z"&&(S.innerHTML=on),ie=a(l),D=i(l,"UL",{"data-svelte-h":!0}),o(D)!=="svelte-j32ek"&&(D.innerHTML=pn),oe=a(l),M(Y.$$.fragment,l),pe=a(l),_=i(l,"P",{"data-svelte-h":!0}),o(_)!=="svelte-y33335"&&(_.innerHTML=Mn),Me=a(l),O=i(l,"P",{"data-svelte-h":!0}),o(O)!=="svelte-1yay3kj"&&(O.textContent=Un),Ue=a(l),M($.$$.fragment,l),re=a(l),ll=i(l,"PRE",{"data-svelte-h":!0}),o(ll)!=="svelte-h6hpdk"&&(ll.textContent=rn),je=a(l),tl=i(l,"P",{"data-svelte-h":!0}),o(tl)!=="svelte-1k6h3dv"&&(tl.innerHTML=jn),we=a(l),el=i(l,"UL",{"data-svelte-h":!0}),o(el)!=="svelte-1gpnsn4"&&(el.innerHTML=wn),ce=a(l),M(sl.$$.fragment,l),Te=a(l),bt=i(l,"IMG",{src:!0}),fe=a(l),nl=i(l,"P",{"data-svelte-h":!0}),o(nl)!=="svelte-1su99xg"&&(nl.textContent=Tn),Je=a(l),M(al.$$.fragment,l),ye=a(l),Al=i(l,"P",{"data-svelte-h":!0}),o(Al)!=="svelte-1q1eqv0"&&(Al.innerHTML=fn),ue=a(l),M(il.$$.fragment,l),me=a(l),ol=i(l,"P",{"data-svelte-h":!0}),o(ol)!=="svelte-120j1u7"&&(ol.textContent=Jn),de=a(l),pl=i(l,"P",{"data-svelte-h":!0}),o(pl)!=="svelte-187cxhr"&&(pl.textContent=yn),Re=a(l),M(Ml.$$.fragment,l),Ce=a(l),Ul=i(l,"P",{"data-svelte-h":!0}),o(Ul)!=="svelte-mw3wdi"&&(Ul.innerHTML=un),he=a(l),M(rl.$$.fragment,l),be=a(l),jl=i(l,"P",{"data-svelte-h":!0}),o(jl)!=="svelte-1pa51hd"&&(jl.innerHTML=mn),Fe=a(l),wl=i(l,"UL",{"data-svelte-h":!0}),o(wl)!=="svelte-1wwyqqn"&&(wl.innerHTML=dn),Be=a(l),cl=i(l,"P",{"data-svelte-h":!0}),o(cl)!=="svelte-1jcvwk2"&&(cl.innerHTML=Rn),ge=a(l),Tl=i(l,"P",{"data-svelte-h":!0}),o(Tl)!=="svelte-ibu9nm"&&(Tl.innerHTML=Cn),Ie=a(l),fl=i(l,"P",{"data-svelte-h":!0}),o(fl)!=="svelte-fspy7m"&&(fl.textContent=hn),ve=a(l),M(Jl.$$.fragment,l),Ee=a(l),yl=i(l,"P",{"data-svelte-h":!0}),o(yl)!=="svelte-1wro3yx"&&(yl.textContent=bn),Ke=a(l),ul=i(l,"P",{"data-svelte-h":!0}),o(ul)!=="svelte-1krpkyx"&&(ul.innerHTML=Fn),Ve=a(l),M(ml.$$.fragment,l),Ne=a(l),M(dl.$$.fragment,l),Xe=a(l),M(Rl.$$.fragment,l),ke=a(l),Cl=i(l,"IMG",{src:!0,height:!0}),Qe=a(l),hl=i(l,"P",{"data-svelte-h":!0}),o(hl)!=="svelte-1k4v1uw"&&(hl.textContent=gn),xe=a(l),bl=i(l,"P",{"data-svelte-h":!0}),o(bl)!=="svelte-1nzosig"&&(bl.innerHTML=In),He=a(l),Fl=i(l,"P",{"data-svelte-h":!0}),o(Fl)!=="svelte-1mlsch3"&&(Fl.innerHTML=vn),qe=a(l),Bl=i(l,"P",{"data-svelte-h":!0}),o(Bl)!=="svelte-1l1mro3"&&(Bl.textContent=En),Ge=a(l),M(gl.$$.fragment,l),Pe=a(l),Il=i(l,"PRE",{"data-svelte-h":!0}),o(Il)!=="svelte-1q4z1pg"&&(Il.textContent=Kn),We=a(l),M(vl.$$.fragment,l),ze=a(l),El=i(l,"P",{"data-svelte-h":!0}),o(El)!=="svelte-1jbxnsj"&&(El.innerHTML=Vn),Ze=a(l),Kl=i(l,"P",{"data-svelte-h":!0}),o(Kl)!=="svelte-15oxcnc"&&(Kl.textContent=Nn),Le=a(l),Vl=i(l,"OL",{"data-svelte-h":!0}),o(Vl)!=="svelte-1x6zhcr"&&(Vl.innerHTML=Xn),Se=a(l),M(Nl.$$.fragment,l),De=a(l),Xl=i(l,"P",{"data-svelte-h":!0}),o(Xl)!=="svelte-jar50q"&&(Xl.textContent=kn),Ye=a(l),kl=i(l,"UL",{"data-svelte-h":!0}),o(kl)!=="svelte-btzwg9"&&(kl.innerHTML=Qn),_e=a(l),Ql=i(l,"P",{"data-svelte-h":!0}),o(Ql)!=="svelte-1lm1kj0"&&(Ql.innerHTML=xn),Oe=a(l),xl=i(l,"P",{"data-svelte-h":!0}),o(xl)!=="svelte-me1why"&&(xl.innerHTML=Hn),$e=a(l),Hl=i(l,"P",{"data-svelte-h":!0}),o(Hl)!=="svelte-6joo08"&&(Hl.textContent=qn),ls=a(l),M(ql.$$.fragment,l),ts=a(l),M(Gl.$$.fragment,l),es=a(l),M(Pl.$$.fragment,l),ss=a(l),Wl=i(l,"P",{"data-svelte-h":!0}),o(Wl)!=="svelte-npbw3t"&&(Wl.textContent=Gn),ns=a(l),zl=i(l,"P",{"data-svelte-h":!0}),o(zl)!=="svelte-h6ikmf"&&(zl.textContent=Pn),as=a(l),M(Zl.$$.fragment,l),As=a(l),Ll=i(l,"PRE",{"data-svelte-h":!0}),o(Ll)!=="svelte-aa4a7a"&&(Ll.textContent=Wn),is=a(l),Sl=i(l,"P",{"data-svelte-h":!0}),o(Sl)!=="svelte-l9rg7w"&&(Sl.textContent=zn),os=a(l),M(Dl.$$.fragment,l),ps=a(l),Yl=i(l,"PRE",{"data-svelte-h":!0}),o(Yl)!=="svelte-lv1631"&&(Yl.textContent=Zn),Ms=a(l),M(_l.$$.fragment,l),Us=a(l),Ol=i(l,"P",{"data-svelte-h":!0}),o(Ol)!=="svelte-13uoub8"&&(Ol.innerHTML=Ln),rs=a(l),$l=i(l,"P",{"data-svelte-h":!0}),o($l)!=="svelte-vhdu58"&&($l.innerHTML=Sn),js=a(l),lt=i(l,"P",{"data-svelte-h":!0}),o(lt)!=="svelte-1b58ltx"&&(lt.innerHTML=Dn),ws=a(l),M(tt.$$.fragment,l),cs=a(l),M(et.$$.fragment,l),Ts=a(l),M(st.$$.fragment,l),fs=a(l),nt=i(l,"P",{"data-svelte-h":!0}),o(nt)!=="svelte-352kfz"&&(nt.textContent=Yn),Js=a(l),M(at.$$.fragment,l),ys=a(l),At=i(l,"PRE",{"data-svelte-h":!0}),o(At)!=="svelte-drvpbm"&&(At.textContent=_n),us=a(l),M(it.$$.fragment,l),ms=a(l),ot=i(l,"PRE",{"data-svelte-h":!0}),o(ot)!=="svelte-8jp8ub"&&(ot.textContent=On),ds=a(l),pt=i(l,"P",{"data-svelte-h":!0}),o(pt)!=="svelte-wgk4la"&&(pt.textContent=$n),Rs=a(l),M(Mt.$$.fragment,l),Cs=a(l),Ut=i(l,"P",{"data-svelte-h":!0}),o(Ut)!=="svelte-1vytx7u"&&(Ut.textContent=la),hs=a(l),M(rt.$$.fragment,l),bs=a(l),jt=i(l,"UL",{"data-svelte-h":!0}),o(jt)!=="svelte-1reib3"&&(jt.innerHTML=ta),Fs=a(l),M(wt.$$.fragment,l),Bs=a(l),ct=i(l,"P",{"data-svelte-h":!0}),o(ct)!=="svelte-1dq1tqp"&&(ct.innerHTML=ea),gs=a(l),Tt=i(l,"UL",{"data-svelte-h":!0}),o(Tt)!=="svelte-euuksf"&&(Tt.innerHTML=sa),Is=a(l),ft=i(l,"P",{"data-svelte-h":!0}),o(ft)!=="svelte-1ykhfl1"&&(ft.innerHTML=na),vs=a(l),Jt=i(l,"UL",{"data-svelte-h":!0}),o(Jt)!=="svelte-1csot73"&&(Jt.innerHTML=aa),Es=a(l),M(yt.$$.fragment,l),Ks=a(l),ut=i(l,"P",{"data-svelte-h":!0}),o(ut)!=="svelte-pzw0dh"&&(ut.innerHTML=Aa),Vs=a(l),mt=i(l,"UL",{"data-svelte-h":!0}),o(mt)!=="svelte-1v6dvb"&&(mt.innerHTML=ia),Ns=a(l),dt=i(l,"P",{"data-svelte-h":!0}),o(dt)!=="svelte-fpwmko"&&(dt.innerHTML=oa),Xs=a(l),Rt=i(l,"UL",{"data-svelte-h":!0}),o(Rt)!=="svelte-v0fpv5"&&(Rt.innerHTML=pa),ks=a(l),M(Ct.$$.fragment,l),Qs=a(l),Bt=i(l,"P",{}),Ma(Bt).forEach(e),this.h()},h(){ht(f,"name","hf:doc:metadata"),ht(f,"content",da),Hs(h.src,Zs="https://huggingface.co/datasets/huggingface/cookbook-images/resolve/main/RAG_workflow.png")||ht(h,"src",Zs),ht(h,"height","700"),Hs(bt.src,cn="data:image/jpeg;base64, ")||ht(bt,"src",cn),Hs(Cl.src,Bn="https://huggingface.co/datasets/huggingface/cookbook-images/resolve/main/PaCMAP_embeddings.png")||ht(Cl,"src",Bn),ht(Cl,"height","700")},m(l,t){fa(document.head,f),s(l,gt,t),s(l,Ft,t),s(l,It,t),U(J,l,t),s(l,vt,t),U(y,l,t),s(l,Et,t),U(u,l,t),s(l,Kt,t),s(l,m,t),s(l,Vt,t),s(l,d,t),s(l,Nt,t),s(l,R,t),s(l,Xt,t),s(l,C,t),s(l,kt,t),s(l,h,t),s(l,Qt,t),s(l,b,t),s(l,xt,t),s(l,F,t),s(l,Ht,t),s(l,B,t),s(l,qt,t),U(g,l,t),s(l,Gt,t),U(I,l,t),s(l,Pt,t),U(v,l,t),s(l,Wt,t),U(E,l,t),s(l,zt,t),U(K,l,t),s(l,Zt,t),U(V,l,t),s(l,Lt,t),U(N,l,t),s(l,St,t),s(l,X,t),s(l,Dt,t),s(l,k,t),s(l,Yt,t),s(l,Q,t),s(l,_t,t),s(l,x,t),s(l,Ot,t),s(l,H,t),s(l,$t,t),s(l,q,t),s(l,le,t),s(l,G,t),s(l,te,t),U(P,l,t),s(l,ee,t),s(l,W,t),s(l,se,t),s(l,z,t),s(l,ne,t),s(l,Z,t),s(l,ae,t),s(l,L,t),s(l,Ae,t),s(l,S,t),s(l,ie,t),s(l,D,t),s(l,oe,t),U(Y,l,t),s(l,pe,t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s(l,Ol,t),s(l,rs,t),s(l,$l,t),s(l,js,t),s(l,lt,t),s(l,ws,t),U(tt,l,t),s(l,cs,t),U(et,l,t),s(l,Ts,t),U(st,l,t),s(l,fs,t),s(l,nt,t),s(l,Js,t),U(at,l,t),s(l,ys,t),s(l,At,t),s(l,us,t),U(it,l,t),s(l,ms,t),s(l,ot,t),s(l,ds,t),s(l,pt,t),s(l,Rs,t),U(Mt,l,t),s(l,Cs,t),s(l,Ut,t),s(l,hs,t),U(rt,l,t),s(l,bs,t),s(l,jt,t),s(l,Fs,t),U(wt,l,t),s(l,Bs,t),s(l,ct,t),s(l,gs,t),s(l,Tt,t),s(l,Is,t),s(l,ft,t),s(l,vs,t),s(l,Jt,t),s(l,Es,t),U(yt,l,t),s(l,Ks,t),s(l,ut,t),s(l,Vs,t),s(l,mt,t),s(l,Ns,t),s(l,dt,t),s(l,Xs,t),s(l,Rt,t),s(l,ks,t),U(Ct,l,t),s(l,Qs,t),s(l,Bt,t),xs=!0},p:ra,i(l){xs||(r(J.$$.fragment,l),r(y.$$.fragment,l),r(u.$$.fragment,l),r(g.$$.fragment,l),r(I.$$.fragment,l),r(v.$$.fragment,l),r(E.$$.fragment,l),r(K.$$.fragment,l),r(V.$$.fragment,l),r(N.$$.fragment,l),r(P.$$.fragment,l),r(Y.$$.fragment,l),r($.$$.fragment,l),r(sl.$$.fragment,l),r(al.$$.fragment,l),r(il.$$.fragment,l),r(Ml.$$.fragment,l),r(rl.$$.fragment,l),r(Jl.$$.fragment,l),r(ml.$$.fragment,l),r(dl.$$.fragment,l),r(Rl.$$.fragment,l),r(gl.$$.fragment,l),r(vl.$$.fragment,l),r(Nl.$$.fragment,l),r(ql.$$.fragment,l),r(Gl.$$.fragment,l),r(Pl.$$.fragment,l),r(Zl.$$.fragment,l),r(Dl.$$.fragment,l),r(_l.$$.fragment,l),r(tt.$$.fragment,l),r(et.$$.fragment,l),r(st.$$.fragment,l),r(at.$$.fragment,l),r(it.$$.fragment,l),r(Mt.$$.fragment,l),r(rt.$$.fragment,l),r(wt.$$.fragment,l),r(yt.$$.fragment,l),r(Ct.$$.fragment,l),xs=!0)},o(l){j(J.$$.fragment,l),j(y.$$.fragment,l),j(u.$$.fragment,l),j(g.$$.fragment,l),j(I.$$.fragment,l),j(v.$$.fragment,l),j(E.$$.fragment,l),j(K.$$.fragment,l),j(V.$$.fragment,l),j(N.$$.fragment,l),j(P.$$.fragment,l),j(Y.$$.fragment,l),j($.$$.fragment,l),j(sl.$$.fragment,l),j(al.$$.fragment,l),j(il.$$.fragment,l),j(Ml.$$.fragment,l),j(rl.$$.fragment,l),j(Jl.$$.fragment,l),j(ml.$$.fragment,l),j(dl.$$.fragment,l),j(Rl.$$.fragment,l),j(gl.$$.fragment,l),j(vl.$$.fragment,l),j(Nl.$$.fragment,l),j(ql.$$.fragment,l),j(Gl.$$.fragment,l),j(Pl.$$.fragment,l),j(Zl.$$.fragment,l),j(Dl.$$.fragment,l),j(_l.$$.fragment,l),j(tt.$$.fragment,l),j(et.$$.fragment,l),j(st.$$.fragment,l),j(at.$$.fragment,l),j(it.$$.fragment,l),j(Mt.$$.fragment,l),j(rt.$$.fragment,l),j(wt.$$.fragment,l),j(yt.$$.fragment,l),j(Ct.$$.fragment,l),xs=!1},d(l){l&&(e(gt),e(Ft),e(It),e(vt),e(Et),e(Kt),e(m),e(Vt),e(d),e(Nt),e(R),e(Xt),e(C),e(kt),e(h),e(Qt),e(b),e(xt),e(F),e(Ht),e(B),e(qt),e(Gt),e(Pt),e(Wt),e(zt),e(Zt),e(Lt),e(St),e(X),e(Dt),e(k),e(Yt),e(Q),e(_t),e(x),e(Ot),e(H),e($t),e(q),e(le),e(G),e(te),e(ee),e(W),e(se),e(z),e(ne),e(Z),e(ae),e(L),e(Ae),e(S),e(ie),e(D),e(oe),e(pe),e(_),e(Me),e(O),e(Ue),e(re),e(ll),e(je),e(tl),e(we),e(el),e(ce),e(Te),e(bt),e(fe),e(nl),e(Je),e(ye),e(Al),e(ue),e(me),e(ol),e(de),e(pl),e(Re),e(Ce),e(Ul),e(he),e(be),e(jl),e(Fe),e(wl),e(Be),e(cl),e(ge),e(Tl),e(Ie),e(fl),e(ve),e(Ee),e(yl),e(Ke),e(ul),e(Ve),e(Ne),e(Xe),e(ke),e(Cl),e(Qe),e(hl),e(xe),e(bl),e(He),e(Fl),e(qe),e(Bl),e(Ge),e(Pe),e(Il),e(We),e(ze),e(El),e(Ze),e(Kl),e(Le),e(Vl),e(Se),e(De),e(Xl),e(Ye),e(kl),e(_e),e(Ql),e(Oe),e(xl),e($e),e(Hl),e(ls),e(ts),e(es),e(ss),e(Wl),e(ns),e(zl),e(as),e(As),e(Ll),e(is),e(Sl),e(os),e(ps),e(Yl),e(Ms),e(Us),e(Ol),e(rs),e($l),e(js),e(lt),e(ws),e(cs),e(Ts),e(fs),e(nt),e(Js),e(ys),e(At),e(us),e(ms),e(ot),e(ds),e(pt),e(Rs),e(Cs),e(Ut),e(hs),e(bs),e(jt),e(Fs),e(Bs),e(ct),e(gs),e(Tt),e(Is),e(ft),e(vs),e(Jt),e(Es),e(Ks),e(ut),e(Vs),e(mt),e(Ns),e(dt),e(Xs),e(Rt),e(ks),e(Qs),e(Bt)),e(f),w(J,l),w(y,l),w(u,l),w(g,l),w(I,l),w(v,l),w(E,l),w(K,l),w(V,l),w(N,l),w(P,l),w(Y,l),w($,l),w(sl,l),w(al,l),w(il,l),w(Ml,l),w(rl,l),w(Jl,l),w(ml,l),w(dl,l),w(Rl,l),w(gl,l),w(vl,l),w(Nl,l),w(ql,l),w(Gl,l),w(Pl,l),w(Zl,l),w(Dl,l),w(_l,l),w(tt,l),w(et,l),w(st,l),w(at,l),w(it,l),w(Mt,l),w(rt,l),w(wt,l),w(yt,l),w(Ct,l)}}}const da='{"title":"使用 LangChain 在 HuggingFace 文档上构建高级 RAG","local":"使用-langchain-在-huggingface-文档上构建高级-rag","sections":[{"title":"加载你的知识基础","local":"加载你的知识基础","sections":[],"depth":3}],"depth":1}';function Ra(qs){return ja(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class ga extends wa{constructor(f){super(),ca(this,f,Ra,ma,Ua,{})}}export{ga as component};
