2024-01-14 11:21:03 +00:00
|
|
|
package xunfei
|
2023-07-29 13:55:57 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/hmac"
|
|
|
|
"crypto/sha256"
|
|
|
|
"encoding/base64"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/gorilla/websocket"
|
2024-01-28 11:38:58 +00:00
|
|
|
"github.com/songquanpeng/one-api/common"
|
|
|
|
"github.com/songquanpeng/one-api/common/helper"
|
|
|
|
"github.com/songquanpeng/one-api/common/logger"
|
2024-04-05 17:02:35 +00:00
|
|
|
"github.com/songquanpeng/one-api/common/random"
|
2024-04-05 17:36:48 +00:00
|
|
|
"github.com/songquanpeng/one-api/relay/adaptor/openai"
|
2024-01-28 11:38:58 +00:00
|
|
|
"github.com/songquanpeng/one-api/relay/constant"
|
2024-04-26 15:05:48 +00:00
|
|
|
"github.com/songquanpeng/one-api/relay/meta"
|
2024-02-17 16:15:31 +00:00
|
|
|
"github.com/songquanpeng/one-api/relay/model"
|
2023-07-29 13:55:57 +00:00
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// https://console.xfyun.cn/services/cbm
|
|
|
|
// https://www.xfyun.cn/doc/spark/Web.html
|
|
|
|
|
2024-02-17 16:15:31 +00:00
|
|
|
func requestOpenAI2Xunfei(request model.GeneralOpenAIRequest, xunfeiAppId string, domain string) *ChatRequest {
|
2024-01-14 11:21:03 +00:00
|
|
|
messages := make([]Message, 0, len(request.Messages))
|
2024-03-31 15:12:29 +00:00
|
|
|
var lastToolCalls []model.Tool
|
2023-07-29 13:55:57 +00:00
|
|
|
for _, message := range request.Messages {
|
2024-03-31 15:12:29 +00:00
|
|
|
if message.ToolCalls != nil {
|
|
|
|
lastToolCalls = message.ToolCalls
|
|
|
|
}
|
2024-03-10 06:32:30 +00:00
|
|
|
messages = append(messages, Message{
|
|
|
|
Role: message.Role,
|
|
|
|
Content: message.StringContent(),
|
|
|
|
})
|
2023-07-29 13:55:57 +00:00
|
|
|
}
|
2024-01-14 11:21:03 +00:00
|
|
|
xunfeiRequest := ChatRequest{}
|
2023-07-29 13:55:57 +00:00
|
|
|
xunfeiRequest.Header.AppId = xunfeiAppId
|
2023-08-19 09:50:34 +00:00
|
|
|
xunfeiRequest.Parameter.Chat.Domain = domain
|
2023-07-29 13:55:57 +00:00
|
|
|
xunfeiRequest.Parameter.Chat.Temperature = request.Temperature
|
|
|
|
xunfeiRequest.Parameter.Chat.TopK = request.N
|
|
|
|
xunfeiRequest.Parameter.Chat.MaxTokens = request.MaxTokens
|
|
|
|
xunfeiRequest.Payload.Message.Text = messages
|
2024-03-31 15:12:29 +00:00
|
|
|
if len(lastToolCalls) != 0 {
|
|
|
|
for _, toolCall := range lastToolCalls {
|
|
|
|
xunfeiRequest.Payload.Functions.Text = append(xunfeiRequest.Payload.Functions.Text, toolCall.Function)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-29 13:55:57 +00:00
|
|
|
return &xunfeiRequest
|
|
|
|
}
|
|
|
|
|
2024-03-31 15:12:29 +00:00
|
|
|
func getToolCalls(response *ChatResponse) []model.Tool {
|
|
|
|
var toolCalls []model.Tool
|
|
|
|
if len(response.Payload.Choices.Text) == 0 {
|
|
|
|
return toolCalls
|
|
|
|
}
|
|
|
|
item := response.Payload.Choices.Text[0]
|
|
|
|
if item.FunctionCall == nil {
|
|
|
|
return toolCalls
|
|
|
|
}
|
|
|
|
toolCall := model.Tool{
|
2024-04-05 17:02:35 +00:00
|
|
|
Id: fmt.Sprintf("call_%s", random.GetUUID()),
|
2024-03-31 15:12:29 +00:00
|
|
|
Type: "function",
|
|
|
|
Function: *item.FunctionCall,
|
|
|
|
}
|
|
|
|
toolCalls = append(toolCalls, toolCall)
|
|
|
|
return toolCalls
|
|
|
|
}
|
|
|
|
|
2024-01-14 11:21:03 +00:00
|
|
|
func responseXunfei2OpenAI(response *ChatResponse) *openai.TextResponse {
|
2023-07-29 13:55:57 +00:00
|
|
|
if len(response.Payload.Choices.Text) == 0 {
|
2024-01-14 11:21:03 +00:00
|
|
|
response.Payload.Choices.Text = []ChatResponseTextItem{
|
2023-07-29 13:55:57 +00:00
|
|
|
{
|
|
|
|
Content: "",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2024-01-14 11:21:03 +00:00
|
|
|
choice := openai.TextResponseChoice{
|
2023-07-29 13:55:57 +00:00
|
|
|
Index: 0,
|
2024-02-17 16:15:31 +00:00
|
|
|
Message: model.Message{
|
2024-03-31 15:12:29 +00:00
|
|
|
Role: "assistant",
|
|
|
|
Content: response.Payload.Choices.Text[0].Content,
|
|
|
|
ToolCalls: getToolCalls(response),
|
2023-07-29 13:55:57 +00:00
|
|
|
},
|
2024-01-14 11:21:03 +00:00
|
|
|
FinishReason: constant.StopFinishReason,
|
2023-07-29 13:55:57 +00:00
|
|
|
}
|
2024-01-14 11:21:03 +00:00
|
|
|
fullTextResponse := openai.TextResponse{
|
2024-04-05 17:02:35 +00:00
|
|
|
Id: fmt.Sprintf("chatcmpl-%s", random.GetUUID()),
|
2023-07-29 13:55:57 +00:00
|
|
|
Object: "chat.completion",
|
2024-01-21 15:21:42 +00:00
|
|
|
Created: helper.GetTimestamp(),
|
2024-01-14 11:21:03 +00:00
|
|
|
Choices: []openai.TextResponseChoice{choice},
|
2023-08-06 05:24:49 +00:00
|
|
|
Usage: response.Payload.Usage.Text,
|
2023-07-29 13:55:57 +00:00
|
|
|
}
|
|
|
|
return &fullTextResponse
|
|
|
|
}
|
|
|
|
|
2024-01-14 11:21:03 +00:00
|
|
|
func streamResponseXunfei2OpenAI(xunfeiResponse *ChatResponse) *openai.ChatCompletionsStreamResponse {
|
2023-07-29 13:55:57 +00:00
|
|
|
if len(xunfeiResponse.Payload.Choices.Text) == 0 {
|
2024-01-14 11:21:03 +00:00
|
|
|
xunfeiResponse.Payload.Choices.Text = []ChatResponseTextItem{
|
2023-07-29 13:55:57 +00:00
|
|
|
{
|
|
|
|
Content: "",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2024-01-14 11:21:03 +00:00
|
|
|
var choice openai.ChatCompletionsStreamResponseChoice
|
2023-07-29 13:55:57 +00:00
|
|
|
choice.Delta.Content = xunfeiResponse.Payload.Choices.Text[0].Content
|
2024-03-31 15:12:29 +00:00
|
|
|
choice.Delta.ToolCalls = getToolCalls(xunfeiResponse)
|
2023-08-12 03:04:53 +00:00
|
|
|
if xunfeiResponse.Payload.Choices.Status == 2 {
|
2024-01-14 11:21:03 +00:00
|
|
|
choice.FinishReason = &constant.StopFinishReason
|
2023-08-12 03:04:53 +00:00
|
|
|
}
|
2024-01-14 11:21:03 +00:00
|
|
|
response := openai.ChatCompletionsStreamResponse{
|
2024-04-05 17:02:35 +00:00
|
|
|
Id: fmt.Sprintf("chatcmpl-%s", random.GetUUID()),
|
2023-07-29 13:55:57 +00:00
|
|
|
Object: "chat.completion.chunk",
|
2024-01-21 15:21:42 +00:00
|
|
|
Created: helper.GetTimestamp(),
|
2023-07-29 13:55:57 +00:00
|
|
|
Model: "SparkDesk",
|
2024-01-14 11:21:03 +00:00
|
|
|
Choices: []openai.ChatCompletionsStreamResponseChoice{choice},
|
2023-07-29 13:55:57 +00:00
|
|
|
}
|
|
|
|
return &response
|
|
|
|
}
|
|
|
|
|
|
|
|
func buildXunfeiAuthUrl(hostUrl string, apiKey, apiSecret string) string {
|
|
|
|
HmacWithShaToBase64 := func(algorithm, data, key string) string {
|
|
|
|
mac := hmac.New(sha256.New, []byte(key))
|
|
|
|
mac.Write([]byte(data))
|
|
|
|
encodeData := mac.Sum(nil)
|
|
|
|
return base64.StdEncoding.EncodeToString(encodeData)
|
|
|
|
}
|
|
|
|
ul, err := url.Parse(hostUrl)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
}
|
|
|
|
date := time.Now().UTC().Format(time.RFC1123)
|
|
|
|
signString := []string{"host: " + ul.Host, "date: " + date, "GET " + ul.Path + " HTTP/1.1"}
|
|
|
|
sign := strings.Join(signString, "\n")
|
|
|
|
sha := HmacWithShaToBase64("hmac-sha256", sign, apiSecret)
|
|
|
|
authUrl := fmt.Sprintf("hmac username=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey,
|
|
|
|
"hmac-sha256", "host date request-line", sha)
|
|
|
|
authorization := base64.StdEncoding.EncodeToString([]byte(authUrl))
|
|
|
|
v := url.Values{}
|
|
|
|
v.Add("host", ul.Host)
|
|
|
|
v.Add("date", date)
|
|
|
|
v.Add("authorization", authorization)
|
|
|
|
callUrl := hostUrl + "?" + v.Encode()
|
|
|
|
return callUrl
|
|
|
|
}
|
|
|
|
|
2024-04-26 15:05:48 +00:00
|
|
|
func StreamHandler(c *gin.Context, meta *meta.Meta, textRequest model.GeneralOpenAIRequest, appId string, apiSecret string, apiKey string) (*model.ErrorWithStatusCode, *model.Usage) {
|
|
|
|
domain, authUrl := getXunfeiAuthUrl(meta.Config.APIVersion, apiKey, apiSecret)
|
2023-09-17 10:16:12 +00:00
|
|
|
dataChan, stopChan, err := xunfeiMakeRequest(textRequest, domain, authUrl, appId)
|
|
|
|
if err != nil {
|
2024-03-24 14:14:45 +00:00
|
|
|
return openai.ErrorWrapper(err, "xunfei_request_failed", http.StatusInternalServerError), nil
|
2023-09-17 10:16:12 +00:00
|
|
|
}
|
2024-01-14 11:21:03 +00:00
|
|
|
common.SetEventStreamHeaders(c)
|
2024-02-17 16:15:31 +00:00
|
|
|
var usage model.Usage
|
2023-09-17 10:16:12 +00:00
|
|
|
c.Stream(func(w io.Writer) bool {
|
|
|
|
select {
|
|
|
|
case xunfeiResponse := <-dataChan:
|
|
|
|
usage.PromptTokens += xunfeiResponse.Payload.Usage.Text.PromptTokens
|
|
|
|
usage.CompletionTokens += xunfeiResponse.Payload.Usage.Text.CompletionTokens
|
|
|
|
usage.TotalTokens += xunfeiResponse.Payload.Usage.Text.TotalTokens
|
|
|
|
response := streamResponseXunfei2OpenAI(&xunfeiResponse)
|
|
|
|
jsonResponse, err := json.Marshal(response)
|
|
|
|
if err != nil {
|
2024-01-21 15:21:42 +00:00
|
|
|
logger.SysError("error marshalling stream response: " + err.Error())
|
2023-09-17 10:16:12 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
c.Render(-1, common.CustomEvent{Data: "data: " + string(jsonResponse)})
|
|
|
|
return true
|
|
|
|
case <-stopChan:
|
|
|
|
c.Render(-1, common.CustomEvent{Data: "data: [DONE]"})
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
})
|
|
|
|
return nil, &usage
|
|
|
|
}
|
|
|
|
|
2024-04-26 15:05:48 +00:00
|
|
|
func Handler(c *gin.Context, meta *meta.Meta, textRequest model.GeneralOpenAIRequest, appId string, apiSecret string, apiKey string) (*model.ErrorWithStatusCode, *model.Usage) {
|
|
|
|
domain, authUrl := getXunfeiAuthUrl(meta.Config.APIVersion, apiKey, apiSecret)
|
2023-09-17 10:16:12 +00:00
|
|
|
dataChan, stopChan, err := xunfeiMakeRequest(textRequest, domain, authUrl, appId)
|
|
|
|
if err != nil {
|
2024-03-24 14:14:45 +00:00
|
|
|
return openai.ErrorWrapper(err, "xunfei_request_failed", http.StatusInternalServerError), nil
|
2023-08-19 09:50:34 +00:00
|
|
|
}
|
2024-02-17 16:15:31 +00:00
|
|
|
var usage model.Usage
|
2023-09-17 10:16:12 +00:00
|
|
|
var content string
|
2024-01-14 11:21:03 +00:00
|
|
|
var xunfeiResponse ChatResponse
|
2023-09-17 10:16:12 +00:00
|
|
|
stop := false
|
|
|
|
for !stop {
|
|
|
|
select {
|
|
|
|
case xunfeiResponse = <-dataChan:
|
2023-10-14 08:11:15 +00:00
|
|
|
if len(xunfeiResponse.Payload.Choices.Text) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
2023-09-17 10:16:12 +00:00
|
|
|
content += xunfeiResponse.Payload.Choices.Text[0].Content
|
|
|
|
usage.PromptTokens += xunfeiResponse.Payload.Usage.Text.PromptTokens
|
|
|
|
usage.CompletionTokens += xunfeiResponse.Payload.Usage.Text.CompletionTokens
|
|
|
|
usage.TotalTokens += xunfeiResponse.Payload.Usage.Text.TotalTokens
|
|
|
|
case stop = <-stopChan:
|
|
|
|
}
|
2023-08-19 09:50:34 +00:00
|
|
|
}
|
2023-12-17 10:06:37 +00:00
|
|
|
if len(xunfeiResponse.Payload.Choices.Text) == 0 {
|
2024-03-24 14:14:45 +00:00
|
|
|
return openai.ErrorWrapper(err, "xunfei_empty_response_detected", http.StatusInternalServerError), nil
|
2023-12-17 10:06:37 +00:00
|
|
|
}
|
2023-09-17 10:16:12 +00:00
|
|
|
xunfeiResponse.Payload.Choices.Text[0].Content = content
|
|
|
|
|
|
|
|
response := responseXunfei2OpenAI(&xunfeiResponse)
|
|
|
|
jsonResponse, err := json.Marshal(response)
|
|
|
|
if err != nil {
|
2024-01-14 11:21:03 +00:00
|
|
|
return openai.ErrorWrapper(err, "marshal_response_body_failed", http.StatusInternalServerError), nil
|
2023-08-19 09:50:34 +00:00
|
|
|
}
|
2023-09-17 10:16:12 +00:00
|
|
|
c.Writer.Header().Set("Content-Type", "application/json")
|
|
|
|
_, _ = c.Writer.Write(jsonResponse)
|
|
|
|
return nil, &usage
|
|
|
|
}
|
|
|
|
|
2024-02-17 16:15:31 +00:00
|
|
|
func xunfeiMakeRequest(textRequest model.GeneralOpenAIRequest, domain, authUrl, appId string) (chan ChatResponse, chan bool, error) {
|
2023-07-29 13:55:57 +00:00
|
|
|
d := websocket.Dialer{
|
|
|
|
HandshakeTimeout: 5 * time.Second,
|
|
|
|
}
|
2023-09-17 10:16:12 +00:00
|
|
|
conn, resp, err := d.Dial(authUrl, nil)
|
2023-07-29 13:55:57 +00:00
|
|
|
if err != nil || resp.StatusCode != 101 {
|
2023-09-17 10:16:12 +00:00
|
|
|
return nil, nil, err
|
2023-07-29 13:55:57 +00:00
|
|
|
}
|
2023-08-19 09:50:34 +00:00
|
|
|
data := requestOpenAI2Xunfei(textRequest, appId, domain)
|
2023-07-29 13:55:57 +00:00
|
|
|
err = conn.WriteJSON(data)
|
|
|
|
if err != nil {
|
2023-09-17 10:16:12 +00:00
|
|
|
return nil, nil, err
|
2023-07-29 13:55:57 +00:00
|
|
|
}
|
2024-03-24 14:14:45 +00:00
|
|
|
_, msg, err := conn.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
2023-09-17 10:16:12 +00:00
|
|
|
|
2024-01-14 11:21:03 +00:00
|
|
|
dataChan := make(chan ChatResponse)
|
2023-07-29 13:55:57 +00:00
|
|
|
stopChan := make(chan bool)
|
|
|
|
go func() {
|
|
|
|
for {
|
2024-03-24 14:14:45 +00:00
|
|
|
if msg == nil {
|
|
|
|
_, msg, err = conn.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
logger.SysError("error reading stream response: " + err.Error())
|
|
|
|
break
|
|
|
|
}
|
2023-07-29 13:55:57 +00:00
|
|
|
}
|
2024-01-14 11:21:03 +00:00
|
|
|
var response ChatResponse
|
2023-07-29 13:55:57 +00:00
|
|
|
err = json.Unmarshal(msg, &response)
|
|
|
|
if err != nil {
|
2024-01-21 15:21:42 +00:00
|
|
|
logger.SysError("error unmarshalling stream response: " + err.Error())
|
2023-07-29 13:55:57 +00:00
|
|
|
break
|
|
|
|
}
|
2024-03-24 14:14:45 +00:00
|
|
|
msg = nil
|
2023-07-29 13:55:57 +00:00
|
|
|
dataChan <- response
|
|
|
|
if response.Payload.Choices.Status == 2 {
|
2023-07-29 15:52:18 +00:00
|
|
|
err := conn.Close()
|
|
|
|
if err != nil {
|
2024-01-21 15:21:42 +00:00
|
|
|
logger.SysError("error closing websocket connection: " + err.Error())
|
2023-07-29 15:52:18 +00:00
|
|
|
}
|
2023-07-29 13:55:57 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
stopChan <- true
|
|
|
|
}()
|
2023-09-17 10:16:12 +00:00
|
|
|
|
|
|
|
return dataChan, stopChan, nil
|
2023-07-29 13:55:57 +00:00
|
|
|
}
|
|
|
|
|
2024-04-26 15:05:48 +00:00
|
|
|
func parseAPIVersionByModelName(modelName string) string {
|
2024-02-18 09:02:36 +00:00
|
|
|
parts := strings.Split(modelName, "-")
|
|
|
|
if len(parts) == 2 {
|
2024-04-26 15:05:48 +00:00
|
|
|
return parts[1]
|
2023-07-29 13:55:57 +00:00
|
|
|
}
|
2024-04-26 15:05:48 +00:00
|
|
|
return ""
|
2024-02-18 09:02:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// https://www.xfyun.cn/doc/spark/Web.html#_1-%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
|
|
|
|
func apiVersion2domain(apiVersion string) string {
|
|
|
|
switch apiVersion {
|
|
|
|
case "v1.1":
|
|
|
|
return "general"
|
|
|
|
case "v2.1":
|
|
|
|
return "generalv2"
|
|
|
|
case "v3.1":
|
|
|
|
return "generalv3"
|
|
|
|
case "v3.5":
|
|
|
|
return "generalv3.5"
|
2023-07-29 13:55:57 +00:00
|
|
|
}
|
2024-02-18 09:02:36 +00:00
|
|
|
return "general" + apiVersion
|
|
|
|
}
|
|
|
|
|
2024-04-26 15:05:48 +00:00
|
|
|
func getXunfeiAuthUrl(apiVersion string, apiKey string, apiSecret string) (string, string) {
|
2024-02-18 09:02:36 +00:00
|
|
|
domain := apiVersion2domain(apiVersion)
|
2023-09-17 10:16:12 +00:00
|
|
|
authUrl := buildXunfeiAuthUrl(fmt.Sprintf("wss://spark-api.xf-yun.com/%s/chat", apiVersion), apiKey, apiSecret)
|
|
|
|
return domain, authUrl
|
2023-07-29 13:55:57 +00:00
|
|
|
}
|