为代理添加RAG(检索增强生成)
为了演示如何在代理中使用RAG引擎作为工具,我们将创建一个非常简单的RAG查询引擎。我们的源数据将是维基百科上关于2023年加拿大联邦预算的页面,我们将其打印为PDF。
引入新的依赖
为了读取PDF并对其进行索引,我们需要一些新的依赖项。它们已经与LlamaIndex的其他部分一起安装,所以我们只需要导入它们:
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, Settings
将LLM添加到设置中
我们之前直接传递了LLM,但现在我们需要在多个地方使用它,因此我们将它添加到全局设置中。
Settings.llm = OpenAI(model="gpt-3.5-turbo", temperature=0)
将此行放在文件的顶部;你可以删除其他llm赋值。
加载和索引文档
我们现在将快速连续地做三件事:从名为“data”的文件夹中加载PDF,使用VectorStoreIndex对其进行索引和嵌入,然后从该索引创建一个查询引擎:
documents = SimpleDirectoryReader("./data").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()
我们可以运行一个快速的烟雾测试,以确保引擎正常工作:
response = query_engine.query(
"What was the total amount of the 2023 Canadian federal budget?"
)
print(response)
响应速度很快:
The total amount of the 2023 Canadian federal budget was $496.9 billion.
添加查询引擎工具
这需要再导入一个模块:
from llama_index.core.tools import QueryEngineTool
现在我们将查询引擎转换为工具,通过提供适当的元数据(对于Python函数,这是自动提取的,所以我们不需要添加它):
budget_tool = QueryEngineTool.from_defaults(
query_engine,
name="canadian_budget_2023",
description="A RAG engine with some basic facts about the 2023 Canadian federal budget.",
)
我们通过将这个引擎添加到我们的工具数组中来修改我们的代理(我们还删除了llm参数,因为它现在由设置提供):
agent = ReActAgent.from_tools(
[multiply_tool, add_tool, budget_tool], verbose=True
)
使用多个工具提问
这是一个有点愚蠢的问题,我们稍后会问一些更有用的问题:
response = agent.chat(
"What is the total amount of the 2023 Canadian federal budget multiplied by 3? Go step by step, using a tool to do any math."
)
print(response)
我们得到了一个完美的答案:
Thought: The current language of the user is English. I need to use the tools to help me answer the question.
Action: canadian_budget_2023
Action Input: {'input': 'total'}
Observation: $496.9 billion
Thought: I need to multiply the total amount of the 2023 Canadian federal budget by 3.
Action: multiply
Action Input: {'a': 496.9, 'b': 3}
Observation: 1490.6999999999998
Thought: I can answer without using any more tools. I'll use the user's language to answer
Answer: The total amount of the 2023 Canadian federal budget multiplied by 3 is $1,490.70 billion.
The total amount of the 2023 Canadian federal budget multiplied by 3 is $1,490.70 billion.
像往常一样,你可以查看仓库以查看所有代码。
太棒了!你的代理现在可以使用任何任意高级的查询引擎来帮助回答问题。你还可以根据需要添加任意数量的不同RAG引擎,以查询不同的数据源。接下来,我们将看看如何使用LlamaParse回答更高级的问题。