Skip to content

Commit

Permalink
Add sql chain
Browse files Browse the repository at this point in the history
  • Loading branch information
hupe1980 committed Jul 26, 2023
1 parent 980aa63 commit dc078bd
Show file tree
Hide file tree
Showing 13 changed files with 735 additions and 4 deletions.
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"go.testFlags": ["-v"]
}
155 changes: 155 additions & 0 deletions chain/sql.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package chain

import (
"context"
"fmt"
"strings"

"github.com/hupe1980/golc"
"github.com/hupe1980/golc/integration/sqldb"
"github.com/hupe1980/golc/prompt"
"github.com/hupe1980/golc/schema"
)

const defaultSQLTemplate = `Given an input question, first create a syntactically correct {{.dialect}} query to run, then look at the results of the query and return the answer. Unless the user specifies in his question a specific number of examples he wishes to obtain, always limit your query to at most {{.topK}} results. You can order the results by a relevant column to return the most interesting examples in the database.
Never query for all the columns from a specific table, only ask for a the few relevant columns given the question.
Pay attention to use only the column names that you can see in the schema description. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.
Use the following format:
Question: Question here
SQLQuery: SQL Query to run
SQLResult: Result of the SQLQuery
Answer: Final answer here
Only use the following tables:
{{.tableInfo}}
Question: {{.input}}`

// Compile time check to ensure SQL satisfies the Chain interface.
var _ schema.Chain = (*SQL)(nil)

type SQLOptions struct {
*schema.CallbackOptions
InputKey string
TablesInputKey string
OutputKey string
TopK uint
}

type SQL struct {
sqldb *sqldb.SQLDB
llmChain *LLM
opts SQLOptions
}

func NewSQL(llm schema.Model, engine sqldb.Engine) (*SQL, error) {
opts := SQLOptions{
InputKey: "query",
OutputKey: "result",
TopK: 5,
CallbackOptions: &schema.CallbackOptions{
Verbose: golc.Verbose,
},
}

sqldb, err := sqldb.New(engine)
if err != nil {
return nil, err
}

llmChain, err := NewLLM(llm, prompt.NewTemplate(defaultSQLTemplate))
if err != nil {
return nil, err
}

return &SQL{
sqldb: sqldb,
llmChain: llmChain,
opts: opts,
}, nil
}

// Call executes the SQL chain with the given context and inputs.
// It returns the outputs of the chain or an error, if any.
func (c *SQL) Call(ctx context.Context, inputs schema.ChainValues, optFns ...func(o *schema.CallOptions)) (schema.ChainValues, error) {
query, ok := inputs[c.opts.InputKey].(string)
if !ok {
return nil, fmt.Errorf("%w: no value for inputKey %s", ErrInvalidInputValues, c.opts.InputKey)
}

tableInfo, err := c.sqldb.TableInfo(ctx)
if err != nil {
return nil, err
}

input := fmt.Sprintf("%s\nSQLQuery:", query)

sqlQuery, err := golc.SimpleCall(ctx, c.llmChain, schema.ChainValues{
"dialect": c.sqldb.Dialect(),
"input": input,
"tableInfo": tableInfo,
"topK": c.opts.TopK,
}, func(sco *golc.SimpleCallOptions) {
sco.Stop = []string{"\nSQLResult:"}
})
if err != nil {
return nil, err
}

queryResult, err := c.sqldb.Query(ctx, sqlQuery)
if err != nil {
return nil, err
}

input += fmt.Sprintf("%s\nSQLResult: %s\nAnswer:", sqlQuery, queryResult)

result, err := golc.SimpleCall(ctx, c.llmChain, schema.ChainValues{
"dialect": c.sqldb.Dialect(),
"input": input,
"tableInfo": tableInfo,
"topK": c.opts.TopK,
}, func(sco *golc.SimpleCallOptions) {
sco.Stop = []string{"\nSQLResult:"}
})
if err != nil {
return nil, err
}

return schema.ChainValues{
c.opts.OutputKey: strings.TrimSpace(result),
}, nil
}

// Memory returns the memory associated with the chain.
func (c *SQL) Memory() schema.Memory {
return nil
}

// Type returns the type of the chain.
func (c *SQL) Type() string {
return "SQL"
}

// Verbose returns the verbosity setting of the chain.
func (c *SQL) Verbose() bool {
return c.opts.CallbackOptions.Verbose
}

// Callbacks returns the callbacks associated with the chain.
func (c *SQL) Callbacks() []schema.Callback {
return c.opts.CallbackOptions.Callbacks
}

// InputKeys returns the expected input keys.
func (c *SQL) InputKeys() []string {
return []string{c.opts.InputKey}
}

// OutputKeys returns the output keys the chain will return.
func (c *SQL) OutputKeys() []string {
return []string{c.opts.OutputKey}
}
2 changes: 1 addition & 1 deletion chain/transform.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func NewTransform(inputKeys, outputKeys []string, transform TransformFunc, optFn
}, nil
}

