智能体的响应质量完全取决于它的搜索能力。更好的搜索 = 更好的响应
让我们通过一些示例来实际体验一下智能体搜索。
智能体RAG
当我们向智能体添加知识库时,在后台,我们会给模型一个工具来搜索该知识库以获取所需信息。 模型会生成一组关键词并调用search_knowledge_base() 工具来检索相关信息或少量示例。
这是一个使用混合搜索 + 重排的工作示例:
如果不需要重排步骤,可以将其移除。
agentic_rag.py
"""本指南展示了如何使用混合搜索和重排来实现智能体RAG。
1. 运行:`pip install agno anthropic cohere lancedb tantivy sqlalchemy` 来安装依赖项
2. 导出你的 ANTHROPIC_API_KEY 和 CO_API_KEY
3. 运行:`python cookbook/agent_concepts/agentic_search/agentic_rag.py` 来运行智能体
"""
from agno.agent import Agent
from agno.embedder.cohere import CohereEmbedder
from agno.knowledge.url import UrlKnowledge
from agno.models.anthropic import Claude
from agno.reranker.cohere import CohereReranker
from agno.vectordb.lancedb import LanceDb, SearchType
# 创建一个知识库,加载自 URL 的文档
knowledge_base = UrlKnowledge(
urls=["https://docs.agno.com/introduction/agents.md"],
# 使用 LanceDB 作为向量数据库,将嵌入存储在 `agno_docs` 表中
vector_db=LanceDb(
uri="tmp/lancedb",
table_name="agno_docs",
search_type=SearchType.hybrid,
embedder=CohereEmbedder(id="embed-v4.0"),
reranker=CohereReranker(model="rerank-v3.5"),
),
)
agent = Agent(
model=Claude(id="claude-3-7-sonnet-latest"),
# 当向 Agent 提供 `knowledge` 时,智能体RAG默认启用。
# `search_knowledge=True` 使 Agent 能够按需搜索
# `search_knowledge` 默认为 True
search_knowledge=True,
instructions=[
"在响应中包含来源。",
"回答问题前务必搜索你的知识库。",
"只在响应中包含输出。不要包含其他任何文本。",
],
markdown=True,
)
if __name__ == "__main__":
# 加载知识库,首次运行时可注释掉此行
# knowledge_base.load(recreate=True)
agent.print_response("什么是智能体?", stream=True)
带推理的智能体RAG
通过赋予智能体推理搜索结果的能力,我们可以进一步提升其搜索能力。 通过增加推理,智能体首先会“思考”要搜索什么,然后“分析”搜索结果。 这是一个使用推理来提高搜索结果质量的智能体RAG智能体示例。agentic_rag_reasoning.py
"""本指南展示了如何实现带推理的智能体RAG。
1. 运行:`pip install agno anthropic cohere lancedb tantivy sqlalchemy` 来安装依赖项
2. 导出你的 ANTHROPIC_API_KEY 和 CO_API_KEY
3. 运行:`python cookbook/agent_concepts/agentic_search/agentic_rag_with_reasoning.py` 来运行智能体
"""
from agno.agent import Agent
from agno.embedder.cohere import CohereEmbedder
from agno.knowledge.url import UrlKnowledge
from agno.models.anthropic import Claude
from agno.reranker.cohere import CohereReranker
from agno.tools.reasoning import ReasoningTools
from agno.vectordb.lancedb import LanceDb, SearchType
# 创建一个知识库,加载自 URL 的文档
knowledge_base = UrlKnowledge(
urls=["https://docs.agno.com/introduction/agents.md"],
# 使用 LanceDB 作为向量数据库,将嵌入存储在 `agno_docs` 表中
vector_db=LanceDb(
uri="tmp/lancedb",
table_name="agno_docs",
search_type=SearchType.hybrid,
embedder=CohereEmbedder(id="embed-v4.0"),
reranker=CohereReranker(model="rerank-v3.5"),
),
)
agent = Agent(
model=Claude(id="claude-3-7-sonnet-latest"),
# 当向 Agent 提供 `knowledge` 时,智能体RAG默认启用。
# `search_knowledge=True` 使 Agent 能够按需搜索
# `search_knowledge` 默认为 True
search_knowledge=True,
tools=[ReasoningTools(add_instructions=True)],
instructions=[
"在响应中包含来源。",
"回答问题前务必搜索你的知识库。",
"只在响应中包含输出。不要包含其他任何文本。",
],
markdown=True,
)
if __name__ == "__main__":
# 加载知识库,首次运行时可注释掉此行
# knowledge_base.load(recreate=True)
agent.print_response(
"什么是智能体?",
stream=True,
show_full_reasoning=True,
stream_intermediate_steps=True,
)