zhangqian
2023-08-26 5193dcb9336e853502baf8a539d3f45efebe2f86
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package system
 
import (
    "context"
    "errors"
    "fmt"
    "github.com/sashabaranov/go-openai"
    "gorm.io/gorm"
    "srm/global"
    "srm/model/system"
    "srm/model/system/request"
    "strings"
)
 
type ChatGptService struct{}
 
func (chat *ChatGptService) CreateSK(option system.SysChatGptOption) error {
    _, err := chat.GetSK()
    if err != nil {
        if errors.Is(err, gorm.ErrRecordNotFound) {
            return global.GVA_DB.Create(option).Error
        }
        return err
    }
    return errors.New("已经存在sk")
}
 
func (chat *ChatGptService) GetSK() (option system.SysChatGptOption, err error) {
    err = global.GVA_DB.First(&option).Error
    return
}
 
func (chat *ChatGptService) DeleteSK() error {
    option, err := chat.GetSK()
    if err != nil {
        return err
    }
    return global.GVA_DB.Delete(option, "sk = ?", option.SK).Error
}
 
func (chat *ChatGptService) GetTable(req request.ChatGptRequest) (sql string, results []map[string]interface{}, err error) {
    if req.DBName == "" {
        return "", nil, errors.New("未选择db")
    }
    var tablesInfo []system.ChatField
    var tableName string
    global.GVA_DB.Table("information_schema.columns").Where("TABLE_SCHEMA = ?", req.DBName).Scan(&tablesInfo)
 
    var tablesMap = make(map[string]bool)
    for i := range tablesInfo {
        tablesMap[tablesInfo[i].TABLE_NAME] = true
    }
    for i := range tablesMap {
        tableName += i + ","
    }
    option, err := chat.GetSK()
    if err != nil {
        return "", nil, err
    }
    client := openai.NewClient(option.SK)
    ctx := context.Background()
 
    tables, err := getTables(ctx, client, tableName, req.Chat)
    if err != nil {
        return "", nil, err
    }
    tableArr := strings.Split(tables, ",")
    if len(tableArr) != 0 {
        firstKeyArr := strings.Split(tableArr[0], ":")
        tableArr[0] = strings.Trim(firstKeyArr[len(firstKeyArr)-1], "\n")
    }
    sql, err = getSql(ctx, client, tableArr, tablesInfo, req.Chat)
    if err != nil {
        return "", nil, err
    }
    err = global.GVA_DB.Raw(sql).Scan(&results).Error
    return sql, results, err
}
 
func getTables(ctx context.Context, client *openai.Client, tables string, chat string) (string, error) {
    var tablePrompt = `You are a database administrator
 
Filter out the table names you might need from the tables I provided formatted as:
 
Table1,Table2,Table3
 
I will provide you with the following table configuration information:
 
Table1,Table2,Table3
 
Do not return information other than the table
 
Configured as:
%s
 
The problem is:
%s
`
    content := fmt.Sprintf(tablePrompt, tables, chat)
    chatReq := openai.ChatCompletionRequest{
        Model: openai.GPT3Dot5Turbo,
        Messages: []openai.ChatCompletionMessage{
            {
                Role:    openai.ChatMessageRoleUser,
                Content: content,
            },
        },
    }
 
    resp, err := client.CreateChatCompletion(ctx, chatReq)
    if err != nil {
        fmt.Printf("Completion error: %v\n", err)
        return "", err
    }
    return resp.Choices[0].Message.Content, nil
}
 
func getSql(ctx context.Context, client *openai.Client, tables []string, ChatField []system.ChatField, chat string) (string, error) {
    var sqlPrompt = `You are a database administrator
 
Give me an SQL statement based on my question
 
I will provide you with my current database table configuration information in the form below
 
Table Name | Column Name | Column Description
 
Do not return information other than SQL
 
Configured as:
 
%s
 
The problem is:
 
%s`
    var configured string
    for ii := range ChatField {
        for i := range tables {
            if strings.Index(tables[i], ChatField[ii].TABLE_NAME) > -1 {
                configured += fmt.Sprintf("%s | %s | %s \n", ChatField[ii].TABLE_NAME, ChatField[ii].COLUMN_NAME, ChatField[ii].COLUMN_COMMENT)
            }
        }
    }
 
    if configured == "" {
        return "", errors.New("未找到表")
    }
    chatReq := openai.ChatCompletionRequest{
        Model: openai.GPT3Dot5Turbo,
        Messages: []openai.ChatCompletionMessage{
            {
                Role:    openai.ChatMessageRoleUser,
                Content: fmt.Sprintf(sqlPrompt, configured, chat),
            },
        },
    }
 
    resp, err := client.CreateChatCompletion(ctx, chatReq)
    if err != nil {
        fmt.Printf("Completion error: %v\n", err)
        return "", err
    }
    sql := resp.Choices[0].Message.Content
    sqlArr := strings.Split(sql, ":")
    sql = sqlArr[len(sqlArr)-1]
    return sql, nil
}