chat_completions_logic.go 14 KB

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