Compare commits
13 Commits
995eea9d67
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
495f32610b
|
|||
|
45bba95f5d
|
|||
|
75ff8fbc2e
|
|||
| 66758e0008 | |||
|
40fc2067a5
|
|||
|
1a56101ca8
|
|||
| e373e3ac63 | |||
| 24a2e609f8 | |||
| e442303847 | |||
| 8b95fbb5da | |||
| 34aa4babc4 | |||
| e6ff1f5ca4 | |||
|
6b6f245e45
|
@@ -1,3 +1,4 @@
|
|||||||
openai-api-route
|
openai-api-route
|
||||||
db.sqlite
|
db.sqlite
|
||||||
/config.yaml
|
/config.yaml
|
||||||
|
/.*
|
||||||
|
|||||||
52
.gitlab-ci.yml
Normal file
52
.gitlab-ci.yml
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
# To contribute improvements to CI/CD templates, please follow the Development guide at:
|
||||||
|
# https://docs.gitlab.com/ee/development/cicd/templates.html
|
||||||
|
# This specific template is located at:
|
||||||
|
# https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Docker.gitlab-ci.yml
|
||||||
|
|
||||||
|
# Build a Docker image with CI/CD and push to the GitLab registry.
|
||||||
|
# Docker-in-Docker documentation: https://docs.gitlab.com/ee/ci/docker/using_docker_build.html
|
||||||
|
#
|
||||||
|
# This template uses one generic job with conditional builds
|
||||||
|
# for the default branch and all other (MR) branches.
|
||||||
|
|
||||||
|
docker-build:
|
||||||
|
# Use the official docker image.
|
||||||
|
image: docker:cli
|
||||||
|
stage: build
|
||||||
|
services:
|
||||||
|
- docker:dind
|
||||||
|
variables:
|
||||||
|
CI_REGISTRY: registry.waykey.net:7999
|
||||||
|
CI_REGISTRY_IMAGE: $CI_REGISTRY/spiderman/datamining/openai-api-route
|
||||||
|
DOCKER_IMAGE_NAME: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
|
||||||
|
before_script:
|
||||||
|
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
|
||||||
|
# All branches are tagged with $DOCKER_IMAGE_NAME (defaults to commit ref slug)
|
||||||
|
# Default branch is also tagged with `latest`
|
||||||
|
script:
|
||||||
|
- docker build --pull -t "$DOCKER_IMAGE_NAME" .
|
||||||
|
- docker push "$DOCKER_IMAGE_NAME"
|
||||||
|
- |
|
||||||
|
if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then
|
||||||
|
docker tag "$DOCKER_IMAGE_NAME" "$CI_REGISTRY_IMAGE:latest"
|
||||||
|
docker push "$CI_REGISTRY_IMAGE:latest"
|
||||||
|
fi
|
||||||
|
# Run this job in a branch where a Dockerfile exists
|
||||||
|
rules:
|
||||||
|
- if: $CI_COMMIT_BRANCH
|
||||||
|
exists:
|
||||||
|
- Dockerfile
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
environment: production
|
||||||
|
image: kroniak/ssh-client
|
||||||
|
stage: deploy
|
||||||
|
before_script:
|
||||||
|
- chmod 600 $CI_SSH_PRIVATE_KEY
|
||||||
|
script:
|
||||||
|
- ssh -o StrictHostKeyChecking=no -i $CI_SSH_PRIVATE_KEY root@192.168.1.13 "cd /mnt/data/srv/openai-api-route && podman-compose pull && podman-compose down && podman-compose up -d"
|
||||||
|
rules:
|
||||||
|
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
|
||||||
|
exists:
|
||||||
|
- Dockerfile
|
||||||
|
|
||||||
24
README.md
24
README.md
@@ -83,6 +83,30 @@ upstreams:
|
|||||||
|
|
||||||
如此,只有携带 `woshimima` 验证头的用户可以使用该上游。
|
如此,只有携带 `woshimima` 验证头的用户可以使用该上游。
|
||||||
|
|
||||||
|
### 复杂配置示例
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
|
||||||
|
# 默认验证头
|
||||||
|
authorization: woshimima
|
||||||
|
|
||||||
|
upstreams:
|
||||||
|
|
||||||
|
# 允许所有人使用的文字转语音
|
||||||
|
- sk: xxx
|
||||||
|
endpoint: http://localhost:5000/v1
|
||||||
|
noauth: true
|
||||||
|
allow:
|
||||||
|
- /v1/audio/transcriptions
|
||||||
|
|
||||||
|
# guest 专用的 gpt-3.5-turbo-0125 模型
|
||||||
|
- sk:
|
||||||
|
endpoint: https://api.xxx.local/v1
|
||||||
|
authorization: guest
|
||||||
|
allow:
|
||||||
|
- gpt-3.5-turbo-0125
|
||||||
|
```
|
||||||
|
|
||||||
## 部署方法
|
## 部署方法
|
||||||
|
|
||||||
有两种推荐的部署方法:
|
有两种推荐的部署方法:
|
||||||
|
|||||||
26
cors.go
26
cors.go
@@ -1,28 +1,20 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"log"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
// this function is aborded
|
|
||||||
func corsMiddleware() gin.HandlerFunc {
|
|
||||||
return func(c *gin.Context) {
|
|
||||||
// set cors header
|
|
||||||
header := c.Request.Header
|
|
||||||
if header.Get("Access-Control-Allow-Origin") == "" {
|
|
||||||
c.Header("Access-Control-Allow-Origin", "*")
|
|
||||||
}
|
|
||||||
if header.Get("Access-Control-Allow-Methods") == "" {
|
|
||||||
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH")
|
|
||||||
}
|
|
||||||
if header.Get("Access-Control-Allow-Headers") == "" {
|
|
||||||
c.Header("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func sendCORSHeaders(c *gin.Context) {
|
func sendCORSHeaders(c *gin.Context) {
|
||||||
|
log.Println("sendCORSHeaders")
|
||||||
|
if c.Writer.Header().Get("Access-Control-Allow-Origin") == "" {
|
||||||
c.Header("Access-Control-Allow-Origin", "*")
|
c.Header("Access-Control-Allow-Origin", "*")
|
||||||
|
}
|
||||||
|
if c.Writer.Header().Get("Access-Control-Allow-Methods") == "" {
|
||||||
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH")
|
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH")
|
||||||
|
}
|
||||||
|
if c.Writer.Header().Get("Access-Control-Allow-Headers") == "" {
|
||||||
c.Header("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type")
|
c.Header("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
89
main.go
89
main.go
@@ -1,9 +1,11 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@@ -13,6 +15,7 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/penglongli/gin-metrics/ginmetrics"
|
"github.com/penglongli/gin-metrics/ginmetrics"
|
||||||
"gorm.io/driver/postgres"
|
"gorm.io/driver/postgres"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
"gorm.io/driver/sqlite"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
@@ -86,7 +89,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
errText := strings.Join(c.Errors.Errors(), "\n")
|
errText := strings.Join(c.Errors.Errors(), "\n")
|
||||||
c.JSON(-1, gin.H{
|
c.JSON(-1, gin.H{
|
||||||
"error": errText,
|
"openai-api-route error": errText,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -100,6 +103,7 @@ func main() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
engine.POST("/v1/*any", func(c *gin.Context) {
|
engine.POST("/v1/*any", func(c *gin.Context) {
|
||||||
|
var err error
|
||||||
hostname, _ := os.Hostname()
|
hostname, _ := os.Hostname()
|
||||||
if config.Hostname != "" {
|
if config.Hostname != "" {
|
||||||
hostname = config.Hostname
|
hostname = config.Hostname
|
||||||
@@ -122,31 +126,54 @@ func main() {
|
|||||||
}
|
}
|
||||||
log.Println("Received authorization '" + authorization + "'")
|
log.Println("Received authorization '" + authorization + "'")
|
||||||
|
|
||||||
for index, upstream := range config.Upstreams {
|
availUpstreams := make([]OPENAI_UPSTREAM, 0)
|
||||||
|
for _, upstream := range config.Upstreams {
|
||||||
if upstream.SK == "" {
|
if upstream.SK == "" {
|
||||||
sendCORSHeaders(c)
|
sendCORSHeaders(c)
|
||||||
c.AbortWithError(500, fmt.Errorf("[processRequest.begin]: invaild SK (secret key) '%s'", upstream.SK))
|
c.AbortWithError(500, fmt.Errorf("[processRequest.begin]: invaild SK (secret key) %s", upstream.SK))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !*noauth && !upstream.Noauth {
|
||||||
|
if checkAuth(authorization, upstream.Authorization) != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
availUpstreams = append(availUpstreams, upstream)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(availUpstreams) == 0 {
|
||||||
|
sendCORSHeaders(c)
|
||||||
|
c.AbortWithError(500, fmt.Errorf("[processRequest.begin]: no available upstream for your token"))
|
||||||
|
}
|
||||||
|
log.Println("[processRequest.begin]: availUpstreams", len(availUpstreams))
|
||||||
|
|
||||||
|
bufIO := bytes.NewBuffer(make([]byte, 0, 1024))
|
||||||
|
wrapedBody := false
|
||||||
|
|
||||||
|
for index, _upstream := range availUpstreams {
|
||||||
|
|
||||||
|
// copy
|
||||||
|
upstream := _upstream
|
||||||
|
record.UpstreamEndpoint = upstream.Endpoint
|
||||||
|
record.UpstreamSK = upstream.SK
|
||||||
|
|
||||||
shouldResponse := index == len(config.Upstreams)-1
|
shouldResponse := index == len(config.Upstreams)-1
|
||||||
|
|
||||||
// check authorization header
|
if len(availUpstreams) == 1 {
|
||||||
if !*noauth && !upstream.Noauth {
|
// [todo] copy problem
|
||||||
if checkAuth(authorization, upstream.Authorization) != nil {
|
upstream.Timeout = 120
|
||||||
if shouldResponse {
|
|
||||||
c.Header("Content-Type", "application/json")
|
|
||||||
sendCORSHeaders(c)
|
|
||||||
c.AbortWithError(403, fmt.Errorf("[processRequest.begin]: wrong authorization header"))
|
|
||||||
}
|
|
||||||
log.Println("[auth] Authorization header check failed for", upstream.SK, authorization)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
log.Println("[auth] Authorization header check pass for", upstream.SK, authorization)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(config.Upstreams) == 1 {
|
// buffer for incoming request
|
||||||
upstream.Timeout = 120
|
if !wrapedBody {
|
||||||
|
log.Println("[processRequest.begin]: wrap request body")
|
||||||
|
c.Request.Body = io.NopCloser(io.TeeReader(c.Request.Body, bufIO))
|
||||||
|
wrapedBody = true
|
||||||
|
} else {
|
||||||
|
log.Println("[processRequest.begin]: reuse request body")
|
||||||
|
c.Request.Body = io.NopCloser(bytes.NewReader(bufIO.Bytes()))
|
||||||
}
|
}
|
||||||
|
|
||||||
if upstream.Type == "replicate" {
|
if upstream.Type == "replicate" {
|
||||||
@@ -157,7 +184,11 @@ func main() {
|
|||||||
err = fmt.Errorf("[processRequest.begin]: unsupported upstream type '%s'", upstream.Type)
|
err = fmt.Errorf("[processRequest.begin]: unsupported upstream type '%s'", upstream.Type)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err == nil {
|
||||||
|
log.Println("[processRequest.done]: Success from upstream", upstream.Endpoint)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
if err == http.ErrAbortHandler {
|
if err == http.ErrAbortHandler {
|
||||||
abortErr := "[processRequest.done]: AbortHandler, client's connection lost?, no upstream will try, stop here"
|
abortErr := "[processRequest.done]: AbortHandler, client's connection lost?, no upstream will try, stop here"
|
||||||
log.Println(abortErr)
|
log.Println(abortErr)
|
||||||
@@ -165,11 +196,27 @@ func main() {
|
|||||||
record.Status = 500
|
record.Status = 500
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
log.Println("[processRequest.done]: Error from upstream", upstream.Endpoint, "should retry", err)
|
log.Println("[processRequest.done]: Error from upstream", upstream.Endpoint, "should retry", err, "should response:", shouldResponse)
|
||||||
continue
|
|
||||||
|
// error process, break
|
||||||
|
if shouldResponse {
|
||||||
|
c.Header("Content-Type", "application/json")
|
||||||
|
sendCORSHeaders(c)
|
||||||
|
c.AbortWithError(500, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
break
|
// parse and record request body
|
||||||
|
requestBodyBytes := bufIO.Bytes()
|
||||||
|
if len(requestBodyBytes) < 1024*1024 && (strings.HasPrefix(c.Request.Header.Get("Content-Type"), "application/json") ||
|
||||||
|
strings.HasPrefix(c.Request.Header.Get("Content-Type"), "text/")) {
|
||||||
|
record.Body = string(requestBodyBytes)
|
||||||
|
}
|
||||||
|
requestBody, err := ParseRequestBody(requestBodyBytes)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("[processRequest.done]: Error to parse request body:", err)
|
||||||
|
} else {
|
||||||
|
record.Model = requestBody.Model
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Println("[final]: Record result:", record.Status, record.Response)
|
log.Println("[final]: Record result:", record.Status, record.Response)
|
||||||
|
|||||||
274
process.go
274
process.go
@@ -8,22 +8,14 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httputil"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"golang.org/x/net/context"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func processRequest(c *gin.Context, upstream *OPENAI_UPSTREAM, record *Record, shouldResponse bool) error {
|
func processRequest(c *gin.Context, upstream *OPENAI_UPSTREAM, record *Record, shouldResponse bool) error {
|
||||||
var errCtx []error
|
|
||||||
|
|
||||||
record.UpstreamEndpoint = upstream.Endpoint
|
|
||||||
record.UpstreamSK = upstream.SK
|
|
||||||
record.Response = ""
|
|
||||||
// [TODO] record request body
|
|
||||||
|
|
||||||
// reverse proxy
|
// reverse proxy
|
||||||
remote, err := url.Parse(upstream.Endpoint)
|
remote, err := url.Parse(upstream.Endpoint)
|
||||||
@@ -32,232 +24,102 @@ func processRequest(c *gin.Context, upstream *OPENAI_UPSTREAM, record *Record, s
|
|||||||
}
|
}
|
||||||
|
|
||||||
path := strings.TrimPrefix(c.Request.URL.Path, "/v1")
|
path := strings.TrimPrefix(c.Request.URL.Path, "/v1")
|
||||||
// recoognize whisper url
|
|
||||||
remote.Path = upstream.URL.Path + path
|
remote.Path = upstream.URL.Path + path
|
||||||
log.Println("[proxy.begin]:", remote)
|
log.Println("[proxy.begin]:", remote)
|
||||||
log.Println("[proxy.begin]: shouldResposne:", shouldResponse)
|
log.Println("[proxy.begin]: shouldResposne:", shouldResponse)
|
||||||
|
|
||||||
haveResponse := false
|
client := &http.Client{}
|
||||||
|
request := &http.Request{}
|
||||||
|
request.ContentLength = c.Request.ContentLength
|
||||||
|
request.Method = c.Request.Method
|
||||||
|
request.URL = remote
|
||||||
|
|
||||||
proxy := httputil.NewSingleHostReverseProxy(remote)
|
// process header
|
||||||
proxy.Director = nil
|
if upstream.KeepHeader {
|
||||||
var inBody []byte
|
request.Header = c.Request.Header
|
||||||
proxy.Rewrite = func(proxyRequest *httputil.ProxyRequest) {
|
} else {
|
||||||
|
request.Header = http.Header{}
|
||||||
in := proxyRequest.In
|
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
|
||||||
proxyRequest.Out = proxyRequest.Out.WithContext(ctx)
|
|
||||||
|
|
||||||
out := proxyRequest.Out
|
|
||||||
|
|
||||||
// read request body
|
|
||||||
inBody, err = io.ReadAll(in.Body)
|
|
||||||
if err != nil {
|
|
||||||
errCtx = append(errCtx, errors.New("[proxy.rewrite]: reverse proxy middleware failed to read request body "+err.Error()))
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// record chat message from user
|
// process header authorization
|
||||||
requestBody, requestBodyOK := ParseRequestBody(inBody)
|
|
||||||
// record if parse success
|
|
||||||
if requestBodyOK == nil && requestBody.Model != "" {
|
|
||||||
record.Model = requestBody.Model
|
|
||||||
record.Body = string(inBody)
|
|
||||||
}
|
|
||||||
|
|
||||||
// check allow list
|
|
||||||
if len(upstream.Allow) > 0 {
|
|
||||||
isAllow := false
|
|
||||||
for _, allow := range upstream.Allow {
|
|
||||||
if allow == record.Model {
|
|
||||||
isAllow = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !isAllow {
|
|
||||||
errCtx = append(errCtx, errors.New("[proxy.rewrite]: model '"+record.Model+"' not allowed"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// check block list
|
|
||||||
if len(upstream.Deny) > 0 {
|
|
||||||
for _, deny := range upstream.Deny {
|
|
||||||
if deny == record.Model {
|
|
||||||
errCtx = append(errCtx, errors.New("[proxy.rewrite]: model '"+record.Model+"' denied"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// set timeout, default is 60 second
|
|
||||||
timeout := time.Duration(upstream.Timeout) * time.Second
|
|
||||||
if requestBodyOK == nil && requestBody.Stream {
|
|
||||||
timeout = time.Duration(upstream.StreamTimeout) * time.Second
|
|
||||||
}
|
|
||||||
|
|
||||||
// timeout out request
|
|
||||||
go func() {
|
|
||||||
time.Sleep(timeout)
|
|
||||||
if !haveResponse {
|
|
||||||
log.Println("[proxy.timeout]: Timeout upstream", upstream.Endpoint, timeout)
|
|
||||||
errTimeout := errors.New("[proxy.timeout]: Timeout upstream")
|
|
||||||
errCtx = append(errCtx, errTimeout)
|
|
||||||
if shouldResponse {
|
|
||||||
c.Header("Content-Type", "application/json")
|
|
||||||
sendCORSHeaders(c)
|
|
||||||
c.AbortWithError(502, errTimeout)
|
|
||||||
}
|
|
||||||
cancel()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
out.Body = io.NopCloser(bytes.NewReader(inBody))
|
|
||||||
|
|
||||||
out.Host = remote.Host
|
|
||||||
out.URL.Scheme = remote.Scheme
|
|
||||||
out.URL.Host = remote.Host
|
|
||||||
|
|
||||||
if !upstream.KeepHeader {
|
|
||||||
out.Header = http.Header{}
|
|
||||||
}
|
|
||||||
out.Header.Set("Host", remote.Host)
|
|
||||||
if upstream.SK == "asis" {
|
if upstream.SK == "asis" {
|
||||||
out.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
|
request.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
|
||||||
} else {
|
} else {
|
||||||
out.Header.Set("Authorization", "Bearer "+upstream.SK)
|
request.Header.Set("Authorization", "Bearer "+upstream.SK)
|
||||||
}
|
}
|
||||||
out.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
|
request.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
|
||||||
}
|
request.Header.Set("Host", remote.Host)
|
||||||
var buf bytes.Buffer
|
request.Header.Set("Content-Length", c.Request.Header.Get("Content-Length"))
|
||||||
var contentType string
|
|
||||||
proxy.ModifyResponse = func(r *http.Response) error {
|
|
||||||
haveResponse = true
|
|
||||||
record.ResponseTime = time.Since(record.CreatedAt)
|
|
||||||
record.Status = r.StatusCode
|
|
||||||
|
|
||||||
// handle reverse proxy cors header if upstream do not set that
|
request.Body = c.Request.Body
|
||||||
if r.Header.Get("Access-Control-Allow-Origin") == "" {
|
|
||||||
c.Header("Access-Control-Allow-Origin", "*")
|
|
||||||
}
|
|
||||||
if r.Header.Get("Access-Control-Allow-Methods") == "" {
|
|
||||||
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH")
|
|
||||||
}
|
|
||||||
if r.Header.Get("Access-Control-Allow-Headers") == "" {
|
|
||||||
c.Header("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type")
|
|
||||||
}
|
|
||||||
|
|
||||||
if !shouldResponse && r.StatusCode != 200 {
|
resp, err := client.Do(request)
|
||||||
log.Println("[proxy.modifyResponse]: upstream return not 200 and should not response", r.StatusCode)
|
|
||||||
return errors.New("upstream return not 200 and should not response")
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.StatusCode != 200 {
|
|
||||||
body, err := io.ReadAll(r.Body)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errRet := errors.New("[proxy.modifyResponse]: failed to read response from upstream " + err.Error())
|
body := []byte{}
|
||||||
return errRet
|
if resp != nil && resp.Body != nil {
|
||||||
|
body, _ = io.ReadAll(resp.Body)
|
||||||
}
|
}
|
||||||
errRet := fmt.Errorf("[error]: openai-api-route upstream return '%s' with '%s'", r.Status, string(body))
|
return errors.New(err.Error() + " " + string(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
record.Status = resp.StatusCode
|
||||||
|
|
||||||
|
if resp.StatusCode != 200 {
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
record.Status = resp.StatusCode
|
||||||
|
errRet := fmt.Errorf("[error]: openai-api-route upstream return '%s' with '%s'", resp.Status, string(body))
|
||||||
log.Println(errRet)
|
log.Println(errRet)
|
||||||
record.Status = r.StatusCode
|
|
||||||
return errRet
|
return errRet
|
||||||
}
|
}
|
||||||
// count success
|
|
||||||
r.Body = io.NopCloser(io.TeeReader(r.Body, &buf))
|
// copy response header
|
||||||
contentType = r.Header.Get("content-type")
|
for k, v := range resp.Header {
|
||||||
return nil
|
c.Header(k, v[0])
|
||||||
}
|
}
|
||||||
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
|
|
||||||
haveResponse = true
|
|
||||||
record.ResponseTime = time.Since(record.CreatedAt)
|
|
||||||
log.Println("[proxy.errorHandler]", err, upstream.SK, upstream.Endpoint, errCtx)
|
|
||||||
|
|
||||||
errCtx = append(errCtx, err)
|
|
||||||
|
|
||||||
// abort to error handle
|
|
||||||
if shouldResponse {
|
|
||||||
c.Header("Content-Type", "application/json")
|
|
||||||
sendCORSHeaders(c)
|
sendCORSHeaders(c)
|
||||||
for _, err := range errCtx {
|
|
||||||
c.AbortWithError(502, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[proxy.errorHandler]: response is", r.Response)
|
respBodyBuffer := bytes.NewBuffer(make([]byte, 0, 4*1024))
|
||||||
|
respBodyTeeReader := io.TeeReader(resp.Body, respBodyBuffer)
|
||||||
|
record.ResponseTime = time.Since(record.CreatedAt)
|
||||||
|
io.Copy(c.Writer, respBodyTeeReader)
|
||||||
|
record.ElapsedTime = time.Since(record.CreatedAt)
|
||||||
|
|
||||||
if record.Status == 0 {
|
// parse and record response
|
||||||
record.Status = 502
|
if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
|
||||||
}
|
|
||||||
record.Response += "[proxy.ErrorHandler]: " + err.Error()
|
|
||||||
if r.Response != nil {
|
|
||||||
record.Status = r.Response.StatusCode
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
err = ServeHTTP(proxy, c.Writer, c.Request)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("[proxy.serve]: error from ServeHTTP:", err)
|
|
||||||
// panic means client has abort the http connection
|
|
||||||
// since the connection is lost, we return
|
|
||||||
// and the reverse process should not try the next upsteam
|
|
||||||
return http.ErrAbortHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
// return context error
|
|
||||||
if len(errCtx) > 0 {
|
|
||||||
log.Println("[proxy.serve]: error from ServeHTTP:", errCtx)
|
|
||||||
// fix inrequest body
|
|
||||||
c.Request.Body = io.NopCloser(bytes.NewReader(inBody))
|
|
||||||
return errCtx[len(errCtx)-1]
|
|
||||||
}
|
|
||||||
|
|
||||||
resp, err := io.ReadAll(io.NopCloser(&buf))
|
|
||||||
if err != nil {
|
|
||||||
record.Response = "failed to read response from upstream " + err.Error()
|
|
||||||
log.Println(record.Response)
|
|
||||||
} else {
|
|
||||||
|
|
||||||
// record response
|
|
||||||
// stream mode
|
|
||||||
if strings.HasPrefix(contentType, "text/event-stream") {
|
|
||||||
for _, line := range strings.Split(string(resp), "\n") {
|
|
||||||
chunk := StreamModeChunk{}
|
|
||||||
line = strings.TrimPrefix(line, "data:")
|
|
||||||
line = strings.TrimSpace(line)
|
|
||||||
if line == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
err := json.Unmarshal([]byte(line), &chunk)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("[proxy.parseChunkError]:", err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(chunk.Choices) == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
record.Response += chunk.Choices[0].Delta.Content
|
|
||||||
}
|
|
||||||
} else if strings.HasPrefix(contentType, "text") {
|
|
||||||
record.Response = string(resp)
|
|
||||||
} else if strings.HasPrefix(contentType, "application/json") {
|
|
||||||
// fallback record response
|
|
||||||
if len(resp) < 1024*128 {
|
|
||||||
record.Response = string(resp)
|
|
||||||
}
|
|
||||||
var fetchResp FetchModeResponse
|
var fetchResp FetchModeResponse
|
||||||
err := json.Unmarshal(resp, &fetchResp)
|
err := json.NewDecoder(respBodyBuffer).Decode(&fetchResp)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
if len(fetchResp.Choices) > 0 {
|
if len(fetchResp.Choices) > 0 {
|
||||||
record.Response = fetchResp.Choices[0].Message.Content
|
record.Response = fetchResp.Choices[0].Message.Content
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
|
||||||
log.Println("[proxy.record]: Unknown content type", contentType)
|
lines := bytes.Split(respBodyBuffer.Bytes(), []byte("\n"))
|
||||||
|
for _, line := range lines {
|
||||||
|
line = bytes.TrimSpace(line)
|
||||||
|
line = bytes.TrimPrefix(line, []byte("data:"))
|
||||||
|
line = bytes.TrimSpace(line)
|
||||||
|
if len(line) == 0 {
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
|
chunk := StreamModeChunk{}
|
||||||
|
err = json.Unmarshal(line, &chunk)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("[proxy.parseChunkError]:", err)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if len(chunk.Choices) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
record.Response += chunk.Choices[0].Delta.Content
|
||||||
|
}
|
||||||
|
} else if strings.HasPrefix(resp.Header.Get("Content-Type"), "text") {
|
||||||
|
body, _ := io.ReadAll(respBodyBuffer)
|
||||||
|
record.Response = string(body)
|
||||||
|
} else {
|
||||||
|
log.Println("[proxy.record]: Unknown content type", resp.Header.Get("Content-Type"))
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
Reference in New Issue
Block a user