chat_completions_logic.go 7.0 KB

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