forked from Dentrax/falco-gpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
276 lines (243 loc) · 6.83 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
// SPDX-License-Identifier: MIT
// Copyright (c) Furkan Türkal
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
"github.com/Dentrax/falco-gpt/pkg/model"
"github.com/Dentrax/falco-gpt/pkg/openai"
"github.com/Dentrax/falco-gpt/pkg/slack"
"github.com/avast/retry-go"
"golang.org/x/time/rate"
natsserver "github.com/nats-io/nats-server/v2/server"
natsgo "github.com/nats-io/nats.go"
)
var (
natsClient *natsgo.Conn
limiter *rate.Limiter
slackClient *slack.Client
openaiClient *openai.Client
minPriority string
ctx context.Context
older float64
)
func init() {
ctx = context.Background()
}
func main() {
flagPort := flag.Int("port", 8080, "port to listen on")
flagQPH := flag.Int("qph", 10, "max queries per HOUR to OpenAI")
flagMinPriority := flag.String("min-priority", "warning", "minimum priority to analyse")
flagGPTModel := flag.String("model", "gpt-3.5-turbo", "Backend AI model")
flatIgnoreOlder := flag.Int("ignore-older", 1, "Ignore events in queue older than X hour(s)")
flagTemplateFile := flag.String("template-file", "", "path custom template file to use for the ChatGPT")
flag.Parse()
minPriority = *flagMinPriority
flagChannel := os.Getenv("SLACK_CHANNEL")
if flagChannel == "" {
log.Fatal("Please specify slack channel")
}
slackToken := os.Getenv("SLACK_TOKEN")
if slackToken == "" {
log.Fatal("SLACK_TOKEN is not set")
}
slackClient, _ = slack.NewClient(flagChannel, slackToken)
openaiToken := os.Getenv("OPENAI_TOKEN")
if openaiToken == "" {
log.Fatal("OPENAI_TOKEN is not set")
}
older = float64(*flatIgnoreOlder)
// client is the OpenAI client for the ChatGPT.
var err error
openaiClient, err = openai.NewClient(openaiToken, *flagGPTModel, *flagTemplateFile)
if err != nil {
log.Fatal(err)
}
// Set up a rate limiter in order to not exceed the API rate limit.
limiter = rate.NewLimiter(rate.Every(time.Hour), *flagQPH)
// Initialize nats server with options
ns, err := natsserver.NewServer(&natsserver.Options{})
if err != nil {
log.Fatal(err)
}
defer ns.Shutdown()
go ns.Start()
if !ns.ReadyForConnections(5 * time.Second) {
log.Fatal("NATS server not ready")
}
natsClient, err = natsgo.Connect(ns.ClientURL())
if err != nil {
log.Fatal(err)
}
defer natsClient.Close()
go subscribeSlackQueue()
go subscribeGPTQueue()
http.HandleFunc("/", handler())
log.Printf("Listening on port %d", *flagPort)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *flagPort), nil))
}
func handler() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if r.Body != nil {
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
w.Write([]byte(err.Error()))
return
}
if body == nil {
w.WriteHeader(http.StatusUnprocessableEntity)
w.Write([]byte("empty body"))
return
}
var payload model.FalcoPayload
if err := json.Unmarshal(body, &payload); err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
w.Write([]byte(err.Error()))
return
}
payload.Raw = string(body)
if payload.Source == "" {
payload.Source = "syscalls"
}
// Put the payload onto the inflight queue for processing
// if the priority is high enough.
if model.ToPriority(payload.Priority) >= model.ToPriority(minPriority) {
msg, err := json.Marshal(payload)
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
w.Write([]byte(err.Error()))
return
}
if err := do(func() error {
return natsClient.Publish("slack", msg)
}); err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusCreated)
return
}
}
w.WriteHeader(http.StatusNoContent)
}
}
// processGPTQueue is a goroutine that processes entries from the queue for ChatGPT.
func subscribeGPTQueue() {
natsClient.Subscribe("gpt", func(msg *natsgo.Msg) {
// Print message data
// Wait for the rate limiter.
var payload model.FalcoPayload
if err := json.Unmarshal(msg.Data, &payload); err != nil {
log.Println(err)
return
}
if time.Since(payload.Time).Hours() > older {
return
}
if err := limiter.Wait(ctx); err != nil {
return
}
// Print the payload to stdout.
truncatedPayload := payload
truncatedPayload.Raw = ""
truncatedPayload.ThreadTS = ""
truncatedPayload.Channel = ""
p, _ := json.Marshal(truncatedPayload)
log.Printf("processing payload: %#v\n", string(p))
if response, err := analyze(ctx, payload.Raw); err != nil {
log.Println(fmt.Errorf("error process: %w", err))
return
} else {
if err := do(func() error {
_, err := slackClient.SendMessage(response, nil, payload.ThreadTS)
if err != nil {
return err
}
return nil
}); err != nil {
log.Println(fmt.Errorf("slack error: %w", err))
return
}
}
})
}
// processSlackQueue is a goroutine that processes entries from the queue for Slack.
func subscribeSlackQueue() {
natsClient.Subscribe("slack", func(msg *natsgo.Msg) {
var payload model.FalcoPayload
if err := json.Unmarshal(msg.Data, &payload); err != nil {
log.Println(fmt.Errorf("error process: %w", err))
return
}
attachment := slack.NewAttachment(payload)
if err := do(func() error {
var err error
payload.ThreadTS, err = slackClient.SendMessage(payload.Output, attachment, "")
if err != nil {
return err
}
return nil
}); err != nil {
log.Println(fmt.Errorf("slack error: %w", err))
return
}
p, err := json.Marshal(payload)
if err != nil {
log.Println(fmt.Errorf("error process: %w", err))
return
}
if err := do(func() error {
return natsClient.Publish("gpt", p)
}); err != nil {
log.Println(fmt.Errorf("nats error: %w", err))
return
}
})
}
// analyze analyzes the given payload with ChatGPT and posts the response to Slack.
func analyze(ctx context.Context, prompt string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
var response string
if err := do(func() error {
var err error
response, err = openaiClient.GetCompletion(ctx, prompt)
if err != nil {
return err
}
return nil
}); err != nil {
return "", fmt.Errorf("get completion: %w", err)
}
return response, nil
}
// do is a wrapper around retry.Do that retry the given function.
func do(doer func() error) error {
const maxRetries = 3
if err := retry.Do(
doer,
retry.Attempts(maxRetries),
retry.DelayType(retry.BackOffDelay),
retry.Delay(10*time.Second),
retry.OnRetry(func(n uint, err error) {
log.Println("retrying after error:", err)
}),
); err != nil {
return fmt.Errorf("do failed after %d retries: %w", maxRetries, err)
}
return nil
}