func.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. package compapi
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "reflect"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "wechat-api/ent"
  15. "wechat-api/ent/custom_types"
  16. "wechat-api/ent/predicate"
  17. "wechat-api/ent/usagedetail"
  18. "wechat-api/ent/usagetotal"
  19. "wechat-api/internal/config"
  20. "wechat-api/internal/types"
  21. "wechat-api/internal/utils/contextkey"
  22. openai "github.com/openai/openai-go"
  23. "github.com/openai/openai-go/option"
  24. "github.com/openai/openai-go/packages/ssestream"
  25. "github.com/redis/go-redis/v9"
  26. "github.com/zeromicro/go-zero/rest/httpx"
  27. )
  28. type ServiceContext struct {
  29. Config config.Config
  30. DB *ent.Client
  31. Rds redis.UniversalClient
  32. }
  33. func AppendUsageDetailLog(ctx context.Context, svcCtx *ServiceContext,
  34. authToken string, req *types.CompApiReq, resp *types.CompOpenApiResp) error {
  35. logType := 5
  36. rawReqResp := custom_types.OriginalData{Request: req, Response: resp}
  37. tmpId := 0
  38. tmpId, _ = strconv.Atoi(resp.ID)
  39. sessionId := uint64(tmpId)
  40. orgId := uint64(0)
  41. apiKeyObj, ok := contextkey.AuthTokenInfoKey.GetValue(ctx)
  42. if ok {
  43. orgId = apiKeyObj.OrganizationID
  44. }
  45. promptTokens := uint64(resp.Usage.PromptTokens)
  46. completionToken := uint64(resp.Usage.CompletionTokens)
  47. totalTokens := promptTokens + completionToken
  48. msgContent := getMessageContentStr(req.Messages[0].Content)
  49. _, _, _ = logType, sessionId, totalTokens
  50. res, err := svcCtx.DB.UsageDetail.Create().
  51. SetNotNilType(&logType).
  52. SetNotNilBotID(&authToken).
  53. SetNotNilReceiverID(&req.EventType).
  54. SetNotNilSessionID(&sessionId).
  55. SetNillableRequest(&msgContent).
  56. SetNillableResponse(&resp.Choices[0].Message.Content).
  57. SetNillableOrganizationID(&orgId).
  58. SetOriginalData(rawReqResp).
  59. SetNillablePromptTokens(&promptTokens).
  60. SetNillableCompletionTokens(&completionToken).
  61. SetNillableTotalTokens(&totalTokens).
  62. Save(ctx)
  63. if err == nil { //插入UsageDetai之后再统计UsageTotal
  64. updateUsageTotal(ctx, svcCtx, authToken, res.ID, orgId)
  65. }
  66. return err
  67. }
  68. func IsValidURL(input *string, adjust bool) bool {
  69. // 合法域名正则(支持通配符、中文域名等场景按需调整)
  70. var domainRegex = regexp.MustCompile(
  71. // 多级域名(如 example.com)
  72. `^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$` +
  73. `|` +
  74. // 单级域名(如 localhost 或 mytest-svc)
  75. `^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$`,
  76. )
  77. // 空值直接返回
  78. if *input == "" {
  79. return false
  80. }
  81. inputStr := *input
  82. // --- 预处理输入:自动补全协议 ---
  83. // 若输入不包含协议头,默认添加 http://
  84. if !strings.Contains(*input, "://") {
  85. inputStr = "http://" + *input
  86. }
  87. // --- 解析 URL ---
  88. u, err := url.Parse(inputStr)
  89. if err != nil {
  90. return false
  91. }
  92. // --- 校验协议 ---
  93. // 只允许常见协议(按需扩展)
  94. switch u.Scheme {
  95. case "http", "https", "ftp", "ftps":
  96. default:
  97. return false
  98. }
  99. // --- 拆分 Host 和 Port ---
  100. host, port, err := net.SplitHostPort(u.Host)
  101. if err != nil {
  102. // 无端口时,整个 Host 作为主机名
  103. host = u.Host
  104. port = ""
  105. }
  106. // --- 校验主机名 ---
  107. // 场景1:IPv4 或 IPv6
  108. if ip := net.ParseIP(host); ip != nil {
  109. // 允许私有或保留 IP(按需调整)
  110. // 示例中允许所有合法 IP
  111. } else {
  112. // 场景2:域名(包括 localhost)
  113. if !domainRegex.MatchString(host) {
  114. return false
  115. }
  116. }
  117. // --- 校验端口 ---
  118. if port != "" {
  119. p, err := net.LookupPort("tcp", port) // 动态获取端口(如 "http" 对应 80)
  120. if err != nil {
  121. // 直接尝试解析为数字端口
  122. numPort, err := strconv.Atoi(port)
  123. if err != nil || numPort < 1 || numPort > 65535 {
  124. return false
  125. }
  126. } else if p == 0 { // 动态端口为 0 时无效
  127. return false
  128. }
  129. }
  130. if adjust {
  131. *input = inputStr
  132. }
  133. return true
  134. }
  135. func getMessageContentStr(input any) string {
  136. str := ""
  137. switch val := input.(type) {
  138. case string:
  139. str = val
  140. case []interface{}:
  141. if len(val) > 0 {
  142. if valc, ok := val[0].(map[string]interface{}); ok {
  143. if valcc, ok := valc["text"]; ok {
  144. str, _ = valcc.(string)
  145. }
  146. }
  147. }
  148. }
  149. return str
  150. }
  151. func getUsagetotalIdByToken(ctx context.Context, svcCtx *ServiceContext,
  152. authToken string) (uint64, error) {
  153. var predicates []predicate.UsageTotal
  154. predicates = append(predicates, usagetotal.BotIDEQ(authToken))
  155. return svcCtx.DB.UsageTotal.Query().Where(predicates...).FirstID(ctx)
  156. }
  157. func replaceUsagetotalTokens(ctx context.Context, svcCtx *ServiceContext,
  158. authToken string, sumTotalTokens uint64, newUsageDetailId uint64, orgId uint64) error {
  159. Id, err := getUsagetotalIdByToken(ctx, svcCtx, authToken)
  160. if err != nil && !ent.IsNotFound(err) {
  161. return err
  162. }
  163. if Id > 0 { //UsageTotal have record by newUsageDetailId
  164. _, err = svcCtx.DB.UsageTotal.UpdateOneID(Id).
  165. SetTotalTokens(sumTotalTokens).
  166. SetEndIndex(newUsageDetailId).
  167. Save(ctx)
  168. } else { //create new record by newUsageDetailId
  169. logType := 5
  170. _, err = svcCtx.DB.UsageTotal.Create().
  171. SetNotNilBotID(&authToken).
  172. SetNotNilEndIndex(&newUsageDetailId).
  173. SetNotNilTotalTokens(&sumTotalTokens).
  174. SetNillableType(&logType).
  175. SetNotNilOrganizationID(&orgId).
  176. Save(ctx)
  177. }
  178. return err
  179. }
  180. func updateUsageTotal(ctx context.Context, svcCtx *ServiceContext,
  181. authToken string, newUsageDetailId uint64, orgId uint64) error {
  182. sumTotalTokens, err := sumTotalTokensByAuthToken(ctx, svcCtx, authToken) //首先sum UsageDetail的TotalTokens
  183. if err == nil {
  184. err = replaceUsagetotalTokens(ctx, svcCtx, authToken, sumTotalTokens, newUsageDetailId, orgId) //再更新(包含新建)Usagetotal的otalTokens
  185. }
  186. return err
  187. }
  188. // sum total_tokens from usagedetail by AuthToken
  189. func sumTotalTokensByAuthToken(ctx context.Context, svcCtx *ServiceContext,
  190. authToken string) (uint64, error) {
  191. var predicates []predicate.UsageDetail
  192. predicates = append(predicates, usagedetail.BotIDEQ(authToken))
  193. var res []struct {
  194. Sum, Min, Max, Count uint64
  195. }
  196. totalTokens := uint64(0)
  197. var err error = nil
  198. err = svcCtx.DB.UsageDetail.Query().Where(predicates...).Aggregate(ent.Sum("total_tokens"),
  199. ent.Min("total_tokens"), ent.Max("total_tokens"), ent.Count()).Scan(ctx, &res)
  200. if err == nil {
  201. if len(res) > 0 {
  202. totalTokens = res[0].Sum
  203. } else {
  204. totalTokens = 0
  205. }
  206. }
  207. return totalTokens, err
  208. }
  209. func IsOpenaiModel(model string) bool {
  210. prefixes := []string{"gpt-4", "gpt-3", "o1", "o3"}
  211. // 遍历所有前缀进行检查
  212. for _, prefix := range prefixes {
  213. if strings.HasPrefix(model, prefix) {
  214. return true
  215. }
  216. }
  217. return false
  218. }
  219. func EntStructGenScanField(structPtr any, ignoredTypes ...reflect.Type) (string, []any, error) {
  220. t := reflect.TypeOf(structPtr)
  221. v := reflect.ValueOf(structPtr)
  222. if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct {
  223. return "", nil, errors.New("input must be a pointer to a struct")
  224. }
  225. t = t.Elem()
  226. v = v.Elem()
  227. var fields []string
  228. var scanArgs []any
  229. ignoredMap := make(map[reflect.Type]struct{})
  230. // 检查调用者是否传入了任何要忽略的类型
  231. if len(ignoredTypes) > 0 {
  232. for _, ignoredType := range ignoredTypes {
  233. if ignoredType != nil { // 防止 nil 类型加入 map
  234. ignoredMap[ignoredType] = struct{}{}
  235. }
  236. }
  237. }
  238. for i := 0; i < t.NumField(); i++ {
  239. field := t.Field(i)
  240. value := v.Field(i)
  241. // Skip unexported fields
  242. if !field.IsExported() {
  243. continue
  244. }
  245. // Get json tag
  246. jsonTag := field.Tag.Get("json")
  247. if jsonTag == "-" || jsonTag == "" {
  248. continue
  249. }
  250. jsonParts := strings.Split(jsonTag, ",")
  251. jsonName := jsonParts[0]
  252. if jsonName == "" {
  253. continue
  254. }
  255. //传入了要忽略的类型时进行处理
  256. if len(ignoredMap) > 0 {
  257. fieldType := field.Type //获取字段的实际 Go 类型
  258. //如果字段是指针,我们通常关心的是指针指向的元素的类型
  259. if fieldType.Kind() == reflect.Ptr {
  260. fieldType = fieldType.Elem() // 获取元素类型
  261. }
  262. if _, shouldIgnore := ignoredMap[fieldType]; shouldIgnore {
  263. continue // 成员类型存在于忽略列表中则忽略
  264. }
  265. }
  266. fields = append(fields, jsonName)
  267. scanArgs = append(scanArgs, value.Addr().Interface())
  268. }
  269. return strings.Join(fields, ", "), scanArgs, nil
  270. }
  271. type StdChatClient struct {
  272. *openai.Client
  273. }
  274. func NewStdChatClient(apiKey string, apiBase string) *StdChatClient {
  275. opts := []option.RequestOption{}
  276. if len(apiKey) > 0 {
  277. opts = append(opts, option.WithAPIKey(apiKey))
  278. }
  279. opts = append(opts, option.WithBaseURL(apiBase))
  280. client := openai.NewClient(opts...)
  281. return &StdChatClient{&client}
  282. }
  283. func NewAiClient(apiKey string, apiBase string) *openai.Client {
  284. opts := []option.RequestOption{}
  285. if len(apiKey) > 0 {
  286. opts = append(opts, option.WithAPIKey(apiKey))
  287. }
  288. opts = append(opts, option.WithBaseURL(apiBase))
  289. client := openai.NewClient(opts...)
  290. return &client
  291. }
  292. func NewFastgptClient(apiKey string) *openai.Client {
  293. //http://fastgpt.ascrm.cn/api/v1/
  294. client := openai.NewClient(option.WithAPIKey(apiKey),
  295. option.WithBaseURL("http://fastgpt.ascrm.cn/api/v1/"))
  296. return &client
  297. }
  298. func NewDeepSeekClient(apiKey string) *openai.Client {
  299. client := openai.NewClient(option.WithAPIKey(apiKey),
  300. option.WithBaseURL("https://api.deepseek.com"))
  301. return &client
  302. }
  303. func DoChatCompletions(ctx context.Context, client *openai.Client, chatInfo *types.CompApiReq) (*types.CompOpenApiResp, error) {
  304. var (
  305. jsonBytes []byte
  306. err error
  307. )
  308. emptyParams := openai.ChatCompletionNewParams{}
  309. if jsonBytes, err = json.Marshal(chatInfo); err != nil {
  310. return nil, err
  311. }
  312. //fmt.Printf("In DoChatCompletions, req: '%s'\n", string(jsonBytes))
  313. //也许应该对请求体不规范成员名进行检查
  314. customResp := types.CompOpenApiResp{}
  315. reqBodyOps := option.WithRequestBody("application/json", jsonBytes)
  316. respBodyOps := option.WithResponseBodyInto(&customResp)
  317. if _, err = client.Chat.Completions.New(ctx, emptyParams, reqBodyOps, respBodyOps); err != nil {
  318. return nil, err
  319. }
  320. if customResp.FgtErrCode != nil && customResp.FgtErrStatusTxt != nil { //针对fastgpt出错但New()不返回错误的情况
  321. return nil, fmt.Errorf("%s(%d)", *customResp.FgtErrStatusTxt, *customResp.FgtErrCode)
  322. }
  323. return &customResp, nil
  324. }
  325. func DoChatCompletionsStream(ctx context.Context, client *openai.Client, chatInfo *types.CompApiReq) (res *types.CompOpenApiResp, err error) {
  326. var (
  327. jsonBytes []byte
  328. raw *http.Response
  329. //raw []byte
  330. ok bool
  331. hw http.ResponseWriter
  332. )
  333. hw, ok = contextkey.HttpResponseWriterKey.GetValue(ctx) //context取出http.ResponseWriter
  334. if !ok {
  335. return nil, errors.New("content get http writer err")
  336. }
  337. flusher, ok := (hw).(http.Flusher)
  338. if !ok {
  339. http.Error(hw, "Streaming unsupported!", http.StatusInternalServerError)
  340. }
  341. emptyParams := openai.ChatCompletionNewParams{}
  342. if jsonBytes, err = json.Marshal(chatInfo); err != nil {
  343. return nil, err
  344. }
  345. reqBodyOps := option.WithRequestBody("application/json", jsonBytes)
  346. respBodyOps := option.WithResponseBodyInto(&raw)
  347. if _, err = client.Chat.Completions.New(ctx, emptyParams, reqBodyOps, respBodyOps, option.WithJSONSet("stream", true)); err != nil {
  348. return nil, err
  349. }
  350. //设置流式输出头 http1.1
  351. hw.Header().Set("Content-Type", "text/event-stream;charset=utf-8")
  352. hw.Header().Set("Connection", "keep-alive")
  353. hw.Header().Set("Cache-Control", "no-cache")
  354. chatStream := ssestream.NewStream[ApiRespStreamChunk](ApiRespStreamDecoder(raw), err)
  355. defer chatStream.Close()
  356. for chatStream.Next() {
  357. chunk := chatStream.Current()
  358. fmt.Fprintf(hw, "data:%s\n\n", chunk.Data.RAW)
  359. flusher.Flush()
  360. //time.Sleep(1 * time.Millisecond)
  361. }
  362. fmt.Fprintf(hw, "data:%s\n\n", "[DONE]")
  363. flusher.Flush()
  364. httpx.Ok(hw)
  365. return nil, nil
  366. }
  367. func NewChatCompletions(ctx context.Context, client *openai.Client, chatInfo *types.CompApiReq) (*types.CompOpenApiResp, error) {
  368. if chatInfo.Stream {
  369. return DoChatCompletionsStream(ctx, client, chatInfo)
  370. } else {
  371. return DoChatCompletions(ctx, client, chatInfo)
  372. }
  373. }
  374. func NewMismatchChatCompletions(ctx context.Context, apiKey string, apiBase string, chatInfo *types.CompApiReq) (*types.CompOpenApiResp, error) {
  375. client := NewAiClient(apiKey, apiBase)
  376. return NewChatCompletions(ctx, client, chatInfo)
  377. }
  378. func NewFastgptChatCompletions(ctx context.Context, apiKey string, apiBase string, chatInfo *types.CompApiReq) (*types.CompOpenApiResp, error) {
  379. client := NewAiClient(apiKey, apiBase)
  380. return NewChatCompletions(ctx, client, chatInfo)
  381. }
  382. func NewDeepSeekChatCompletions(ctx context.Context, apiKey string, chatInfo *types.CompApiReq, chatModel openai.ChatModel) (res *types.CompOpenApiResp, err error) {
  383. client := NewDeepSeekClient(apiKey)
  384. if chatModel != ChatModelDeepSeekV3 {
  385. chatModel = ChatModelDeepSeekR1
  386. }
  387. chatInfo.Model = chatModel
  388. return NewChatCompletions(ctx, client, chatInfo)
  389. }
  390. func DoChatCompletionsStreamOld(ctx context.Context, client *openai.Client, chatInfo *types.CompApiReq) (res *types.CompOpenApiResp, err error) {
  391. var (
  392. jsonBytes []byte
  393. )
  394. emptyParams := openai.ChatCompletionNewParams{}
  395. if jsonBytes, err = json.Marshal(chatInfo); err != nil {
  396. return nil, err
  397. }
  398. reqBodyOps := option.WithRequestBody("application/json", jsonBytes)
  399. //customResp := types.CompOpenApiResp{}
  400. //respBodyOps := option.WithResponseBodyInto(&customResp)
  401. //chatStream := client.Chat.Completions.NewStreaming(ctx, emptyParams, reqBodyOps, respBodyOps)
  402. chatStream := client.Chat.Completions.NewStreaming(ctx, emptyParams, reqBodyOps)
  403. // optionally, an accumulator helper can be used
  404. acc := openai.ChatCompletionAccumulator{}
  405. httpWriter, ok := ctx.Value("HttpResp-Writer").(http.ResponseWriter)
  406. if !ok {
  407. return nil, errors.New("content get writer err")
  408. }
  409. //httpWriter.Header().Set("Content-Type", "text/event-stream;charset=utf-8")
  410. //httpWriter.Header().Set("Connection", "keep-alive")
  411. //httpWriter.Header().Set("Cache-Control", "no-cache")
  412. idx := 0
  413. for chatStream.Next() {
  414. chunk := chatStream.Current()
  415. acc.AddChunk(chunk)
  416. fmt.Printf("=====>get %d chunk:%v\n", idx, chunk)
  417. if _, err := fmt.Fprintf(httpWriter, "%v", chunk); err != nil {
  418. fmt.Printf("Error writing to client:%v \n", err)
  419. break
  420. }
  421. if content, ok := acc.JustFinishedContent(); ok {
  422. println("Content stream finished:", content)
  423. }
  424. // if using tool calls
  425. if tool, ok := acc.JustFinishedToolCall(); ok {
  426. println("Tool call stream finished:", tool.Index, tool.Name, tool.Arguments)
  427. }
  428. if refusal, ok := acc.JustFinishedRefusal(); ok {
  429. println("Refusal stream finished:", refusal)
  430. }
  431. // it's best to use chunks after handling JustFinished events
  432. if len(chunk.Choices) > 0 {
  433. idx++
  434. fmt.Printf("idx:%d get =>'%s'\n", idx, chunk.Choices[0].Delta.Content)
  435. }
  436. }
  437. if err := chatStream.Err(); err != nil {
  438. return nil, err
  439. }
  440. return nil, nil
  441. }
  442. func GetWorkInfoByID(eventType string, workId string) (string, uint) {
  443. val, exist := fastgptWorkIdMap[workId]
  444. if !exist {
  445. val = fastgptWorkIdMap["default"]
  446. }
  447. return val.Id, val.Idx
  448. }
  449. // 获取workToken
  450. func GetWorkTokenByID(eventType string, workId string) string {
  451. id, _ := GetWorkInfoByID(eventType, workId)
  452. return id
  453. }
  454. // 获取workIdx
  455. func GetWorkIdxByID(eventType string, workId string) uint {
  456. _, idx := GetWorkInfoByID(eventType, workId)
  457. return idx
  458. }