Notebooks
H
Hugging Face
Multiagent Rag System

Multiagent Rag System

zh-CNhf-cookbooknotebooks

多智能体 RAG 系统 🤖🤝🤖

作者: Sergio Paniego

🚨 注意:本教程较为高级。在开始之前,你应该对以下教程中讨论的概念有充分的理解:

在本 Notebook 中,我们将创建一个 多智能体 RAG 系统,这是一个多个智能体协作检索和生成信息的系统,结合了 基于检索的系统生成模型 的优势。

什么是多智能体 RAG 系统? 🤔

多智能体检索增强生成 (RAG) 系统由多个智能体组成,这些智能体协作执行复杂的任务。检索智能体负责检索相关的文档或信息,而生成智能体则将这些信息综合起来生成有意义的输出。系统中还会有一个管理智能体,它负责协调各个智能体,并根据用户输入选择最合适的智能体来完成任务。

这个教程的原始概念来源于 这篇文章。你可以在那里找到更多细节。

以下是我们将要构建的系统架构。

multiagent_rag_system.png

1. 安装依赖

首先,让我们安装依赖:

[ ]
[ ]

让我们登录来调用 HF 推理 API

[ ]

2. 创建我们的多智能体 RAG 系统

在本节中,我们将创建我们的 RAG 系统中所涉及的每个智能体。

我们将拥有 3 个由中央智能体管理的智能体(请参见图片了解详细信息):

  • 🕵💬 网络搜索智能体:它将包含 DuckDuckGoSearchTool 工具和 VisitWebpageTool 工具。正如您所看到的,每个智能体可以包含一组工具。
  • 🕵💬 检索智能体:它将包含两个工具,用于从两个不同的知识库中检索信息。
  • 🕵💬 图像生成智能体:它将包含一个提示生成工具,并附带图像生成工具。

💡 除了这些智能体,中央/协调智能体 还将访问 代码解释器工具 以执行代码。

我们将使用 Qwen/Qwen2.5-72B-Instruct 作为每个组件的语言模型(LLM),该模型将通过推理 API 进行访问。根据智能体的不同,可能会使用不同的 LLM 模型。

注意: 推理 API 托管的模型根据不同的标准进行选择,已部署的模型可能会在没有通知的情况下更新或替换。了解更多信息,请访问 此链接

[ ]

让我们深入了解每个智能体的详细信息!

2.1 网络搜索智能体 🔍

网络搜索智能体将使用 DuckDuckGoSearchTool 来进行网页搜索并收集相关信息。这个工具充当搜索引擎,根据指定的关键词进行查询。

为了使搜索结果可操作,我们还需要让智能体能够访问 DuckDuckGo 检索到的网页。这可以通过使用内置的 VisitWebpageTool 来实现。

让我们探索如何设置并将其集成到我们的系统中!

以下代码来自原始的 让多个智能体在多智能体层级中协作 🤖🤝🤖 示例,因此可以参考该教程了解更多细节。

2.1.1 构建我们的多工具网络智能体 🤖

现在我们已经设置了基本的搜索和网页工具,接下来让我们构建一个 多工具网络智能体。这个智能体将结合多个工具,执行更复杂的任务,并利用 ReactJsonAgent 的能力。

ReactJsonAgent 特别适合用于网络搜索任务,因为它的 JSON 动作形式只需要简单的参数,并且能够在单一动作的顺序链中无缝工作。这使得它成为搜索相关信息并从特定网页检索详细内容的理想选择。相比之下,CodeAgent 的动作形式更适合涉及多个或并行工具调用的场景。

通过集成多个工具,我们可以确保我们的智能体以更加复杂和高效的方式与网络进行交互。

让我们深入了解如何设置这个智能体,并将其集成到我们的系统中!

[5]

现在我们已经创建了第一个智能体,接下来让我们将其包装为一个 ManagedAgent,这样中央智能体就可以使用它了。

[6]

2.2 检索智能体 🤖🔍

我们的多智能体系统中的第二个智能体是 检索智能体。该智能体负责从不同来源收集相关信息。为了实现这一目标,它将利用两个工具,从两个独立的知识库中检索数据。

我们将重用在其他 RAG 示例中使用过的两个数据源,这将使检索器能够高效地收集信息,以供后续处理。

通过利用这些工具,检索智能体可以访问多样化的数据集,确保在将信息传递给系统的下一步之前,能够全面收集到相关的信息。

让我们探索如何设置检索器,并将其集成到我们的多智能体系统中!

2.2.1 HF 文档检索工具 📚

第一个检索工具来自于 Agentic RAG: 使用查询重构和自我查询加速你的 RAG 🚀 示例。

对于这个检索器,我们将使用一个包含各种 huggingface 包文档页面的数据库,所有文档都存储为 Markdown 文件。这个数据集将作为检索智能体的知识库,用于搜索和检索相关的文档。

为了使我们的智能体能够轻松访问这个数据集,我们将执行以下步骤:

  1. 下载数据集:我们首先获取 Markdown 格式的文档。
  2. 嵌入数据:然后我们将使用 FAISS 向量存储 将文档转换为嵌入,以便高效地进行相似度搜索。

