relay-xunfei.go 9.1 KB

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