PgVector Vector Database

Use PgVector as a vector database for your Knowledge Base.

The example uses OpenAI-backed embeddings or models. Set your key before running it:

export OPENAI_API_KEY="your-api-key"

Setup

uv pip install -U sqlalchemy psycopg pgvector pypdf openai agno

Run PgVector with Docker:

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

Example

Session storage uses the same PostgreSQL server through PostgresDb. The two requests reuse the Agent session, so the history tool can retrieve the earlier question.

agent_with_knowledge.py
from agno.agent import Agent
from agno.db.postgres import PostgresDb
from agno.models.openai import OpenAIResponses
from agno.knowledge.knowledge import Knowledge
from agno.vectordb.pgvector import PgVector, SearchType

db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
knowledge_base = Knowledge(
    vector_db=PgVector(table_name="recipes", db_url=db_url, search_type=SearchType.hybrid),
)

if __name__ == "__main__":
    knowledge_base.insert(
        url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"
    )

    agent = Agent(
        model=OpenAIResponses(id="gpt-5.2"),
        knowledge=knowledge_base,
        db=PostgresDb(db_url=db_url),
        # Add a tool to read chat history.
        read_chat_history=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)

Async Support ⚡

PgVector exposes async methods. Embedding and reader work can be awaited, while some ingestion writes still use synchronous SQLAlchemy and async search runs the synchronous search in a worker thread.

async_pgvector.py
import asyncio

from agno.agent import Agent
from agno.knowledge.knowledge import Knowledge
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 = Knowledge(
    vector_db=vector_db,
)

agent = Agent(knowledge=knowledge_base)

if __name__ == "__main__":
    # Load knowledge base asynchronously
    asyncio.run(knowledge_base.ainsert(
            url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"
        )
    )

    # Create and use the agent asynchronously
    asyncio.run(agent.aprint_response("How to make Tom Kha Gai", markdown=True))

Use ainsert() and aprint_response() to integrate with async application code. These methods do not make every database operation nonblocking; measure concurrency for your workload.

PgVector Params

ParameterTypeDefaultDescription
table_namestr-Name of the table to store vector data.
schemastr"ai"Database schema name.
nameOptional[str]NoneName of the vector database.
descriptionOptional[str]NoneDescription of the vector database.
idOptional[str]NoneID of the vector database. Generated from db_url and table_name if not provided.
db_urlOptional[str]NoneDatabase connection URL.
db_engineOptional[Engine]NoneSQLAlchemy database engine.
embedderOptional[Embedder]NoneEmbedder for creating embeddings. Defaults to OpenAIEmbedder if not provided.
search_typeSearchTypevectorType of search to perform.
vector_indexUnion[Ivfflat, HNSW]HNSW()Vector index configuration.
distanceDistancecosineDistance metric for vector comparisons.
prefix_matchboolFalseEnable prefix matching for full-text search.
vector_score_weightfloat0.5Weight for vector similarity in hybrid search. Must be between 0 and 1.
content_languagestr"english"Language for full-text search.
schema_versionint1Version of the database schema.
rerankerOptional[Reranker]NoneReranker for reranking search results.
create_schemaboolTrueCreate the database schema if it does not exist. Set to False if schema is managed externally.
similarity_thresholdOptional[float]NoneMinimum similarity score (0.0-1.0) to filter results.
dbOptional[PostgresDb]NoneKeyword-only: borrow a synchronous PostgreSQL database engine. Cannot be combined with db_url or db_engine.