通过这种方式,检索工具可以根据搜索查询快速访问相关的文档片段,使智能体能够提供准确和详细的信息。

让我们继续设置这个工具,处理文档检索!

[ ]
[ ]

现在我们已经将文档嵌入到 FAISS 向量存储中,让我们创建 RetrieverTool。这个工具将查询 FAISS 向量存储,以根据用户的查询检索最相关的文档。

这将使检索智能体能够在收到查询时,访问并提供相关的文档内容。

[9]
[10]

2.2.2 PEFT 问题检索工具

对于第二个检索器,我们将使用 PEFT 问题 作为数据源,正如在 使用 Hugging Face Zephyr 和 LangChain 的简单 RAG 架构处理 GitHub 问题 中所示。

同样,以下代码来自该示例,因此可以参考该教程了解更多细节!

[11]
[12]
[13]
[14]

现在,让我们使用相同的 RetrieverTool 来生成第二个检索工具。

[15]

2.2.3 构建检索智能体

现在我们已经创建了两个检索工具,接下来是时候构建 检索智能体 了。这个智能体将管理这两个工具,并根据用户的查询检索相关信息。

我们将使用 ManagedAgent 来集成这两个工具,并将该智能体传递给中央智能体进行协调。这样,中央智能体就能够控制和调度检索智能体,从而确保系统在执行任务时能够有效地检索并提供信息。

[16]
[17]

2.3 图像生成智能体 🎨

系统中的第三个智能体是 图像生成智能体。该智能体将有两个工具:一个用于优化用户查询,另一个用于根据查询生成图像。在这种情况下,我们将使用 CodeAgent 而不是 ReactAgent,因为一组动作可以一次性执行。

关于图像生成智能体的更多细节,你可以参考 Agents, supercharged - Multi-agents, External tools, and more 文档。

让我们深入了解这些工具如何协同工作,根据用户输入生成图像!

[ ]
[ ]

🖼 同样,我们使用 ManagedAgent 来告诉中央智能体它可以管理该智能体。此外,我们还包含了一个 additional_prompting 参数,以确保智能体返回生成的图像,而不仅仅是文本描述。

[52]

3. 添加中央智能体管理器来协调系统

中央智能体管理器将负责协调各个智能体之间的任务。具体来说,它将:

  • 接收用户输入并决定由哪个智能体(网络搜索、检索、图像生成)来处理。
  • 委派任务给合适的智能体,依据用户的查询类型。
  • 收集并综合来自各个智能体的结果。
  • 将最终输出返回给用户。

我们将所有已经开发的智能体作为 managed_agents 添加进来,并在 additional_authorized_imports 中加入必要的代码执行器导入。这样,中央智能体管理器不仅能协调任务,还能确保系统能够根据不同的需求动态选择合适的智能体并执行复杂的操作。

[53]

现在,一切都已设置完毕,让我们测试多智能体 RAG 系统的性能!

为此,我们将提供一些示例查询,观察系统如何在智能体之间委派任务、处理信息并返回最终结果。

这将帮助我们了解智能体协作的效率和有效性,并在必要时识别出优化的方向。

让我们开始运行一些测试吧!

3.1 示例:触发搜索智能体

[22]
======== New task ========
How many years ago was Stripe founded?
=== Agent thoughts:
Thought: To solve this problem, I need to find out the year Stripe was founded and then calculate the difference between the current year and the year of founding.
>>> Agent is executing the code below:
founding_year = search("When was Stripe founded?")
print(founding_year)
====
======== New task ========
You're a helpful agent named 'search'.
You have been submitted this task by your manager.
---
Task:
When was Stripe founded?
---
You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible so that they have a clear understanding of the answer.

Your final_answer WILL HAVE to contain these parts:
### 1. Task outcome (short version):
### 2. Task outcome (extremely detailed version):
### 3. Additional context (if relevant):

Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.
=== Agent thoughts:
Thought: I will start by performing a web search to find when Stripe was founded and gather detailed information about the company's founding.
>>> Calling tool: 'web_search' with arguments: {'query': 'When was Stripe founded'}
=== Agent thoughts:
Thought: I found several sources indicating when Stripe was founded and additional information about the company’s founding. I’ll gather the relevant details to provide a comprehensive answer.
>>> Calling tool: 'final_answer' with arguments: {'answer': "### 1. Task outcome (short version):\nStripe was founded in 2010 by brothers John and Patrick Collison.\n\n### 2. Task outcome (extremely detailed version):\nStripe, Inc. is an Irish-American multinational financial services and software as a service (SaaS) company. It was founded in 2010 by Irish entrepreneur brothers John and Patrick Collison in Palo Alto, California. The Collison brothers started working on Stripe while they were still in high school and college, aiming to create a payment platform that would give developers the tools they needed to create secure and novel buying experiences. Patrick Collison serves as the company's CEO, while John Collison is the president.\n\n### 3. Additional context (if relevant):\nThe Collison brothers moved to the USA from a rural village in Ireland at a young age to pursue their entrepreneurial dreams. They identified a gap in the market for a payment platform that would make it easy for small businesses to accept payments from anywhere in the world. Stripe debuted in 2010 and grew exponentially due to its user-friendly front-end and robust back-end infrastructure. Today, more than $1 trillion in payments pass through Stripe's software on behalf of customers, and the company has achieved a valuation of nearly $100 billion."}
Print outputs:
### 1. Task outcome (short version):
Stripe was founded in 2010 by brothers John and Patrick Collison.

