智能体 RAG:通过查询重构和自查询来增强你的 RAG !🚀
作者: Aymeric Roucher
这个教程比较高级,建议你先看看另一个更基础的教程。
检索增强生成(RAG)是一种用大型语言模型(LLM)来回答问题的方法,但它会先从知识库中查找相关信息。这种方法比只用大型语言模型有很多好处,比如可以基于真实的事实来回答问题,减少虚构内容,还可以让模型获取特定领域的知识,并且可以精确控制模型从知识库中获取信息。
不过,普通的RAG方法有两个主要问题:
- 它只进行一次信息检索,如果检索的结果不好,那么回答也会差。
- 它计算语义相似性时是以用户的提问为参照,这可能不太理想。比如,用户提出的问题通常是用疑问句,而包含答案的文档通常是陈述句,这样就会导致真正含有答案的文档和用户提问的相似性得分不高,可能会错过重要的信息。
为了解决这些问题,我们可以创建一个带有检索功能的 RAG 智能体。
这个智能体可以 ✅ 自己构建查询,并且 ✅ 在需要的时候重新检索信息。
所以,我们得用点高级的 RAG 技术!
- 不直接使用用户的提问去搜索,而是智能体自行制定一个更接近目标文档的参考句子,就像 HyDE 那样
- 智能体能生成片段并在需要时重新检索,就像 Self-Query 那样
让我们开始做这个系统吧。🛠️
运行下面的命令来安装所需的软件包:
我们首先加载一个知识库,以便在其上执行 RAG:这个数据集是许多 huggingface 软件包的文档页面的汇总,以 markdown 格式存储。
/Users/aymeric/Documents/Code/cookbook/.venv/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm
现在我们通过处理数据集并将其存储到向量数据库中,为检索器准备知识库。我们使用 LangChain,因为它具有出色的向量数据库工具。对于嵌入模型,我们使用 thenlper/gte-small,因为它在我们的 RAG_evaluation 指南中表现良好。
Splitting documents...
100%|██████████| 2647/2647 [00:34<00:00, 76.04it/s] /Users/aymeric/Documents/Code/cookbook/.venv/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:139: LangChainDeprecationWarning: The class `HuggingFaceEmbeddings` was deprecated in LangChain 0.2.2 and will be removed in 0.3.0. An updated version of the class exists in the langchain-huggingface package and should be used instead. To use it run `pip install -U langchain-huggingface` and import as `from langchain_huggingface import HuggingFaceEmbeddings`. warn_deprecated(
Embedding documents... This should take a few minutes (5 minutes on MacBook with M1 Pro)
现在数据库已经准备好了:让我们构建我们的智能体 RAG 系统吧!
👉 我们只需要一个 RetrieverTool,我们的智能体可以利用它从知识库中检索信息。
现在创建一个利用这个工具的智能体就简单了!
智能体在初始化时需要以下参数:
tools:智能体能够调用的工具列表。llm_engine:为智能体提供动力的LLM。
我们的 llm_engine 必须是一个可调用的对象,它接受一个 messages 列表作为输入并返回文本。它还需要接受一个 stop_sequences 参数,该参数指示何时停止生成。为了方便起见,我们直接使用包中提供的 HfModel 类来获取一个调用我们的 Inference API 的 LLM 引擎。
我们使用 CohereForAI/c4ai-command-r-plus 作为 llm 引擎,因为:
- 它有一个长达 128k 的上下文,这对于处理长源文档很有帮助
- 它在 HF 的 Inference API 上始终免费提供!
既然我们已经将智能体初始化为 ToolCallingAgent,它就已经自动赋予了一个默认的系统提示,告诉 LLM 引擎要逐步处理并生成工具调用作为 JSON 块(你可以根据需要用你自己的提示模板替换这个)。
然后,当它的 .run() 方法被启动时,智能体负责调用 LLM 引擎,解析工具调用的 JSON 块并执行这些工具调用,所有这些都在一个循环中进行,只有当提供最终答案时才会结束。
======== New task ======== How can I push a model to the Hub? System prompt is as follows: You are an expert assistant who can solve any task using JSON tool calls. You will be given a task to solve as best you can. To do so, you have been given access to the following tools: 'retriever', 'final_answer' The way you use the tools is by specifying a json blob, ending with '<end_action>'. Specifically, this json should have an `action` key (name of the tool to use) and an `action_input` key (input to the tool). The $ACTION_JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. It should be formatted in json. Do not try to escape special characters. Here is the template of a valid $ACTION_JSON_BLOB: { "action": $TOOL_NAME, "action_input": $INPUT }<end_action> Make sure to have the $INPUT as a dictionary in the right format for the tool you are using, and do not put variable names as input if you can find the right values. You should ALWAYS use the following format: Thought: you should always think about one action to take. Then use the action as follows: Action: $ACTION_JSON_BLOB Observation: the result of the action ... (this Thought/Action/Observation can repeat N times, you should take several steps when needed. The $ACTION_JSON_BLOB must only use a SINGLE action at a time.) You can use the result of the previous action as input for the next action. The observation will always be a string: it can represent a file, like "image_1.jpg". Then you can use it as input for the next action. You can do it for instance as follows: Observation: "image_1.jpg" Thought: I need to transform the image that I received in the previous observation to make it green. Action: { "action": "image_transformer", "action_input": {"image": "image_1.jpg"} }<end_action> To provide the final answer to the task, use an action blob with "action": "final_answer" tool. It is the only way to complete the task, else you will be stuck on a loop. So your final output should look like this: Action: { "action": "final_answer", "action_input": {"answer": "insert your final answer here"} }<end_action> Here are a few examples using notional tools: --- Task: "Generate an image of the oldest person in this document." Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer. Action: { "action": "document_qa", "action_input": {"document": "document.pdf", "question": "Who is the oldest person mentioned?"} }<end_action> Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland." Thought: I will now generate an image showcasing the oldest person. Action: { "action": "image_generator", "action_input": {"text": ""A portrait of John Doe, a 55-year-old man living in Canada.""} }<end_action> Observation: "image.png" Thought: I will now return the generated image. Action: { "action": "final_answer", "action_input": "image.png" }<end_action> --- Task: "What is the result of the following operation: 5 + 3 + 1294.678?" Thought: I will use python code evaluator to compute the result of the operation and then return the final answer using the `final_answer` tool Action: { "action": "python_interpreter", "action_input": {"code": "5 + 3 + 1294.678"} }<end_action> Observation: 1302.678 Thought: Now that I know the result, I will now return it. Action: { "action": "final_answer", "action_input": "1302.678" }<end_action> --- Task: "Which city has the highest population , Guangzhou or Shanghai?" Thought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities. Action: { "action": "search", "action_input": "Population Guangzhou" }<end_action> Observation: ['Guangzhou has a population of 15 million inhabitants as of 2021.'] Thought: Now let's get the population of Shanghai using the tool 'search'. Action: { "action": "search", "action_input": "Population Shanghai" } Observation: '26 million (2019)' Thought: Now I know that Shanghai has a larger population. Let's return the result. Action: { "action": "final_answer", "action_input": "Shanghai" }<end_action> Above example were using notional tools that might not exist for you. You only have access to those tools: - retriever: Using semantic similarity, retrieves some documents from the knowledge base that have the closest embeddings to the input query. Takes inputs: {'query': {'type': 'text', 'description': 'The query to perform. This should be semantically close to your target documents. Use the affirmative form rather than a question.'}} - final_answer: Provides a final answer to the given problem Takes inputs: {'answer': {'type': 'text', 'description': 'The final answer to the problem'}} Here are the rules you should always follow to solve your task: 1. ALWAYS provide a 'Thought:' sequence, and an 'Action:' sequence that ends with <end_action>, else you will fail. 2. Always use the right arguments for the tools. Never use variable names in the 'action_input' field, use the value instead. 3. Call a tool only when needed: do not call the search agent if you do not need information, try to solve the task yourself. 4. Never re-do a tool call that you previously did with the exact same parameters. Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000. ===== New step ===== ===== Calling LLM with this last message: ===== {'role': <MessageRole.USER: 'user'>, 'content': 'Task: How can I push a model to the Hub?'} ===== Output message of the LLM: ===== Thought: I can use the "retriever" tool to find documents relevant to the question, "How can I push a model to the Hub?" I will then read through the retrieved documents to find the relevant information and provide an answer to the question. Action: ```json { "action": "retriever", "action_input": { "query": "How can I push a model to the Hub?" } } ===== Extracting action ===== Calling tool: 'retriever' with arguments: {'query': 'How can I push a model to the Hub?'} Retrieved documents: ===== Document 0 ===== # Step 7. Push everything to the Hub api.upload_folder( repo_id=repo_id, folder_path=repo_local_path, path_in_repo=".", ) print("Your model is pushed to the Hub. You can view your model here: ", repo_url) ``` ### . By using `push_to_hub` **you evaluate, record a replay, generate a model card of your agent and push it to the Hub**.===== Document 1 ===== ```py >>> trainer.push_to_hub() ``` </pt> <tf> Share a model to the Hub with [`PushToHubCallback`]. In the [`PushToHubCallback`] function, add: - An output directory for your model. - A tokenizer. - The `hub_model_id`, which is your Hub username and model name. ```py >>> from transformers import PushToHubCallback >>> push_to_hub_callback = PushToHubCallback( ... output_dir="./your_model_save_path", tokenizer=tokenizer, hub_model_id="your-username/my-awesome-model" ... ) ```===== Document 2 ===== Let's pretend we've now fine-tuned the model. The next step would be to push it to the Hub! We can do this with the `timm.models.hub.push_to_hf_hub` function. ```py >>> model_cfg = dict(labels=['a', 'b', 'c', 'd']) >>> timm.models.hub.push_to_hf_hub(model, 'resnet18-random', model_config=model_cfg) ``` Running the above would push the model to `<your-username>/resnet18-random` on the Hub. You can now share this model with your friends, or use it in your own code! ## Loading a Model===== Document 3 ===== processor.push_to_hub(hub_model_id) trainer.push_to_hub(**kwargs) ``` # 4. Inference Now comes the exciting part, using our fine-tuned model! In this section, we'll show how you can load your model from the hub and use it for inference.===== Document 4 ===== --push_to_hub ```===== Document 5 ===== . The second way to upload a model, though, is to call model.push_to_hub(). So this is more of a once-off method - it's not called regularly during training. You can just call this manually whenever you want to upload a model to the hub. So we recommend running this after the end of training, just to make sure that you have a commit message just to guarantee that this was the final version of the model at the end of training. And it just makes sure that you're working with the definitive end-of-training model and not accidentally using a model that's from a checkpoint somewhere along the way===== Document 6 ===== Finally, if you want, you can push your model up to the hub. Here, we'll push it up if you specified `push_to_hub=True` in the training configuration. Note that in order to push to hub, you'll have to have git-lfs installed and be logged into your Hugging Face account (which can be done via `huggingface-cli login`). ```python kwargs = { "finetuned_from": model.config._name_or_path, "tasks": "image-classification", "dataset": 'beans', "tags": ['image-classification'], } ===== New step ===== ===== Calling LLM with this last message: ===== {'role': <MessageRole.TOOL_RESPONSE: 'tool-response'>, 'content': 'Observation: Retrieved documents:\n===== Document 0 =====\n# Step 7. Push everything to the Hub\n api.upload_folder(\n repo_id=repo_id,\n folder_path=repo_local_path,\n path_in_repo=".",\n )\n\n print("Your model is pushed to the Hub. You can view your model here: ", repo_url)\n```\n\n### .\n\nBy using `push_to_hub` **you evaluate, record a replay, generate a model card of your agent and push it to the Hub**.===== Document 1 =====\n```py\n>>> trainer.push_to_hub()\n```\n</pt>\n<tf>\nShare a model to the Hub with [`PushToHubCallback`]. In the [`PushToHubCallback`] function, add:\n\n- An output directory for your model.\n- A tokenizer.\n- The `hub_model_id`, which is your Hub username and model name.\n\n```py\n>>> from transformers import PushToHubCallback\n\n>>> push_to_hub_callback = PushToHubCallback(\n... output_dir="./your_model_save_path", tokenizer=tokenizer, hub_model_id="your-username/my-awesome-model"\n... )\n```===== Document 2 =====\nLet\'s pretend we\'ve now fine-tuned the model. The next step would be to push it to the Hub! We can do this with the `timm.models.hub.push_to_hf_hub` function.\n\n```py\n>>> model_cfg = dict(labels=[\'a\', \'b\', \'c\', \'d\'])\n>>> timm.models.hub.push_to_hf_hub(model, \'resnet18-random\', model_config=model_cfg)\n```\n\nRunning the above would push the model to `<your-username>/resnet18-random` on the Hub. You can now share this model with your friends, or use it in your own code!\n\n## Loading a Model===== Document 3 =====\nprocessor.push_to_hub(hub_model_id)\ntrainer.push_to_hub(**kwargs)\n```\n\n# 4. Inference\n\nNow comes the exciting part, using our fine-tuned model! In this section, we\'ll show how you can load your model from the hub and use it for inference.===== Document 4 =====\n--push_to_hub\n```===== Document 5 =====\n. The second way to upload a model, though, is to call model.push_to_hub(). So this is more of a once-off method - it\'s not called regularly during training. You can just call this manually whenever you want to upload a model to the hub. So we recommend running this after the end of training, just to make sure that you have a commit message just to guarantee that this was the final version of the model at the end of training. And it just makes sure that you\'re working with the definitive end-of-training model and not accidentally using a model that\'s from a checkpoint somewhere along the way===== Document 6 =====\nFinally, if you want, you can push your model up to the hub. Here, we\'ll push it up if you specified `push_to_hub=True` in the training configuration. Note that in order to push to hub, you\'ll have to have git-lfs installed and be logged into your Hugging Face account (which can be done via `huggingface-cli login`).\n\n```python\nkwargs = {\n "finetuned_from": model.config._name_or_path,\n "tasks": "image-classification",\n "dataset": \'beans\',\n "tags": [\'image-classification\'],\n}'} ===== Output message of the LLM: ===== Thought: I have found multiple ways to push a model to the Hub. In order to answer comprehensively, I will provide each code snippet that describes how to push a model to the Hub. Action: ```json { "action": "final_answer", "action_input": { "answer": "There are multiple ways to push a model to the Hub. Here are a few examples using different libraries and functions:\n\nUsing the `api`:\n```python\napi.upload_folder(\n repo_id=repo_id,\n folder_path=repo_local_path,\n path_in_repo=\".\",\n)\n\nprint(\"Your model is pushed to the Hub. You can view your model here:\", repo_url)\n```\n\nWith Transformers:\n```python\nfrom transformers import PushToHubCallback\n\n# Initialize the callback with the output directory,\ntokenizer, and your Hub username and model name\npush_to_hub_callback = PushToHubCallback(\n output_dir=\"./your_model_save_path\",\n tokenizer=tokenizer,\n hub_model_id=\"your-username/my-awesome-model\"\n)\n\n# Assuming `trainer` is your Trainer object\ntrainer.add_callback(push_to_hub_callback)\n```\n\nUsing `timm`:\n```python\nfrom timm.models.hub import push_to_hf_hub\n\n# Assuming `model` is your fine-tuned model\nmodel_cfg = {\"labels\": [\"a\", \"b\", \"c\", \"d\"]}\npush_to_hf_hub(model, 'resnet18-random', model_config=model_cfg)\n```\n\nFor computer vision models, you can also use `push_to_hub`:\n```python\nprocessor.push_to_hub(hub_model_id)\ntrainer.push_to_hub(**kwargs)\n```\n\nYou can also manually push a model with `model.push_to_hub()`:\n```python\nmodel.push_to_hub()\n```\n\nAdditionally, you can opt to push your model to the Hub at the end of training by specifying `push_to_hub=True` in the training configuration. Don't forget to have git-lfs installed and be logged into your Hugging Face account." } } ===== Extracting action ===== Calling tool: 'final_answer' with arguments: {'answer': "There are multiple ways to push a model to the Hub. Here are a few examples using different libraries and functions:\n\nUsing the `api`:\npython\napi.upload_folder(\n repo_id=repo_id,\n folder_path=repo_local_path,\n path_in_repo='.',\n)\n\nprint('Your model is pushed to the Hub. You can view your model here:', repo_url)\n\n\nWith Transformers:\npython\nfrom transformers import PushToHubCallback\n\n# Initialize the callback with the output directory,\ntokenizer, and your Hub username and model name\npush_to_hub_callback = PushToHubCallback(\n output_dir='./your_model_save_path',\n tokenizer=tokenizer,\n hub_model_id='your-username/my-awesome-model'\n)\n\n# Assuming `trainer` is your Trainer object\ntrainer.add_callback(push_to_hub_callback)\n\n\nUsing `timm`:\npython\nfrom timm.models.hub import push_to_hf_hub\n\n# Assuming `model` is your fine-tuned model\nmodel_cfg = {'labels': ['a', 'b', 'c', 'd']}\npush_to_hf_hub(model, 'resnet18-random', model_config=model_cfg)\n\n\nFor computer vision models, you can also use `push_to_hub`:\npython\nprocessor.push_to_hub(hub_model_id)\ntrainer.push_to_hub(**kwargs)\n\n\nYou can also manually push a model with `model.push_to_hub()`:\npython\nmodel.push_to_hub()\n\n\nAdditionally, you can opt to push your model to the Hub at the end of training by specifying `push_to_hub=True` in the training configuration. Don't forget to have git-lfs installed and be logged into your Hugging Face account."}
Final output:
There are multiple ways to push a model to the Hub. Here are a few examples using different libraries and functions:
Using the `api`:
python
api.upload_folder(
repo_id=repo_id,
folder_path=repo_local_path,
path_in_repo='.',
)
print('Your model is pushed to the Hub. You can view your model here:', repo_url)
With Transformers:
python
from transformers import PushToHubCallback
# Initialize the callback with the output directory,
tokenizer, and your Hub username and model name
push_to_hub_callback = PushToHubCallback(
output_dir='./your_model_save_path',
tokenizer=tokenizer,
hub_model_id='your-username/my-awesome-model'
)
# Assuming `trainer` is your Trainer object
trainer.add_callback(push_to_hub_callback)
Using `timm`:
python
from timm.models.hub import push_to_hf_hub
# Assuming `model` is your fine-tuned model
model_cfg = {'labels': ['a', 'b', 'c', 'd']}
push_to_hf_hub(model, 'resnet18-random', model_config=model_cfg)
For computer vision models, you can also use `push_to_hub`:
python
processor.push_to_hub(hub_model_id)
trainer.push_to_hub(**kwargs)
You can also manually push a model with `model.push_to_hub()`:
python
model.push_to_hub()
Additionally, you can opt to push your model to the Hub at the end of training by specifying `push_to_hub=True` in the training configuration. Don't forget to have git-lfs installed and be logged into your Hugging Face account.
智能体RAG与标准RAG的比较
智能体 RAG 和标准 RAG,哪个更好?我们用 LLM Judge 来比一比。
我们会用一个非常强的模型 meta-llama/Meta-Llama-3-70B-Instruct 来做这个评估。
在运行测试之前,让我们让智能体输出更简洁一些。
评估提示遵循了我们的 llm_judge cookbook 中展示的一些最佳原则:它遵循一个小的整数李克特量表,有明确的评分标准和每个分数的描述。
100%|██████████| 65/65 [02:24<00:00, 2.23s/it]
Average score for agentic RAG: 78.5%
100%|██████████| 65/65 [02:17<00:00, 2.12s/it]
Average score for standard RAG: 70.0%
让我们回顾一下:与标准的 RAG 相比,智能体设置提高了 8.5% 的得分!(从 70.0% 提高到 78.5%)
这是一个巨大的改进,而且设置非常简单🚀
(作为基准,不使用知识库的 Llama-3-70B 得分为 36%)