Agents 课程文档
构建 Agentic RAG 系统
并获得增强的文档体验
开始使用
构建 Agentic RAG 系统
检索增强生成 (RAG) 系统结合了数据检索和生成模型的功能,以提供上下文感知的响应。例如,用户的查询被传递到搜索引擎,检索到的结果与查询一起提供给模型。然后,模型根据查询和检索到的信息生成响应。
Agentic RAG(检索增强生成)通过将自主 Agent 与动态知识检索相结合,扩展了传统的 RAG 系统。
虽然传统的 RAG 系统使用 LLM 根据检索到的数据回答查询,但 Agentic RAG 实现了对检索和生成过程的智能控制,从而提高了效率和准确性。
传统的 RAG 系统面临关键的局限性,例如依赖于单个检索步骤,并且专注于与用户查询的直接语义相似性,这可能会忽略相关信息。
Agentic RAG 通过允许 Agent 自主制定搜索查询、评判检索结果以及执行多个检索步骤来解决这些问题,从而获得更量身定制和全面的输出。
使用 DuckDuckGo 的基本检索
让我们构建一个简单的 Agent,它可以使用 DuckDuckGo 搜索网络。此 Agent 将检索信息并综合响应以回答查询。借助 Agentic RAG,Alfred 的 Agent 可以
- 搜索最新的超级英雄派对趋势
- 优化结果以包含奢华元素
- 将信息合成为完整的计划
以下是 Alfred 的 Agent 如何实现这一目标
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
# Initialize the search tool
search_tool = DuckDuckGoSearchTool()
# Initialize the model
model = HfApiModel()
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)
Agent 遵循以下流程
- 分析请求:Alfred 的 Agent 识别查询的关键要素——豪华超级英雄主题派对策划,重点关注装饰、娱乐和餐饮。
- 执行检索:Agent 利用 DuckDuckGo 搜索最相关和最新的信息,确保其符合 Alfred 对豪华活动的优化偏好。
- 综合信息:收集结果后,Agent 将它们处理成针对 Alfred 的连贯、可操作的计划,涵盖派对的各个方面。
- 存储以供将来参考:Agent 存储检索到的信息,以便在计划未来活动时轻松访问,从而优化后续任务的效率。
自定义知识库工具
对于专门的任务,自定义知识库可能非常宝贵。让我们创建一个工具,查询技术文档或专门知识的向量数据库。使用语义搜索,Agent 可以找到最符合 Alfred 需求的信息。
向量数据库存储机器学习模型创建的文本或其他数据的数值表示(嵌入)。它通过识别高维空间中相似的含义来实现语义搜索。
这种方法将预定义的知识与语义搜索相结合,为事件策划提供上下文感知的解决方案。通过访问专门知识,Alfred 可以完善派对的每个细节。
在本例中,我们将创建一个工具,从自定义知识库中检索派对策划创意。我们将使用 BM25 检索器搜索知识库并返回最热门的结果,并使用 RecursiveCharacterTextSplitter
将文档拆分为更小的块,以便更有效地搜索。
from langchain.docstore.document import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from smolagents import Tool
from langchain_community.retrievers import BM25Retriever
from smolagents import CodeAgent, HfApiModel
class PartyPlanningRetrieverTool(Tool):
name = "party_planning_retriever"
description = "Uses semantic 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=HfApiModel())
# Example usage
response = agent.run(
"Find ideas for a luxury superhero-themed party, including entertainment, catering, and decoration options."
)
print(response)
这种增强的 Agent 可以
- 首先检查文档以获取相关信息
- 结合来自知识库的见解
- 在内存中维护对话上下文
增强的检索能力
在构建 Agentic RAG 系统时,Agent 可以采用复杂的策略,例如
- 查询重构:Agent 可以创建优化的搜索词,而不是使用原始用户查询,这些搜索词可以更好地匹配目标文档
- 多步骤检索:Agent 可以执行多次搜索,使用初始结果来告知后续查询
- 来源整合:信息可以从多个来源(如网络搜索和本地文档)组合
- 结果验证:可以分析检索到的内容的相关性和准确性,然后再将其包含在响应中
有效的 Agentic RAG 系统需要仔细考虑几个关键方面。Agent 应根据查询类型和上下文在可用工具之间进行选择。内存系统有助于维护对话历史记录并避免重复检索。拥有回退策略可确保即使在主要检索方法失败时,系统仍然可以提供价值。此外,实施验证步骤有助于确保检索信息的准确性和相关性。
资源
- Agentic RAG:通过查询重构和自查询加速您的 RAG!🚀 - 使用 smolagents 开发 Agentic RAG 系统的食谱。