### 2. Task outcome (extremely detailed version):
Stripe, Inc. is an Irish-American multinational financial services and software as a service (SaaS) company. It was founded in 2010 by Irish entrepreneur brothers John and Patrick Collison in Palo Alto, California. The Collison brothers started working on Stripe while they were still in high school and college, aiming to create a payment platform that would give developers the tools they needed to create secure and novel buying experiences. Patrick Collison serves as the company's CEO, while John Collison is the president.

### 3. Additional context (if relevant):
The Collison brothers moved to the USA from a rural village in Ireland at a young age to pursue their entrepreneurial dreams. They identified a gap in the market for a payment platform that would make it easy for small businesses to accept payments from anywhere in the world. Stripe debuted in 2010 and grew exponentially due to its user-friendly front-end and robust back-end infrastructure. Today, more than $1 trillion in payments pass through Stripe's software on behalf of customers, and the company has achieved a valuation of nearly $100 billion.

=== Agent thoughts:
Thought: I can see that Stripe was founded in 2010. Now, I will calculate the difference between the current year and the founding year to find out how many years ago Stripe was founded.
>>> Agent is executing the code below:
import datetime

founding_year = 2010  # From the search result
current_year = datetime.datetime.now().year

years_since_founded = current_year - founding_year
final_answer(years_since_founded)
====
Print outputs:

Last output from code snippet:
14
Final answer:
14
14

3.2 示例:触发图像生成智能体

[54]
======== New task ========
Improve this prompt, then generate an image of it.
You have been provided with these initial arguments: {'prompt': 'A rabbit wearing a space suit'}.
=== Agent thoughts:
Thought: I will first improve the prompt to make it more detailed and then use the `image_generation` tool to generate an image based on the improved prompt. I will store the improved prompt in a variable and print it for the next step.
>>> Agent is executing the code below:
improved_prompt = "A rabbit wearing a space suit, jumping in a zero-gravity environment, surrounded by stars and planets."
print(improved_prompt)
====
Print outputs:
A rabbit wearing a space suit, jumping in a zero-gravity environment, surrounded by stars and planets.

=== Agent thoughts:
Thought: Now that I have the improved prompt, I will use the `image_generation` tool to generate the image.
>>> Agent is executing the code below:
image_generation(improved_prompt)
====
======== New task ========
You're a helpful agent named 'image_generation'.
You have been submitted this task by your manager.
---
Task:
A rabbit wearing a space suit, jumping in a zero-gravity environment, surrounded by stars and planets.
---
You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible so that they have a clear understanding of the answer.

Your final_answer WILL HAVE to contain these parts:
### 1. Task outcome (short version):
### 2. Task outcome (extremely detailed version):
### 3. Additional context (if relevant):

Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.

Your final answer MUST BE only the generated image location.
=== Agent thoughts:
Thought: I will use the `image_generator` tool to generate an image based on the description provided in the task. I will include additional details to make the image more visually appealing and descriptive.
>>> Agent is executing the code below:
prompt = "A rabbit wearing a space suit, jumping in a zero-gravity environment, surrounded by stars and planets, high-res, photorealistic, vibrant colors, detailed textures, and a sense of movement."
image = image_generator(prompt=prompt)
final_answer(image)
====
Print outputs:

Last output from code snippet:
/tmp/tmpvvp0x99l/f589dffc-4741-4589-8d45-ce1ef3f126c1.png
=== Agent thoughts:
Thought: The image has been generated successfully. I will use the `final_answer` tool to provide the final answer to the task.
>>> Agent is executing the code below:
final_answer('/tmp/tmpvvp0x99l/f589dffc-4741-4589-8d45-ce1ef3f126c1.png')
====
Print outputs:

Last output from code snippet:
/tmp/tmpvvp0x99l/f589dffc-4741-4589-8d45-ce1ef3f126c1.png
Final answer:
/tmp/tmpvvp0x99l/f589dffc-4741-4589-8d45-ce1ef3f126c1.png
[56]
Output

3.3 示例:触发检索智能体以访问 Hugging Face 文档知识库

