cloudsql

package
v0.1.14 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2025 License: MIT Imports: 8 Imported by: 1

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 Chat Message History 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
    }
}

Chat Message History Usage

Use a table to store the history of chat messages.

package main

import (
  "context"
  "fmt"

  "github.com/tmc/langchaingo/internal/cloudsqlutil"
  "github.com/tmc/langchaingo/llms"
  "github.com/tmc/langchaingo/memory/cloudsql"
)

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

	// Creates a new table in the Postgres database, which will be used for storing Chat History.
	err = cloudSQLEngine.InitChatHistoryTable(ctx, "tableName")
	if err != nil {
		log.Fatal(err)
	}

    // Creates a new Chat Message History
    cmh, err := cloudsql.NewChatMessageHistory(ctx, *cloudSQLEngine, "tableName", "sessionID")
    if err != nil {
        log.Fatal(err)
    }

    // Creates individual messages and adds them to the chat message history.
    aiMessage := llms.AIChatMessage{Content: "test AI message"}
    humanMessage := llms.HumanChatMessage{Content: "test HUMAN message"}
    // Adds a user message to the chat message history.
    err = cmh.AddUserMessage(ctx, string(aiMessage.GetContent()))
    if err != nil {
        log.Fatal(err)
    }
    // Adds a user message to the chat message history.
    err = cmh.AddUserMessage(ctx, string(humanMessage.GetContent()))
    if err != nil {
        log.Fatal(err)
    }
    msgs, err := cmh.Messages(ctx)
    if err != nil {
        log.Fatal(err)
    }
    for _, msg := range msgs {
        fmt.Println("Message:", msg)
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ChatMessageHistory

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

func NewChatMessageHistory

func NewChatMessageHistory(ctx context.Context,
	engine cloudsqlutil.PostgresEngine,
	tableName,
	sessionID string,
	opts ...ChatMessageHistoryStoresOption,
) (ChatMessageHistory, error)

NewChatMessageHistory creates a new NewChatMessageHistory with options.

func (*ChatMessageHistory) AddAIMessage

func (c *ChatMessageHistory) AddAIMessage(ctx context.Context, content string) error

AddAIMessage adds an AI-generated message to the ChatMessageHistory.

func (*ChatMessageHistory) AddMessage

func (c *ChatMessageHistory) AddMessage(ctx context.Context, message llms.ChatMessage) error

AddMessage adds a message to the ChatMessageHistory.

func (*ChatMessageHistory) AddMessages

func (c *ChatMessageHistory) AddMessages(ctx context.Context, messages []llms.ChatMessage) error

AddMessages adds multiple messages to the ChatMessageHistory for a given session.

func (*ChatMessageHistory) AddUserMessage

func (c *ChatMessageHistory) AddUserMessage(ctx context.Context, content string) error

AddUserMessage adds a user-generated message to the ChatMessageHistory.

func (*ChatMessageHistory) Clear

func (c *ChatMessageHistory) Clear(ctx context.Context) error

Clear removes all messages associated with a session from the ChatMessageHistory.

func (*ChatMessageHistory) Messages

func (c *ChatMessageHistory) Messages(ctx context.Context) ([]llms.ChatMessage, error)

Messages retrieves all messages associated with a session from the ChatMessageHistory.

func (*ChatMessageHistory) SetMessages

func (c *ChatMessageHistory) SetMessages(ctx context.Context, messages []llms.ChatMessage) error

SetMessages clears the current messages from the ChatMessageHistory for a given session and then adds new messages to it.

type ChatMessageHistoryStoresOption

type ChatMessageHistoryStoresOption func(c *ChatMessageHistory)

ChatMessageHistoryStoresOption is a function for creating chat message history with other than the default values.

func WithSchemaName

func WithSchemaName(schemaName string) ChatMessageHistoryStoresOption

WithSchemaName sets the schemaName field for the ChatMessageHistory.