-
-
Notifications
You must be signed in to change notification settings - Fork 622
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
memory/postgre #186
Closed
Closed
memory/postgre #186
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
c490724
Initial commit for the postgre buffer, this is still a WIP as I'm not…
Struki84 f98f90e
Replaced PostgreBuffer with PersistentBuffer that has a DBAdapter int…
Struki84 ad04e91
Added the memory file
Struki84 94f8427
Removed old postgre implementation
Struki84 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
package internal | ||
|
||
import ( | ||
"errors" | ||
|
||
"github.com/tmc/langchaingo/schema" | ||
"gorm.io/driver/postgres" | ||
"gorm.io/gorm" | ||
) | ||
|
||
var ( | ||
ErrDBConnection = errors.New("can't connect to database") | ||
ErrDBMigration = errors.New("can't migrate database") | ||
ErrMissingSessionID = errors.New("session id can not be empty") | ||
) | ||
|
||
type Database struct { | ||
gorm *gorm.DB | ||
history *ChatHistory | ||
sessionID string | ||
} | ||
|
||
func NewDatabase(dsn string) (*Database, error) { | ||
database := &Database{ | ||
history: &ChatHistory{}, | ||
} | ||
|
||
gorm, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) | ||
if err != nil { | ||
return nil, ErrDBConnection | ||
} | ||
|
||
database.gorm = gorm | ||
|
||
err = database.gorm.AutoMigrate(ChatHistory{}) | ||
if err != nil { | ||
return nil, ErrDBMigration | ||
} | ||
|
||
return database, nil | ||
} | ||
|
||
func (db *Database) SetSession(id string) { | ||
db.sessionID = id | ||
} | ||
|
||
func (db *Database) SessionID() string { | ||
return db.sessionID | ||
} | ||
|
||
func (db *Database) SaveHistory(msgs []schema.ChatMessage, bs string) error { | ||
if db.sessionID == "" { | ||
return ErrMissingSessionID | ||
} | ||
|
||
newMsgs := Messages{} | ||
for _, msg := range msgs { | ||
newMsgs = append(newMsgs, Message{ | ||
Type: string(msg.GetType()), | ||
Text: msg.GetText(), | ||
}) | ||
} | ||
|
||
db.history.SessionID = db.sessionID | ||
db.history.ChatHistory = &newMsgs | ||
db.history.BufferString = bs | ||
|
||
err := db.gorm.Save(&db.history).Error | ||
if err != nil { | ||
return err | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (db *Database) GetHistroy() ([]schema.ChatMessage, error) { | ||
if db.sessionID == "" { | ||
return nil, ErrMissingSessionID | ||
} | ||
|
||
err := db.gorm.Where(ChatHistory{SessionID: db.sessionID}).Find(&db.history).Error | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
msgs := []schema.ChatMessage{} | ||
if db.history.ChatHistory != nil { | ||
for i := range *db.history.ChatHistory { | ||
msg := (*db.history.ChatHistory)[i] | ||
|
||
if msg.Type == "human" { | ||
msgs = append(msgs, schema.HumanChatMessage{Text: msg.Text}) | ||
} | ||
|
||
if msg.Type == "ai" { | ||
msgs = append(msgs, schema.AIChatMessage{Text: msg.Text}) | ||
} | ||
} | ||
} | ||
|
||
return msgs, nil | ||
} | ||
|
||
func (db *Database) ClearHistroy() error { | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package internal | ||
|
||
import ( | ||
"database/sql/driver" | ||
"encoding/json" | ||
"errors" | ||
) | ||
|
||
var ErrScanType = errors.New("could not scan type into Message") | ||
|
||
type ChatHistory struct { | ||
ID int `gorm:"primary_key"` | ||
SessionID string `gorm:"type:varchar(256)"` | ||
BufferString string `gorm:"type:text"` | ||
ChatHistory *Messages `gorm:"type:jsonb;column:chat_history" json:"chat_history"` | ||
} | ||
|
||
type Message struct { | ||
Type string `json:"type"` | ||
Text string `json:"text"` | ||
} | ||
|
||
type Messages []Message | ||
|
||
// Value implements the driver.Valuer interface, this method allows us to | ||
// customize how we store the Message type in the database. | ||
func (m Messages) Value() (driver.Value, error) { | ||
return json.Marshal(m) | ||
} | ||
|
||
// Scan implements the sql.Scanner interface, this method allows us to | ||
// define how we convert the Message data from the database into our Message type. | ||
func (m *Messages) Scan(src interface{}) error { | ||
if bytes, ok := src.([]byte); ok { | ||
return json.Unmarshal(bytes, m) | ||
} | ||
return ErrScanType | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,183 @@ | ||
package postgre | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"log" | ||
|
||
"github.com/tmc/langchaingo/memory" | ||
"github.com/tmc/langchaingo/memory/postgre/internal" | ||
"github.com/tmc/langchaingo/schema" | ||
) | ||
|
||
// ErrInvalidInputValues is returned when input values given to a memory in save context are invalid. | ||
var ErrInvalidInputValues = errors.New("invalid input values") | ||
|
||
type PostgreBuffer struct { | ||
ChatHistory *memory.ChatMessageHistory | ||
DB *internal.Database | ||
|
||
ReturnMessages bool | ||
InputKey string | ||
OutputKey string | ||
HumanPrefix string | ||
AIPrefix string | ||
MemoryKey string | ||
} | ||
|
||
var _ schema.Memory = &PostgreBuffer{} | ||
|
||
func NewPostgreBuffer(dsn string) *PostgreBuffer { | ||
buffer := PostgreBuffer{ | ||
ChatHistory: memory.NewChatMessageHistory(), | ||
|
||
ReturnMessages: false, | ||
InputKey: "", | ||
OutputKey: "", | ||
HumanPrefix: "Human", | ||
AIPrefix: "AI", | ||
MemoryKey: "history", | ||
} | ||
|
||
db, err := internal.NewDatabase(dsn) | ||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
|
||
buffer.DB = db | ||
|
||
return &buffer | ||
} | ||
|
||
func (buffer *PostgreBuffer) SetSession(id string) { | ||
buffer.DB.SetSession(id) | ||
} | ||
|
||
func (buffer *PostgreBuffer) SessionID() string { | ||
return buffer.DB.SessionID() | ||
} | ||
|
||
func (buffer *PostgreBuffer) MemoryVariables() []string { | ||
return []string{buffer.MemoryKey} | ||
} | ||
|
||
func (buffer *PostgreBuffer) LoadMemoryVariables(inputs map[string]any) (map[string]any, error) { | ||
msgs, err := buffer.DB.GetHistroy() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
buffer.ChatHistory = memory.NewChatMessageHistory( | ||
memory.WithPreviousMessages(msgs), | ||
) | ||
|
||
if buffer.ReturnMessages { | ||
return map[string]any{ | ||
buffer.MemoryKey: buffer.ChatHistory.Messages(), | ||
}, nil | ||
} | ||
|
||
bufferString, err := schema.GetBufferString(buffer.ChatHistory.Messages(), buffer.HumanPrefix, buffer.AIPrefix) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return map[string]any{ | ||
buffer.MemoryKey: bufferString, | ||
}, nil | ||
} | ||
|
||
// SaveContext saves the context of the PostgreBuffer. | ||
// | ||
// It takes in two maps, inputs and outputs, which contain key-value pairs of any type. | ||
// The function retrieves the value associated with buffer.InputKey from the inputs map | ||
// and adds it as a user message to the ChatHistory. Then, it retrieves the value | ||
// associated with buffer.OutputKey from the outputs map and adds it as an AI message | ||
// to the ChatHistory. The function then uses the ChatHistory, HumanPrefix, and AIPrefix | ||
// properties of the buffer to generate a bufferString using the GetBufferString function | ||
// from the schema package. Finally, it saves the ChatHistory messages and bufferString | ||
// to the DB using the SaveHistory function, and returns any error encountered. | ||
// | ||
// Return type: error. | ||
func (buffer *PostgreBuffer) SaveContext(inputs map[string]any, outputs map[string]any) error { | ||
userInputValue, err := getInputValue(inputs, buffer.InputKey) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
buffer.ChatHistory.AddUserMessage(userInputValue) | ||
|
||
aiOutPutValue, err := getInputValue(outputs, buffer.OutputKey) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
buffer.ChatHistory.AddAIMessage(aiOutPutValue) | ||
|
||
bufferString, err := schema.GetBufferString(buffer.ChatHistory.Messages(), buffer.HumanPrefix, buffer.AIPrefix) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
err = buffer.DB.SaveHistory(buffer.ChatHistory.Messages(), bufferString) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (buffer *PostgreBuffer) Clear() error { | ||
buffer.ChatHistory.Clear() | ||
err := buffer.DB.ClearHistroy() | ||
if err != nil { | ||
return err | ||
} | ||
return nil | ||
} | ||
|
||
func getInputValue(inputValues map[string]any, inputKey string) (string, error) { | ||
// If the input key is set, return the value in the inputValues with the input key. | ||
if inputKey != "" { | ||
inputValue, ok := inputValues[inputKey] | ||
if !ok { | ||
return "", fmt.Errorf( | ||
"%w: %v do not contain inputKey %s", | ||
ErrInvalidInputValues, | ||
inputValues, | ||
inputKey, | ||
) | ||
} | ||
|
||
return getInputValueReturnToString(inputValue) | ||
} | ||
|
||
// Otherwise error if length of map isn't one, or return the only entry in the map. | ||
if len(inputValues) > 1 { | ||
return "", fmt.Errorf( | ||
"%w: multiple keys and no input key set", | ||
ErrInvalidInputValues, | ||
) | ||
} | ||
|
||
for _, inputValue := range inputValues { | ||
return getInputValueReturnToString(inputValue) | ||
} | ||
|
||
return "", fmt.Errorf("%w: 0 keys", ErrInvalidInputValues) | ||
} | ||
|
||
func getInputValueReturnToString( | ||
inputValue interface{}, | ||
) (string, error) { | ||
switch value := inputValue.(type) { | ||
case string: | ||
return value, nil | ||
default: | ||
return "", fmt.Errorf( | ||
"%w: input value %v not string", | ||
ErrInvalidInputValues, | ||
inputValue, | ||
) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we have alot of deps already, let's make this optional behind an interface
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Take a look ;)