[!TIP] 您可以按照代码进行操作。 这个笔记本 您可以使用 Google Colab来运行它。
检索增强生成(RAG)系统结合了数据检索和生成模型的能力,以提供具有上下文意识的响应。例如,用户的查询被传递给搜索引擎,检索到的结果与查询一起传递给模型。模型然后根据查询和检索到的信息生成响应。
智能体式RAG(检索增强生成)通过以下方式扩展了传统的RAG系统: 将智能体与动态知识检索相结合.
传统 RAG 系统使用大型语言模型来根据检索到的数据回答查询,而智能体 RAG 实现对检索和生成过程的智能控制提高效率和准确性。
传统的 RAG 系统存在关键限制,例如 仅依赖一次检索步骤 并专注于与用户查询的直接语义相似性,这可能会忽略相关信息。
智能体RAG通过让智能体自主制定搜索查询、对检索到的结果进行评论,以及进行多次检索步骤,从而解决这些问题,以获得更定制化和全面的输出结果。
使用 DuckDuckGo 进行基础检索
让我们构建一个简单的智能体,它能够使用DuckDuckGo在网页上进行搜索。这个智能体将检索信息并合成回应来回答查询。借助Agentic RAG,Alfred的智能体可以:
- 搜索最新的超级英雄派对趋势
- 优化结果以包含奢侈品元素
- 将信息整合成一个完整的计划
以下是阿尔弗雷德的智能体实现这一功能的方式:
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel
# Initialize the search tool
search_tool = DuckDuckGoSearchTool()
# Initialize the model
model = InferenceClientModel()
agent = CodeAgent(
model=model,
tools=[search_tool],
)
# Example usage
response = agent.run(
"Search for luxury superhero-themed party ideas, including decorations, entertainment, and catering."
)
print(response)
智能体遵循以下流程:
- 分析请求: 阿尔弗雷德的智能体识别了查询的关键要素——以奢侈超级英雄为主题的派对策划,重点在于装饰、娱乐和餐饮方面。
- 执行检索: 该智能体利用 DuckDuckGo 来搜索最相关且最新的信息,确保这些信息与 Alfred 对奢华活动的精细偏好相符。
- 信息综合: 在收集到结果后,智能体将其处理成一份针对阿尔弗雷德的、涵盖活动所有方面的、连贯且可行的计划。
- 供未来参考的存储: 智能体存储检索到的信息,以便在规划未来事件时方便访问,从而在后续任务中优化效率。
自定义知识库工具
对于专业任务,自定义知识库非常有价值。让我们创建一个工具,用于查询包含派对策划方案的自定义知识库。通过使用BM25的词汇搜索,智能体可以找到与阿尔弗雷德的需求最相关的信息。
向量数据库存储由机器学习模型生成的文本或其他数据的数值表示(嵌入)。它可以通过在高维空间中识别相似的语义来实现语义搜索。然而,在示例中,我们将使用BM25进行词汇检索,而不是基于嵌入的向量搜索。
这种方法将预定义的知识与词汇检索相结合,为活动策划提供相关信息。通过专门的知识访问功能,Alfred能够完美处理活动的每一个细节。
在这个示例中,我们将创建一个工具,该工具从自定义知识库中提取派对策划的灵感。我们将使用 BM25 检索器来搜索知识库并返回最顶级的查询结果。 RecursiveCharacterTextSplitter 将文档分割成更小的块,以实现更高效的搜索。
from langchain_community.docstore.document import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
from smolagents import Tool
from langchain_community.retrievers import BM25Retriever
from smolagents import CodeAgent, InferenceClientModel
class PartyPlanningRetrieverTool(Tool):
name = "party_planning_retriever"
description = "Uses BM25 lexical search to retrieve relevant party planning ideas for Alfred’s superhero-themed party at Wayne Manor."
inputs = {
"query": {
"type": "string",
"description": "The query to perform. This should be a query related to party planning or superhero themes.",
}
}
output_type = "string"
def __init__(self, docs, **kwargs):
super().__init__(**kwargs)
self.retriever = BM25Retriever.from_documents(
docs, k=5 # Retrieve the top 5 documents
)
def forward(self, query: str) -> str:
assert isinstance(query, str), "Your search query must be a string"
docs = self.retriever.invoke(
query,
)
return "\nRetrieved ideas:\n" + "".join(
[
f"\n\n===== Idea {str(i)} =====\n" + doc.page_content
for i, doc in enumerate(docs)
]
)
# Simulate a knowledge base about party planning
party_ideas = [
{"text": "A superhero-themed masquerade ball with luxury decor, including gold accents and velvet curtains.", "source": "Party Ideas 1"},
{"text": "Hire a professional DJ who can play themed music for superheroes like Batman and Wonder Woman.", "source": "Entertainment Ideas"},
{"text": "For catering, serve dishes named after superheroes, like 'The Hulk's Green Smoothie' and 'Iron Man's Power Steak.'", "source": "Catering Ideas"},
{"text": "Decorate with iconic superhero logos and projections of Gotham and other superhero cities around the venue.", "source": "Decoration Ideas"},
{"text": "Interactive experiences with VR where guests can engage in superhero simulations or compete in themed games.", "source": "Entertainment Ideas"}
]
source_docs = [
Document(page_content=doc["text"], metadata={"source": doc["source"]})
for doc in party_ideas
]
# Split the documents into smaller chunks for more efficient search
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=500,
chunk_overlap=50,
add_start_index=True,
strip_whitespace=True,
separators=["\n\n", "\n", ".", " ", ""],
)
docs_processed = text_splitter.split_documents(source_docs)
# Create the retriever tool
party_planning_retriever = PartyPlanningRetrieverTool(docs_processed)
# Initialize the agent
agent = CodeAgent(tools=[party_planning_retriever], model=InferenceClientModel())
# Example usage
response = agent.run(
"Find ideas for a luxury superhero-themed party, including entertainment, catering, and decoration options."
)
print(response)
这个增强型智能体可以:
- 首先查看文档以获取相关信息。
- 结合知识库的见解
- 在内存中保留对话上下文
增强的检索能力
在构建智能体式RAG系统时,智能体可以采用诸如以下复杂的策略:
- 查询重构: 智能体可以使用优化的搜索词来替代原始的用户查询,从而更好地匹配目标文档。
- 查询分解: 直接使用用户查询的方式并不合适,如果查询中包含多条信息,可以将其分解为多个查询。
- 查询扩展: 与Query Reformulation类似,但通过多次尝试用不同的措辞来表达查询,以全面查询各种可能性。
- 重新排序: 使用交叉编码器为检索到的文档和搜索查询分配更全面和语义相关的评分
- 多步检索: 智能体可以执行多次搜索,利用初步的结果来指导后续的查询。
- 源集成: 信息可以从多个来源整合而来,比如网络搜索和本地文档。
- 结果验证: 在将获取的内容包含在回复之前,可以对其相关性和准确性进行分析。
有效的智能体RAG系统需要仔细考虑几个关键方面。智能体 需要根据查询类型和上下文在可用的工具之间进行选择。记忆系统有助于保存对话历史记录,避免重复检索。设置备用策略可以确保即使主要检索方法出现故障时,系统仍能提供价值。此外,实施验证步骤有助于确保检索到的信息的准确性和相关性。
资源
- 智能体式RAG:通过查询重构和自查询来加速你的RAG处理!🚀 使用 smolagents 开发智能体 RAG 系统的配方。