PostgresKnowledgeBase

PostgresKnowledgeBase is a PostgreSQL-backed vector knowledge base class that supports fast document retrieval using semantic vector search and traditional text-based queries. It leverages the pgvector extension for similarity search and is built to integrate with LLMs and embeddings models.

Installation

uv add "trusttest[rag-postgres]"

Environment Variables

You can use environment variables for seamless config:

POSTGRES_URL=localhost
POSTGRES_USERNAME=postgres
POSTGRES_PASSWORD=secret
POSTGRES_DATABASE=docs

Example Usage

from trusttest.kb import PostgresKnowledgeBase
from trusttest.embeddings import EmbeddingsOpenAi

kb = PostgresKnowledgeBase(
    database="music",
    uri="localhost",
    username="postgres",
    password="password",
    fields_mapping={
        "id": "id",
        "content": "lyrics",
        "embedding": "embedding",
        "table": "Song",
    },
    embeddings_model=EmbeddingsOpenAi(api="openai", model="text-embedding-3-small"),
    seed_topics=["love", "party", "nature", "sadness"]
)

results = kb.search("ocean")

Notes & Tips

  • If the embedding field is not specified, semantic search will be disabled.
  • To enable pgvector, make sure your database has the extension installed:
CREATE EXTENSION IF NOT EXISTS vector;
  • Semantic similarity uses the <-> operator for efficient ANN search.