-
Notifications
You must be signed in to change notification settings - Fork 110
/
handler.go
156 lines (140 loc) · 3.72 KB
/
handler.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
package api
import (
"fmt"
"io"
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/generative-ai-go/genai"
openai "github.com/sashabaranov/go-openai"
"google.golang.org/api/option"
"github.com/zhu327/gemini-openai-proxy/pkg/adapter"
)
func IndexHandler(c *gin.Context) {
c.JSON(http.StatusMisdirectedRequest, gin.H{
"message": "Welcome to the OpenAI API! Documentation is available at https://platform.openai.com/docs/api-reference",
})
}
func ModelListHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"object": "list",
"data": []any{
openai.Model{
CreatedAt: 1686935002,
ID: openai.GPT3Dot5Turbo,
Object: "model",
OwnedBy: "openai",
},
openai.Model{
CreatedAt: 1686935002,
ID: openai.GPT4,
Object: "model",
OwnedBy: "openai",
},
openai.Model{
CreatedAt: 1686935002,
ID: openai.GPT4TurboPreview,
Object: "model",
OwnedBy: "openai",
},
openai.Model{
CreatedAt: 1686935002,
ID: openai.GPT4VisionPreview,
Object: "model",
OwnedBy: "openai",
},
},
})
}
func ModelRetrieveHandler(c *gin.Context) {
model := c.Param("model")
c.JSON(http.StatusOK, openai.Model{
CreatedAt: 1686935002,
ID: model,
Object: "model",
OwnedBy: "openai",
})
}
func ChatProxyHandler(c *gin.Context) {
// Retrieve the Authorization header value
authorizationHeader := c.GetHeader("Authorization")
// Declare a variable to store the OPENAI_API_KEY
var openaiAPIKey string
// Use fmt.Sscanf to extract the Bearer token
_, err := fmt.Sscanf(authorizationHeader, "Bearer %s", &openaiAPIKey)
if err != nil {
c.JSON(http.StatusBadRequest, openai.APIError{
Code: http.StatusBadRequest,
Message: err.Error(),
})
return
}
req := &adapter.ChatCompletionRequest{}
// Bind the JSON data from the request to the struct
if err := c.ShouldBindJSON(req); err != nil {
c.JSON(http.StatusBadRequest, openai.APIError{
Code: http.StatusBadRequest,
Message: err.Error(),
})
return
}
messages, err := req.ToGenaiMessages()
if err != nil {
c.JSON(http.StatusBadRequest, openai.APIError{
Code: http.StatusBadRequest,
Message: err.Error(),
})
return
}
ctx := c.Request.Context()
client, err := genai.NewClient(ctx, option.WithAPIKey(openaiAPIKey))
if err != nil {
log.Printf("new genai client error %v\n", err)
c.JSON(http.StatusBadRequest, openai.APIError{
Code: http.StatusBadRequest,
Message: err.Error(),
})
return
}
defer client.Close()
model := req.ToGenaiModel()
gemini := adapter.NewGeminiAdapter(client, model)
if !req.Stream {
resp, err := gemini.GenerateContent(ctx, req, messages)
if err != nil {
log.Printf("genai generate content error %v\n", err)
c.JSON(http.StatusBadRequest, openai.APIError{
Code: http.StatusBadRequest,
Message: err.Error(),
})
return
}
c.JSON(http.StatusOK, resp)
return
}
dataChan, err := gemini.GenerateStreamContent(ctx, req, messages)
if err != nil {
log.Printf("genai generate content error %v\n", err)
c.JSON(http.StatusBadRequest, openai.APIError{
Code: http.StatusBadRequest,
Message: err.Error(),
})
return
}
setEventStreamHeaders(c)
c.Stream(func(w io.Writer) bool {
if data, ok := <-dataChan; ok {
c.Render(-1, adapter.Event{Data: "data: " + data})
return true
}
c.Render(-1, adapter.Event{Data: "data: [DONE]"})
return false
})
}
func setEventStreamHeaders(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "text/event-stream")
c.Writer.Header().Set("Cache-Control", "no-cache")
c.Writer.Header().Set("Connection", "keep-alive")
c.Writer.Header().Set("Transfer-Encoding", "chunked")
c.Writer.Header().Set("X-Accel-Buffering", "no")
}