chat_completions_logic.go 15 KB

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