[ ]
======== New task ========
How can I push a model to the Hub?
=== Agent thoughts:
Thought: To provide instructions on how to push a model to the Hugging Face Hub, it would be most effective to retrieve official documentation or a guide that gives detailed steps. I'll use the `retriever` tool to find relevant information in the Hugging Face documentation or the PEFT issues section.
>>> Agent is executing the code below:
retriever(query="How to push a model to the Hugging Face Hub")
====
Code execution failed due to the following error:
ManagedAgent.__call__() missing 1 required positional argument: 'request'
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/agents.py", line 1135, in step
    result = self.python_evaluator(
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/python_interpreter.py", line 902, in evaluate_python_code
    result = evaluate_ast(node, state, static_tools, custom_tools, authorized_imports)
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/python_interpreter.py", line 782, in evaluate_ast
    return evaluate_ast(expression.value, state, static_tools, custom_tools)
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/python_interpreter.py", line 746, in evaluate_ast
    return evaluate_call(expression, state, static_tools, custom_tools)
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/python_interpreter.py", line 439, in evaluate_call
    output = func(*args, **kwargs)
TypeError: ManagedAgent.__call__() missing 1 required positional argument: 'request'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/agents.py", line 811, in direct_run
    step_logs = self.step()
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/agents.py", line 1154, in step
    raise AgentExecutionError(error_msg)
transformers.agents.agents.AgentExecutionError: Code execution failed due to the following error:
ManagedAgent.__call__() missing 1 required positional argument: 'request'
=== Agent thoughts:
Thought: It appears that I encountered an error because I did not include the request parameter when calling the `retriever` tool. To correct this, I will provide a detailed request as an argument to the `retriever` tool. I will request the retrieval of documents or guides that explain the process of pushing a model to the Hugging Face Hub.
>>> Agent is executing the code below:
retriever(request="Please retrieve documentation or a guide on how to push a model to the Hugging Face Hub.")
====
======== New task ========
You're a helpful agent named 'retriever'.
You have been submitted this task by your manager.
---
Task:
Please retrieve documentation or a guide on how to push a model to the Hugging Face Hub.
---
You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible so that they have a clear understanding of the answer.

Your final_answer WILL HAVE to contain these parts:
### 1. Task outcome (short version):
### 2. Task outcome (extremely detailed version):
### 3. Additional context (if relevant):

Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.
=== Agent thoughts:
Thought: To complete this task, I need to retrieve relevant documentation or guides on how to push a model to the Hugging Face Hub. I'll use the `retriever` tool to find the most relevant documents.
>>> Calling tool: 'retriever' with arguments: {'query': 'How to push a model to the Hugging Face Hub'}
=== Agent thoughts:
Thought: The retrieved documents provide useful information about pushing a model to the Hugging Face Hub. I will summarize the information and provide a detailed answer.
>>> Calling tool: 'final_answer' with arguments: {'answer': "### 1. Task outcome (short version):\n\nThe process of pushing a model to the Hugging Face Hub involves several steps, including preparing your model, installing necessary dependencies, and using the `huggingface_hub` library to upload the model.\n\n### 2. Task outcome (extremely detailed version):\n\n1. **Prepare Your Model**: Ensure your model is trained and saved in a format compatible with the Hugging Face Transformers library. This typically involves saving the model and tokenizer using the `save_pretrained` method.\n\n2. **Install Dependencies**: Install the `huggingface_hub` library if you haven't already. You can do this using pip:\n\n   bash\n   pip install huggingface_hub\n   \n\n3. **Login to Hugging Face**: You need to be logged in to your Hugging Face account. Use the `huggingface-cli` to log in:\n\n   bash\n   huggingface-cli login\n   \n\n   This will prompt you to enter your Hugging Face API token, which you can find in your account settings on the Hugging Face website.\n\n4. **Create a Repository**: Create a new repository on the Hugging Face Hub using the `create_repo` command. Replace `<model_name>` with the name you want for your model:\n\n   bash\n   huggingface-cli repo create <model_name> --organization <your_organization> --private\n   \n\n   If you are creating a personal model, you can omit the `--organization` flag.\n\n5. **Upload the Model**: Use the `push_to_hub` method to upload your model to the Hugging Face Hub. This method is available in the `transformers` library and can be used as follows:\n\n   python\n   from transformers import AutoModel, AutoTokenizer\n\n   model = AutoModel.from_pretrained('path/to/your/model')\n   tokenizer = AutoTokenizer.from_pretrained('path/to/your/tokenizer')\n\n   model.push_to_hub('<model_name>')\n   tokenizer.push_to_hub('<model_name>')\n   \n\n6. **Verify the Upload**: Once the model is uploaded, you can verify it by navigating to your Hugging Face profile or the specified organization's page and checking if the model is listed.\n\n### 3. Additional context (if relevant):\n\n- **Error Handling**: If you encounter errors during the upload process, ensure that your API token is correct and that you have the necessary permissions. Additionally, check that your model and tokenizer are saved correctly.\n- **Private vs. Public Models**: You can choose to make your model private by using the `--private` flag when creating the repository. Private models are only accessible to you and any collaborators you specify.\n- **Using Docker**: If you are working in a Docker environment, you may need to mount your model directory and set environment variables for the Hugging Face API token. An example of this is provided in one of the retrieved documents.\n- **Fine-tuning and Adapters**: If you are working with fine-tuned models or adapters, ensure that you merge the adapter with the base model before pushing it to the Hub. This can be done using the `PeftModel` class from the `peft` library.\n- **Dependencies and Requirements**: Ensure that your model's dependencies are included in a `requirements.txt` file. This is especially important if you are using custom layers or components in your model."}
Print outputs:

Last output from code snippet:
### 1. Task outcome (short version):

The process of pushing a model to the Hugging Face Hub involves several steps, including preparing your model, installing necessary dependencies, and using the `huggingface_hub` library to upload the model.

### 2. Task outcome (extremely detailed version):

1. **Prepare Your Model**: Ensure your model is trained and saved in a format compatible with the Hugging Face Transformers library. This typically involves saving the model and tokenizer using the `save_pretrained` method.

2. **Install Dependencies**: Install the `huggingface_hub` library if you haven't already. You can do this using pip:

   bash
   pip install huggingface_hub
   

3. **Login to Hugging Face**: You need to be logged in to your Hugging Face account. Use the `huggingface-cli` to log in:

   bash
   huggingface-cli login
   

   This will prompt you to enter your Hugging Face API token, which you can find in your account settings on the Hugging Face website.

4. **Create a Repository**: Create a new repository on the Hugging Face Hub using the `create_repo` command. Replace `<model_name>` with the name you want for your model:

   bash
   huggingface-cli repo create <model_name> --organization <your_organization> --private
   

   If you are creating a personal model, you can omit the `--organization` flag.

5. **Upload the Model**: Use the `push_to_hub` method to upload your model to the Hugging Face Hub. This method is available in the `transformers` library and can be used as follows:

   python
   from transformers import AutoModel, AutoTokenizer

   model = AutoModel.from_pretrained('path/to/your/model')
   tokenizer = AutoTokenizer.from_pretrained('path/to/your/tokenizer')

   model.push_to_hub('<model_name>')
   tokenizer.push_to_hub('<model_name>')
   

6. **Verify the Upload**: Once the model is uploaded, you can verify it by navigating to your Hugging Face profile or the specified organization's page and checking if the model is listed.

### 3. Additional context (if relevant):

- **Error Handling**: If you encounter errors during the upload process, ensure that your API token is correct and that you have the necessary permissions. Additionally, check that your model and tokenizer are saved correctly.
- **Private vs. Public Models**: You can choose to make your model private by using the `--private` flag when creating the repository. Private models are only accessible to you and any collaborators you specify.
- **Using Docker**: If you are working in a Docker environment, you may need to mount your model directory and set environment variables for the Hugging Face API token. An example of this is provided in one of the retrieved documents.
- **Fine-tuning and Adapters**: If you are working with fine-tuned models or adapters, ensure that you merge the adapter with the base model before pushing it to the Hub. This can be done using the `PeftModel` class from the `peft` library.
- **Dependencies and Requirements**: Ensure that your model's dependencies are included in a `requirements.txt` file. This is especially important if you are using custom layers or components in your model.
=== Agent thoughts:
Thought: The information provided in the retrieval output is comprehensive and detailed. I will format this information into a clear, step-by-step guide and use the `final_answer` tool to provide the final answer to the task.
>>> Agent is executing the code below:
steps = """
1. **Prepare Your Model**: Ensure your model is trained and saved in a format compatible with the Hugging Face Transformers library. This typically involves saving the model and tokenizer using the `save_pretrained` method.

2. **Install Dependencies**: Install the `huggingface_hub` library if you haven't already. You can do this using pip:
   ```bash
   pip install huggingface_hub
   ```

3. **Login to Hugging Face**: You need to be logged in to your Hugging Face account. Use the `huggingface-cli` to log in:
   ```bash
   huggingface-cli login
   ```
   This will prompt you to enter your Hugging Face API token, which you can find in your account settings on the Hugging Face website.

4. **Create a Repository**: Create a new repository on the Hugging Face Hub using the `create_repo` command. Replace `<model_name>` with the name you want for your model:
   ```bash
   huggingface-cli repo create <model_name> --organization <your_organization> --private
   ```
   If you are creating a personal model, you can omit the `--organization` flag.

5. **Upload the Model**: Use the `push_to_hub` method to upload your model to the Hugging Face Hub. This method is available in the `transformers` library and can be used as follows:
   ```python
   from transformers import AutoModel, AutoTokenizer

   model = AutoModel.from_pretrained('path/to/your/model')
   tokenizer = AutoTokenizer.from_pretrained('path/to/your/tokenizer')

   model.push_to_hub('<model_name>')
   tokenizer.push_to_hub('<model_name>')
   ```

6. **Verify the Upload**: Once the model is uploaded, you can verify it by navigating to your Hugging Face profile or the specified organization's page and checking if the model is listed.
"""

final_answer(steps)
====
Print outputs:

Last output from code snippet:

1. **Prepare Your Model**: Ensure your model is trained and saved in a format compatible with the Hugging Face Transformers library. This typically involves saving the model and tokenizer using the `save_pretrained` method.

2. **Install Dependencies**: Install the `huggingface_hub` library if you haven't already. You can do this using pip:
   ```bash
   pip install huggingface_hub
   ```

3. **Login to Hugging Face**: You need to be logged in to your Hugging Face account. Use the `huggingface-cli` to log in:
   ```bash
   huggingface-cli login
   ```
   This will prompt you to enter your Hugging Face API token, which you can find in your account settings on the Hugging Face website.

4. **Create a Repository**: Create a new repository on the Hugging Face Hub using the `create_repo` command. Replace `<model_name>` with the name you want for your model:
   ```bash
   huggingface-cli repo create <model_name> --organization <your_organization> --private
   ```
   If you are creating a personal model, you can omit the `--organization` flag.

5. **Upload the Model**: Use the `push_to_hub` method to upload your model to the Hugging Face Hub. This method is available in the `transformers` library and can be used as follows:
   ```python
   from transformers import AutoModel, AutoTokenizer

   model = AutoModel.from_pretrained('path/to/your/model')
   tokenizer = AutoTokenizer.from_pretrained('path/to/your/tokenizer')

   model.push_to_hub('<model_name>')
   tokenizer.push_to_hub('<model_name>')
   ```

6. **Verify the Upload**: Once the model is uploaded, you can verify it by navigating to your Hugging Face profile or the specified organization's page and checking if the model is listed.

Final answer:

1. **Prepare Your Model**: Ensure your model is trained and saved in a format compatible with the Hugging Face Transformers library. This typically involves saving the model and tokenizer using the `save_pretrained` method.

2. **Install Dependencies**: Install the `huggingface_hub` library if you haven't already. You can do this using pip:
   ```bash
   pip install huggingface_hub
   ```

3. **Login to Hugging Face**: You need to be logged in to your Hugging Face account. Use the `huggingface-cli` to log in:
   ```bash
   huggingface-cli login
   ```
   This will prompt you to enter your Hugging Face API token, which you can find in your account settings on the Hugging Face website.

4. **Create a Repository**: Create a new repository on the Hugging Face Hub using the `create_repo` command. Replace `<model_name>` with the name you want for your model:
   ```bash
   huggingface-cli repo create <model_name> --organization <your_organization> --private
   ```
   If you are creating a personal model, you can omit the `--organization` flag.

5. **Upload the Model**: Use the `push_to_hub` method to upload your model to the Hugging Face Hub. This method is available in the `transformers` library and can be used as follows:
   ```python
   from transformers import AutoModel, AutoTokenizer

   model = AutoModel.from_pretrained('path/to/your/model')
   tokenizer = AutoTokenizer.from_pretrained('path/to/your/tokenizer')

   model.push_to_hub('<model_name>')
   tokenizer.push_to_hub('<model_name>')
   ```

6. **Verify the Upload**: Once the model is uploaded, you can verify it by navigating to your Hugging Face profile or the specified organization's page and checking if the model is listed.

"\n1. **Prepare Your Model**: Ensure your model is trained and saved in a format compatible with the Hugging Face Transformers library. This typically involves saving the model and tokenizer using the `save_pretrained` method.\n\n2. **Install Dependencies**: Install the `huggingface_hub` library if you haven't already. You can do this using pip:\n   ```bash\n   pip install huggingface_hub\n   ```\n\n3. **Login to Hugging Face**: You need to be logged in to your Hugging Face account. Use the `huggingface-cli` to log in:\n   ```bash\n   huggingface-cli login\n   ```\n   This will prompt you to enter your Hugging Face API token, which you can find in your account settings on the Hugging Face website.\n\n4. **Create a Repository**: Create a new repository on the Hugging Face Hub using the `create_repo` command. Replace `<model_name>` with the name you want for your model:\n   ```bash\n   huggingface-cli repo create <model_name> --organization <your_organization> --private\n   ```\n   If you are creating a personal model, you can omit the `--organization` flag.\n\n5. **Upload the Model**: Use the `push_to_hub` method to upload your model to the Hugging Face Hub. This method is available in the `transformers` library and can be used as follows:\n   ```python\n   from transformers import AutoModel, AutoTokenizer\n\n   model = AutoModel.from_pretrained('path/to/your/model')\n   tokenizer = AutoTokenizer.from_pretrained('path/to/your/tokenizer')\n\n   model.push_to_hub('<model_name>')\n   tokenizer.push_to_hub('<model_name>')\n   ```\n\n6. **Verify the Upload**: Once the model is uploaded, you can verify it by navigating to your Hugging Face profile or the specified organization's page and checking if the model is listed.\n"

3.4 示例:触发检索智能体以访问 PEFT 问题知识库

[ ]
======== New task ========
How do you combine multiple adapters in peft?
=== Agent thoughts:
Thought: To combine multiple adapters in PEFT, I need to understand the mechanism for doing so. I will use the `retriever` tool to search for relevant information in the PEFT documentation or issues.
>>> Agent is executing the code below:
retriever(query="combine multiple adapters in peft")
====
Code execution failed due to the following error:
ManagedAgent.__call__() missing 1 required positional argument: 'request'
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/agents.py", line 1135, in step
    result = self.python_evaluator(
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/python_interpreter.py", line 902, in evaluate_python_code
    result = evaluate_ast(node, state, static_tools, custom_tools, authorized_imports)
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/python_interpreter.py", line 782, in evaluate_ast
    return evaluate_ast(expression.value, state, static_tools, custom_tools)
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/python_interpreter.py", line 746, in evaluate_ast
    return evaluate_call(expression, state, static_tools, custom_tools)
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/python_interpreter.py", line 439, in evaluate_call
    output = func(*args, **kwargs)
TypeError: ManagedAgent.__call__() missing 1 required positional argument: 'request'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/agents.py", line 811, in direct_run
    step_logs = self.step()
  File "/usr/local/lib/python3.10/dist-packages/transformers/agents/agents.py", line 1154, in step
    raise AgentExecutionError(error_msg)
transformers.agents.agents.AgentExecutionError: Code execution failed due to the following error:
ManagedAgent.__call__() missing 1 required positional argument: 'request'
=== Agent thoughts:
Thought: I need to provide a request to the `retriever` tool. Let's retry with the correct usage.
>>> Agent is executing the code below:
retriever(request="combine multiple adapters in peft")
====
======== New task ========
You're a helpful agent named 'retriever'.
You have been submitted this task by your manager.
---
Task:
combine multiple adapters in peft
---
You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible so that they have a clear understanding of the answer.

Your final_answer WILL HAVE to contain these parts:
### 1. Task outcome (short version):
### 2. Task outcome (extremely detailed version):
### 3. Additional context (if relevant):

Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.
=== Agent thoughts:
Thought: I will first use the retriever tool to find relevant documents that might provide information about combining multiple adapters in PEFT (Parameter-Efficient Fine-Tuning).
>>> Calling tool: 'retriever' with arguments: {'query': 'combine multiple adapters in peft'}
=== Agent thoughts:
Thought: I have retrieved documents that provide information about combining multiple adapters in PEFT. I will now summarize the key points and provide a detailed explanation.
>>> Calling tool: 'final_answer' with arguments: {'answer': '### 1. Task outcome (short version):\nCombining multiple adapters in PEFT is possible but has some limitations. Currently, PEFT allows loading and inferring only adapters of the same type, such as LoRA or IA3. To combine multiple adapters, you can use the `add_weighted_adapter` function to add and merge adapters, but this functionality may not be fully implemented for adapter heads.\n\n### 2. Task outcome (extremely detailed version):\nCombining multiple adapters in PEFT is a crucial feature for parameter-efficient fine-tuning (PEFT) of large language models. Here are the details:\n\n1. **Adapter Types**: PEFT supports different adapter types, such as LoRA (Low-Rank Adaptation) and IA3 (Inducing Attention with Adapter). Each adapter type has its own benefits, such as reduced memory footprint and customizable model tuning.\n\n2. **Current Limitations**:\n   - **Single Adapter Type**: Currently, PEFT allows loading and inferring only adapters of the same type. For example, you cannot load both LoRA and LoHa adapters and switch between them during inference. This means if you need to use multiple adapter types, you must unload all adapters of the first type before loading adapters of another type.\n\n3. **Combining Adapters**:\n   - **`add_weighted_adapter` Function**: To combine multiple adapters of the same type, you can use the `add_weighted_adapter` function. This function allows you to add and merge adapters with weighted contributions. However, the merging of adapter heads, which are the output layers of the adapters, is not fully implemented in the `add_weighted_adapter` function.\n\n4. **Expected Behavior**:\n   - **Merging Adapter Heads**: When merging multiple adapters using `add_weighted_adapter`, it is expected that the corresponding adapter heads should also be merged. However, the current implementation may not handle this merging, and you might need to ensure that the adapter heads are kept in sync manually.\n\n### 3. Additional context (if relevant):\n- **Documentation and References**:\n  - [PEFT Documentation](https://huggingface.co/docs/transformers/main/peft)\n  - [LoraModel.merge_and_unload](https://huggingface.co/docs/peft/package_reference/tuners#peft.LoraModel.merge_and_unload)\n  - [LoraModel.add_weighted_adapter](https://github.com/huggingface/peft/blob/main/src/peft/tuners/lora/model.py#L520)\n\n- **GitHub Discussions**: There are ongoing discussions and potential solutions for this issue, such as keeping the adapter configurations in sync manually or implementing more robust merging functionality.'}
Print outputs:

Last output from code snippet:
### 1. Task outcome (short version):
Combining multiple adapters in PEFT is possible but has some limitations. Currently, PEFT allows loading and inferring only adapters of the same type, such as LoRA or IA3. To combine multiple adapters, you can use the `add_weighted_adapter` function to add and merge adapters, but this functionality may not be fully implemented for adapter heads.

### 2. Task outcome (extremely detailed version):
Combining multiple adapters in PEFT is a crucial feature for parameter-efficient fine-tuning (PEFT) of large language models. Here are the details:

1. **Adapter Types**: PEFT supports different adapter types, such as LoRA (Low-Rank Adaptation) and IA3 (Inducing Attention with Adapter). Each adapter type has its own benefits, such as reduced memory footprint and customizable model tuning.

2. **Current Limitations**:
   - **Single Adapter Type**: Currently, PEFT allows loading and inferring only adapters of the same type. For example, you cannot load both LoRA and LoHa adapters and switch between them during inference. This means if you need to use multiple adapter types, you must unload all adapters of the first type before loading adapters of another type.

3. **Combining Adapters**:
   - **`add_weighted_adapter` Function**: To combine multiple adapters of the same type, you can use the `add_weighted_adapter` function. This function allows you to add and merge adapters with weighted contributions. However, the merging of adapter heads, which are the output layers of the adapters, is not fully implemented in the `add_weighted_adapter` function.

4. **Expected Behavior**:
   - **Merging Adapter Heads**: When merging multiple adapters using `add_weighted_adapter`, it is expected that the corresponding adapter heads should also be merged. However, the current implementation may not handle this merging, and you might need to ensure that the adapter heads are kept in sync manually.

### 3. Additional context (if relevant):
- **Documentation and References**:
  - [PEFT Documentation](https://huggingface.co/docs/transformers/main/peft)
  - [LoraModel.merge_and_unload](https://huggingface.co/docs/peft/package_reference/tuners#peft.LoraModel.merge_and_unload)
  - [LoraModel.add_weighted_adapter](https://github.com/huggingface/peft/blob/main/src/peft/tuners/lora/model.py#L520)

- **GitHub Discussions**: There are ongoing discussions and potential solutions for this issue, such as keeping the adapter configurations in sync manually or implementing more robust merging functionality.
=== Agent thoughts:
Thought: From the retrieved information, combining multiple adapters in PEFT is possible but has some limitations. I will summarize the key points and provide a high-level explanation of how to combine multiple adapters using the `add_weighted_adapter` function.
>>> Agent is executing the code below:
# Summary of combining multiple adapters in PEFT
summary = """
Combining multiple adapters in PEFT is possible but has some limitations:
1. Only adapters of the same type (e.g., LoRA, IA3) can be loaded and inferred together.
2. Use the `add_weighted_adapter` function to add and merge adapters.
3. Merging adapter heads is not fully implemented and may require manual handling.

To combine multiple adapters:
1. Ensure all adapters are of the same type.
2. Use the `add_weighted_adapter` function to merge adapters with weighted contributions.
3. Manually handle the merging of adapter heads if necessary.
"""

print(summary)
====
Print outputs:

Combining multiple adapters in PEFT is possible but has some limitations:
1. Only adapters of the same type (e.g., LoRA, IA3) can be loaded and inferred together.
2. Use the `add_weighted_adapter` function to add and merge adapters.
3. Merging adapter heads is not fully implemented and may require manual handling.

To combine multiple adapters:
1. Ensure all adapters are of the same type.
2. Use the `add_weighted_adapter` function to merge adapters with weighted contributions.
3. Manually handle the merging of adapter heads if necessary.


=== Agent thoughts:
Thought: I have summarized the key points on how to combine multiple adapters in PEFT. Now, I will return this summary as the final answer.
>>> Agent is executing the code below:
final_answer(summary)
====
Print outputs:

Last output from code snippet:

Combining multiple adapters in PEFT is possible but has some limitations:
1. Only adapters of the same type (e.g., LoRA, IA3) can be loaded and inferred together.
2. Use the `add_weighted_adapter` function to add and merge adapters.
3. Merging adapter heads is not fully implemented and may require manual handling.

To combine multiple adapters:
1. Ensure all adapters are of the same type.
2. Use the `add_weighted_adapter` function to merge adapters with weighted contributions.
3. Manually handle the merging of adapter heads if necessary.

Final answer:

Combining multiple adapters in PEFT is possible but has some limitations:
1. Only adapters of the same type (e.g., LoRA, IA3) can be loaded and inferred together.
2. Use the `add_weighted_adapter` function to add and merge adapters.
3. Merging adapter heads is not fully implemented and may require manual handling.

To combine multiple adapters:
1. Ensure all adapters are of the same type.
2. Use the `add_weighted_adapter` function to merge adapters with weighted contributions.
3. Manually handle the merging of adapter heads if necessary.

'\nCombining multiple adapters in PEFT is possible but has some limitations:\n1. Only adapters of the same type (e.g., LoRA, IA3) can be loaded and inferred together.\n2. Use the `add_weighted_adapter` function to add and merge adapters.\n3. Merging adapter heads is not fully implemented and may require manual handling.\n\nTo combine multiple adapters:\n1. Ensure all adapters are of the same type.\n2. Use the `add_weighted_adapter` function to merge adapters with weighted contributions.\n3. Manually handle the merging of adapter heads if necessary.\n'

🏁 最终思考

我们已经成功构建了一个多智能体 RAG 系统,该系统集成了网络搜索、文档检索和图像生成智能体,所有智能体都由中央智能体管理器协调。这个架构使得任务能够无缝分配,处理效率高,并且能够灵活地处理各种用户查询。

🔍 深入探索

感谢你跟随我们完成这一旅程!希望这个系统能为你带来更多灵感,帮助你构建更智能、更高效的应用。