2023-04-23 10:24:11 +00:00
|
|
|
package controller
|
|
|
|
|
|
|
|
import (
|
2023-04-25 12:27:53 +00:00
|
|
|
"bufio"
|
2023-04-28 08:58:55 +00:00
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
2023-04-23 10:24:11 +00:00
|
|
|
"fmt"
|
|
|
|
"github.com/gin-gonic/gin"
|
2023-04-28 10:36:17 +00:00
|
|
|
"github.com/pkoukk/tiktoken-go"
|
2023-04-23 10:24:11 +00:00
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"one-api/common"
|
2023-04-26 02:45:34 +00:00
|
|
|
"one-api/model"
|
2023-04-25 12:27:53 +00:00
|
|
|
"strings"
|
2023-04-23 10:24:11 +00:00
|
|
|
)
|
|
|
|
|
2023-04-28 08:58:55 +00:00
|
|
|
type Message struct {
|
|
|
|
Role string `json:"role"`
|
|
|
|
Content string `json:"content"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type TextRequest struct {
|
|
|
|
Model string `json:"model"`
|
|
|
|
Messages []Message `json:"messages"`
|
|
|
|
Prompt string `json:"prompt"`
|
|
|
|
//Stream bool `json:"stream"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type Usage struct {
|
|
|
|
PromptTokens int `json:"prompt_tokens"`
|
|
|
|
CompletionTokens int `json:"completion_tokens"`
|
|
|
|
TotalTokens int `json:"total_tokens"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type TextResponse struct {
|
|
|
|
Usage `json:"usage"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type StreamResponse struct {
|
|
|
|
Choices []struct {
|
|
|
|
Delta struct {
|
|
|
|
Content string `json:"content"`
|
|
|
|
} `json:"delta"`
|
|
|
|
FinishReason string `json:"finish_reason"`
|
|
|
|
} `json:"choices"`
|
|
|
|
}
|
|
|
|
|
2023-04-28 10:36:17 +00:00
|
|
|
var tokenEncoder, _ = tiktoken.GetEncoding("cl100k_base")
|
|
|
|
|
|
|
|
func countToken(text string) int {
|
|
|
|
token := tokenEncoder.Encode(text, nil, nil)
|
|
|
|
return len(token)
|
|
|
|
}
|
|
|
|
|
2023-04-23 10:24:11 +00:00
|
|
|
func Relay(c *gin.Context) {
|
2023-04-28 09:11:57 +00:00
|
|
|
err := relayHelper(c)
|
|
|
|
if err != nil {
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
|
|
"error": gin.H{
|
|
|
|
"message": err.Error(),
|
|
|
|
"type": "one_api_error",
|
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func relayHelper(c *gin.Context) error {
|
2023-04-23 10:24:11 +00:00
|
|
|
channelType := c.GetInt("channel")
|
2023-04-26 02:45:34 +00:00
|
|
|
tokenId := c.GetInt("token_id")
|
2023-04-28 08:58:55 +00:00
|
|
|
consumeQuota := c.GetBool("consume_quota")
|
2023-04-23 11:19:43 +00:00
|
|
|
baseURL := common.ChannelBaseURLs[channelType]
|
2023-04-23 12:35:49 +00:00
|
|
|
if channelType == common.ChannelTypeCustom {
|
|
|
|
baseURL = c.GetString("base_url")
|
|
|
|
}
|
2023-04-28 10:36:17 +00:00
|
|
|
var textRequest TextRequest
|
2023-04-28 10:16:59 +00:00
|
|
|
if consumeQuota {
|
|
|
|
requestBody, err := io.ReadAll(c.Request.Body)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = c.Request.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = json.Unmarshal(requestBody, &textRequest)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Reset request body
|
|
|
|
c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
|
2023-04-28 08:58:55 +00:00
|
|
|
}
|
2023-04-26 02:45:34 +00:00
|
|
|
requestURL := c.Request.URL.String()
|
|
|
|
req, err := http.NewRequest(c.Request.Method, fmt.Sprintf("%s%s", baseURL, requestURL), c.Request.Body)
|
2023-04-23 10:24:11 +00:00
|
|
|
if err != nil {
|
2023-04-28 09:11:57 +00:00
|
|
|
return err
|
|
|
|
}
|
2023-04-25 02:47:25 +00:00
|
|
|
req.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
|
|
|
|
req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
|
2023-04-25 12:27:53 +00:00
|
|
|
req.Header.Set("Accept", c.Request.Header.Get("Accept"))
|
|
|
|
req.Header.Set("Connection", c.Request.Header.Get("Connection"))
|
2023-04-23 10:24:11 +00:00
|
|
|
client := &http.Client{}
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
2023-04-28 09:11:57 +00:00
|
|
|
return err
|
2023-04-23 10:24:11 +00:00
|
|
|
}
|
2023-04-28 08:58:55 +00:00
|
|
|
err = req.Body.Close()
|
|
|
|
if err != nil {
|
2023-04-28 09:11:57 +00:00
|
|
|
return err
|
2023-04-28 08:58:55 +00:00
|
|
|
}
|
2023-04-29 06:49:10 +00:00
|
|
|
err = c.Request.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-04-28 08:58:55 +00:00
|
|
|
var textResponse TextResponse
|
|
|
|
isStream := resp.Header.Get("Content-Type") == "text/event-stream"
|
|
|
|
var streamResponseText string
|
2023-04-26 02:45:34 +00:00
|
|
|
|
|
|
|
defer func() {
|
2023-04-28 08:58:55 +00:00
|
|
|
if consumeQuota {
|
|
|
|
quota := 0
|
2023-05-11 12:59:35 +00:00
|
|
|
usingGPT4 := strings.HasPrefix(textRequest.Model, "gpt-4")
|
|
|
|
completionRatio := 1
|
|
|
|
if usingGPT4 {
|
|
|
|
completionRatio = 2
|
|
|
|
}
|
2023-04-28 08:58:55 +00:00
|
|
|
if isStream {
|
2023-05-11 12:59:35 +00:00
|
|
|
var promptText string
|
2023-04-28 10:36:17 +00:00
|
|
|
for _, message := range textRequest.Messages {
|
2023-05-11 12:59:35 +00:00
|
|
|
promptText += fmt.Sprintf("%s: %s\n", message.Role, message.Content)
|
2023-04-28 10:36:17 +00:00
|
|
|
}
|
2023-05-11 12:59:35 +00:00
|
|
|
completionText := fmt.Sprintf("%s: %s\n", "assistant", streamResponseText)
|
|
|
|
quota = countToken(promptText) + countToken(completionText)*completionRatio + 3
|
2023-04-28 11:16:37 +00:00
|
|
|
} else {
|
2023-05-11 12:59:35 +00:00
|
|
|
quota = textResponse.Usage.PromptTokens + textResponse.Usage.CompletionTokens*completionRatio
|
2023-04-28 11:16:37 +00:00
|
|
|
}
|
2023-05-11 12:59:35 +00:00
|
|
|
ratio := common.GetModelRatio(textRequest.Model)
|
2023-04-28 11:16:37 +00:00
|
|
|
quota = int(float64(quota) * ratio)
|
2023-05-04 02:20:39 +00:00
|
|
|
err := model.DecreaseTokenQuota(tokenId, quota)
|
2023-04-26 02:45:34 +00:00
|
|
|
if err != nil {
|
2023-04-28 08:58:55 +00:00
|
|
|
common.SysError("Error consuming token remain quota: " + err.Error())
|
2023-04-26 02:45:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
2023-04-28 08:58:55 +00:00
|
|
|
|
2023-04-25 13:50:57 +00:00
|
|
|
if isStream {
|
|
|
|
scanner := bufio.NewScanner(resp.Body)
|
|
|
|
scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
|
|
|
|
if atEOF && len(data) == 0 {
|
|
|
|
return 0, nil, nil
|
|
|
|
}
|
2023-04-25 12:27:53 +00:00
|
|
|
|
2023-04-25 13:50:57 +00:00
|
|
|
if i := strings.Index(string(data), "\n\n"); i >= 0 {
|
|
|
|
return i + 2, data[0:i], nil
|
|
|
|
}
|
2023-04-25 12:27:53 +00:00
|
|
|
|
2023-04-25 13:50:57 +00:00
|
|
|
if atEOF {
|
|
|
|
return len(data), data, nil
|
|
|
|
}
|
2023-04-25 12:27:53 +00:00
|
|
|
|
2023-04-25 13:50:57 +00:00
|
|
|
return 0, nil, nil
|
|
|
|
})
|
|
|
|
dataChan := make(chan string)
|
|
|
|
stopChan := make(chan bool)
|
|
|
|
go func() {
|
|
|
|
for scanner.Scan() {
|
|
|
|
data := scanner.Text()
|
|
|
|
dataChan <- data
|
2023-04-28 08:58:55 +00:00
|
|
|
data = data[6:]
|
|
|
|
if data != "[DONE]" {
|
|
|
|
var streamResponse StreamResponse
|
|
|
|
err = json.Unmarshal([]byte(data), &streamResponse)
|
|
|
|
if err != nil {
|
|
|
|
common.SysError("Error unmarshalling stream response: " + err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
for _, choice := range streamResponse.Choices {
|
|
|
|
streamResponseText += choice.Delta.Content
|
|
|
|
}
|
|
|
|
}
|
2023-04-25 12:45:50 +00:00
|
|
|
}
|
2023-04-25 13:50:57 +00:00
|
|
|
stopChan <- true
|
|
|
|
}()
|
|
|
|
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.Stream(func(w io.Writer) bool {
|
|
|
|
select {
|
|
|
|
case data := <-dataChan:
|
|
|
|
c.Render(-1, common.CustomEvent{Data: data})
|
|
|
|
return true
|
|
|
|
case <-stopChan:
|
2023-04-25 12:45:50 +00:00
|
|
|
return false
|
2023-04-25 12:27:53 +00:00
|
|
|
}
|
2023-04-25 13:50:57 +00:00
|
|
|
})
|
2023-04-28 09:11:57 +00:00
|
|
|
err = resp.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
2023-04-25 13:50:57 +00:00
|
|
|
} else {
|
|
|
|
for k, v := range resp.Header {
|
|
|
|
c.Writer.Header().Set(k, v[0])
|
|
|
|
}
|
2023-04-28 10:16:59 +00:00
|
|
|
if consumeQuota {
|
|
|
|
responseBody, err := io.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = resp.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = json.Unmarshal(responseBody, &textResponse)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Reset response body
|
|
|
|
resp.Body = io.NopCloser(bytes.NewBuffer(responseBody))
|
2023-04-28 08:58:55 +00:00
|
|
|
}
|
2023-04-25 13:50:57 +00:00
|
|
|
_, err = io.Copy(c.Writer, resp.Body)
|
|
|
|
if err != nil {
|
2023-04-28 09:11:57 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = resp.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2023-04-25 12:27:53 +00:00
|
|
|
}
|
2023-04-28 09:11:57 +00:00
|
|
|
return nil
|
2023-04-25 13:50:57 +00:00
|
|
|
}
|
2023-04-23 10:24:11 +00:00
|
|
|
}
|
2023-04-28 08:58:55 +00:00
|
|
|
|
|
|
|
func RelayNotImplemented(c *gin.Context) {
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
|
|
"error": gin.H{
|
|
|
|
"message": "Not Implemented",
|
|
|
|
"type": "one_api_error",
|
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|