chat_completions_logic.go 13 KB

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