Help us shape the future of Go! Take the 2026 Go Developer Survey

postgresql

package
v1.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README

PostgreSQL plugin

PostgreSQL plugin provides indexer and retriever implementations that use PostgreSQL with the pgvector extension for vector similarity search.

Building with a coding agent? Install the Genkit Go skill first.

npx skills add genkit-ai/skills --skill developing-genkit-go

It teaches your agent the current Genkit Go APIs and common gotchas. Source, manual install and skills for other languages: genkit-ai/skills.

Configuration

To use this plugin, first create a PostgresEngine instance:

// Create PostgresEngine instance
// with basic authentication
pEngine, err := NewPostgresEngine(ctx,
		WithUser('user'),
		WithPassword('password'),
		WithCloudSQLInstance('my-project', 'us-central1', 'my-instance'),
		WithDatabase('my-database')

// with email authentication
pEngine, err := NewPostgresEngine(ctx,
    WithCloudSQLInstance('my-project', 'us-central1', 'my-instance'),
    WithDatabase('my-database'),
    WithIAMAccountEmail('mail@company.com'))

// with custom pool
pool, err := pgxpool.New(ctx, "add_your_connection_string")
if err != nil {
  return err
}

pEngine, err := NewPostgresEngine(ctx,
    WithDatabase("db_test"),
    WithPool(pool))

// Create the vector store table

err = pEngine.InitVectorstoreTable(ctx, VectorstoreTableOptions{
    TableName:          "documents",
    VectorSize:         768,
    SchemaName:         "public",
    ContentColumnName:  "content",
    EmbeddingColumn:    "embedding",
    MetadataJSONColumn: "custom_metadata",
    IDColumn: Column{
      Name:     custom_id,
      Nullable: false,
    },
    MetadataColumns: []Column{
      {
        Name:     "source",
        DataType: "text",
        Nullable: true,
      },
      {
        Name:     "category",
        DataType: "text",
        Nullable: true,
      },
    },
    OverwriteExisting: true,
    StoreMetadata:     true,
})

Then, specify the plugin when you initialize Genkit:

	postgres := &Postgres{
		engine: pEngine,
	}

	g, err := genkit.Init(ctx, genkit.WithPlugins(postgres))
  if err != nil {
    return nil
}

// To use the table you configured when you loaded the plugin:

  cfg := &Config{
    TableName:             'documents',
    SchemaName:            'public',
    ContentColumn:         "content",
    EmbeddingColumn:       "embedding",
    MetadataColumns:       []string{"source", "category"},
    IDColumn:              "custom_id",
    MetadataJSONColumn:    "custom_metadata",
    Embedder:              embedder,
    EmbedderOptions:       nil,
  }

// To index and retrieve from the configured table:
doc, retriever, err := DefineRetriever(ctx, g, postgres, cfg)
if err != nil {
  retrun err
}

docs := []*ai.Document{{
  Content: []*ai.Part{{
    Kind:        ai.PartText,
    ContentType: "text/plain",
    Text:        "The product features include...",
  }},
  Metadata: map[string]any{"source": "website", "category": "product-docs", "custom_id": "doc-123"},
}}

if err := doc.Index(ctx, docs); err != nil {
 return err
}

d2 := ai.DocumentFromText( "The product features include..." , nil)

resp, err := retriever.Retrieve(ctx, &ai.RetrieverRequest{
    Query: d2,
    k:5,
    filter: "source='website' AND category='product-docs'"
})

if err != nil {
    retrun err
}

See the Retrieval-augmented generation page for a general discussion on indexers and retrievers.

Session store

exp.NewPostgresSessionStore persists agent session snapshots in PostgreSQL through the pool of the plugin registered with genkit.Init. It creates its table when the table does not exist, and it delivers status changes over LISTEN/NOTIFY, so background runs and their abort work across instances.

import pgexp "github.com/firebase/genkit/go/plugins/postgresql/exp"

engine, err := postgresql.NewPostgresEngine(ctx, postgresql.WithPool(pool))
g := genkit.Init(ctx,
	genkit.WithExperimental(),
	genkit.WithPlugins(&postgresql.Postgres{Engine: engine}))

store, err := pgexp.NewPostgresSessionStore[ChatState](ctx, g)
chatAgent := genkitx.DefineAgent(g, "chat",
	aix.InlinePrompt{ai.WithModelName("googleai/gemini-flash-latest")},
	aix.WithSessionStore(store),
)

WithTableName, WithSchemaName, WithCheckpointInterval, WithSnapshotPathPrefix (per-tenant isolation), and WithPollInterval configure it. Connect directly or through a session-mode pooler: a transaction-mode pooler cannot deliver notifications, and subscriptions then rely on the poll. Each store holds one connection for LISTEN while runs are subscribed to it, so share one store among the agents with the same State type.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Retriever

func Retriever(g *genkit.Genkit, id string) ai.Retriever

Retriever returns the retriever with the given index id.

Types

type BaseIndex

type BaseIndex struct {
	// contains filtered or unexported fields
}

func NewBaseIndex

func NewBaseIndex(indexName, indexType string, strategy DistanceStrategy, partialIndexes []string, opts Index) BaseIndex

type Column

type Column struct {
	Name     string
	DataType string
	Nullable bool
}

type Config

type Config struct {
	// TableName the table name in which documents will be stored and searched.
	TableName string
	// SchemaName schema name in which documents will be stored and searched.
	SchemaName string
	// ContentColumn column name which contains content of the document. Defaults to content
	ContentColumn string
	// EmbeddingColumn column name which contains the vector. Defaults to embedding
	EmbeddingColumn string
	// MetadataColumns a list of columns to create for custom metadata
	MetadataColumns []string
	// IDColumn column name which represents the identifier of the table. Defaults to id
	IDColumn string
	// MetadataJSONColumn the column to store extra metadata in JSON format
	MetadataJSONColumn string
	// IgnoreMetadataColumns column(s) to ignore in pre-existing tables for a document's metadata. Can not be used with metadata_columns.
	IgnoreMetadataColumns []string
	// Embedder to use. Required.
	Embedder ai.Embedder
	// EmbedderOptions options to pass to the Embedder.
	EmbedderOptions any
}

Config provides configuration options for DefineRetriever.

type CosineDistance

type CosineDistance struct{}

func (CosineDistance) String

func (c CosineDistance) String() string

type DistanceStrategy

type DistanceStrategy interface {
	String() string
	// contains filtered or unexported methods
}

type DocStore

type DocStore struct {
	// contains filtered or unexported fields
}

func DefineRetriever

func DefineRetriever(ctx context.Context, g *genkit.Genkit, p *Postgres, cfg *Config) (*DocStore, ai.Retriever, error)

DefineRetriever defines a Retriever with the given configuration.

func (*DocStore) Index

func (ds *DocStore) Index(ctx context.Context, docs []*ai.Document) error

Index implements the genkit.Index method.

func (*DocStore) Retrieve

func (ds *DocStore) Retrieve(ctx context.Context, req *ai.RetrieverRequest) (*ai.RetrieverResponse, error)

Retrieve returns the result of the query

type Euclidean

type Euclidean struct{}

func (Euclidean) String

func (e Euclidean) String() string

type HNSWOptions

type HNSWOptions struct {
	M              int
	EfConstruction int
}

HNSWOptions holds the configuration for the hnsw index.

func (HNSWOptions) Options

func (h HNSWOptions) Options() string

type IVFFlatOptions

type IVFFlatOptions struct {
	Lists int
}

IVFFlatOptions holds the configuration for the ivfflat index.

func (IVFFlatOptions) Options

func (i IVFFlatOptions) Options() string

type Index

type Index interface {
	Options() string
}

type InnerProduct

type InnerProduct struct{}

func (InnerProduct) String

func (i InnerProduct) String() string

type IpType

type IpType string

IpType type of IP address, public or private

const (
	PUBLIC  IpType = "PUBLIC"
	PRIVATE IpType = "PRIVATE"
)

type Option

type Option func(p *engineConfig)

Option is a function type that can be used to modify the Engine.

func WithCloudSQLInstance

func WithCloudSQLInstance(projectID, region, instance string) Option

WithCloudSQLInstance sets the project, region, and instance fields.

func WithDatabase

func WithDatabase(database string) Option

WithDatabase sets the database to connect to. Required unless the engine uses a pool given with WithPool.

func WithIAMAccountEmail

func WithIAMAccountEmail(email string) Option

WithIAMAccountEmail sets the IAMAccountEmail field.

func WithIPType

func WithIPType(ipType IpType) Option

WithIPType sets the IpType field.

func WithPassword

func WithPassword(password string) Option

WithPassword sets the Password field.

func WithPool

func WithPool(pool *pgxpool.Pool) Option

WithPool gives the engine an existing connection pool, used as is: the engine dials nothing, needs no WithDatabase, and leaves the pool open on Close.

func WithUser

func WithUser(user string) Option

WithUser sets the User field.

type Postgres

type Postgres struct {
	Engine *PostgresEngine
	// contains filtered or unexported fields
}

Postgres holds the current plugin state.

func (*Postgres) ApplyVectorIndex

func (p *Postgres) ApplyVectorIndex(ctx context.Context, config *Config, index BaseIndex, name string, concurrently bool) error

ApplyVectorIndex creates an index in the table of the embeddings.

func (*Postgres) DropVectorIndex

func (p *Postgres) DropVectorIndex(ctx context.Context, config *Config, indexName string) error

DropVectorIndex drops the vector index from the table.

func (*Postgres) Init

func (p *Postgres) Init(ctx context.Context) []api.Action

Init initialize the PostgreSQL

func (*Postgres) IsValidIndex

func (p *Postgres) IsValidIndex(ctx context.Context, config *Config, indexName string) (bool, error)

IsValidIndex checks if index exists in the table.

func (*Postgres) Name

func (p *Postgres) Name() string

func (*Postgres) ReIndex

func (p *Postgres) ReIndex(ctx context.Context, config *Config) error

ReIndex recreates the index on the table.

func (*Postgres) ReIndexWithName

func (p *Postgres) ReIndexWithName(ctx context.Context, indexName string) error

ReIndexWithName recreates the index on the table by name.

type PostgresEngine

type PostgresEngine struct {
	Pool *pgxpool.Pool
	// contains filtered or unexported fields
}

PostgresEngine holds the connection pool the plugin's features share.

func NewPostgresEngine

func NewPostgresEngine(ctx context.Context, opts ...Option) (*PostgresEngine, error)

NewPostgresEngine creates a new Postgres Engine. It either uses the pool given with WithPool or dials the Cloud SQL instance given with WithCloudSQLInstance, and pings the database before returning.

func (*PostgresEngine) Close

func (pgEngine *PostgresEngine) Close()

Close releases what the engine created: the pool NewPostgresEngine built and the Cloud SQL dialer behind it. A pool given with WithPool, or set on Pool directly, belongs to the caller, who closes it.

func (*PostgresEngine) GetClient

func (pgEngine *PostgresEngine) GetClient() *pgxpool.Pool

func (*PostgresEngine) InitVectorstoreTable

func (pgEngine *PostgresEngine) InitVectorstoreTable(ctx context.Context, opts VectorstoreTableOptions) error

initVectorstoreTable creates a table for saving of vectors to be used with PostgresVectorStore.

type RetrieverOptions

type RetrieverOptions struct {
	// Filter values to be used in the where clause. Defaults is nil
	Filter any
	// K the number of documents to return from search. Defaults to 4.
	K int
	// DistanceStrategy distance strategy to use for vector similarity search. Defaults to CosineDistance
	DistanceStrategy DistanceStrategy
}

RetrieverOptions options for retriever

type VectorstoreTableOptions

type VectorstoreTableOptions struct {
	TableName          string
	VectorSize         int
	SchemaName         string
	ContentColumnName  string
	EmbeddingColumn    string
	MetadataJSONColumn string
	IDColumn           Column
	MetadataColumns    []Column
	OverwriteExisting  bool
	StoreMetadata      bool
}

Directories

Path Synopsis
Package exp provides experimental PostgreSQL integrations for Genkit's agent runtime (see github.com/firebase/genkit/go/ai/exp).
Package exp provides experimental PostgreSQL integrations for Genkit's agent runtime (see github.com/firebase/genkit/go/ai/exp).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL