cloudsql

package
v0.1.15 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: MIT Imports: 12 Imported by: 0

README

Cloud SQL for PostgreSQL for LangChain Go

The Cloud SQL for PostgreSQL for LangChain package provides a first class experience for connecting to Cloud SQL instances from the LangChain ecosystem while providing the following benefits:

  • Simplified & Secure Connections: easily and securely create shared connection pools to connect to Google Cloud databases utilizing IAM for authorization and database authentication without needing to manage SSL certificates, configure firewall rules, or enable authorized networks.
  • Improved performance & Simplified management: use a single-table schema can lead to faster query execution, especially for large collections.
  • Improved metadata handling: store metadata in columns instead of JSON, resulting in significant performance improvements.
  • Clear separation: clearly separate table and extension creation, allowing for distinct permissions and streamlined workflows.

Quick Start

In order to use this package, you first need to go through the following steps:

  1. Select or create a Cloud Platform project.
  2. Enable billing for your project.
  3. Enable the Cloud SQL API.
  4. Authentication with CloudSDK.

Supported Go Versions

Go version >= go 1.22.0

Engine Creation

The CloudSQLEngine configures a connection pool to your CloudSQL database.

package main

import (
  "context"
  "fmt"

  "github.com/tmc/langchaingo/internal/cloudsqlutil"
)

func NewCloudSQLEngine(ctx context.Context) (*cloudsqlutil.PostgresEngine, error) {
	// Call NewPostgresEngine to initialize the database connection
    pgEngine, err := cloudsqlutil.NewPostgresEngine(ctx,
        cloudsqlutil.WithUser("my-user"),
        cloudsqlutil.WithPassword("my-password"),
        cloudsqlutil.WithDatabase("my-database"),
        cloudsqlutil.WithCloudSQLInstance("my-project-id", "region", "my-instance"),
    )
    if err != nil {
        return nil, fmt.Errorf("Error creating PostgresEngine: %s", err)
    }
    return pgEngine, nil
}

func main() {
    ctx := context.Background()
    cloudSQLEngine, err := NewCloudSQLEngine(ctx)
    if err != nil {
         return nil, err
    }
}

See the full Vector Store example and tutorial.

Engine Creation WithPool

Create a CloudSQLEngine with the WithPool method to connect to an instance of CloudSQL Omni or to customize your connection pool.

package main

import (
  "context"
  "fmt"

  "github.com/jackc/pgx/v5/pgxpool"
  "github.com/tmc/langchaingo/internal/cloudsqlutil"
)

func NewCloudSQLWithPoolEngine(ctx context.Context) (*cloudsqlutil.PostgresEngine, error) {
    myPool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
    if err != nil {
        return err
    }
	// Call NewPostgresEngine to initialize the database connection
    pgEngineWithPool, err := cloudsqlutil.NewPostgresEngine(ctx, cloudsqlutil.WithPool(myPool))
    if err != nil {
        return nil, fmt.Errorf("Error creating PostgresEngine with pool: %s", err)
    }
    return pgEngineWithPool, nil
}

func main() {
    ctx := context.Background()
    cloudSQLEngine, err := NewCloudSQLWithPoolEngine(ctx)
    if err != nil {
        return nil, err
    }
}

Vector Store Usage

Use a vector store to store embedded data and perform vector search.

package main

import (
  "context"
  "fmt"

  "github.com/tmc/langchaingo/embeddings"
  "github.com/tmc/langchaingo/internal/cloudsqlutil"
  "github.com/tmc/langchaingo/llms/googleai/vertex"
  "github.com/tmc/langchaingo/vectorstores/cloudsql"
)

