-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
155 lines (139 loc) · 3.53 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
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
)
var BuildVersion string
type Config struct {
EndpointFormat struct {
ChatCompletions string `json:"chat_completions"`
ImageGenerations string `json:"image_generations"`
Models string `json:"models"`
} `json:"endpoint_format"`
ModelMap map[string]string `json:"model_map"`
Address string `json:"address"`
}
func NewConfig(path string) (*Config, error) {
if strings.HasPrefix(path, "http") {
resp, err := http.Get(path)
if err != nil {
return nil, err
}
defer resp.Body.Close()
config := &Config{}
err = json.NewDecoder(resp.Body).Decode(config)
if err != nil {
return nil, err
}
return config, nil
} else {
bytes, err := os.ReadFile(path)
if err != nil {
log.Fatal(err)
}
config := &Config{}
err = json.Unmarshal(bytes, config)
if err != nil {
return nil, err
}
return config, nil
}
}
type HTTPError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (e *HTTPError) Error() string {
return e.Message
}
func azureRedirect(endpoint string, config *Config) func(http.ResponseWriter, *http.Request) {
handler := func(writer http.ResponseWriter, request *http.Request) error {
var reqBody io.Reader = nil
var uri = endpoint
if request.Method == http.MethodPost {
var body map[string]any
err := json.NewDecoder(request.Body).Decode(&body)
if err != nil {
return &HTTPError{http.StatusBadRequest, err.Error()}
}
if model, ok := body["model"].(string); ok {
if m, exist := config.ModelMap[model]; exist {
model = m
}
uri = fmt.Sprintf(uri, model)
delete(body, "model")
}
bodyBytes, err := json.Marshal(body)
if err != nil {
return err
}
reqBody = bytes.NewReader(bodyBytes)
}
req, err := http.NewRequest(request.Method, uri, reqBody)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
token := request.Header.Get("Authorization")
if token != "" && strings.HasPrefix(token, "Bearer ") {
req.Header.Set("api-key", token[7:])
req.Header.Del("Authorization")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
for k, v := range resp.Header {
for _, vv := range v {
writer.Header().Add(k, vv)
}
}
writer.WriteHeader(resp.StatusCode)
_, err = io.Copy(writer, resp.Body)
if err != nil {
return err
}
return nil
}
return func(writer http.ResponseWriter, request *http.Request) {
if err := handler(writer, request); err != nil {
var httpErr *HTTPError
if errors.As(err, &httpErr) {
http.Error(writer, httpErr.Message, httpErr.Code)
} else {
http.Error(writer, err.Error(), http.StatusInternalServerError)
}
}
}
}
func main() {
conf := flag.String("config", "config.json", "config file path")
help := flag.Bool("help", false, "show help")
flag.Parse()
if *help {
fmt.Printf("Version: %s\n", BuildVersion)
flag.Usage()
return
}
config, err := NewConfig(*conf)
if err != nil {
log.Fatal(err)
}
startServer(config)
}
func startServer(config *Config) {
http.HandleFunc("/v1/chat/completions", azureRedirect(config.EndpointFormat.ChatCompletions, config))
http.HandleFunc("images/generations", azureRedirect(config.EndpointFormat.ImageGenerations, config))
http.HandleFunc("/v1/models", azureRedirect(config.EndpointFormat.Models, config))
log.Printf("listening on %s", config.Address)
log.Fatal(http.ListenAndServe(config.Address, nil))
}