relay-xunfei.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 int `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) *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: 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: message.Content,
  87. })
  88. }
  89. }
  90. xunfeiRequest := XunfeiChatRequest{}
  91. xunfeiRequest.Header.AppId = xunfeiAppId
  92. xunfeiRequest.Parameter.Chat.Domain = "general"
  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. choice := OpenAITextResponseChoice{
  108. Index: 0,
  109. Message: Message{
  110. Role: "assistant",
  111. Content: response.Payload.Choices.Text[0].Content,
  112. },
  113. }
  114. fullTextResponse := OpenAITextResponse{
  115. Object: "chat.completion",
  116. Created: common.GetTimestamp(),
  117. Choices: []OpenAITextResponseChoice{choice},
  118. Usage: response.Payload.Usage.Text,
  119. }
  120. return &fullTextResponse
  121. }
  122. func streamResponseXunfei2OpenAI(xunfeiResponse *XunfeiChatResponse) *ChatCompletionsStreamResponse {
  123. if len(xunfeiResponse.Payload.Choices.Text) == 0 {
  124. xunfeiResponse.Payload.Choices.Text = []XunfeiChatResponseTextItem{
  125. {
  126. Content: "",
  127. },
  128. }
  129. }
  130. var choice ChatCompletionsStreamResponseChoice
  131. choice.Delta.Content = xunfeiResponse.Payload.Choices.Text[0].Content
  132. if xunfeiResponse.Payload.Choices.Status == 2 {
  133. choice.FinishReason = &stopFinishReason
  134. }
  135. response := ChatCompletionsStreamResponse{
  136. Object: "chat.completion.chunk",
  137. Created: common.GetTimestamp(),
  138. Model: "SparkDesk",
  139. Choices: []ChatCompletionsStreamResponseChoice{choice},
  140. }
  141. return &response
  142. }
  143. func buildXunfeiAuthUrl(hostUrl string, apiKey, apiSecret string) string {
  144. HmacWithShaToBase64 := func(algorithm, data, key string) string {
  145. mac := hmac.New(sha256.New, []byte(key))
  146. mac.Write([]byte(data))
  147. encodeData := mac.Sum(nil)
  148. return base64.StdEncoding.EncodeToString(encodeData)
  149. }
  150. ul, err := url.Parse(hostUrl)
  151. if err != nil {
  152. fmt.Println(err)
  153. }
  154. date := time.Now().UTC().Format(time.RFC1123)
  155. signString := []string{"host: " + ul.Host, "date: " + date, "GET " + ul.Path + " HTTP/1.1"}
  156. sign := strings.Join(signString, "\n")
  157. sha := HmacWithShaToBase64("hmac-sha256", sign, apiSecret)
  158. authUrl := fmt.Sprintf("hmac username=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey,
  159. "hmac-sha256", "host date request-line", sha)
  160. authorization := base64.StdEncoding.EncodeToString([]byte(authUrl))
  161. v := url.Values{}
  162. v.Add("host", ul.Host)
  163. v.Add("date", date)
  164. v.Add("authorization", authorization)
  165. callUrl := hostUrl + "?" + v.Encode()
  166. return callUrl
  167. }
  168. func xunfeiStreamHandler(c *gin.Context, textRequest GeneralOpenAIRequest, appId string, apiSecret string, apiKey string) (*OpenAIErrorWithStatusCode, *Usage) {
  169. var usage Usage
  170. d := websocket.Dialer{
  171. HandshakeTimeout: 5 * time.Second,
  172. }
  173. hostUrl := "wss://aichat.xf-yun.com/v1/chat"
  174. conn, resp, err := d.Dial(buildXunfeiAuthUrl(hostUrl, apiKey, apiSecret), nil)
  175. if err != nil || resp.StatusCode != 101 {
  176. return errorWrapper(err, "dial_failed", http.StatusInternalServerError), nil
  177. }
  178. data := requestOpenAI2Xunfei(textRequest, appId)
  179. err = conn.WriteJSON(data)
  180. if err != nil {
  181. return errorWrapper(err, "write_json_failed", http.StatusInternalServerError), nil
  182. }
  183. dataChan := make(chan XunfeiChatResponse)
  184. stopChan := make(chan bool)
  185. go func() {
  186. for {
  187. _, msg, err := conn.ReadMessage()
  188. if err != nil {
  189. common.SysError("error reading stream response: " + err.Error())
  190. break
  191. }
  192. var response XunfeiChatResponse
  193. err = json.Unmarshal(msg, &response)
  194. if err != nil {
  195. common.SysError("error unmarshalling stream response: " + err.Error())
  196. break
  197. }
  198. dataChan <- response
  199. if response.Payload.Choices.Status == 2 {
  200. err := conn.Close()
  201. if err != nil {
  202. common.SysError("error closing websocket connection: " + err.Error())
  203. }
  204. break
  205. }
  206. }
  207. stopChan <- true
  208. }()
  209. setEventStreamHeaders(c)
  210. c.Stream(func(w io.Writer) bool {
  211. select {
  212. case xunfeiResponse := <-dataChan:
  213. usage.PromptTokens += xunfeiResponse.Payload.Usage.Text.PromptTokens
  214. usage.CompletionTokens += xunfeiResponse.Payload.Usage.Text.CompletionTokens
  215. usage.TotalTokens += xunfeiResponse.Payload.Usage.Text.TotalTokens
  216. response := streamResponseXunfei2OpenAI(&xunfeiResponse)
  217. jsonResponse, err := json.Marshal(response)
  218. if err != nil {
  219. common.SysError("error marshalling stream response: " + err.Error())
  220. return true
  221. }
  222. c.Render(-1, common.CustomEvent{Data: "data: " + string(jsonResponse)})
  223. return true
  224. case <-stopChan:
  225. c.Render(-1, common.CustomEvent{Data: "data: [DONE]"})
  226. return false
  227. }
  228. })
  229. return nil, &usage
  230. }
  231. func xunfeiHandler(c *gin.Context, resp *http.Response) (*OpenAIErrorWithStatusCode, *Usage) {
  232. var xunfeiResponse XunfeiChatResponse
  233. responseBody, err := io.ReadAll(resp.Body)
  234. if err != nil {
  235. return errorWrapper(err, "read_response_body_failed", http.StatusInternalServerError), nil
  236. }
  237. err = resp.Body.Close()
  238. if err != nil {
  239. return errorWrapper(err, "close_response_body_failed", http.StatusInternalServerError), nil
  240. }
  241. err = json.Unmarshal(responseBody, &xunfeiResponse)
  242. if err != nil {
  243. return errorWrapper(err, "unmarshal_response_body_failed", http.StatusInternalServerError), nil
  244. }
  245. if xunfeiResponse.Header.Code != 0 {
  246. return &OpenAIErrorWithStatusCode{
  247. OpenAIError: OpenAIError{
  248. Message: xunfeiResponse.Header.Message,
  249. Type: "xunfei_error",
  250. Param: "",
  251. Code: xunfeiResponse.Header.Code,
  252. },
  253. StatusCode: resp.StatusCode,
  254. }, nil
  255. }
  256. fullTextResponse := responseXunfei2OpenAI(&xunfeiResponse)
  257. jsonResponse, err := json.Marshal(fullTextResponse)
  258. if err != nil {
  259. return errorWrapper(err, "marshal_response_body_failed", http.StatusInternalServerError), nil
  260. }
  261. c.Writer.Header().Set("Content-Type", "application/json")
  262. c.Writer.WriteHeader(resp.StatusCode)
  263. _, err = c.Writer.Write(jsonResponse)
  264. return nil, &fullTextResponse.Usage
  265. }