// Call executes the ConversationalRetrieval chain with the given context and inputs.
// Call executes the Transform chain with the given context and inputs.
// It returns the outputs of the chain or an error, if any.
func (c *Transform) Call(ctx context.Context, inputs schema.ChainValues, optFns ...func(o *schema.CallOptions)) (schema.ChainValues, error) {
return c.transform(ctx, inputs, optFns...)
Expand Down
67 changes: 67 additions & 0 deletions docs/content/en/docs/chains/sql.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
---
title: SQL
description: All about sql chains.
weight: 70
---
```go
package main

import (
"context"
"fmt"
"log"
"os"

"github.com/hupe1980/golc"
"github.com/hupe1980/golc/chain"
"github.com/hupe1980/golc/integration/sqldb"
"github.com/hupe1980/golc/model/llm"

// Add your sql db driver, see https://github.com/golang/go/wiki/SQLDrivers
_ "github.com/mattn/go-sqlite3"
)

func main() {
ctx := context.Background()

openai, err := llm.NewOpenAI(os.Getenv("OPENAI_API_KEY"))
if err != nil {
log.Fatal(err)
}

engine, err := sqldb.NewSQLite3(":memory:")
if err != nil {
log.Fatal(err)
}

// Only for demonstration
_, exErr := engine.Exec(ctx, "CREATE TABLE IF NOT EXISTS employee ( id int not null );")
if exErr != nil {
log.Fatal(exErr)
}

// Only for demonstration
for i := 0; i < 4; i++ {
_, qErr := engine.Exec(ctx, "INSERT INTO employee (id) VALUES (?) ;", i)
if qErr != nil {
log.Fatal(qErr)
}
}

sql, err := chain.NewSQL(openai, engine)
if err != nil {
log.Fatal(err)
}

result, err := golc.SimpleCall(ctx, sql, "How many employees are there?")
if err != nil {
log.Fatal(err)
}

fmt.Println(result)
}
```
Output:
```text
There are 4 employees.
```
53 changes: 53 additions & 0 deletions examples/sql/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package main

import (
"context"
"fmt"
"log"
"os"

"github.com/hupe1980/golc"
"github.com/hupe1980/golc/chain"
"github.com/hupe1980/golc/integration/sqldb"
"github.com/hupe1980/golc/model/llm"

_ "github.com/mattn/go-sqlite3"
)

func main() {
ctx := context.Background()

openai, err := llm.NewOpenAI(os.Getenv("OPENAI_API_KEY"))
if err != nil {
log.Fatal(err)
}

engine, err := sqldb.NewSQLite3(":memory:")
if err != nil {
log.Fatal(err)
}

_, exErr := engine.Exec(ctx, "CREATE TABLE IF NOT EXISTS employee ( id int not null );")
if exErr != nil {
log.Fatal(exErr)
}

for i := 0; i < 4; i++ {
_, qErr := engine.Exec(ctx, "INSERT INTO employee (id) VALUES (?) ;", i)
if qErr != nil {
log.Fatal(qErr)
}
}

sql, err := chain.NewSQL(openai, engine)
if err != nil {
log.Fatal(err)
}

result, err := golc.SimpleCall(ctx, sql, "How many employees are there?")
if err != nil {
log.Fatal(err)
}

fmt.Println(result)
}
10 changes: 10 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ require (

require (
cloud.google.com/go/longrunning v0.5.1 // indirect
github.com/agext/levenshtein v1.2.1 // indirect
github.com/andybalholm/cascadia v1.3.2 // indirect
github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.35 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.29 // indirect
Expand All @@ -36,6 +38,7 @@ require (
github.com/go-jose/go-jose/v3 v3.0.0 // indirect
github.com/go-openapi/analysis v0.21.4 // indirect
github.com/go-openapi/errors v0.20.4 // indirect
github.com/go-openapi/inflect v0.19.0 // indirect
github.com/go-openapi/jsonpointer v0.20.0 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/loads v0.21.2 // indirect
Expand All @@ -44,16 +47,21 @@ require (
github.com/go-openapi/validate v0.22.1 // indirect
github.com/go-stack/stack v1.8.1 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.0 // indirect
github.com/hashicorp/hcl/v2 v2.10.0 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/oklog/ulid v1.3.1 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/zclconf/go-cty v1.8.0 // indirect
go.mongodb.org/mongo-driver v1.12.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/mod v0.8.0 // indirect
golang.org/x/net v0.12.0 // indirect
golang.org/x/oauth2 v0.10.0 // indirect
golang.org/x/sys v0.10.0 // indirect
Expand All @@ -67,6 +75,7 @@ require (
)

require (
ariga.io/atlas v0.12.0
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver/v3 v3.2.1 // indirect
github.com/PuerkitoBio/goquery v1.8.1
Expand All @@ -84,6 +93,7 @@ require (
github.com/hupe1980/go-promptlayer v0.0.6
github.com/hupe1980/go-tiktoken v0.0.5
github.com/imdario/mergo v0.3.16 // indirect
github.com/mattn/go-sqlite3 v1.14.17
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/pinecone-io/go-pinecone v0.3.0
Expand Down
Loading

0 comments on commit dc078bd

Please sign in to comment.