chat_completions_logic.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. package chat
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/url"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "wechat-api/ent"
  13. "wechat-api/internal/svc"
  14. "wechat-api/internal/types"
  15. "wechat-api/internal/utils/compapi"
  16. "wechat-api/internal/utils/contextkey"
  17. "wechat-api/ent/custom_types"
  18. "wechat-api/ent/predicate"
  19. "wechat-api/ent/usagedetail"
  20. "wechat-api/ent/usagetotal"
  21. "github.com/zeromicro/go-zero/core/logx"
  22. )
  23. type ChatCompletionsLogic struct {
  24. logx.Logger
  25. ctx context.Context
  26. svcCtx *svc.ServiceContext
  27. }
  28. type FastgptChatLogic struct {
  29. ChatCompletionsLogic
  30. }
  31. type MismatchChatLogic struct {
  32. ChatCompletionsLogic
  33. }
  34. type baseLogicWorkflow interface {
  35. AppendAsyncRequest(apiKeyObj *ent.ApiKey, req *types.CompApiReq) error
  36. DoSyncRequest(apiKeyObj *ent.ApiKey, req *types.CompApiReq) (*types.CompOpenApiResp, error)
  37. AppendUsageDetailLog(authToken string, req *types.CompApiReq, resp *types.CompOpenApiResp) error
  38. AdjustRequest(req *types.CompApiReq, apiKeyObj *ent.ApiKey)
  39. }
  40. func NewChatCompletionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChatCompletionsLogic {
  41. return &ChatCompletionsLogic{
  42. Logger: logx.WithContext(ctx),
  43. ctx: ctx,
  44. svcCtx: svcCtx}
  45. }
  46. func (l *FastgptChatLogic) AdjustRequest(req *types.CompApiReq, apiKeyObj *ent.ApiKey) {
  47. l.ChatCompletionsLogic.AdjustRequest(req, apiKeyObj) //先父类的参数调整
  48. if req.EventType != "fastgpt" {
  49. return
  50. }
  51. if len(req.Model) > 0 {
  52. if req.Variables == nil {
  53. req.Variables = make(map[string]string)
  54. }
  55. req.Variables["model"] = req.Model
  56. }
  57. if len(req.ChatId) > 0 && len(req.FastgptChatId) == 0 {
  58. req.FastgptChatId = req.ChatId
  59. } else if len(req.ChatId) == 0 && len(req.FastgptChatId) > 0 {
  60. req.ChatId = req.FastgptChatId
  61. }
  62. }
  63. func (l *ChatCompletionsLogic) ChatCompletions(req *types.CompApiReq) (asyncMode bool, resp *types.CompOpenApiResp, err error) {
  64. // todo: add your logic here and delete this line
  65. var (
  66. apiKeyObj *ent.ApiKey
  67. ok bool
  68. )
  69. asyncMode = false
  70. //从上下文中获取鉴权中间件埋下的apiAuthInfo
  71. apiKeyObj, ok = contextkey.AuthTokenInfoKey.GetValue(l.ctx)
  72. if !ok {
  73. return asyncMode, nil, errors.New("content get auth info err")
  74. }
  75. if req.WorkId == "TEST_DOUYIN" || req.WorkId == "TEST_DOUYIN_CN" || req.WorkId == "travel" || req.WorkId == "loreal" || req.WorkId == "xiulike-dc" { //临时加
  76. apiKeyObj.OpenaiBase = "http://cn-agent.gkscrm.com/api/v1/"
  77. if req.WorkId == "TEST_DOUYIN" || req.WorkId == "TEST_DOUYIN_CN" {
  78. workToken = "fastgpt-jsMmQKEM5uX7tDimT1zHlZHkBhMHRT2k61YaxyDJRZTUHehID7sG8BKXADNIU"
  79. } else if req.WorkId == "travel" {
  80. workToken = "fastgpt-bcnfFtw1lXWdmYGOv165UVD5R1kY28tyXX8SJv8MHhrSMOgVJsuU"
  81. } else if req.WorkId == "loreal" {
  82. workToken = "fastgpt-qqJeBEkwhgx7wR9fvGToQygmOb7FVjAbGBTFjOAMbd95InEtndke"
  83. } else if req.WorkId == "xiulike-dc" {
  84. workToken = "fastgpt-ir9RgnKHMT9HIOnPsUCFChN15ZbW9kt1lbd5Y0ohfLw9gOz3KcPrfaZWHRB"
  85. }
  86. }
  87. /*
  88. fmt.Println("=========================================")
  89. fmt.Printf("In ChatCompletion Get Token Info:\nKey:'%s'\n", apiKeyObj.Key)
  90. fmt.Printf("Auth Token:'%s'\n", apiKeyObj.Key)
  91. fmt.Printf("ApiKey AgentID:%d\n", apiKeyObj.AgentID)
  92. fmt.Printf("ApiKey APIBase:'%s'\n", apiKeyObj.Edges.Agent.APIBase)
  93. fmt.Printf("ApiKey APIKey:'%s'\n", apiKeyObj.Edges.Agent.APIKey)
  94. fmt.Printf("ApiKey Type:%d\n", apiKeyObj.Edges.Agent.Type)
  95. fmt.Printf("ApiKey Model:'%s'\n", apiKeyObj.Edges.Agent.Model)
  96. fmt.Printf("EventType:'%s'\n", req.EventType)
  97. fmt.Printf("req.ChatId:'%s VS req.FastgptChatId:'%s'\n", req.ChatId, req.FastgptChatId)
  98. fmt.Println("=========================================")
  99. */
  100. //根据请求产生相关的工作流接口集
  101. wf, err := l.getLogicWorkflow(apiKeyObj, req)
  102. if err != nil {
  103. return false, nil, err
  104. }
  105. //微调部分请求参数
  106. wf.AdjustRequest(req, apiKeyObj)
  107. if isAsyncReqest(req) { //异步请求处理模式
  108. asyncMode = true
  109. err = wf.AppendAsyncRequest(apiKeyObj, req)
  110. } else { //同步请求处理模式
  111. resp, err = wf.DoSyncRequest(apiKeyObj, req)
  112. if err == nil && resp != nil && len(resp.Choices) > 0 {
  113. wf.AppendUsageDetailLog(apiKeyObj.Key, req, resp) //请求记录
  114. } else if resp != nil && len(resp.Choices) == 0 {
  115. err = errors.New("返回结果缺失,请检查访问地址及权限")
  116. }
  117. }
  118. return asyncMode, resp, err
  119. }
  120. func (l *ChatCompletionsLogic) getLogicWorkflow(apiKeyObj *ent.ApiKey, req *types.CompApiReq) (baseLogicWorkflow, error) {
  121. var (
  122. err error
  123. wf baseLogicWorkflow
  124. )
  125. if apiKeyObj.Edges.Agent.Type != 2 {
  126. err = fmt.Errorf("api agent type not support(%d)", apiKeyObj.Edges.Agent.Type)
  127. } else if req.EventType == "mismatch" {
  128. wf = &MismatchChatLogic{ChatCompletionsLogic: *l}
  129. } else {
  130. wf = &FastgptChatLogic{ChatCompletionsLogic: *l}
  131. }
  132. return wf, err
  133. }
  134. func (l *ChatCompletionsLogic) AdjustRequest(req *types.CompApiReq, apiKeyObj *ent.ApiKey) {
  135. if len(req.EventType) == 0 {
  136. req.EventType = "fastgpt"
  137. }
  138. if len(req.Model) == 0 && len(apiKeyObj.Edges.Agent.Model) > 0 {
  139. req.Model = apiKeyObj.Edges.Agent.Model
  140. }
  141. //异步任务相关参数调整
  142. if req.IsBatch {
  143. //流模式暂时不支持异步模式
  144. //Callback格式非法则取消批量模式
  145. if req.Stream || !IsValidURL(&req.Callback, true) {
  146. req.IsBatch = false
  147. }
  148. }
  149. }
  150. func (l *ChatCompletionsLogic) DoSyncRequest(apiKeyObj *ent.ApiKey, req *types.CompApiReq) (*types.CompOpenApiResp, error) {
  151. //return compapi.NewFastgptChatCompletions(l.ctx, apiKeyObj.Edges.Agent.APIKey, apiKeyObj.Edges.Agent.APIBase, req)
  152. return compapi.NewClient(l.ctx, compapi.WithApiBase(apiKeyObj.Edges.Agent.APIBase),
  153. compapi.WithApiKey(apiKeyObj.Edges.Agent.APIKey)).
  154. Chat(req)
  155. }
  156. func (l *ChatCompletionsLogic) AppendAsyncRequest(apiKeyObj *ent.ApiKey, req *types.CompApiReq) error {
  157. rawReqBs, err := json.Marshal(*req)
  158. if err != nil {
  159. return err
  160. }
  161. rawReqStr := string(rawReqBs)
  162. res, err := l.svcCtx.DB.CompapiAsynctask.Create().
  163. SetNotNilAuthToken(&apiKeyObj.Key).
  164. SetNotNilOpenaiBase(&apiKeyObj.Edges.Agent.APIBase).
  165. SetNotNilOpenaiKey(&apiKeyObj.Edges.Agent.APIKey).
  166. SetNotNilOrganizationID(&apiKeyObj.OrganizationID).
  167. SetNotNilEventType(&req.EventType).
  168. SetNillableModel(&req.Model).
  169. SetNillableChatID(&req.ChatId).
  170. SetNillableResponseChatItemID(&req.ResponseChatItemId).
  171. SetNotNilRequestRaw(&rawReqStr).
  172. SetNotNilCallbackURL(&req.Callback).
  173. Save(l.ctx)
  174. if err == nil {
  175. logx.Infof("appendAsyncRequest succ,get id:%d", res.ID)
  176. }
  177. return err
  178. }
  179. func (l *ChatCompletionsLogic) AppendUsageDetailLog(authToken string, req *types.CompApiReq, resp *types.CompOpenApiResp) error {
  180. logType := 5
  181. rawReqResp := custom_types.OriginalData{Request: req, Response: resp}
  182. tmpId := 0
  183. tmpId, _ = strconv.Atoi(resp.ID)
  184. sessionId := uint64(tmpId)
  185. orgId := uint64(0)
  186. apiKeyObj, ok := contextkey.AuthTokenInfoKey.GetValue(l.ctx)
  187. if ok {
  188. orgId = apiKeyObj.OrganizationID
  189. }
  190. promptTokens := uint64(resp.Usage.PromptTokens)
  191. completionToken := uint64(resp.Usage.CompletionTokens)
  192. totalTokens := promptTokens + completionToken
  193. msgContent := getMessageContentStr(req.Messages[0].Content)
  194. _, _, _ = logType, sessionId, totalTokens
  195. res, err := l.svcCtx.DB.UsageDetail.Create().
  196. SetNotNilType(&logType).
  197. SetNotNilBotID(&authToken).
  198. SetNotNilReceiverID(&req.EventType).
  199. SetNotNilSessionID(&sessionId).
  200. SetNillableRequest(&msgContent).
  201. SetNillableResponse(&resp.Choices[0].Message.Content).
  202. SetNillableOrganizationID(&orgId).
  203. SetOriginalData(rawReqResp).
  204. SetNillablePromptTokens(&promptTokens).
  205. SetNillableCompletionTokens(&completionToken).
  206. SetNillableTotalTokens(&totalTokens).
  207. Save(l.ctx)
  208. if err == nil { //插入UsageDetai之后再统计UsageTotal
  209. l.updateUsageTotal(authToken, res.ID, orgId)
  210. }
  211. return err
  212. }
  213. func (l *ChatCompletionsLogic) getUsagetotalIdByToken(authToken string) (uint64, error) {
  214. var predicates []predicate.UsageTotal
  215. predicates = append(predicates, usagetotal.BotIDEQ(authToken))
  216. return l.svcCtx.DB.UsageTotal.Query().Where(predicates...).FirstID(l.ctx)
  217. }
  218. func (l *ChatCompletionsLogic) replaceUsagetotalTokens(authToken string, sumTotalTokens uint64, newUsageDetailId uint64, orgId uint64) error {
  219. Id, err := l.getUsagetotalIdByToken(authToken)
  220. if err != nil && !ent.IsNotFound(err) {
  221. return err
  222. }
  223. if Id > 0 { //UsageTotal have record by newUsageDetailId
  224. _, err = l.svcCtx.DB.UsageTotal.UpdateOneID(Id).
  225. SetTotalTokens(sumTotalTokens).
  226. SetEndIndex(newUsageDetailId).
  227. Save(l.ctx)
  228. } else { //create new record by newUsageDetailId
  229. logType := 5
  230. _, err = l.svcCtx.DB.UsageTotal.Create().
  231. SetNotNilBotID(&authToken).
  232. SetNotNilEndIndex(&newUsageDetailId).
  233. SetNotNilTotalTokens(&sumTotalTokens).
  234. SetNillableType(&logType).
  235. SetNotNilOrganizationID(&orgId).
  236. Save(l.ctx)
  237. }
  238. return err
  239. }
  240. func (l *ChatCompletionsLogic) updateUsageTotal(authToken string, newUsageDetailId uint64, orgId uint64) error {
  241. sumTotalTokens, err := l.sumTotalTokensByAuthToken(authToken) //首先sum UsageDetail的TotalTokens
  242. if err == nil {
  243. err = l.replaceUsagetotalTokens(authToken, sumTotalTokens, newUsageDetailId, orgId) //再更新(包含新建)Usagetotal的otalTokens
  244. }
  245. return err
  246. }
  247. // sum total_tokens from usagedetail by AuthToken
  248. func (l *ChatCompletionsLogic) sumTotalTokensByAuthToken(authToken string) (uint64, error) {
  249. var predicates []predicate.UsageDetail
  250. predicates = append(predicates, usagedetail.BotIDEQ(authToken))
  251. var res []struct {
  252. Sum, Min, Max, Count uint64
  253. }
  254. totalTokens := uint64(0)
  255. var err error = nil
  256. err = l.svcCtx.DB.UsageDetail.Query().Where(predicates...).Aggregate(ent.Sum("total_tokens"),
  257. ent.Min("total_tokens"), ent.Max("total_tokens"), ent.Count()).Scan(l.ctx, &res)
  258. if err == nil {
  259. if len(res) > 0 {
  260. totalTokens = res[0].Sum
  261. } else {
  262. totalTokens = 0
  263. }
  264. }
  265. return totalTokens, err
  266. }
  267. func apiKeyObjAdjust(eventType string, workId string, obj *ent.ApiKey) {
  268. if eventType != "fastgpt" {
  269. return
  270. }
  271. obj.OpenaiKey, _ = compapi.GetWorkInfoByID(eventType, workId)
  272. }
  273. // 合法域名正则(支持通配符、中文域名等场景按需调整)
  274. var domainRegex = regexp.MustCompile(
  275. // 多级域名(如 example.com)
  276. `^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$` +
  277. `|` +
  278. // 单级域名(如 localhost 或 mytest-svc)
  279. `^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$`,
  280. )
  281. func IsValidURL(input *string, adjust bool) bool {
  282. // 空值直接返回
  283. if *input == "" {
  284. return false
  285. }
  286. inputStr := *input
  287. // --- 预处理输入:自动补全协议 ---
  288. // 若输入不包含协议头,默认添加 http://
  289. if !strings.Contains(*input, "://") {
  290. inputStr = "http://" + *input
  291. }
  292. // --- 解析 URL ---
  293. u, err := url.Parse(inputStr)
  294. if err != nil {
  295. return false
  296. }
  297. // --- 校验协议 ---
  298. // 只允许常见协议(按需扩展)
  299. switch u.Scheme {
  300. case "http", "https", "ftp", "ftps":
  301. default:
  302. return false
  303. }
  304. // --- 拆分 Host 和 Port ---
  305. host, port, err := net.SplitHostPort(u.Host)
  306. if err != nil {
  307. // 无端口时,整个 Host 作为主机名
  308. host = u.Host
  309. port = ""
  310. }
  311. // --- 校验主机名 ---
  312. // 场景1:IPv4 或 IPv6
  313. if ip := net.ParseIP(host); ip != nil {
  314. // 允许私有或保留 IP(按需调整)
  315. // 示例中允许所有合法 IP
  316. } else {
  317. // 场景2:域名(包括 localhost)
  318. if !domainRegex.MatchString(host) {
  319. return false
  320. }
  321. }
  322. // --- 校验端口 ---
  323. if port != "" {
  324. p, err := net.LookupPort("tcp", port) // 动态获取端口(如 "http" 对应 80)
  325. if err != nil {
  326. // 直接尝试解析为数字端口
  327. numPort, err := strconv.Atoi(port)
  328. if err != nil || numPort < 1 || numPort > 65535 {
  329. return false
  330. }
  331. } else if p == 0 { // 动态端口为 0 时无效
  332. return false
  333. }
  334. }
  335. if adjust {
  336. *input = inputStr
  337. }
  338. return true
  339. }
  340. func getMessageContentStr(input any) string {
  341. str := ""
  342. switch val := input.(type) {
  343. case string:
  344. str = val
  345. case []interface{}:
  346. if len(val) > 0 {
  347. if valc, ok := val[0].(map[string]interface{}); ok {
  348. if valcc, ok := valc["text"]; ok {
  349. str, _ = valcc.(string)
  350. }
  351. }
  352. }
  353. }
  354. return str
  355. }
  356. func isAsyncReqest(req *types.CompApiReq) bool {
  357. return req.IsBatch
  358. }