Skip to content

Commit

Permalink
[Fix] 🐛 OpenAI API Bug
Browse files Browse the repository at this point in the history
  • Loading branch information
Harry-zklcdc committed Jan 14, 2024
1 parent 7d289b8 commit c578652
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 35 deletions.
136 changes: 104 additions & 32 deletions api/v1/openai.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,25 @@ package v1

import (
"adams549659584/go-proxy-bingai/api"
"adams549659584/go-proxy-bingai/api/helper"
"adams549659584/go-proxy-bingai/common"
"encoding/json"
"io"
"log"
"math/rand"
"net/http"
"os"
"strings"
"time"

binglib "github.com/Harry-zklcdc/bing-lib"
"github.com/Harry-zklcdc/bing-lib/lib/hex"
"github.com/Harry-zklcdc/bing-lib/lib/request"
)

var (
apikey = os.Getenv("APIKEY")

globalChat = binglib.NewChat("")
globalImage = binglib.NewImage("")
)

var STOPFLAG = "stop"
Expand All @@ -31,53 +34,55 @@ func ChatHandler(w http.ResponseWriter, r *http.Request) {
if apikey != "" {
if r.Header.Get("Authorization") != "Bearer "+apikey {
w.WriteHeader(http.StatusUnauthorized)
log.Println(r.RemoteAddr, r.Method, r.URL, "401")
return
}
}

chat := globalChat.Clone()

cookie := r.Header.Get("Cookie")
if cookie == "" {
if len(common.USER_TOKEN_LIST) > 0 {
seed := time.Now().UnixNano()
rng := rand.New(rand.NewSource(seed))
cookie = common.USER_TOKEN_LIST[rng.Intn(len(common.USER_TOKEN_LIST))]
chat.SetCookies(cookie)
} else {
if common.BypassServer != "" {
resp, err := api.Bypass(common.BypassServer, cookie, "")
if err != nil {
cookie = resp.Result.Cookies
}
}
cookie = chat.GetCookies()
}
}
chat.SetCookies(cookie)

resqB, err := io.ReadAll(r.Body)
if err != nil {
helper.CommonResult(w, http.StatusInternalServerError, err.Error(), nil)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}

var resq chatRequest
json.Unmarshal(resqB, &resq)

if resq.Model != binglib.BALANCED && resq.Model != binglib.BALANCED_OFFLINE && resq.Model != binglib.CREATIVE && resq.Model != binglib.CREATIVE_OFFLINE && resq.Model != binglib.PRECISE && resq.Model != binglib.PRECISE_OFFLINE {
helper.CommonResult(w, http.StatusBadRequest, "Invalid model", nil)
w.WriteHeader(http.StatusBadRequest)
return
}
chat := binglib.NewChat(cookie)

if common.BingBaseUrl != "" {
chat.SetBingBaseUrl(strings.ReplaceAll(strings.ReplaceAll(common.BingBaseUrl, "http://", ""), "https://", ""))
}
if common.SydneyBaseUrl != "" {
chat.SetSydneyBaseUrl(strings.ReplaceAll(strings.ReplaceAll(common.SydneyBaseUrl, "http://", ""), "https://", ""))
}

err = chat.NewConversation()
if err != nil {
helper.CommonResult(w, http.StatusInternalServerError, err.Error(), nil)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}

chat.SetStyle(resq.Model)
if common.BingBaseUrl != "" {
chat.SetBingBaseUrl(common.BingBaseUrl)
}
if common.SydneyBaseUrl != "" {
chat.SetSydneyBaseUrl(common.SydneyBaseUrl)
}

prompt, msg := chat.MsgComposer(resq.Messages)
resp := chatResponse{
Expand All @@ -96,8 +101,6 @@ func ChatHandler(w http.ResponseWriter, r *http.Request) {
}

w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
flusher.Flush()

text := make(chan string)
go chat.ChatStream(prompt, msg, text)
Expand All @@ -119,7 +122,8 @@ func ChatHandler(w http.ResponseWriter, r *http.Request) {
resp.Choices[0].FinishReason = &STOPFLAG
resData, err := json.Marshal(resp)
if err != nil {
helper.CommonResult(w, http.StatusInternalServerError, err.Error(), nil)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Write([]byte("data: "))
Expand All @@ -128,18 +132,31 @@ func ChatHandler(w http.ResponseWriter, r *http.Request) {
}
resData, err := json.Marshal(resp)
if err != nil {
helper.CommonResult(w, http.StatusInternalServerError, err.Error(), nil)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Write([]byte("data: "))
w.Write(resData)
w.Write([]byte("\n\n"))
flusher.Flush()

if tmp == "User needs to solve CAPTCHA to continue." {
if common.BypassServer != "" {
go func(cookie string) {
t, _ := getCookie(cookie)
if t != "" {
globalChat.SetCookies(t)
}
}(globalChat.GetCookies())
}
}
}
} else {
text, err := chat.Chat(prompt, msg)
if err != nil {
helper.CommonResult(w, http.StatusInternalServerError, err.Error(), nil)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}

Expand All @@ -154,45 +171,75 @@ func ChatHandler(w http.ResponseWriter, r *http.Request) {

resData, err := json.Marshal(resp)
if err != nil {
helper.CommonResult(w, http.StatusInternalServerError, err.Error(), nil)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
w.Write(resData)

if text == "User needs to solve CAPTCHA to continue." {
if common.BypassServer != "" {
go func(cookie string) {
t, _ := getCookie(cookie)
if t != "" {
globalChat.SetCookies(t)
}
}(globalChat.GetCookies())
}
}
}
}

func ImageHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
log.Println(r.RemoteAddr, r.Method, r.URL, "500")
return
}

if apikey != "" {
if r.Header.Get("Authorization") != "Bearer "+apikey {
w.WriteHeader(http.StatusUnauthorized)
log.Println(r.RemoteAddr, r.Method, r.URL, "401")
return
}
}

image := globalImage.Clone()

cookie := r.Header.Get("Cookie")
if cookie == "" {
if len(common.USER_TOKEN_LIST) > 0 {
seed := time.Now().UnixNano()
rng := rand.New(rand.NewSource(seed))
cookie = common.USER_TOKEN_LIST[rng.Intn(len(common.USER_TOKEN_LIST))]
} else {
if common.BypassServer != "" {
t, _ := getCookie(cookie)
if t != "" {
cookie = t
}
}
}
}
image.SetCookies(cookie)

resqB, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(r.RemoteAddr, r.Method, r.URL, "500")
w.Write([]byte(err.Error()))
return
}

var resq imageRequest
json.Unmarshal(resqB, &resq)

image := binglib.NewImage(cookie)
if common.BingBaseUrl != "" {
image.SetBingBaseUrl(strings.ReplaceAll(strings.ReplaceAll(common.BingBaseUrl, "http://", ""), "https://", ""))
}
imgs, _, err := image.Image(resq.Prompt)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(r.RemoteAddr, r.Method, r.URL, "500")
w.Write([]byte(err.Error()))
return
}

Expand All @@ -208,9 +255,34 @@ func ImageHandler(w http.ResponseWriter, r *http.Request) {
resData, err := json.Marshal(resp)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(r.RemoteAddr, r.Method, r.URL, "500")
w.Write([]byte(err.Error()))
return
}
w.Write(resData)
log.Println(r.RemoteAddr, r.Method, r.URL, "200")
}

