chat_completions_logic.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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" { //临时加
  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. }
  51. }
  52. /*
  53. fmt.Println("=========================================")
  54. fmt.Printf("In ChatCompletion Get Token Info:\nKey:'%s'\n", apiKeyObj.Key)
  55. fmt.Printf("Title:'%s'\n", apiKeyObj.Title)
  56. fmt.Printf("OpenaiBase:'%s'\n", apiKeyObj.OpenaiBase)
  57. fmt.Printf("OpenaiKey:'%s'\n", apiKeyObj.OpenaiKey)
  58. fmt.Printf("workToken:'%s' because %s/%s\n", workToken, req.EventType, req.WorkId)
  59. fmt.Println("=========================================")
  60. */
  61. if len(apiKeyObj.OpenaiBase) == 0 || len(workToken) == 0 {
  62. return nil, errors.New("not auth info")
  63. }
  64. apiResp, err := l.workForFastgpt(req, workToken, apiKeyObj.OpenaiBase)
  65. if err == nil && apiResp != nil {
  66. l.doRequestLog(req, apiResp) //请求记录
  67. }
  68. return apiResp, err
  69. }
  70. func (l *ChatCompletionsLogic) doRequestLog(req *types.CompApiReq, resp *types.CompOpenApiResp) error {
  71. authToken, ok := contextkey.OpenapiTokenKey.GetValue(l.ctx)
  72. if !ok {
  73. return errors.New("content get auth token err")
  74. }
  75. return l.appendUsageDetailLog(authToken, req, resp)
  76. }
  77. func (l *ChatCompletionsLogic) getUsagetotalIdByToken(authToken string) (uint64, error) {
  78. var predicates []predicate.UsageTotal
  79. predicates = append(predicates, usagetotal.BotIDEQ(authToken))
  80. return l.svcCtx.DB.UsageTotal.Query().Where(predicates...).FirstID(l.ctx)
  81. }
  82. func (l *ChatCompletionsLogic) replaceUsagetotalTokens(authToken string, sumTotalTokens uint64, newUsageDetailId uint64, orgId uint64) error {
  83. Id, err := l.getUsagetotalIdByToken(authToken)
  84. if err != nil && !ent.IsNotFound(err) {
  85. return err
  86. }
  87. if Id > 0 { //UsageTotal have record by newUsageDetailId
  88. _, err = l.svcCtx.DB.UsageTotal.UpdateOneID(Id).
  89. SetTotalTokens(sumTotalTokens).
  90. SetEndIndex(newUsageDetailId).
  91. Save(l.ctx)
  92. } else { //create new record by newUsageDetailId
  93. logType := 5
  94. _, err = l.svcCtx.DB.UsageTotal.Create().
  95. SetNotNilBotID(&authToken).
  96. SetNotNilEndIndex(&newUsageDetailId).
  97. SetNotNilTotalTokens(&sumTotalTokens).
  98. SetNillableType(&logType).
  99. SetNotNilOrganizationID(&orgId).
  100. Save(l.ctx)
  101. }
  102. return err
  103. }
  104. func (l *ChatCompletionsLogic) updateUsageTotal(authToken string, newUsageDetailId uint64, orgId uint64) error {
  105. sumTotalTokens, err := l.sumTotalTokensByAuthToken(authToken) //首先sum UsageDetail的TotalTokens
  106. if err == nil {
  107. err = l.replaceUsagetotalTokens(authToken, sumTotalTokens, newUsageDetailId, orgId) //再更新(包含新建)Usagetotal的otalTokens
  108. }
  109. return err
  110. }
  111. // sum total_tokens from usagedetail by AuthToken
  112. func (l *ChatCompletionsLogic) sumTotalTokensByAuthToken(authToken string) (uint64, error) {
  113. var predicates []predicate.UsageDetail
  114. predicates = append(predicates, usagedetail.BotIDEQ(authToken))
  115. var res []struct {
  116. Sum, Min, Max, Count uint64
  117. }
  118. totalTokens := uint64(0)
  119. var err error = nil
  120. err = l.svcCtx.DB.UsageDetail.Query().Where(predicates...).Aggregate(ent.Sum("total_tokens"),
  121. ent.Min("total_tokens"), ent.Max("total_tokens"), ent.Count()).Scan(l.ctx, &res)
  122. if err == nil {
  123. if len(res) > 0 {
  124. totalTokens = res[0].Sum
  125. } else {
  126. totalTokens = 0
  127. }
  128. }
  129. return totalTokens, err
  130. }
  131. func (l *ChatCompletionsLogic) appendUsageDetailLog(authToken string, req *types.CompApiReq, resp *types.CompOpenApiResp) error {
  132. logType := 5
  133. workIdx := compapi.GetWorkIdxByID(req.EventType, req.WorkId)
  134. rawReqResp := custom_types.OriginalData{Request: req, Response: resp}
  135. tmpId := 0
  136. tmpId, _ = strconv.Atoi(resp.ID)
  137. sessionId := uint64(tmpId)
  138. orgId := uint64(0)
  139. apiKeyObj, ok := contextkey.AuthTokenInfoKey.GetValue(l.ctx)
  140. if ok {
  141. orgId = apiKeyObj.OrganizationID
  142. }
  143. promptTokens := uint64(resp.Usage.PromptTokens)
  144. completionToken := uint64(resp.Usage.CompletionTokens)
  145. totalTokens := promptTokens + completionToken
  146. msgContent := ""
  147. switch val := req.Messages[0].Content.(type) {
  148. case string:
  149. msgContent = val
  150. case []interface{}:
  151. if len(val) > 0 {
  152. if valc, ok := val[0].(map[string]interface{}); ok {
  153. if valcc, ok := valc["text"]; ok {
  154. msgContent, _ = valcc.(string)
  155. }
  156. }
  157. }
  158. }
  159. res, err := l.svcCtx.DB.UsageDetail.Create().
  160. SetNotNilType(&logType).
  161. SetNotNilBotID(&authToken).
  162. SetNotNilReceiverID(&req.EventType).
  163. SetNotNilSessionID(&sessionId).
  164. SetNillableApp(&workIdx).
  165. //SetNillableRequest(&req.Messages[0].Content).
  166. SetNillableRequest(&msgContent).
  167. SetNillableResponse(&resp.Choices[0].Message.Content).
  168. SetNillableOrganizationID(&orgId).
  169. SetOriginalData(rawReqResp).
  170. SetNillablePromptTokens(&promptTokens).
  171. SetNillableCompletionTokens(&completionToken).
  172. SetNillableTotalTokens(&totalTokens).
  173. Save(l.ctx)
  174. if err == nil { //插入UsageDetai之后再统计UsageTotal
  175. l.updateUsageTotal(authToken, res.ID, orgId)
  176. }
  177. return err
  178. }
  179. func (l *ChatCompletionsLogic) workForFastgpt(req *types.CompApiReq, apiKey string, apiBase string) (resp *types.CompOpenApiResp, err error) {
  180. //apiKey := "fastgpt-d2uehCb2T40h9chNGjf4bpFrVKmMkCFPbrjfVLZ6DAL2zzqzOFJWP"
  181. if len(req.ChatId) > 0 && len(req.FastgptChatId) == 0 {
  182. req.FastgptChatId = req.ChatId
  183. }
  184. if len(req.Model) > 0 {
  185. if req.Variables == nil {
  186. req.Variables = make(map[string]string)
  187. }
  188. req.Variables["model"] = req.Model
  189. }
  190. return compapi.NewFastgptChatCompletions(l.ctx, apiKey, apiBase, req)
  191. }