relay-xunfei.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. package controller
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha256"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "github.com/gin-gonic/gin"
  9. "github.com/gorilla/websocket"
  10. "io"
  11. "net/http"
  12. "net/url"
  13. "one-api/common"
  14. "strings"
  15. "time"
  16. )
  17. // https://console.xfyun.cn/services/cbm
  18. // https://www.xfyun.cn/doc/spark/Web.html
  19. type XunfeiMessage struct {
  20. Role string `json:"role"`
  21. Content string `json:"content"`
  22. }
  23. type XunfeiChatRequest struct {
  24. Header struct {
  25. AppId string `json:"app_id"`
  26. } `json:"header"`
  27. Parameter struct {
  28. Chat struct {
  29. Domain string `json:"domain,omitempty"`
  30. Temperature float64 `json:"temperature,omitempty"`
  31. TopK int `json:"top_k,omitempty"`
  32. MaxTokens uint `json:"max_tokens,omitempty"`
  33. Auditing bool `json:"auditing,omitempty"`
  34. } `json:"chat"`
  35. } `json:"parameter"`
  36. Payload struct {
  37. Message struct {
  38. Text []XunfeiMessage `json:"text"`
  39. } `json:"message"`
  40. } `json:"payload"`
  41. }
  42. type XunfeiChatResponseTextItem struct {
  43. Content string `json:"content"`
  44. Role string `json:"role"`
  45. Index int `json:"index"`
  46. }
  47. type XunfeiChatResponse struct {
  48. Header struct {
  49. Code int `json:"code"`
  50. Message string `json:"message"`
  51. Sid string `json:"sid"`
  52. Status int `json:"status"`
  53. } `json:"header"`
  54. Payload struct {
  55. Choices struct {
  56. Status int `json:"status"`
  57. Seq int `json:"seq"`
  58. Text []XunfeiChatResponseTextItem `json:"text"`
  59. } `json:"choices"`
  60. Usage struct {
  61. //Text struct {
  62. // QuestionTokens string `json:"question_tokens"`
  63. // PromptTokens string `json:"prompt_tokens"`
  64. // CompletionTokens string `json:"completion_tokens"`
  65. // TotalTokens string `json:"total_tokens"`
  66. //} `json:"text"`
  67. Text Usage `json:"text"`
  68. } `json:"usage"`
  69. } `json:"payload"`
  70. }
  71. func requestOpenAI2Xunfei(request GeneralOpenAIRequest, xunfeiAppId string, domain string) *XunfeiChatRequest {
  72. messages := make([]XunfeiMessage, 0, len(request.Messages))
  73. for _, message := range request.Messages {
  74. if message.Role == "system" {
  75. messages = append(messages, XunfeiMessage{
  76. Role: "user",
  77. Content: string(message.Content),
  78. })
  79. messages = append(messages, XunfeiMessage{
  80. Role: "assistant",
  81. Content: "Okay",
  82. })
  83. } else {
  84. messages = append(messages, XunfeiMessage{
  85. Role: message.Role,
  86. Content: string(message.Content),
  87. })
  88. }
  89. }
  90. xunfeiRequest := XunfeiChatRequest{}
  91. xunfeiRequest.Header.AppId = xunfeiAppId
  92. xunfeiRequest.Parameter.Chat.Domain = domain
  93. xunfeiRequest.Parameter.Chat.Temperature = request.Temperature
  94. xunfeiRequest.Parameter.Chat.TopK = request.N
  95. xunfeiRequest.Parameter.Chat.MaxTokens = request.MaxTokens
  96. xunfeiRequest.Payload.Message.Text = messages
  97. return &xunfeiRequest
  98. }
  99. func responseXunfei2OpenAI(response *XunfeiChatResponse) *OpenAITextResponse {
  100. if len(response.Payload.Choices.Text) == 0 {
  101. response.Payload.Choices.Text = []XunfeiChatResponseTextItem{
  102. {
  103. Content: "",
  104. },
  105. }
  106. }
  107. content, _ := json.Marshal(response.Payload.Choices.Text[0].Content)
  108. choice := OpenAITextResponseChoice{
  109. Index: 0,
  110. Message: Message{
  111. Role: "assistant",
  112. Content: content,
  113. },
  114. FinishReason: stopFinishReason,
  115. }
  116. fullTextResponse := OpenAITextResponse{
  117. Object: "chat.completion",
  118. Created: common.GetTimestamp(),
  119. Choices: []OpenAITextResponseChoice{choice},
  120. Usage: response.Payload.Usage.Text,
  121. }
  122. return &fullTextResponse
  123. }
  124. func streamResponseXunfei2OpenAI(xunfeiResponse *XunfeiChatResponse) *ChatCompletionsStreamResponse {
  125. if len(xunfeiResponse.Payload.Choices.Text) == 0 {
  126. xunfeiResponse.Payload.Choices.Text = []XunfeiChatResponseTextItem{
  127. {
  128. Content: "",
  129. },
  130. }
  131. }
  132. var choice ChatCompletionsStreamResponseChoice
  133. choice.Delta.Content = xunfeiResponse.Payload.Choices.Text[0].Content
  134. if xunfeiResponse.Payload.Choices.Status == 2 {
  135. choice.FinishReason = &stopFinishReason
  136. }
  137. response := ChatCompletionsStreamResponse{
  138. Object: "chat.completion.chunk",
  139. Created: common.GetTimestamp(),
  140. Model: "SparkDesk",
  141. Choices: []ChatCompletionsStreamResponseChoice{choice},
  142. }
  143. return &response
  144. }
  145. func buildXunfeiAuthUrl(hostUrl string, apiKey, apiSecret string) string {
  146. HmacWithShaToBase64 := func(algorithm, data, key string) string {
  147. mac := hmac.New(sha256.New, []byte(key))
  148. mac.Write([]byte(data))
  149. encodeData := mac.Sum(nil)
  150. return base64.StdEncoding.EncodeToString(encodeData)
  151. }
  152. ul, err := url.Parse(hostUrl)
  153. if err != nil {
  154. fmt.Println(err)
  155. }
  156. date := time.Now().UTC().Format(time.RFC1123)
  157. signString := []string{"host: " + ul.Host, "date: " + date, "GET " + ul.Path + " HTTP/1.1"}
  158. sign := strings.Join(signString, "\n")
  159. sha := HmacWithShaToBase64("hmac-sha256", sign, apiSecret)
  160. authUrl := fmt.Sprintf("hmac username=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey,
  161. "hmac-sha256", "host date request-line", sha)
  162. authorization := base64.StdEncoding.EncodeToString([]byte(authUrl))
  163. v := url.Values{}
  164. v.Add("host", ul.Host)
  165. v.Add("date", date)
  166. v.Add("authorization", authorization)
  167. callUrl := hostUrl + "?" + v.Encode()
  168. return callUrl
  169. }
  170. func xunfeiStreamHandler(c *gin.Context, textRequest GeneralOpenAIRequest, appId string, apiSecret string, apiKey string) (*OpenAIErrorWithStatusCode, *Usage) {
  171. domain, authUrl := getXunfeiAuthUrl(c, apiKey, apiSecret)
  172. dataChan, stopChan, err := xunfeiMakeRequest(textRequest, domain, authUrl, appId)
  173. if err != nil {
  174. return errorWrapper(err, "make xunfei request err", http.StatusInternalServerError), nil
  175. }
  176. setEventStreamHeaders(c)
  177. var usage Usage
  178. c.Stream(func(w io.Writer) bool {
  179. select {
  180. case xunfeiResponse := <-dataChan:
  181. usage.PromptTokens += xunfeiResponse.Payload.Usage.Text.PromptTokens
  182. usage.CompletionTokens += xunfeiResponse.Payload.Usage.Text.CompletionTokens
  183. usage.TotalTokens += xunfeiResponse.Payload.Usage.Text.TotalTokens
  184. response := streamResponseXunfei2OpenAI(&xunfeiResponse)
  185. jsonResponse, err := json.Marshal(response)
  186. if err != nil {
  187. common.SysError("error marshalling stream response: " + err.Error())
  188. return true
  189. }
  190. c.Render(-1, common.CustomEvent{Data: "data: " + string(jsonResponse)})
  191. return true
  192. case <-stopChan:
  193. c.Render(-1, common.CustomEvent{Data: "data: [DONE]"})
  194. return false
  195. }
  196. })
  197. return nil, &usage
  198. }
  199. func xunfeiHandler(c *gin.Context, textRequest GeneralOpenAIRequest, appId string, apiSecret string, apiKey string) (*OpenAIErrorWithStatusCode, *Usage) {
  200. domain, authUrl := getXunfeiAuthUrl(c, apiKey, apiSecret)
  201. dataChan, stopChan, err := xunfeiMakeRequest(textRequest, domain, authUrl, appId)
  202. if err != nil {
  203. return errorWrapper(err, "make xunfei request err", http.StatusInternalServerError), nil
  204. }
  205. var usage Usage
  206. var content string
  207. var xunfeiResponse XunfeiChatResponse
  208. stop := false
  209. for !stop {
  210. select {
  211. case xunfeiResponse = <-dataChan:
  212. if len(xunfeiResponse.Payload.Choices.Text) == 0 {
  213. continue
  214. }
  215. content += xunfeiResponse.Payload.Choices.Text[0].Content
  216. usage.PromptTokens += xunfeiResponse.Payload.Usage.Text.PromptTokens
  217. usage.CompletionTokens += xunfeiResponse.Payload.Usage.Text.CompletionTokens
  218. usage.TotalTokens += xunfeiResponse.Payload.Usage.Text.TotalTokens
  219. case stop = <-stopChan:
  220. }
  221. }
  222. xunfeiResponse.Payload.Choices.Text[0].Content = content
  223. response := responseXunfei2OpenAI(&xunfeiResponse)
  224. jsonResponse, err := json.Marshal(response)
  225. if err != nil {
  226. return errorWrapper(err, "marshal_response_body_failed", http.StatusInternalServerError), nil
  227. }
  228. c.Writer.Header().Set("Content-Type", "application/json")
  229. _, _ = c.Writer.Write(jsonResponse)
  230. return nil, &usage
  231. }
  232. func xunfeiMakeRequest(textRequest GeneralOpenAIRequest, domain, authUrl, appId string) (chan XunfeiChatResponse, chan bool, error) {
  233. d := websocket.Dialer{
  234. HandshakeTimeout: 5 * time.Second,
  235. }
  236. conn, resp, err := d.Dial(authUrl, nil)
  237. if err != nil || resp.StatusCode != 101 {
  238. return nil, nil, err
  239. }
  240. data := requestOpenAI2Xunfei(textRequest, appId, domain)
  241. err = conn.WriteJSON(data)
  242. if err != nil {
  243. return nil, nil, err
  244. }
  245. dataChan := make(chan XunfeiChatResponse)
  246. stopChan := make(chan bool)
  247. go func() {
  248. for {
  249. _, msg, err := conn.ReadMessage()
  250. if err != nil {
  251. common.SysError("error reading stream response: " + err.Error())
  252. break
  253. }
  254. var response XunfeiChatResponse
  255. err = json.Unmarshal(msg, &response)
  256. if err != nil {
  257. common.SysError("error unmarshalling stream response: " + err.Error())
  258. break
  259. }
  260. dataChan <- response
  261. if response.Payload.Choices.Status == 2 {
  262. err := conn.Close()
  263. if err != nil {
  264. common.SysError("error closing websocket connection: " + err.Error())
  265. }
  266. break
  267. }
  268. }
  269. stopChan <- true
  270. }()
  271. return dataChan, stopChan, nil
  272. }
  273. func getXunfeiAuthUrl(c *gin.Context, apiKey string, apiSecret string) (string, string) {
  274. query := c.Request.URL.Query()
  275. apiVersion := query.Get("api-version")
  276. if apiVersion == "" {
  277. apiVersion = c.GetString("api_version")
  278. }
  279. if apiVersion == "" {
  280. apiVersion = "v1.1"
  281. common.SysLog("api_version not found, use default: " + apiVersion)
  282. }
  283. domain := "general"
  284. if apiVersion != "v1.1" {
  285. domain += strings.Split(apiVersion, ".")[0]
  286. }
  287. authUrl := buildXunfeiAuthUrl(fmt.Sprintf("wss://spark-api.xf-yun.com/%s/chat", apiVersion), apiKey, apiSecret)
  288. return domain, authUrl
  289. }