func ModelsHandler(w http.ResponseWriter, r *http.Request) {

}

func getCookie(reqCookie string) (cookie string, err error) {
cookie = reqCookie
c := request.NewRequest()
res := c.SetUrl(common.BingBaseUrl+"/search?q=Bing+AI&showconv=1&FORM=hpcodx&ajaxhist=0&ajaxserp=0&cc=us").
SetHeader("User-Agent", common.User_Agent).
SetHeader("Cookie", cookie).Do()
headers := res.GetHeaders()
for k, v := range headers {
if strings.ToLower(k) == "set-cookie" {
for _, i := range v {
cookie += strings.Split(i, "; ")[0] + "; "
}
}
}
cookie = strings.TrimLeft(strings.Trim(cookie, "; "), "; ")
resp, err := api.Bypass(common.BypassServer, cookie, "local-gen-"+hex.NewUUID())
if err != nil {
return
}
return resp.Result.Cookies, nil
}
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ go 1.21.4
toolchain go1.21.6

require (
github.com/Harry-zklcdc/bing-lib v1.0.7
github.com/Harry-zklcdc/bing-lib v1.1.2
github.com/andybalholm/brotli v1.1.0
github.com/refraction-networking/utls v1.6.1
)

require (
github.com/cloudflare/circl v1.3.7 // indirect
github.com/google/uuid v1.5.0 // indirect
github.com/gorilla/websocket v1.5.1 // indirect
github.com/klauspost/compress v1.17.4 // indirect
github.com/quic-go/quic-go v0.40.1 // indirect
golang.org/x/crypto v0.18.0 // indirect
Expand Down
6 changes: 4 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
github.com/Harry-zklcdc/bing-lib v1.0.7 h1:AaehJwxhMs5OCLeZceEOooyLLCq446phRBWXtAK5j1w=
github.com/Harry-zklcdc/bing-lib v1.0.7/go.mod h1:S7hZEU4p2EDr7P+lMsjuJFPZfEt3AfYb82Rw60vpcFM=
github.com/Harry-zklcdc/bing-lib v1.1.2 h1:ttHDSUX72OHNs+Vaq1SLPm884DI2UaK7tQlUl5a1xZo=
github.com/Harry-zklcdc/bing-lib v1.1.2/go.mod h1:avLdR5UthMY/WhaDqptTXC55aPrkyRd3V4RD5yKeoQo=
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU=
Expand All @@ -14,6 +14,8 @@ github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 h1:yAJXTCF9TqKcTiHJAE
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4=
github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=
github.com/onsi/ginkgo/v2 v2.9.5 h1:+6Hr4uxzP4XIUyAkg61dWBw8lb/gc4/X5luuxN/EC+Q=
Expand Down

0 comments on commit c578652

Please sign in to comment.