chat_completions_logic.go 12 KB

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