Agno 知识库进阶模式实战:自定义检索、分块、Graph RAG、KnowledgeTools 与多用户隔离

原创2026-09-09 19:38:471,997 阅读
文章标签:人工智能AI AgentAgent 框架多智能体Agent 工作流工具调用RAGAI 评测后端MCP 服务可观测性

Agno 知识库进阶模式实战:自定义检索、分块、Graph RAG、KnowledgeTools 与多用户隔离

导读

本指南以 cookbook/07_knowledge/04_advanced/README.md 为核心骨架,系统讲解 Agno 面向高阶用户与自定义集成的知识(Knowledge)进阶能力:绕过 Knowledge 类实现自定义检索器、编写自定义分块策略、接入 LightRAG 知识图谱、使用 KnowledgeTools 的 think/search/analyze 工具集、实现自定义 KnowledgeProtocol、利用 PgVector 前缀匹配打造边输入边搜索(search-as-you-type),以及跨 17 种向量后端的按用户 RAG 隔离。读完本文,你将掌握在不改动 Agno 框架源码的前提下,把任意数据源接入 Agent 知识体系并深度定制检索逻辑的完整方案。

前置条件与环境准备

原文档要求先完成以下环境准备,本文结合仓库实际内容做补充说明:

  1. 启动 Qdrant 向量数据库:./cookbook/scripts/run_qdrant.sh
  2. 启动 PgVector(用于前缀搜索示例):./cookbook/scripts/run_pgvector.sh
  3. 设置 OPENAI_API_KEY 环境变量:示例中的 embedder(如 text-embedding-3-small)与模型(如 OpenAIResponses(id="gpt-5.2"))均依赖 OpenAI 接口
  4. Graph RAG 额外依赖:pip install lightrag-agno
  5. 按用户隔离示例:参见 07_per_user_isolation/ 子目录,其中对每个向量后端还有各自的运行前提(详见下文)

运行方式统一为:

.venvs/demo/bin/python cookbook/07_knowledge/04_advanced/01_custom_retriever.py

各示例文件均可直接替换文件名执行,且大多在 __main__ 中通过 asyncio.run() 完成知识插入与 Agent 交互,天然支持重复运行。

自定义检索器:绕过 Knowledge 类的完全控制

当标准向量检索无法满足需求时,示例 01_custom_retriever.py 展示了如何直接注入一个自定义检索函数,完全绕开 Knowledge 类。

适用场景

  • 非向量检索:SQL 查询、API 调用、文件系统查找
  • 自定义排序逻辑
  • 以自定义逻辑组合多个数据源

函数签名与实现要点

检索函数必须遵循如下签名(与 libs/agno/agno/agent/agent.py 中 knowledge_retriever 参数的类型注解一致):

def company_retriever(
    agent: Agent, query: str, num_documents: Optional[int] = None, **kwargs
) -> Optional[List[Union[Dict, str]]]:

关键约束:返回值必须是 dict(或字符串)列表,而非 Document 对象。示例内部用简单的关键词匹配模拟企业知识库(engineering/sales/hr 三个部门文档),并对 num_documents 做截断:

matched = results or list(documents.values())
if num_documents is not None:
    matched = matched[:num_documents]
return matched

注入 Agent

通过 Agent 的 knowledge_retriever 参数注入,并可与流式输出配合:

agent = Agent(
    model=OpenAIResponses(id="gpt-5.2"),
    knowledge_retriever=company_retriever,
    markdown=True,
)

agent.print_response("What is the PTO policy?", stream=True)
agent.print_response("How did Q4 sales go?", stream=True)

两个不同查询会命中不同文档,直观演示"同一 Agent、不同检索结果"的效果。对照标准实现可参考 01_getting_started/02_agentic_rag.py(基于 Knowledge 的标准 Agentic RAG)。

自定义分块策略:实现自己的 ChunkingStrategy

内置分块策略无法适配领域内容时(如法律条款、医疗记录、含自定义分隔符的结构化数据),示例 02_custom_chunking.py 给出范式:分块策略是一个接收 Document、返回 Document 分块列表的类。

实现 ParagraphChunking

from agno.knowledge.chunking.strategy import ChunkingStrategy
from agno.knowledge.document import Document

