relay-tencent.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. package tencent
  2. import (
  3. "bufio"
  4. "crypto/hmac"
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "github.com/gin-gonic/gin"
  11. "io"
  12. "net/http"
  13. "one-api/common"
  14. "one-api/dto"
  15. relaycommon "one-api/relay/common"
  16. "one-api/service"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. // https://cloud.tencent.com/document/product/1729/97732
  22. func requestOpenAI2Tencent(a *Adaptor, request dto.GeneralOpenAIRequest) *TencentChatRequest {
  23. messages := make([]*TencentMessage, 0, len(request.Messages))
  24. for i := 0; i < len(request.Messages); i++ {
  25. message := request.Messages[i]
  26. messages = append(messages, &TencentMessage{
  27. Content: message.StringContent(),
  28. Role: message.Role,
  29. })
  30. }
  31. var req = TencentChatRequest{
  32. Stream: &request.Stream,
  33. Messages: messages,
  34. Model: &request.Model,
  35. }
  36. if request.TopP != 0 {
  37. req.TopP = &request.TopP
  38. }
  39. if request.Temperature != 0 {
  40. req.Temperature = &request.Temperature
  41. }
  42. return &req
  43. }
  44. func responseTencent2OpenAI(response *TencentChatResponse) *dto.OpenAITextResponse {
  45. fullTextResponse := dto.OpenAITextResponse{
  46. Id: response.Id,
  47. Object: "chat.completion",
  48. Created: common.GetTimestamp(),
  49. Usage: dto.Usage{
  50. PromptTokens: response.Usage.PromptTokens,
  51. CompletionTokens: response.Usage.CompletionTokens,
  52. TotalTokens: response.Usage.TotalTokens,
  53. },
  54. }
  55. if len(response.Choices) > 0 {
  56. content, _ := json.Marshal(response.Choices[0].Messages.Content)
  57. choice := dto.OpenAITextResponseChoice{
  58. Index: 0,
  59. Message: dto.Message{
  60. Role: "assistant",
  61. Content: content,
  62. },
  63. FinishReason: response.Choices[0].FinishReason,
  64. }
  65. fullTextResponse.Choices = append(fullTextResponse.Choices, choice)
  66. }
  67. return &fullTextResponse
  68. }
  69. func streamResponseTencent2OpenAI(TencentResponse *TencentChatResponse) *dto.ChatCompletionsStreamResponse {
  70. response := dto.ChatCompletionsStreamResponse{
  71. Object: "chat.completion.chunk",
  72. Created: common.GetTimestamp(),
  73. Model: "tencent-hunyuan",
  74. }
  75. if len(TencentResponse.Choices) > 0 {
  76. var choice dto.ChatCompletionsStreamResponseChoice
  77. choice.Delta.SetContentString(TencentResponse.Choices[0].Delta.Content)
  78. if TencentResponse.Choices[0].FinishReason == "stop" {
  79. choice.FinishReason = &relaycommon.StopFinishReason
  80. }
  81. response.Choices = append(response.Choices, choice)
  82. }
  83. return &response
  84. }
  85. func tencentStreamHandler(c *gin.Context, resp *http.Response) (*dto.OpenAIErrorWithStatusCode, string) {
  86. var responseText string
  87. scanner := bufio.NewScanner(resp.Body)
  88. scanner.Split(bufio.ScanLines)
  89. service.SetEventStreamHeaders(c)
  90. for scanner.Scan() {
  91. data := scanner.Text()
  92. if len(data) < 5 || !strings.HasPrefix(data, "data:") {
  93. continue
  94. }
  95. data = strings.TrimPrefix(data, "data:")
  96. var tencentResponse TencentChatResponse
  97. err := json.Unmarshal([]byte(data), &tencentResponse)
  98. if err != nil {
  99. common.SysError("error unmarshalling stream response: " + err.Error())
  100. continue
  101. }
  102. response := streamResponseTencent2OpenAI(&tencentResponse)
  103. if len(response.Choices) != 0 {
  104. responseText += response.Choices[0].Delta.GetContentString()
  105. }
  106. err = service.ObjectData(c, response)
  107. if err != nil {
  108. common.SysError(err.Error())
  109. }
  110. }
  111. if err := scanner.Err(); err != nil {
  112. common.SysError("error reading stream: " + err.Error())
  113. }
  114. service.Done(c)
  115. err := resp.Body.Close()
  116. if err != nil {
  117. return service.OpenAIErrorWrapper(err, "close_response_body_failed", http.StatusInternalServerError), ""
  118. }
  119. return nil, responseText
  120. }
  121. func tencentHandler(c *gin.Context, resp *http.Response) (*dto.OpenAIErrorWithStatusCode, *dto.Usage) {
  122. var tencentSb TencentChatResponseSB
  123. responseBody, err := io.ReadAll(resp.Body)
  124. if err != nil {
  125. return service.OpenAIErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError), nil
  126. }
  127. err = resp.Body.Close()
  128. if err != nil {
  129. return service.OpenAIErrorWrapper(err, "close_response_body_failed", http.StatusInternalServerError), nil
  130. }
  131. err = json.Unmarshal(responseBody, &tencentSb)
  132. if err != nil {
  133. return service.OpenAIErrorWrapper(err, "unmarshal_response_body_failed", http.StatusInternalServerError), nil
  134. }
  135. if tencentSb.Response.Error.Code != 0 {
  136. return &dto.OpenAIErrorWithStatusCode{
  137. Error: dto.OpenAIError{
  138. Message: tencentSb.Response.Error.Message,
  139. Code: tencentSb.Response.Error.Code,
  140. },
  141. StatusCode: resp.StatusCode,
  142. }, nil
  143. }
  144. fullTextResponse := responseTencent2OpenAI(&tencentSb.Response)
  145. jsonResponse, err := json.Marshal(fullTextResponse)
  146. if err != nil {
  147. return service.OpenAIErrorWrapper(err, "marshal_response_body_failed", http.StatusInternalServerError), nil
  148. }
  149. c.Writer.Header().Set("Content-Type", "application/json")
  150. c.Writer.WriteHeader(resp.StatusCode)
  151. _, err = c.Writer.Write(jsonResponse)
  152. return nil, &fullTextResponse.Usage
  153. }
  154. func parseTencentConfig(config string) (appId int64, secretId string, secretKey string, err error) {
  155. parts := strings.Split(config, "|")
  156. if len(parts) != 3 {
  157. err = errors.New("invalid tencent config")
  158. return
  159. }
  160. appId, err = strconv.ParseInt(parts[0], 10, 64)
  161. secretId = parts[1]
  162. secretKey = parts[2]
  163. return
  164. }
  165. func sha256hex(s string) string {
  166. b := sha256.Sum256([]byte(s))
  167. return hex.EncodeToString(b[:])
  168. }
  169. func hmacSha256(s, key string) string {
  170. hashed := hmac.New(sha256.New, []byte(key))
  171. hashed.Write([]byte(s))
  172. return string(hashed.Sum(nil))
  173. }
  174. func getTencentSign(req TencentChatRequest, adaptor *Adaptor, secId, secKey string) string {
  175. // build canonical request string
  176. host := "hunyuan.tencentcloudapi.com"
  177. httpRequestMethod := "POST"
  178. canonicalURI := "/"
  179. canonicalQueryString := ""
  180. canonicalHeaders := fmt.Sprintf("content-type:%s\nhost:%s\nx-tc-action:%s\n",
  181. "application/json", host, strings.ToLower(adaptor.Action))
  182. signedHeaders := "content-type;host;x-tc-action"
  183. payload, _ := json.Marshal(req)
  184. hashedRequestPayload := sha256hex(string(payload))
  185. canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s",
  186. httpRequestMethod,
  187. canonicalURI,
  188. canonicalQueryString,
  189. canonicalHeaders,
  190. signedHeaders,
  191. hashedRequestPayload)
  192. // build string to sign
  193. algorithm := "TC3-HMAC-SHA256"
  194. requestTimestamp := strconv.FormatInt(adaptor.Timestamp, 10)
  195. timestamp, _ := strconv.ParseInt(requestTimestamp, 10, 64)
  196. t := time.Unix(timestamp, 0).UTC()
  197. // must be the format 2006-01-02, ref to package time for more info
  198. date := t.Format("2006-01-02")
  199. credentialScope := fmt.Sprintf("%s/%s/tc3_request", date, "hunyuan")
  200. hashedCanonicalRequest := sha256hex(canonicalRequest)
  201. string2sign := fmt.Sprintf("%s\n%s\n%s\n%s",
  202. algorithm,
  203. requestTimestamp,
  204. credentialScope,
  205. hashedCanonicalRequest)
  206. // sign string
  207. secretDate := hmacSha256(date, "TC3"+secKey)
  208. secretService := hmacSha256("hunyuan", secretDate)
  209. secretKey := hmacSha256("tc3_request", secretService)
  210. signature := hex.EncodeToString([]byte(hmacSha256(string2sign, secretKey)))
  211. // build authorization
  212. authorization := fmt.Sprintf("%s Credential=%s/%s, SignedHeaders=%s, Signature=%s",
  213. algorithm,
  214. secId,
  215. credentialScope,
  216. signedHeaders,
  217. signature)
  218. return authorization
  219. }