chat_completions_logic.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package chat
  2. import (
  3. "context"
  4. "errors"
  5. "strconv"
  6. "wechat-api/ent"
  7. "wechat-api/internal/svc"
  8. "wechat-api/internal/types"
  9. "wechat-api/internal/utils/compapi"
  10. "wechat-api/internal/utils/contextkey"
  11. "wechat-api/ent/custom_types"
  12. "wechat-api/ent/predicate"
  13. "wechat-api/ent/usagedetail"
  14. "wechat-api/ent/usagetotal"
  15. "github.com/zeromicro/go-zero/core/logx"
  16. )
  17. type ChatCompletionsLogic struct {
  18. logx.Logger
  19. ctx context.Context
  20. svcCtx *svc.ServiceContext
  21. }
  22. func NewChatCompletionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChatCompletionsLogic {
  23. return &ChatCompletionsLogic{
  24. Logger: logx.WithContext(ctx),
  25. ctx: ctx,
  26. svcCtx: svcCtx}
  27. }
  28. func (l *ChatCompletionsLogic) ChatCompletions(req *types.CompApiReq) (resp *types.CompOpenApiResp, err error) {
  29. // todo: add your logic here and delete this line
  30. /*
  31. 1.鉴权获得token
  32. 2.必要参数检测及转换
  33. 3. 根据event_type选择不同处理路由
  34. */
  35. var (
  36. apiKeyObj *ent.ApiKey
  37. ok bool
  38. )
  39. workToken := compapi.GetWorkTokenByID(req.EventType, req.WorkId)
  40. apiKeyObj, ok = contextkey.AuthTokenInfoKey.GetValue(l.ctx)
  41. if !ok {
  42. return nil, errors.New("content get token err")
  43. }
  44. if req.WorkId == "TEST_DOUYIN" || req.WorkId == "TEST_DOUYIN_CN" || req.WorkId == "travel" || req.WorkId == "loreal" { //临时加
  45. apiKeyObj.OpenaiBase = "http://cn-agent.gkscrm.com/api/v1/"
  46. if req.WorkId == "TEST_DOUYIN" || req.WorkId == "TEST_DOUYIN_CN" {
  47. workToken = "fastgpt-jsMmQKEM5uX7tDimT1zHlZHkBhMHRT2k61YaxyDJRZTUHehID7sG8BKXADNIU"
  48. } else if req.WorkId == "travel" {
  49. workToken = "fastgpt-bcnfFtw1lXWdmYGOv165UVD5R1kY28tyXX8SJv8MHhrSMOgVJsuU"
  50. } else if req.WorkId == "loreal" {
  51. workToken = "fastgpt-qqJeBEkwhgx7wR9fvGToQygmOb7FVjAbGBTFjOAMbd95InEtndke"
  52. }
  53. }
  54. /*
  55. fmt.Println("=========================================")
  56. fmt.Printf("In ChatCompletion Get Token Info:\nKey:'%s'\n", apiKeyObj.Key)
  57. fmt.Printf("Title:'%s'\n", apiKeyObj.Title)
  58. fmt.Printf("OpenaiBase:'%s'\n", apiKeyObj.OpenaiBase)
  59. fmt.Printf("OpenaiKey:'%s'\n", apiKeyObj.OpenaiKey)
  60. fmt.Printf("workToken:'%s' because %s/%s\n", workToken, req.EventType, req.WorkId)
  61. fmt.Println("=========================================")
  62. */
  63. if len(apiKeyObj.OpenaiBase) == 0 || len(workToken) == 0 {
  64. return nil, errors.New("not auth info")
  65. }
  66. apiResp, err := l.workForFastgpt(req, workToken, apiKeyObj.OpenaiBase)
  67. if err == nil && apiResp != nil {
  68. l.doRequestLog(req, apiResp) //请求记录
  69. }
  70. return apiResp, err
  71. }
  72. func (l *ChatCompletionsLogic) doRequestLog(req *types.CompApiReq, resp *types.CompOpenApiResp) error {
  73. authToken, ok := contextkey.OpenapiTokenKey.GetValue(l.ctx)
  74. if !ok {
  75. return errors.New("content get auth token err")
  76. }
  77. return l.appendUsageDetailLog(authToken, req, resp)
  78. }
  79. func (l *ChatCompletionsLogic) getUsagetotalIdByToken(authToken string) (uint64, error) {
  80. var predicates []predicate.UsageTotal
  81. predicates = append(predicates, usagetotal.BotIDEQ(authToken))
  82. return l.svcCtx.DB.UsageTotal.Query().Where(predicates...).FirstID(l.ctx)
  83. }
  84. func (l *ChatCompletionsLogic) replaceUsagetotalTokens(authToken string, sumTotalTokens uint64, newUsageDetailId uint64, orgId uint64) error {
  85. Id, err := l.getUsagetotalIdByToken(authToken)
  86. if err != nil && !ent.IsNotFound(err) {
  87. return err
  88. }
  89. if Id > 0 { //UsageTotal have record by newUsageDetailId
  90. _, err = l.svcCtx.DB.UsageTotal.UpdateOneID(Id).
  91. SetTotalTokens(sumTotalTokens).
  92. SetEndIndex(newUsageDetailId).
  93. Save(l.ctx)
  94. } else { //create new record by newUsageDetailId
  95. logType := 5
  96. _, err = l.svcCtx.DB.UsageTotal.Create().
  97. SetNotNilBotID(&authToken).
  98. SetNotNilEndIndex(&newUsageDetailId).
  99. SetNotNilTotalTokens(&sumTotalTokens).
  100. SetNillableType(&logType).
  101. SetNotNilOrganizationID(&orgId).
  102. Save(l.ctx)
  103. }
  104. return err
  105. }
  106. func (l *ChatCompletionsLogic) updateUsageTotal(authToken string, newUsageDetailId uint64, orgId uint64) error {
  107. sumTotalTokens, err := l.sumTotalTokensByAuthToken(authToken) //首先sum UsageDetail的TotalTokens
  108. if err == nil {
  109. err = l.replaceUsagetotalTokens(authToken, sumTotalTokens, newUsageDetailId, orgId) //再更新(包含新建)Usagetotal的otalTokens
  110. }
  111. return err
  112. }
  113. // sum total_tokens from usagedetail by AuthToken
  114. func (l *ChatCompletionsLogic) sumTotalTokensByAuthToken(authToken string) (uint64, error) {
  115. var predicates []predicate.UsageDetail
  116. predicates = append(predicates, usagedetail.BotIDEQ(authToken))
  117. var res []struct {
  118. Sum, Min, Max, Count uint64
  119. }
  120. totalTokens := uint64(0)
  121. var err error = nil
  122. err = l.svcCtx.DB.UsageDetail.Query().Where(predicates...).Aggregate(ent.Sum("total_tokens"),
  123. ent.Min("total_tokens"), ent.Max("total_tokens"), ent.Count()).Scan(l.ctx, &res)
  124. if err == nil {
  125. if len(res) > 0 {
  126. totalTokens = res[0].Sum
  127. } else {
  128. totalTokens = 0
  129. }
  130. }
  131. return totalTokens, err
  132. }
  133. func (l *ChatCompletionsLogic) appendUsageDetailLog(authToken string, req *types.CompApiReq, resp *types.CompOpenApiResp) error {
  134. logType := 5
  135. workIdx := compapi.GetWorkIdxByID(req.EventType, req.WorkId)
  136. rawReqResp := custom_types.OriginalData{Request: req, Response: resp}
  137. tmpId := 0
  138. tmpId, _ = strconv.Atoi(resp.ID)
  139. sessionId := uint64(tmpId)
  140. orgId := uint64(0)
  141. apiKeyObj, ok := contextkey.AuthTokenInfoKey.GetValue(l.ctx)
  142. if ok {
  143. orgId = apiKeyObj.OrganizationID
  144. }
  145. promptTokens := uint64(resp.Usage.PromptTokens)
  146. completionToken := uint64(resp.Usage.CompletionTokens)
  147. totalTokens := promptTokens + completionToken
  148. msgContent := ""
  149. switch val := req.Messages[0].Content.(type) {
  150. case string:
  151. msgContent = val
  152. case []interface{}:
  153. if len(val) > 0 {
  154. if valc, ok := val[0].(map[string]interface{}); ok {
  155. if valcc, ok := valc["text"]; ok {
  156. msgContent, _ = valcc.(string)
  157. }
  158. }
  159. }
  160. }
  161. res, err := l.svcCtx.DB.UsageDetail.Create().
  162. SetNotNilType(&logType).
  163. SetNotNilBotID(&authToken).
  164. SetNotNilReceiverID(&req.EventType).
  165. SetNotNilSessionID(&sessionId).
  166. SetNillableApp(&workIdx).
  167. //SetNillableRequest(&req.Messages[0].Content).
  168. SetNillableRequest(&msgContent).
  169. SetNillableResponse(&resp.Choices[0].Message.Content).
  170. SetNillableOrganizationID(&orgId).
  171. SetOriginalData(rawReqResp).
  172. SetNillablePromptTokens(&promptTokens).
  173. SetNillableCompletionTokens(&completionToken).
  174. SetNillableTotalTokens(&totalTokens).
  175. Save(l.ctx)
  176. if err == nil { //插入UsageDetai之后再统计UsageTotal
  177. l.updateUsageTotal(authToken, res.ID, orgId)
  178. }
  179. return err
  180. }
  181. func (l *ChatCompletionsLogic) workForFastgpt(req *types.CompApiReq, apiKey string, apiBase string) (resp *types.CompOpenApiResp, err error) {
  182. //apiKey := "fastgpt-d2uehCb2T40h9chNGjf4bpFrVKmMkCFPbrjfVLZ6DAL2zzqzOFJWP"
  183. if len(req.ChatId) > 0 && len(req.FastgptChatId) == 0 {
  184. req.FastgptChatId = req.ChatId
  185. }
  186. if len(req.Model) > 0 {
  187. if req.Variables == nil {
  188. req.Variables = make(map[string]string)
  189. }
  190. req.Variables["model"] = req.Model
  191. }
  192. return compapi.NewFastgptChatCompletions(l.ctx, apiKey, apiBase, req)
  193. }