TextKnowledgeBase 读取 本地 txt 文件,将其转换为向量嵌入并加载到向量数据库中。
本示例使用本地 PgVector 数据库。确保其运行
from agno.knowledge.text import TextKnowledgeBase
from agno.vectordb.pgvector import PgVector
knowledge_base = TextKnowledgeBase(
path="data/txt_files",
# 表名: ai.text_documents
vector_db=PgVector(
table_name="text_documents",
db_url="postgresql+psycopg://ai:ai@localhost:5532/ai",
),
)
然后将 knowledge_base
与 Agent 一起使用:
from agno.agent import Agent
from knowledge_base import knowledge_base
agent = Agent(
knowledge_base=knowledge_base,
search_knowledge=True,
)
agent.knowledge.load(recreate=False)
agent.print_response("Ask me about something from the knowledge base")
TextKnowledgeBase 也支持异步加载。
pip install qdrant-client
本示例使用本地 Qdrant 数据库。确保其运行
import asyncio
from pathlib import Path
from agno.agent import Agent
from agno.knowledge.text import TextKnowledgeBase
from agno.vectordb.qdrant import Qdrant
COLLECTION_NAME = "essay-txt"
vector_db = Qdrant(collection=COLLECTION_NAME, url="http://localhost:6333")
# 初始化 TextKnowledgeBase
knowledge_base = TextKnowledgeBase(
path=Path("tmp/docs"),
vector_db=vector_db,
num_documents=5,
)
# 使用 knowledge_base 初始化 Assistant
agent = Agent(
knowledge=knowledge_base,
search_knowledge=True,
)
if __name__ == "__main__":
# 首次运行时注释掉此行
asyncio.run(knowledge_base.aload(recreate=False))
asyncio.run(
agent.aprint_response(
"What knowledge is available in my knowledge base?", markdown=True
)
)
参数 | 类型 | 默认值 | 描述 |
---|
path | Union[str, Path] | - | 文本文件路径。可以指向单个文本文件或目录。 |
formats | List[str] | [".txt"] | 此知识库接受的格式。 |
reader | TextReader | TextReader() | 用于将文本文件转换为向量数据库 Documents 的 TextReader 。 |
TextKnowledgeBase
是 AgentKnowledge 类的子类,可以访问相同的参数。
开发资源
Responses are generated using AI and may contain mistakes.