class ParagraphChunking(ChunkingStrategy):
    """Splits documents on double newlines (paragraphs)."""

    def chunk(self, document: Document) -> list[Document]:
        chunks = []
        if not document.content:
            return chunks
        paragraphs = document.content.split("\n\n")
        for i, paragraph in enumerate(paragraphs):
            paragraph = paragraph.strip()
            if paragraph:
                chunks.append(
                    Document(
                        name="%s_chunk_%d" % (document.name, i),
                        content=paragraph,
                        meta_data={
                            **(document.meta_data or {}),
                            "chunk_index": i,
                            "chunking_strategy": "paragraph",
                        },
                    )
                )
        return chunks

实现要点:空内容直接返回空列表;以 \n\n 双换行切分段落;跳过空白段;子文档继承父文档 meta_data 并追加 chunk_index 与 chunking_strategy 标记,便于溯源。

与 Reader、Knowledge、Agent 组合

qdrant_url = "http://localhost:6333"

knowledge = Knowledge(
    vector_db=Qdrant(
        collection="custom_chunking",
        url=qdrant_url,
        search_type=SearchType.hybrid,
        embedder=OpenAIEmbedder(id="text-embedding-3-small"),
    ),
)

reader = PDFReader(chunking_strategy=ParagraphChunking())

agent = Agent(
    model=OpenAIResponses(id="gpt-5.2"),
    knowledge=knowledge,
    search_knowledge=True,
    markdown=True,
)

写入时把自定义 reader 传给 knowledge.ainsert(url=..., reader=reader);本例从公开的泰国菜谱 PDF 构建知识库,随后询问"What Thai recipes do you know about?"。内置策略的完整清单可对照 02_building_blocks/01_chunking_strategies.py。

Graph RAG:LightRAG 知识图谱集成

示例 03_graph_rag.py 演示将 LightRAG 作为托管知识后端接入 Agno。LightRAG 自行完成文档摄取与检索,与标准向量 RAG 的关键差异在于:

  • 从文档中抽取实体与关系
  • 构建支持多跳推理的知识图谱
  • 支持图谱遍历式查询

用法上只需把 Knowledge.vector_db 换成 LightRag,并指向 LightRAG 服务:

from agno.vectordb.lightrag import LightRag

knowledge = Knowledge(
    vector_db=LightRag(
        server_url="http://localhost:9621",
    ),
)

agent = Agent(
    model=OpenAIResponses(id="gpt-5.2"),
    knowledge=knowledge,
    search_knowledge=True,
    markdown=True,
)

脚本对 ImportError 做了防御(未安装 lightrag-agno 时置空并提示安装),演示查询是跨食谱寻找共享食材——这正是图谱多跳推理的典型问题。前置依赖:pip install lightrag-agno,并自行启动 LightRAG 服务(默认端口 9621)。

KnowledgeTools:think + search + analyze 组合工具

基础 search_knowledge 只提供单一检索工具;04_knowledge_tools.py 引入的 KnowledgeTools 提供更丰富的知识交互工具集:

  • think:Agent 在检索前先对查询进行推理
  • search:标准知识库检索
  • analyze:对检索结果进行深度分析
from agno.tools.knowledge import KnowledgeTools

knowledge = Knowledge(
    vector_db=Qdrant(
        collection="knowledge_tools_demo",
        url=qdrant_url,
        search_type=SearchType.hybrid,
        embedder=OpenAIEmbedder(id="text-embedding-3-small"),
    ),
)

knowledge_tools = KnowledgeTools(
    knowledge=knowledge,
    enable_think=True,
    enable_search=True,
    enable_analyze=True,
    add_few_shot=True,
)

agent = Agent(
    model=OpenAIChat(id="gpt-5.6-luna"),
    tools=[knowledge_tools],
    markdown=True,
)

