chat_completions_logic.go 7.2 KB

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