设置

docker run -d \
  -e POSTGRES_DB=ai \
  -e POSTGRES_USER=ai \
  -e POSTGRES_PASSWORD=ai \
  -e PGDATA=/var/lib/postgresql/data/pgdata \
  -v pgvolume:/var/lib/postgresql/data \
  -p 5532:5432 \
  --name pgvector \
  agnohq/pgvector:16

示例

agent_with_knowledge.py
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.knowledge.pdf_url import PDFUrlKnowledgeBase
from agno.vectordb.pgvector import PgVector, SearchType

db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
knowledge_base = PDFUrlKnowledgeBase(
    urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"],
    vector_db=PgVector(table_name="recipes", db_url=db_url, search_type=SearchType.hybrid),
)
# 加载知识库:首次运行后注释掉此行
knowledge_base.load(recreate=True, upsert=True)

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    knowledge=knowledge_base,
    # 添加一个读取聊天记录的工具。
    read_chat_history=True,
    show_tool_calls=True,
    markdown=True,
    # debug_mode=True,
)
agent.print_response("How do I make chicken and galangal in coconut milk soup", stream=True)
agent.print_response("What was my last question?", stream=True)

异步支持 ⚡

PgVector 还支持异步操作,能够实现并发,从而带来更好的性能。

async_pgvector.py
import asyncio

from agno.agent import Agent
from agno.knowledge.pdf_url import PDFUrlKnowledgeBase
from agno.vectordb.pgvector import PgVector

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

vector_db = PgVector(table_name="recipes", db_url=db_url)

knowledge_base = PDFUrlKnowledgeBase(
    urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"],
    vector_db=vector_db,
)

agent = Agent(knowledge=knowledge_base, show_tool_calls=True)

if __name__ == "__main__":
    # 首次运行后注释掉此行
    asyncio.run(knowledge_base.aload(recreate=False))

    # 创建并使用代理
    asyncio.run(agent.aprint_response("How to make Tom Kha Gai", markdown=True))

在处理高吞吐量应用程序时,请使用 aload()aprint_response() 方法与 asyncio.run() 一起使用,以实现非阻塞操作。

PgVector 参数

ParameterTypeDefault说明
table_namestr-要使用的表的名称。
schemastr-要使用的模式。
db_urlstr-要连接的数据库 URL。
db_engineEngine-要使用的数据库引擎。
embedderEmbedder-要使用的嵌入器。
search_typeSearchTypevector要使用的搜索类型。
vector_indexUnion[Ivfflat, HNSW]-要使用的向量索引。
distanceDistancecosine要使用的距离。
prefix_matchbool-是否使用前缀匹配。
vector_score_weightfloat0.5混合搜索中向量相似度的权重。必须在 0 到 1 之间。
content_languagestr-要使用的内容语言。
schema_versionint-要使用的模式版本。
auto_upgrade_schemabool-是否自动升级模式。

开发者资源