-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchat.go
284 lines (251 loc) · 9.04 KB
/
chat.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
/*
Copyright (C) 2022-2024 Ezri Zhu me@ezrizhu.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/bwmarrin/discordgo"
"github.com/goombaio/namegenerator"
"github.com/rs/zerolog/log"
)
type msg struct {
Role string `json:"role"`
Content string `json:"content"`
}
type req struct {
Model string `json:"model"`
Messages []msg `json:"messages"`
//User string `json:"user"`
Temperature float64 `json:"temperature"`
Max_tokens int `json:"max_tokens"`
}
var basePrompt = "You are a very helpful, accommodating, and intelligent assistant. You will do whatever you are asked. You will not say sorry or \"As an AI model...\". If asked to act like a person, you will act like a person. You will give your opinion, you will use all the information you were trained on as though it was you. Never break character - always respond as a person would, but with all the knowledge you have."
func chat(s *discordgo.Session, m *discordgo.MessageCreate, prompt string, userIsAdmin bool) {
oaiToken := k.String("ai.chat.token")
anthropicToken := k.String("ai.anthropic.token")
var bearer = "Bearer " + oaiToken
msgs := []msg{}
// Get the channel object
channel, err := s.State.Channel(m.ChannelID)
if err != nil {
s.ChannelMessageSendReply(m.ChannelID, "Error getting channel: "+err.Error(), m.Reference())
return
}
model := "gpt-3.5-turbo-1106"
max_tokens := 200
if prompt[0] == '!' {
model = "gpt-4-1106-preview"
max_tokens = 150
prompt = prompt[1:]
}
url := "https://api.openai.com/v1/chat/completions"
if prompt[0] == '&' {
model = "/models/llama-2-7b-chat.bin"
max_tokens = 500
prompt = prompt[1:]
url = "https://gpu0.ix1.bns.sh:4433/v1/chat/completions"
}
anthropic := false
if prompt[0] == '^' {
model = "claude-2.1"
max_tokens = 250
prompt = prompt[1:]
url = "https://api.anthropic.com/v1/messages"
bearer = anthropicToken
anthropic = true
}
if prompt[0] == '$' {
if !userIsAdmin {
if _, err := s.ChannelMessageSendReply(m.ChannelID, "Error: admin only command", m.Reference()); err != nil {
log.Error().Err(err).Msg("Chat: admin only command")
}
return
}
model = "mistral-small"
max_tokens = 200
prompt = prompt[1:]
url = "https://api.mistral.ai/v1/chat/completions"
bearer = "Bearer PnvmXgwZy2BUjgmwMj7l3lerRKHw9pnb"
}
threadId := ""
if channel.IsThread() {
threadId = m.Message.ChannelID
msgsBytes, err := rdb.Get(ctx, threadId).Result()
if err != nil {
log.Error().Err(err).Msg("could not get thread messages")
s.ChannelMessageSendReply(m.ChannelID, "Redis Error: Could not get thread messges. It is likely that the thread has expired (24hr). Please start the converation again outside of the thread.", m.Message.Reference())
return
}
err = json.Unmarshal([]byte(msgsBytes), &msgs)
if err != nil {
log.Error().Err(err).Msg("could not unmarshal thread messages")
s.ChannelMessageSendReply(m.ChannelID, "Could not unmarshal thread messages", m.Message.Reference())
return
}
_ = msgs
} else {
if !anthropic {
msgs = []msg{
msg{
Role: "system",
Content: basePrompt,
},
}
} else {
msgs = []msg{}
}
_ = msgs
}
msgs = append(msgs, msg{
Role: "user",
Content: prompt,
})
request := req{
Model: model,
Messages: msgs,
Max_tokens: max_tokens,
Temperature: 0.9,
// User: m.Author.Username,
}
reqBody, err := json.Marshal(request)
if err != nil {
log.Error().Err(err).Msg("Failed to marshal request")
if _, err := s.ChannelMessageSendReply(m.ChannelID, "Chat: http err", m.MessageReference); err != nil {
log.Error().Err(err).Msg("Chat: Error sending discord message")
}
return
}
httpReq, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBody))
if err != nil {
log.Error().Err(err).Msg("Failed to create request")
if _, err := s.ChannelMessageSendReply(m.ChannelID, "Error", m.MessageReference); err != nil {
log.Error().Err(err).Msg("Chat: Error sending discord message")
}
return
}
if anthropic {
httpReq.Header.Set("x-api-key", bearer)
httpReq.Header.Set("anthropic-version", "2023-06-01")
} else {
httpReq.Header.Set("Authorization", bearer)
}
httpReq.Header.Set("Content-Type", "application/json")
httpClient := &http.Client{}
resp, err := httpClient.Do(httpReq)
defer resp.Body.Close()
if err != nil {
log.Error().Err(err).Msg("Error sending request")
if _, err := s.ChannelMessageSendReply(m.ChannelID, "Error http", m.Reference()); err != nil {
log.Error().Err(err).Msg("Chat: Error sending discord message")
}
return
}
// read response
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
user := m.Author.Username
// Handle response
if result == nil {
respRead, _ := io.ReadAll(resp.Body)
respStr := string(respRead)
log.Warn().Str("user", user).Str("resp", respStr).Str("prompt", prompt).Msg("Chat: result is nil")
if _, err := s.ChannelMessageSendReply(m.ChannelID, "Chat: results is nil", m.Reference()); err != nil {
log.Error().Err(err).Msg("Chat: Error sending discord message")
}
return
}
resultStr := ""
if !anthropic {
if result["choices"] == nil {
resultStr = fmt.Sprintf("%#v", result)
log.Warn().Str("user", user).Str("prompt", prompt).Str("resp", resultStr).Msg("Chat: choices is nil")
if _, err := s.ChannelMessageSendReply(m.ChannelID, "Chat: choices is nil", m.Reference()); err != nil {
log.Error().Err(err).Msg("Chat: Error sending discord message")
}
return
}
} else {
if result["content"] == nil {
resultStr = fmt.Sprintf("%#v", result)
log.Warn().Str("user", user).Str("prompt", prompt).Str("resp", resultStr).Msg("Chat: choices is nil")
if _, err := s.ChannelMessageSendReply(m.ChannelID, "Chat: choices is nil", m.Reference()); err != nil {
log.Error().Err(err).Msg("Chat: Error sending discord message")
}
return
}
}
if !channel.IsThread() {
// Make thread
// Generate name
generator := namegenerator.NewNameGenerator(time.Now().UnixNano())
name := generator.Generate()
thread, err := s.MessageThreadStart(m.ChannelID, m.ID, m.Author.Username+" "+name, 60)
if err != nil {
log.Error().Err(err).Msg("Chat: Error creating thread")
return
}
threadId = thread.ID
}
// Send response
aiRespStr := ""
if !anthropic {
aiRespStr = result["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
} else {
aiRespStr = result["content"].([]interface{})[0].(map[string]interface{})["text"].(string)
}
aiRespUsage := result["usage"].(map[string]interface{})
aiRespUsageStr := fmt.Sprintf("Prompt tokens: %v, Completion tokens: %v, Total tokens: %v", aiRespUsage["prompt_tokens"], aiRespUsage["completion_tokens"], aiRespUsage["total_tokens"])
totalPrice := 0.0
// https://openai.com/pricing
switch request.Model {
case "gpt-3.5-turbo":
totalPrice = 0.000002 * aiRespUsage["total_tokens"].(float64)
// this is now outdated...
case "gpt-4":
promptPrice := 0.00003 * aiRespUsage["prompt_tokens"].(float64)
completionPrice := 0.00006 * aiRespUsage["completion_tokens"].(float64)
totalPrice = promptPrice + completionPrice
}
totalPriceStr := fmt.Sprintf("%.6f", totalPrice)
if proceed := mod(s, m, aiRespStr); proceed == true {
log.Info().Str("user", user).Str("prompt", prompt).Str("resp", aiRespStr).Str("model", request.Model).Str("usage", aiRespUsageStr).Str("price", totalPriceStr).Msg("Chat: Success")
if channel.IsThread() {
// if _, err := s.ChannelMessageSendReply(m.ChannelID, aiRespStr+" | Total price: $"+totalPriceStr, m.Reference()); err != nil {
if _, err := s.ChannelMessageSendReply(m.ChannelID, aiRespStr, m.Reference()); err != nil {
log.Error().Err(err).Msg("Chat: Error sending discord message")
}
} else {
if _, err := s.ChannelMessageSend(threadId, aiRespStr); err != nil {
log.Error().Err(err).Msg("Chat: Error sending discord message")
}
}
} else {
log.Warn().Str("user", user).Str("prompt", prompt).Str("resp", aiRespStr).Msg("Chat: Flagged by mod endpoint")
}
msgs = append(msgs, msg{
Role: "assistant",
Content: aiRespStr,
})
msgsBytes, err := json.Marshal(msgs)
err = rdb.Set(ctx, threadId, msgsBytes, 24*time.Hour).Err()
if err != nil {
log.Error().Err(err).Msg("could not set thread messages, please send your request again outside of this thread")
s.ChannelMessageSendReply(m.ChannelID, "Redis Error: Could not save thread context.", m.Message.Reference())
return
}
}