func.go 16 KB

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