alloydb

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2025 License: Apache-2.0 Imports: 18 Imported by: 0

README

AlloyDB plugin

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

Configuration

To use this plugin, first create a PostgresEngine instance:

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

// with email authentication
pEngine, err := NewPostgresEngine(ctx,
    WithCloudSQLInstance('my-project', 'us-central1', 'my-cluster', '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 err
  }

// 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.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Retriever

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

Retriever returns the retriever with the given index name.

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
	ContentColumn string
	// EmbeddingColumn column name which contains the vector
	EmbeddingColumn string
	// MetadataColumns a list of columns to create for custom metadata
	MetadataColumns []string
	// IDColumn column name which represents the identifier of the table
	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 is used to index documents .

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 WithAlloyDBInstance

func WithAlloyDBInstance(projectID, region, cluster, instance string) Option

WithAlloyDBInstance sets the project, region, and instance fields.

func WithDatabase

func WithDatabase(database string) Option

WithDatabase sets the Database field.

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 sets the Port field.

func WithUser

func WithUser(user string) Option

WithUser sets the User field.

type Postgres

type Postgres struct {
	// 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, g *genkit.Genkit) error

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
}

PostgresEngine postgres engine

func NewPostgresEngine

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

NewPostgresEngine creates a new Postgres Engine.

func (*PostgresEngine) Close

func (pgEngine *PostgresEngine) Close()

Close closes the pool connection.

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 filter 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
}

Jump to

Keyboard shortcuts

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