-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
341 lines (302 loc) · 9.51 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Package chatgpt
// Author: Evsikov Artem
package chatgpt
import (
"bytes"
"database/sql"
"einstein-server/database"
"einstein-server/tools"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"sort"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/rs/zerolog"
)
const ApiToken = ""
const SummarizePrompt = "Summarize following text: \n %s"
var logger = zerolog.New(os.Stdout).Level(zerolog.DebugLevel)
type ChatCompletionResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
} `json:"usage"`
Choices []struct {
Message ChatMessageWithToolRequest `json:"message"`
FinishReason string `json:"finish_reason"`
Index int `json:"index"`
} `json:"choices"`
}
type ToolCalls struct {
ID string `json:"id"`
Type string `json:"type"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
}
type ChatMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type ChatMessageWithToolResponse struct {
Role string `json:"role"`
Content string `json:"content"`
ToolCallId string `json:"tool_call_id"`
}
type ChatMessageWithToolRequest struct {
Role string `json:"role"`
Content string `json:"content"`
ToolCalls []ToolCalls `json:"tool_calls"`
}
type Tool struct {
Type string `json:"type"`
Function Function `json:"function"`
}
type FunctionParameter struct {
Type string `json:"type"`
Properties interface{} `json:"properties"`
Required []string `json:"required"`
}
type Function struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters FunctionParameter `json:"parameters"`
}
type ChatCompletionRequest struct {
Model string `json:"model"`
Messages []interface{} `json:"messages"`
Tools []map[string]interface{} `json:"tools"`
ToolChoice string `json:"tool_choice,omitempty"`
Temperature float32 `json:"temperature"`
}
type ErrorString struct {
s string
}
func (e *ErrorString) Error() string {
return e.s
}
func NewError(text string) error {
return &ErrorString{text}
}
func SaveUsageStatistics(amountIn int, amountOut int, messagesAmount int, userId uuid.UUID) {
var us database.UsageStatistics
db := database.GetConnection()
defer db.Close()
err := db.Get(&us, database.SqlUsageStatisticsSelectByUserAndDate, userId, time.Now())
if err != nil {
if err == sql.ErrNoRows {
us = database.UsageStatistics{ID: uuid.New(), UserId: userId, Date: time.Now(), TokensIn: 0, TokensOut: 0}
db.NamedExec(database.SqlUsageStatisticsInsert, us)
} else {
logger.Error().Msgf("Error while selecting usage_statistics: %s \n", err)
}
}
us.TokensIn += amountIn
us.TokensOut += amountOut
us.MessagesAmount += messagesAmount
db.NamedExec(database.SqlUsageStatisticsUpdate, us)
db.Close()
}
/*
Make context that follow conditions
- If inContextForce = true, then mandatory include to context
- If inContext = false, then exclude from context
- If context capacity exceeded, then include mandatory messages first. Clip messages by timestamp (clip the oldest ones) to fit context.
*/
func ClipContentToContextWindow(messages []database.Message) []database.Message {
var totalContent string
var contextMessages []database.Message
for i := len(messages) - 1; i >= 0; i-- {
if !messages[i].InContextByForce {
continue
}
contextMessages = append(contextMessages, messages[i])
if len(messages[i].SummarizedContent.String) > 0 {
totalContent += messages[i].SummarizedContent.String
} else {
totalContent += messages[i].Content
}
}
for i := len(messages) - 1; i >= 0; i-- {
if !messages[i].InContext {
continue
}
contextMessages = append(contextMessages, messages[i])
if len(messages[i].SummarizedContent.String) > 0 {
totalContent += messages[i].SummarizedContent.String
} else {
totalContent += messages[i].Content
}
// for worst case where 1 symbol = 1 token make filter + leave something on tools and technical info (e.g. file ids)
if len(totalContent) > 10000 {
break
}
}
sort.SliceStable(contextMessages, func(i, j int) bool {
return contextMessages[i].CreatedAt.Before(contextMessages[j].CreatedAt)
})
return contextMessages
}
func ChatRequest(messages []interface{}, tools []map[string]interface{}, userId uuid.UUID) (ChatCompletionResponse, error) {
const url = "https://api.openai.com/v1/chat/completions"
var toolChoice string
if len(tools) > 0 {
toolChoice = "auto"
}
jsonBody := ChatCompletionRequest{
Model: "gpt-3.5-turbo-16k",
Messages: messages,
Tools: tools,
ToolChoice: toolChoice,
Temperature: 0.4,
}
b, err := json.Marshal(jsonBody)
logger.Debug().Msg(string(b))
if err != nil {
logger.Err(err)
return ChatCompletionResponse{}, err
}
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(b))
if err != nil {
logger.Err(err)
return ChatCompletionResponse{}, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", ApiToken))
client := http.Client{
Timeout: 180 * time.Second,
}
res, err := client.Do(req)
if err != nil {
logger.Err(err)
return ChatCompletionResponse{}, err
}
var data ChatCompletionResponse
if res.StatusCode != 200 {
buf := bytes.NewBuffer(nil)
if _, err := io.Copy(buf, res.Body); err != nil {
buf = bytes.NewBuffer([]byte("Error while reading body"))
}
logger.Printf("%d %+v", res.StatusCode, buf.String())
return ChatCompletionResponse{}, fmt.Errorf("Unseccessful status code: %d", res.StatusCode)
}
err = json.NewDecoder(res.Body).Decode(&data)
if err != nil {
return ChatCompletionResponse{}, err
}
SaveUsageStatistics(data.Usage.PromptTokens, data.Usage.CompletionTokens, 0, userId)
return data, nil
}
func InjectDataIntoMessages(clippedMessages []database.Message) []interface{} {
var content string
var messagesGPT []interface{}
for _, v := range clippedMessages {
if len(v.SummarizedContent.String) > 0 {
content = v.SummarizedContent.String
} else {
content = v.Content
}
if v.Attachments != nil && len(v.Attachments) > 0 {
for _, f := range v.Attachments {
content = fmt.Sprintf("My file has id: %s \n", f.ID) + content
}
}
if v.Role == database.RoleUser {
content = fmt.Sprintf("My user id: %s \n", v.UserId) + content
content = fmt.Sprintf("Message has been sent at: %s \n", v.CreatedAt.Format(time.RFC1123)) + content
}
messagesGPT = append(messagesGPT, ChatMessage{Role: v.Role, Content: content})
}
return messagesGPT
}
func RequestCompletion(user database.User, db *sqlx.DB, recursionMessages *[]interface{}) (ChatCompletionResponse, error) {
var err error
var response ChatCompletionResponse
var messagesGPT []interface{}
// Prepare messages
if recursionMessages == nil {
messages, err := database.SelectMessageByUser(user)
if err != nil {
return response, err
}
clippedMessages := ClipContentToContextWindow(messages)
if len(clippedMessages) == 0 {
return ChatCompletionResponse{}, NewError("Message too long. Please shorten it. 😅")
}
messagesGPT = InjectDataIntoMessages(clippedMessages)
} else {
messagesGPT = *recursionMessages
}
// Prepare tools
var availableToolsGPT []map[string]interface{}
for _, v := range tools.AvailableTools {
availableToolsGPT = append(availableToolsGPT, tools.GetFunctionParamsByName(v))
}
// Make request
response, err = ChatRequest(messagesGPT, availableToolsGPT, user.ID.UUID)
if err != nil {
return response, err
}
if len(response.Choices) == 0 {
return response, fmt.Errorf("Zero choices returned")
}
// Condition for recursion
if len(response.Choices[0].Message.ToolCalls) > 0 {
messagesGPT = append(messagesGPT, response.Choices[0].Message)
for _, call := range response.Choices[0].Message.ToolCalls {
callable := tools.GetFunctionByName(call.Function.Name)
logger.Printf("Calling tool with name: %s; params: %s;\n", call.Function.Name, call.Function.Arguments)
result, err := callable(call.Function.Arguments)
if err != nil {
logger.Err(err).Msg("")
}
messagesGPT = append(messagesGPT, ChatMessageWithToolResponse{
ToolCallId: call.ID,
Role: database.RoleTool,
Content: result,
})
}
response, err = RequestCompletion(user, db, &messagesGPT)
if err != nil {
return response, err
}
if len(response.Choices) == 0 {
return response, fmt.Errorf("Error requesting chatgpt: %+v", response)
}
} else {
answer := database.Message{
ID: uuid.New(),
UserId: user.ID.UUID,
Content: response.Choices[0].Message.Content,
Role: database.RoleAssistant,
}
if len(answer.Content) > 200 {
var sumPrompt []interface{}
sumPrompt = append(sumPrompt, ChatMessage{
Content: fmt.Sprintf(SummarizePrompt, answer.Content),
Role: database.RoleUser,
})
sum, _ := ChatRequest(sumPrompt, nil, user.ID.UUID)
if len(sum.Choices) > 0 {
answer.SummarizedContent = sql.NullString{String: sum.Choices[0].Message.Content, Valid: true}
}
}
_, err = db.NamedExec(database.SqlMessageInsert, answer)
if err != nil {
return response, err
}
logger.Debug().Msgf("Got new message %+v \n", response)
SaveUsageStatistics(0, 0, 1, user.ID.UUID)
}
return response, nil
}