func main() {
    ctx := context.Background()
    cloudSQLEngine, err := NewCloudSQLEngine(ctx)
    if err != nil {
        return nil, err
    }

    // Initialize table for the Vectorstore to use. You only need to do this the first time you use this table.
    vectorstoreTableoptions, err := &cloudsqlutil.VectorstoreTableOptions{
        TableName:  "table",
        VectorSize: 768,
    }
    if err != nil {
        log.Fatal(err)
    }

    err = pgEngine.InitVectorstoreTable(ctx, *vectorstoreTableoptions,
        []alloydbutil.Column{
            alloydbutil.Column{
                Name:     "area",
                DataType: "int",
                Nullable: false,
            },
            alloydbutil.Column{
                Name:     "population",
                DataType: "int",
                Nullable: false,
            },
        },
    )
    if err != nil {
        log.Fatal(err)
    }

    // Initialize VertexAI LLM
    llm, err := vertex.New(ctx, googleai.WithCloudProject(projectID), googleai.WithCloudLocation(cloudLocation), googleai.WithDefaultModel("text-embedding-005"))
    if err != nil {
        log.Fatal(err)
    }

    myEmbedder, err := embeddings.NewEmbedder(llm)
    if err != nil {
        log.Fatal(err)
    }

    vectorStore := cloudsql.NewVectorStore(cloudSQLEngine, myEmbedder, "my-table", cloudsql.WithMetadataColumns([]string{"area", "population"}))
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BaseIndex

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

type CosineDistance

type CosineDistance struct{}

func (CosineDistance) String

func (CosineDistance) String() string

type Euclidean

type Euclidean struct{}

func (Euclidean) String

func (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 (InnerProduct) String() string

type SearchDocument

type SearchDocument struct {
	Content           string
	LangchainMetadata string
	Distance          float32
}

type VectorStore

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

func NewVectorStore

func NewVectorStore(engine cloudsqlutil.PostgresEngine,
	embedder embeddings.Embedder,
	tableName string,
	opts ...VectorStoreOption,
) (VectorStore, error)

NewVectorStore creates a new VectorStore with options.

func (*VectorStore) AddDocuments

func (vs *VectorStore) AddDocuments(ctx context.Context, docs []schema.Document, _ ...vectorstores.Option) ([]string, error)

AddDocuments adds documents to the Postgres collection, and returns the ids of the added documents.

func (*VectorStore) ApplyVectorIndex

func (vs *VectorStore) ApplyVectorIndex(ctx context.Context, index BaseIndex, name string, concurrently bool) error

ApplyVectorIndex creates an index in the table of the embeddings.

func (*VectorStore) DropVectorIndex

func (vs *VectorStore) DropVectorIndex(ctx context.Context, indexName string) error

DropVectorIndex drops the vector index from the VectorStore.

func (*VectorStore) IsValidIndex

func (vs *VectorStore) IsValidIndex(ctx context.Context, indexName string) (bool, error)

IsValidIndex checks if index exists in the VectorStore.

func (*VectorStore) NewBaseIndex

func (*VectorStore) NewBaseIndex(indexName, indexType string, strategy distanceStrategy, partialIndexes []string, opts Index) BaseIndex

func (*VectorStore) ReIndex

func (vs *VectorStore) ReIndex(ctx context.Context) error

ReIndex recreates the index on the VectorStore.

func (*VectorStore) ReIndexWithName

func (vs *VectorStore) ReIndexWithName(ctx context.Context, indexName string) error

ReIndex recreates the index on the VectorStore by name.

func (*VectorStore) SimilaritySearch

func (vs *VectorStore) SimilaritySearch(ctx context.Context, query string, _ int, options ...vectorstores.Option) ([]schema.Document, error)

SimilaritySearch performs a similarity search on the database using the query vector.

type VectorStoreOption

type VectorStoreOption func(vs *VectorStore)

VectorStoreOption is a function for creating new vector store with other than the default values.

func WithContentColumn

func WithContentColumn(contentColumn string) VectorStoreOption

WithContentColumn sets the VectorStore's ContentColumn field.

func WithDistanceStrategy

func WithDistanceStrategy(distanceStrategy distanceStrategy) VectorStoreOption

WithDistanceStrategy sets the distance strategy used by the VectorStore.

func WithEmbeddingColumn

func WithEmbeddingColumn(embeddingColumn string) VectorStoreOption

WithEmbeddingColumn sets the EmbeddingColumn field.

func WithIDColumn

func WithIDColumn(idColumn string) VectorStoreOption

WithContentColumn sets VectorStore's the idColumn field.

func WithK

func WithK(k int) VectorStoreOption

WithK sets the number of Documents to return from the VectorStore.

func WithMetadataColumns

func WithMetadataColumns(metadataColumns []string) VectorStoreOption

WithMetadataColumns sets the VectorStore's MetadataColumns field.

func WithMetadataJSONColumn

func WithMetadataJSONColumn(metadataJSONColumn string) VectorStoreOption

WithMetadataJSONColumn sets VectorStore's the metadataJSONColumn field.

func WithSchemaName

func WithSchemaName(schemaName string) VectorStoreOption

WithSchemaName sets the VectorStore's schemaName field.

Jump to

Keyboard shortcuts

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