chat_completions_logic.go 6.5 KB

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