-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
295 lines (245 loc) · 6.32 KB
/
main.go
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package main
import (
"context"
"database/sql"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"github.com/jime567/NaturalSQL-AI/structs"
openai "github.com/sashabaranov/go-openai"
)
var (
db *sql.DB
client1 *openai.Client
client2 *openai.Client
background string
)
func main() {
// Initialize database and OpenAI client
initDB()
initOpenAIClient()
content, err := ioutil.ReadFile("background.txt")
if err != nil {
log.Fatalf("Error reading file: %v", err)
}
background = string(content)
// Initialize Gin router
router := gin.Default()
// Enable CORS
router.Use(cors.Default())
// Routes
router.GET("/getCyclists", getCyclistsHandler)
router.GET("/getBikes", getBikesHandler)
router.GET("/getAddresses", getAddressesHandler)
router.POST("/ask", askHandler)
// Start server
port := ":8080"
fmt.Printf("Starting server on port %s...\n", port)
log.Fatal(router.Run(port))
}
func initDB() {
// Credentials
dbUser := os.Getenv("AI_SQL_USER")
if dbUser == "" {
log.Fatal("SQL_USER environment variable not set")
}
dbPass := os.Getenv("AI_SQL_PASS")
if dbPass == "" {
log.Fatal("SQL_PASS environment variable not set")
}
dsn := fmt.Sprintf("%s:%s@tcp(localhost:3306)/cyclists_db", dbUser, dbPass)
// Open a database connection
var err error
db, err = sql.Open("mysql", dsn)
if err != nil {
log.Fatal("Unable to open connection: ", err)
}
// Verify the connection
if err := db.Ping(); err != nil {
log.Fatal("Connection Failed: ", err)
}
fmt.Println("Successfully connected to the database!")
}
func initOpenAIClient() {
// Credentials
AIKEY := os.Getenv("OPENAI_KEY")
if AIKEY == "" {
log.Fatal("OPENAI_KEY environment variable not set")
}
// Initialize OpenAI client
client1 = openai.NewClient(AIKEY)
client2 = openai.NewClient(AIKEY)
}
func getCyclistsHandler(c *gin.Context) {
cyclists := getCyclists()
c.JSON(http.StatusOK, cyclists)
}
func getBikesHandler(c *gin.Context) {
bikes := getBikes()
c.JSON(http.StatusOK, bikes)
}
func getAddressesHandler(c *gin.Context) {
addresses := getAddresses()
c.JSON(http.StatusOK, addresses)
}
func askHandler(c *gin.Context) {
var requestBody struct {
Text string `json:"text"`
}
if err := c.ShouldBindJSON(&requestBody); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
question := requestBody.Text
query := askChatbotSQL(client1, question, background)
sqlReturn, _ := executeSQL(query)
humanReturn := askChatbot(client2, question, sqlReturn)
response := humanReturn + " \n\n SQL:\n" + query + "\n\n " + sqlReturn
c.JSON(http.StatusOK, gin.H{"response": response})
}
func executeSQL(query string) (string, error) {
var result string
rows, err := db.Query(query)
if err != nil {
return "", err
}
defer rows.Close()
// Get column names
columns, err := rows.Columns()
if err != nil {
return "", err
}
// Make a slice for the values
values := make([]sql.RawBytes, len(columns))
scanArgs := make([]interface{}, len(values))
for i := range values {
scanArgs[i] = &values[i]
}
// Iterate over the rows
for rows.Next() {
if err := rows.Scan(scanArgs...); err != nil {
return "", err
}
// print the values from 'values' slice
var row string
for i, col := range values {
if col == nil {
row += fmt.Sprintf("%s: NULL, ", columns[i])
} else {
row += fmt.Sprintf("%s: %s, ", columns[i], col)
}
}
// Remove trailing comma and space
row = row[:len(row)-2] + "\n"
result += row
}
if err := rows.Err(); err != nil {
return "", err
}
return result, nil
}
func getCyclists() []structs.Cyclist {
var cyclists []structs.Cyclist
rows, err := db.Query("SELECT * FROM cyclists")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
// Iterate over the rows
for rows.Next() {
var cyclist structs.Cyclist
if err := rows.Scan(&cyclist.ID, &cyclist.Name, &cyclist.PhoneNumber, &cyclist.SkillLevel, &cyclist.AddressID, &cyclist.BikeID); err != nil {
log.Fatal(err)
}
cyclists = append(cyclists, cyclist)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
return cyclists
}
func getBikes() []structs.Bike {
var bikes []structs.Bike
rows, err := db.Query("SELECT * FROM bikes")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
// Iterate over the rows
for rows.Next() {
var bike structs.Bike
if err := rows.Scan(&bike.ID, &bike.Nickname, &bike.SerialNumber, &bike.Year, &bike.Model, &bike.Make, &bike.Mileage); err != nil {
log.Fatal(err)
}
bikes = append(bikes, bike)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
return bikes
}
func getAddresses() []structs.Address {
var addresses []structs.Address
rows, err := db.Query("SELECT * FROM addresses")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
// Iterate over the rows
for rows.Next() {
var address structs.Address
if err := rows.Scan(&address.ID, &address.Street, &address.Zip, &address.State); err != nil {
log.Fatal(err)
}
addresses = append(addresses, address)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
return addresses
}
func askChatbotSQL(client *openai.Client, question string, background string) string {
question = background + question
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: question,
},
},
},
)
if err != nil {
fmt.Printf("ChatCompletion error: %v\n", err)
return ""
}
return resp.Choices[0].Message.Content
}
func askChatbot(client *openai.Client, question string, response string) string {
question = "The following question or request was made in regards to an sql database: " + question + " The response to this question or request is: " + response + " Give me the human readable version of this response without telling me that you are."
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: question,
},
},
},
)
if err != nil {
fmt.Printf("ChatCompletion error: %v\n", err)
return ""
}
return resp.Choices[0].Message.Content
}