-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
295 lines (249 loc) · 6.96 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 (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
"github.com/confluentinc/confluent-kafka-go/kafka"
"github.com/joho/godotenv"
)
//Generic log struct
type LogRequest struct {
AccountID string `json:"account_id"`
UserID string `json:"user"`
Path string `json:"path"`
Method string `json:"method"`
Body string `json:"body"`
SentAt int64 `json:"sent_at"`
}
type LogResponse struct {
ID string `json:"id"`
AccountID string `json:"account_id"`
UserID string `json:"user_id"`
Path string `json:"path"`
Method string `json:"method"`
Body string `json:"body"`
StatusCode int `json:"status_code"`
SentAt int64 `json:"sent_at"`
}
// Usage log struct
type LogUsage struct {
ID string `json:"id"`
AccountID string `json:"account_id"`
UserID string `json:"user_id"`
Model string `json:"model"`
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
CreatedTime int64 `json:"created_time"`
Latency int64 `json:"latency"`
}
type OpenAIResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Model string `json:"model"`
Choices []struct {
Message `json:"message"`
Index int `json:"index"`
FinishReason string `json:"finish_reason"`
} `json:"choices"`
Usage Usage `json:"usage"`
Created int64 `json:"created"`
}
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
}
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
Name string `json:"name"`
}
type Config struct {
logging bool
}
var (
Producer *kafka.Producer
producerError error
Port string
ConfigSettings Config
)
func init() {
// load .env file if local
if os.Getenv("ENV") != "production" {
err := godotenv.Load(".env")
if err != nil {
log.Fatal("Error loading .env file")
}
}
Port = getenv("PORT", "8080")
//connect to kafka
Producer, producerError = kafka.NewProducer(&kafka.ConfigMap{
"bootstrap.servers": os.Getenv("CLUSTER_BOOTSRTAP_SERVERS"),
"security.protocol": "SASL_SSL",
"sasl.mechanisms": "PLAIN",
"sasl.username": os.Getenv("CLUSTER_API_KEY"),
"sasl.password": os.Getenv("CLUSTER_API_SECRET"),
"acks": "all"})
if producerError != nil {
log.Fatal("Error connecting to kafka")
} else {
fmt.Println("Connected to kafka")
}
ConfigSettings = Config{
logging: true,
}
}
func makeTimestamp() int64 {
return time.Now().UnixMilli()
}
func extractMessages(body map[string]interface{}) []Message {
// Extract the messages part
messagesInterface, ok := body["messages"].([]interface{})
if !ok {
log.Fatal("Error: messages is not an array")
}
// Marshal the messages interface back into JSON
messagesJSON, err := json.Marshal(messagesInterface)
if err != nil {
log.Fatalf("Error occurred during re-marshaling. Error: %s", err.Error())
}
// Unmarshal the JSON into a slice of Message structs
var messages []Message
err = json.Unmarshal(messagesJSON, &messages)
if err != nil {
log.Fatalf("Error occurred during unmarshaling of messages. Error: %s", err.Error())
}
return messages
}
func getenv(key, fallback string) string {
value := os.Getenv(key)
if len(value) == 0 {
return fallback
}
return value
}
func handleRequestAndRedirect(res http.ResponseWriter, req *http.Request) {
fmt.Println("Received request for", req.URL.Path)
startTimestamp := makeTimestamp()
url := "https://api.openai.com/v1/"
// Read the body
reqBodyBytes, readErr := io.ReadAll(req.Body)
if readErr != nil {
fmt.Println(readErr)
}
_ = req.Body.Close() // must close
req.Body = io.NopCloser(bytes.NewBuffer(reqBodyBytes))
// Create a request to the destination server
proxyReq, err := http.NewRequest(req.Method, url+req.URL.Path, req.Body)
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
var userAPIKey string
// Copy the headers from the original request to the new request
for header, values := range req.Header {
for _, value := range values {
if header == "X-Api-Key" {
userAPIKey = value
fmt.Println("User:", userAPIKey)
} else if header == "Accept-Encoding" {
// ignore
} else {
proxyReq.Header.Add(header, value)
}
}
}
// proxyReq.Header.Add("Content-Type", "application/json")
var body map[string]interface{}
json.Unmarshal(reqBodyBytes, &body)
userID, ok := body["user"].(string)
if !ok {
userID = ""
}
if ConfigSettings.logging {
// log request
logRequest := LogRequest{
AccountID: userAPIKey,
UserID: userID,
Path: req.URL.Path,
Method: req.Method,
Body: string(reqBodyBytes),
SentAt: time.Now().Unix(),
}
logRequestBytes, _ := json.Marshal(logRequest)
SendLog(userAPIKey, logRequestBytes, "requests")
}
// Send the request to the destination server
client := &http.Client{}
resp, err := client.Do(proxyReq)
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
// Copy the headers from the response to the original response
for header, values := range resp.Header {
for _, value := range values {
res.Header().Add(header, value)
}
}
res.WriteHeader(resp.StatusCode)
// Read the res body
respBodyBytes, readRespErr := io.ReadAll(resp.Body)
if readRespErr != nil {
fmt.Println(readRespErr)
}
defer resp.Body.Close() // must close
resp.Body = io.NopCloser(bytes.NewBuffer(respBodyBytes))
io.Copy(res, resp.Body)
fmt.Println("Returning response with status", resp.StatusCode)
var resBody OpenAIResponse
json.Unmarshal(respBodyBytes, &resBody)
// log response
if ConfigSettings.logging {
logResponse := LogResponse{
ID: resBody.ID,
AccountID: userAPIKey,
UserID: userID,
Path: req.URL.Path,
Method: req.Method,
Body: string(respBodyBytes),
StatusCode: resp.StatusCode,
SentAt: time.Now().Unix(),
}
logResponseBytes, _ := json.Marshal(logResponse)
SendLog(userAPIKey, logResponseBytes, "responses")
}
// log usage
if (req.URL.Path == "/chat/completions") && req.Method == "POST" {
// var messages []Message = extractMessages(body)
var inputTokens int
var outputTokens int
usage := resBody.Usage
inputTokens = usage.PromptTokens
outputTokens = usage.CompletionTokens
endTimestamp := makeTimestamp()
logUsage := LogUsage{
ID: resBody.ID,
AccountID: userAPIKey,
UserID: userID,
Model: resBody.Model,
InputTokens: inputTokens,
OutputTokens: outputTokens,
CreatedTime: resBody.Created,
Latency: endTimestamp - startTimestamp,
}
logUsageBytes, _ := json.Marshal(logUsage)
SendLog(userAPIKey, logUsageBytes, "usage")
}
}
func main() {
// Start the server
fmt.Printf("Starting the server on port %s", Port)
http.HandleFunc("/", handleRequestAndRedirect)
log.Fatal(http.ListenAndServe(":"+Port, nil))
}