chat_completions_logic.go 11 KB

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