relay-tencent.go 6.9 KB

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