chat_completions_logic.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. switch wf.(type) {
  97. case *MismatchChatLogic:
  98. fmt.Println("MismatchChatLogic Flow.....")
  99. case *FastgptChatLogic:
  100. fmt.Println("FastgptChatLogic Flow.....")
  101. default:
  102. fmt.Println("Other Flow.....")
  103. }
  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. resp, err := compapi.NewClient(l.ctx, compapi.WithApiBase(apiKeyObj.Edges.Agent.APIBase),
  153. compapi.WithApiKey(apiKeyObj.Edges.Agent.APIKey)).
  154. Chat(req)
  155. /*
  156. if err != nil {
  157. return nil, err
  158. }
  159. if req.EventType == "mismatch" {
  160. client := compapi.MismatchClient{}
  161. taskData := ent.CompapiAsynctask{}
  162. taskData.ID = 1234
  163. taskData.ResponseChatItemID = req.ResponseChatItemId
  164. taskData.EventType = req.EventType
  165. taskData.ChatID = req.ChatId
  166. var err error
  167. taskData.ResponseRaw, err = resp.ToString()
  168. if err != nil {
  169. fmt.Println(err)
  170. return nil, err
  171. }
  172. var bs []byte
  173. bs, err = client.CallbackPrepare(&taskData)
  174. if err != nil {
  175. fmt.Println(err)
  176. return nil, err
  177. }
  178. fmt.Println(string(bs))
  179. nres := map[string]string{}
  180. err = json.Unmarshal(bs, &nres)
  181. if err != nil {
  182. fmt.Println(err)
  183. return nil, err
  184. }
  185. fmt.Println(typekit.PrettyPrint(nres))
  186. res := compapi.MismatchResponse{}
  187. err = compapi.NewChatResult(resp).ParseContentAs(&res)
  188. fmt.Println(err)
  189. fmt.Println(typekit.PrettyPrint(res))
  190. }
  191. */
  192. return resp, err
  193. }
  194. func (l *ChatCompletionsLogic) AppendAsyncRequest(apiKeyObj *ent.ApiKey, req *types.CompApiReq) error {
  195. rawReqBs, err := json.Marshal(*req)
  196. if err != nil {
  197. return err
  198. }
  199. rawReqStr := string(rawReqBs)
  200. res, err := l.svcCtx.DB.CompapiAsynctask.Create().
  201. SetNotNilAuthToken(&apiKeyObj.Key).
  202. SetNotNilOpenaiBase(&apiKeyObj.Edges.Agent.APIBase).
  203. SetNotNilOpenaiKey(&apiKeyObj.Edges.Agent.APIKey).
  204. SetNotNilOrganizationID(&apiKeyObj.OrganizationID).
  205. SetNotNilEventType(&req.EventType).
  206. SetNillableModel(&req.Model).
  207. SetNillableChatID(&req.ChatId).
  208. SetNillableResponseChatItemID(&req.ResponseChatItemId).
  209. SetNotNilRequestRaw(&rawReqStr).
  210. SetNotNilCallbackURL(&req.Callback).
  211. Save(l.ctx)
  212. if err == nil {
  213. logx.Infof("appendAsyncRequest succ,get id:%d", res.ID)
  214. }
  215. return err
  216. }
  217. func (l *ChatCompletionsLogic) AppendUsageDetailLog(authToken string, req *types.CompApiReq, resp *types.CompOpenApiResp) error {
  218. logType := 5
  219. rawReqResp := custom_types.OriginalData{Request: req, Response: resp}
  220. tmpId := 0
  221. tmpId, _ = strconv.Atoi(resp.ID)
  222. sessionId := uint64(tmpId)
  223. orgId := uint64(0)
  224. apiKeyObj, ok := contextkey.AuthTokenInfoKey.GetValue(l.ctx)
  225. if ok {
  226. orgId = apiKeyObj.OrganizationID
  227. }
  228. promptTokens := uint64(resp.Usage.PromptTokens)
  229. completionToken := uint64(resp.Usage.CompletionTokens)
  230. totalTokens := promptTokens + completionToken
  231. msgContent := getMessageContentStr(req.Messages[0].Content)
  232. _, _, _ = logType, sessionId, totalTokens
  233. res, err := l.svcCtx.DB.UsageDetail.Create().
  234. SetNotNilType(&logType).
  235. SetNotNilBotID(&authToken).
  236. SetNotNilReceiverID(&req.EventType).
  237. SetNotNilSessionID(&sessionId).
  238. SetNillableRequest(&msgContent).
  239. SetNillableResponse(&resp.Choices[0].Message.Content).
  240. SetNillableOrganizationID(&orgId).
  241. SetOriginalData(rawReqResp).
  242. SetNillablePromptTokens(&promptTokens).
  243. SetNillableCompletionTokens(&completionToken).
  244. SetNillableTotalTokens(&totalTokens).
  245. Save(l.ctx)
  246. if err == nil { //插入UsageDetai之后再统计UsageTotal
  247. l.updateUsageTotal(authToken, res.ID, orgId)
  248. }
  249. return err
  250. }
  251. func (l *ChatCompletionsLogic) getUsagetotalIdByToken(authToken string) (uint64, error) {
  252. var predicates []predicate.UsageTotal
  253. predicates = append(predicates, usagetotal.BotIDEQ(authToken))
  254. return l.svcCtx.DB.UsageTotal.Query().Where(predicates...).FirstID(l.ctx)
  255. }
  256. func (l *ChatCompletionsLogic) replaceUsagetotalTokens(authToken string, sumTotalTokens uint64, newUsageDetailId uint64, orgId uint64) error {
  257. Id, err := l.getUsagetotalIdByToken(authToken)
  258. if err != nil && !ent.IsNotFound(err) {
  259. return err
  260. }
  261. if Id > 0 { //UsageTotal have record by newUsageDetailId
  262. _, err = l.svcCtx.DB.UsageTotal.UpdateOneID(Id).
  263. SetTotalTokens(sumTotalTokens).
  264. SetEndIndex(newUsageDetailId).
  265. Save(l.ctx)
  266. } else { //create new record by newUsageDetailId
  267. logType := 5
  268. _, err = l.svcCtx.DB.UsageTotal.Create().
  269. SetNotNilBotID(&authToken).
  270. SetNotNilEndIndex(&newUsageDetailId).
  271. SetNotNilTotalTokens(&sumTotalTokens).
  272. SetNillableType(&logType).
  273. SetNotNilOrganizationID(&orgId).
  274. Save(l.ctx)
  275. }
  276. return err
  277. }
  278. func (l *ChatCompletionsLogic) updateUsageTotal(authToken string, newUsageDetailId uint64, orgId uint64) error {
  279. sumTotalTokens, err := l.sumTotalTokensByAuthToken(authToken) //首先sum UsageDetail的TotalTokens
  280. if err == nil {
  281. err = l.replaceUsagetotalTokens(authToken, sumTotalTokens, newUsageDetailId, orgId) //再更新(包含新建)Usagetotal的otalTokens
  282. }
  283. return err
  284. }
  285. // sum total_tokens from usagedetail by AuthToken
  286. func (l *ChatCompletionsLogic) sumTotalTokensByAuthToken(authToken string) (uint64, error) {
  287. var predicates []predicate.UsageDetail
  288. predicates = append(predicates, usagedetail.BotIDEQ(authToken))
  289. var res []struct {
  290. Sum, Min, Max, Count uint64
  291. }
  292. totalTokens := uint64(0)
  293. var err error = nil
  294. err = l.svcCtx.DB.UsageDetail.Query().Where(predicates...).Aggregate(ent.Sum("total_tokens"),
  295. ent.Min("total_tokens"), ent.Max("total_tokens"), ent.Count()).Scan(l.ctx, &res)
  296. if err == nil {
  297. if len(res) > 0 {
  298. totalTokens = res[0].Sum
  299. } else {
  300. totalTokens = 0
  301. }
  302. }
  303. return totalTokens, err
  304. }
  305. func apiKeyObjAdjust(eventType string, workId string, obj *ent.ApiKey) {
  306. if eventType != "fastgpt" {
  307. return
  308. }
  309. obj.OpenaiKey, _ = compapi.GetWorkInfoByID(eventType, workId)
  310. }
  311. // 合法域名正则(支持通配符、中文域名等场景按需调整)
  312. var domainRegex = regexp.MustCompile(
  313. // 多级域名(如 example.com)
  314. `^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$` +
  315. `|` +
  316. // 单级域名(如 localhost 或 mytest-svc)
  317. `^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$`,
  318. )
  319. func IsValidURL(input *string, adjust bool) bool {
  320. // 空值直接返回
  321. if *input == "" {
  322. return false
  323. }
  324. inputStr := *input
  325. // --- 预处理输入:自动补全协议 ---
  326. // 若输入不包含协议头,默认添加 http://
  327. if !strings.Contains(*input, "://") {
  328. inputStr = "http://" + *input
  329. }
  330. // --- 解析 URL ---
  331. u, err := url.Parse(inputStr)
  332. if err != nil {
  333. return false
  334. }
  335. // --- 校验协议 ---
  336. // 只允许常见协议(按需扩展)
  337. switch u.Scheme {
  338. case "http", "https", "ftp", "ftps":
  339. default:
  340. return false
  341. }
  342. // --- 拆分 Host 和 Port ---
  343. host, port, err := net.SplitHostPort(u.Host)
  344. if err != nil {
  345. // 无端口时,整个 Host 作为主机名
  346. host = u.Host
  347. port = ""
  348. }
  349. // --- 校验主机名 ---
  350. // 场景1:IPv4 或 IPv6
  351. if ip := net.ParseIP(host); ip != nil {
  352. // 允许私有或保留 IP(按需调整)
  353. // 示例中允许所有合法 IP
  354. } else {
  355. // 场景2:域名(包括 localhost)
  356. if !domainRegex.MatchString(host) {
  357. return false
  358. }
  359. }
  360. // --- 校验端口 ---
  361. if port != "" {
  362. p, err := net.LookupPort("tcp", port) // 动态获取端口(如 "http" 对应 80)
  363. if err != nil {
  364. // 直接尝试解析为数字端口
  365. numPort, err := strconv.Atoi(port)
  366. if err != nil || numPort < 1 || numPort > 65535 {
  367. return false
  368. }
  369. } else if p == 0 { // 动态端口为 0 时无效
  370. return false
  371. }
  372. }
  373. if adjust {
  374. *input = inputStr
  375. }
  376. return true
  377. }
  378. func getMessageContentStr(input any) string {
  379. str := ""
  380. switch val := input.(type) {
  381. case string:
  382. str = val
  383. case []interface{}:
  384. if len(val) > 0 {
  385. if valc, ok := val[0].(map[string]interface{}); ok {
  386. if valcc, ok := valc["text"]; ok {
  387. str, _ = valcc.(string)
  388. }
  389. }
  390. }
  391. }
  392. return str
  393. }
  394. func isAsyncReqest(req *types.CompApiReq) bool {
  395. return req.IsBatch
  396. }