This repository has been archived by the owner on Aug 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 379
/
Copy pathhandlers.go
191 lines (178 loc) · 4.98 KB
/
handlers.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
package main
import (
"bufio"
"encoding/json"
"freechatgpt/internal/chatgpt"
"freechatgpt/internal/tokens"
typings "freechatgpt/internal/typings"
"freechatgpt/internal/typings/responses"
"io"
"os"
"strings"
"github.com/gin-gonic/gin"
)
func passwordHandler(c *gin.Context) {
// Get the password from the request (json) and update the password
type password_struct struct {
Password string `json:"password"`
}
var password password_struct
err := c.BindJSON(&password)
if err != nil {
c.String(400, "password not provided")
return
}
ADMIN_PASSWORD = password.Password
// Set environment variable
os.Setenv("ADMIN_PASSWORD", ADMIN_PASSWORD)
c.String(200, "password updated")
}
func tokensHandler(c *gin.Context) {
// Get the request_tokens from the request (json) and update the request_tokens
var request_tokens []string
err := c.BindJSON(&request_tokens)
if err != nil {
c.String(400, "tokens not provided")
return
}
ACCESS_TOKENS = tokens.NewAccessToken(request_tokens)
c.String(200, "tokens updated")
}
func optionsHandler(c *gin.Context) {
// Set headers for CORS
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "POST")
c.Header("Access-Control-Allow-Headers", "*")
c.JSON(200, gin.H{
"message": "pong",
})
}
func nightmare(c *gin.Context) {
var original_request typings.APIRequest
err := c.BindJSON(&original_request)
if err != nil {
c.JSON(400, gin.H{
"error": "invalid request",
"details": err.Error(),
})
return
}
// Throw error when model contains gpt-4
if strings.Contains(original_request.Model, "gpt-4") {
c.JSON(400, gin.H{
"error": "gpt-4 is not supported",
})
return
}
// Convert the chat request to a ChatGPT request
translated_request := chatgpt.ConvertAPIRequest(original_request)
// c.JSON(200, chatgpt_request)
// authHeader := c.GetHeader("Authorization")
token := ACCESS_TOKENS.GetToken()
// if authHeader != "" {
// customAccessToken := strings.Replace(authHeader, "Bearer ", "", 1)
// if customAccessToken != "" {
// token = customAccessToken
// println("customAccessToken set:" + customAccessToken)
// }
// }
response, err := chatgpt.SendRequest(translated_request, token)
if err != nil {
c.JSON(500, gin.H{
"error": "error sending request",
})
return
}
defer response.Body.Close()
if response.StatusCode != 200 {
// Try read response body as JSON
var error_response map[string]interface{}
err = json.NewDecoder(response.Body).Decode(&error_response)
if err != nil {
c.JSON(500, gin.H{"error": gin.H{
"message": "Unknown error",
"type": "internal_server_error",
"param": nil,
"code": "500",
}})
return
}
c.JSON(response.StatusCode, gin.H{"error": gin.H{
"message": error_response["detail"],
"type": response.Status,
"param": nil,
"code": "error",
}})
return
}
// Create a bufio.Reader from the response body
reader := bufio.NewReader(response.Body)
var fulltext string
// Read the response byte by byte until a newline character is encountered
if original_request.Stream {
// Response content type is text/event-stream
c.Header("Content-Type", "text/event-stream")
} else {
// Response content type is application/json
c.Header("Content-Type", "application/json")
}
for {
line, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
return
}
if len(line) < 6 {
continue
}
// Remove "data: " from the beginning of the line
line = line[6:]
// Check if line starts with [DONE]
if !strings.HasPrefix(line, "[DONE]") {
// Parse the line as JSON
var original_response responses.Data
err = json.Unmarshal([]byte(line), &original_response)
if err != nil {
continue
}
if original_response.Error != nil {
return
}
if original_response.Message.Content.Parts[0] == "" || original_response.Message.Author.Role != "assistant" {
continue
}
if original_response.Message.Metadata.Timestamp == "absolute" {
continue
}
tmp_fulltext := original_response.Message.Content.Parts[0]
original_response.Message.Content.Parts[0] = strings.ReplaceAll(original_response.Message.Content.Parts[0], fulltext, "")
translated_response := responses.NewChatCompletionChunk(original_response.Message.Content.Parts[0])
// Stream the response to the client
response_string := translated_response.String()
if original_request.Stream {
_, err = c.Writer.WriteString("data: " + string(response_string) + "\n\n")
if err != nil {
return
}
}
// Flush the response writer buffer to ensure that the client receives each line as it's written
c.Writer.Flush()
fulltext = tmp_fulltext
} else {
if !original_request.Stream {
full_response := responses.NewChatCompletion(fulltext)
if err != nil {
return
}
c.JSON(200, full_response)
return
}
final_line := responses.StopChunk()
c.Writer.WriteString("data: " + final_line.String() + "\n\n")
c.String(200, "data: [DONE]\n\n")
return
}
}
}