enable_* 三个开关分别控制 think/search/analyze 工具是否暴露给 Agent,add_few_shot=True 则给工具注入 few-shot 示例引导模型正确使用。示例向知识库写入 Agno 官方文档全文(https://docs.agno.com/llms-full.txt),再让 Agent 回答"如何在 Agno 中构建多 Agent 团队"——需要 think 拆解、search 检索、analyze 归纳三步协作,可观察工具链的完整调用过程。

KnowledgeProtocol:自定义知识源接口

当知识来自非标准数据源(文件系统、API、数据库),或检索逻辑不适合向量库模型、需要对接既有检索系统时,可以实现 libs/agno/agno/knowledge/protocol.py 中定义的 KnowledgeProtocol(@runtime_checkable 结构化协议,具备类型安全性)。

必需与可选方法

按协议源码注释与示例 05_knowledge_protocol.py:

方法 必需/可选 职责
build_context(**kwargs) -> str 必需 返回注入 Agent 系统提示词的指令文本,说明如何用该知识源
get_tools(**kwargs) -> List[Callable] 必需 返回暴露给 Agent 的可调用工具(实现方自定,不强制叫 search)
aget_tools(**kwargs) -> List[Callable] 必需 上述方法的异步版本
retrieve(query, **kwargs) -> List[Document] 可选 供 search_knowledge / 上下文注入特性使用,未实现则跳过
aretrieve(query, **kwargs) -> List[Document] 可选 异步版本

最小实现示例

class InMemoryKnowledge(KnowledgeProtocol):
    def __init__(self):
        self.documents: list[Document] = []

    def add(self, name: str, content: str) -> None:
        self.documents.append(Document(name=name, content=content))

    def build_context(self, **kwargs) -> str:
        return "Use the search tool to find information in the knowledge base."

    def get_tools(self, **kwargs) -> List[Callable]:
        return []

    async def aget_tools(self, **kwargs) -> List[Callable]:
        return []

    # Optional: enables search_knowledge feature
    def retrieve(self, query: str, **kwargs) -> List[Document]:
        max_results = kwargs.get("max_results", 5)
        return self._search(query, limit=max_results)

    async def aretrieve(self, query: str, **kwargs) -> List[Document]:
        return self.retrieve(query, **kwargs)

使用方式与内置 Knowledge 完全一致:Agent(knowledge=custom_knowledge, search_knowledge=True),search_knowledge=True 会触发 retrieve 将检索结果注入上下文。协议源码还给出了官方推荐形态:get_tools() 返回真实检索函数(如 search_docs),从而让 Agent 主动调用工具,而非被动注入上下文。

PgVector 前缀匹配:实现"边输入边搜索"的帮助中心

示例 06_prefix_search.py 展示真实业务场景:用户输入部分单词时立刻返回候选文章。例如输入 auth,立即看到 authentication、authorization、authenticator app 等文章。

关键开关 prefix_match

db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"

# 开启前缀匹配,支持 search-as-you-type
help_center = PgVector(
    table_name="help_center_articles",
    db_url=db_url,
    search_type=SearchType.hybrid,
    prefix_match=True,  # enables search-as-you-type
    embedder=OpenAIEmbedder(id="text-embedding-3-small"),
)

# 同一张表,关闭前缀匹配做对照
help_center_standard = PgVector(
    table_name="help_center_articles",
    db_url=db_url,
    search_type=SearchType.hybrid,
    prefix_match=False,  # default - exact word match only
    embedder=OpenAIEmbedder(id="text-embedding-3-small"),
)

prefix_match=False(默认)要求完整单词才能命中;prefix_match=True 时部分前缀即可匹配,从而支撑打字过程中的即时提示(typeahead)。注意该能力依赖 PgVector 后端(前置:./cookbook/scripts/run_pgvector.sh,连接串端口 5532)。

演示:模拟逐步输入

写入帮助文章(认证、授权、API 密钥、账单等 5 篇),然后对 ["au", "auth", "authent"] 三个渐进查询分别用两种配置检索并对比相似度分数:

help_center.create()
help_center.upsert(documents=help_articles, content_hash="v1")

for query in ["au", "auth", "authent"]:
    results = help_center_standard.search(query, limit=2)  # 无前缀匹配
    results = help_center.search(query, limit=2)           # 前缀匹配
    score = doc.meta_data.get("similarity_score", 0)

content_hash="v1" 用于内容去重/版本管理;相似度分数从 doc.meta_data["similarity_score"] 读取。该模式可无缝迁移到各类站内搜索、文档系统与客服知识库。

多用户 RAG 隔离:一套知识库,每个用户私有视图

目录 07_per_user_isolation/ 是进阶模式的压轴主题:一个知识库,为每个用户提供私有视图。核心机制是 Knowledge.asearch(user_id=...) 将检索范围限定为"调用者自己的分块 + 共享分块";user_id=None 时不做作用域限制,即管理员视图。

场景脚本统一为:Alice、Bob 各上传一份私有文档,第三份无属主的上传因此成为共享文档;随后通过 Agent(user_id="alice") 重复该场景,并断言 RunOutput.references 中的文档。值得注意的设计:user_id 被丢弃后会退化为 None(管理员视图),因此损坏的交接不会抛错,而是返回所有人的分块——这正是示例用断言而非异常来校验的原因。

前置条件差异

  • LanceDB、Chroma、Qdrant 内嵌运行,无需额外启动
  • 服务型后端需运行对应脚本:run_pgvector.sh、run_weaviate.sh、run_opensearch.sh、run_redis.sh、run_valkey.sh、run_clickhouse.sh、run_cassandra.sh、run_couchbase.sh、run_surrealdb.sh、run_singlestore.sh(位于 cookbook/scripts/)
  • Milvus 需独立服务:bash standalone_embed.sh start(Milvus Lite 在读取路径上丢弃标量字段);MongoDB 需 Atlas Local 容器:docker run -d -p 27017:27017 mongodb/mongodb-atlas-local:latest(普通 MongoDB 无 $vectorSearch)
  • 云后端:Pinecone 需 PINECONE_API_KEY;Upstash 需 UPSTASH_VECTOR_REST_URL 与 UPSTASH_VECTOR_REST_TOKEN(1536 维索引);SingleStore、Couchbase 需各自凭据环境变量
  • Redis 与 Valkey 均绑定 6379 端口,同时只能运行其一;各示例启动时自行删除本集合,可安全重复运行

各后端的隔离原语

文件 隔离实现原语
pgvector_db.py 可空 user_id 列,WHERE user_id = X OR user_id IS NULL
lance_db.py user_id 列,.where("user_id = X OR user_id IS NULL", prefilter=True)
chroma_db.py 每用户一个集合({base}__{user_id}),基础集合为共享桶
qdrant_db.py 索引 user_id payload 字段,should 匹配 + is-empty
milvus_db.py user_id 标量字段,__shared__ 哨兵值标记无主分块
mongo_db.py 顶层 user_id 字段,$vectorSearch 前 $match {$in: [X, null]}
weaviate_db.py user_id 文本属性,where OR is_none
opensearch_db.py user_id keyword 字段,term OR must_not exists
redis_db.py user_id TAG 字段,__shared__ 哨兵标签
valkey_db.py 同 Redis:TAG 字段 + __shared__ 哨兵
clickhouse_db.py 非空 String 列,"" 哨兵标记共享
cassandra_db.py user_id 元数据,__shared__ 哨兵
couchbase_db.py Keyword 索引的 FTS user_id 字段,__shared__ 哨兵
singlestore_db.py 可空 user_id 列,WHERE user_id = X OR user_id IS NULL
surreal_db.py user_id 字段,专用 $scope_user_id 绑定
pinecone_db.py 向量元数据中的 user_id,$or [{$eq: X}, {$exists: false}]
upstash_db.py 元数据 user_id,user_id = X OR HAS NOT FIELD user_id

该目录是"同一套隔离语义、17 种后端实现"的最佳学习范本——对比各文件即可看出不同数据库在过滤语法、空值语义上的差异。运行示例:

.venvs/demo/bin/python cookbook/07_knowledge/04_advanced/07_per_user_isolation/pgvector_db.py

运行与验证

  • 全部示例按 README 约定用 .venvs/demo 虚拟环境执行;隔离示例逐个运行(多个后端共享默认端口)
  • 隔离示例每次启动会删除自身集合,重复运行安全
  • 自定义检索器示例无需任何向量库,只依赖 OpenAI API,可作为最快上手验证

小结

从"绕过 Knowledge 类"到"自定义分块""图谱 RAG""工具化知识交互""协议化知识源""前缀检索"再到"跨 17 后端的按用户隔离",Agno 的知识体系在 07_knowledge 这一目录中形成了从入门(01_getting_started)、构建模块(02_building_blocks)、生产化(03_production)到高级模式(04_advanced)的完整进阶路径。上述 6 个独立示例加上 17 个隔离示例均可直接复制运行,是理解 Agno 知识机制与向量后端差异的最快捷径。

登录后查看全文
agno