ratio_sync.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. package controller
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/http"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/QuantumNous/new-api/logger"
  13. "github.com/QuantumNous/new-api/dto"
  14. "github.com/QuantumNous/new-api/model"
  15. "github.com/QuantumNous/new-api/setting/ratio_setting"
  16. "github.com/gin-gonic/gin"
  17. )
  18. const (
  19. defaultTimeoutSeconds = 10
  20. defaultEndpoint = "/api/ratio_config"
  21. maxConcurrentFetches = 8
  22. maxRatioConfigBytes = 10 << 20 // 10MB
  23. floatEpsilon = 1e-9
  24. )
  25. func nearlyEqual(a, b float64) bool {
  26. if a > b {
  27. return a-b < floatEpsilon
  28. }
  29. return b-a < floatEpsilon
  30. }
  31. func valuesEqual(a, b interface{}) bool {
  32. af, aok := a.(float64)
  33. bf, bok := b.(float64)
  34. if aok && bok {
  35. return nearlyEqual(af, bf)
  36. }
  37. return a == b
  38. }
  39. var ratioTypes = []string{"model_ratio", "completion_ratio", "cache_ratio", "model_price"}
  40. type upstreamResult struct {
  41. Name string `json:"name"`
  42. Data map[string]any `json:"data,omitempty"`
  43. Err string `json:"err,omitempty"`
  44. }
  45. func FetchUpstreamRatios(c *gin.Context) {
  46. var req dto.UpstreamRequest
  47. if err := c.ShouldBindJSON(&req); err != nil {
  48. c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": err.Error()})
  49. return
  50. }
  51. if req.Timeout <= 0 {
  52. req.Timeout = defaultTimeoutSeconds
  53. }
  54. var upstreams []dto.UpstreamDTO
  55. if len(req.Upstreams) > 0 {
  56. for _, u := range req.Upstreams {
  57. if strings.HasPrefix(u.BaseURL, "http") {
  58. if u.Endpoint == "" {
  59. u.Endpoint = defaultEndpoint
  60. }
  61. u.BaseURL = strings.TrimRight(u.BaseURL, "/")
  62. upstreams = append(upstreams, u)
  63. }
  64. }
  65. } else if len(req.ChannelIDs) > 0 {
  66. intIds := make([]int, 0, len(req.ChannelIDs))
  67. for _, id64 := range req.ChannelIDs {
  68. intIds = append(intIds, int(id64))
  69. }
  70. dbChannels, err := model.GetChannelsByIds(intIds)
  71. if err != nil {
  72. logger.LogError(c.Request.Context(), "failed to query channels: "+err.Error())
  73. c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "查询渠道失败"})
  74. return
  75. }
  76. for _, ch := range dbChannels {
  77. if base := ch.GetBaseURL(); strings.HasPrefix(base, "http") {
  78. upstreams = append(upstreams, dto.UpstreamDTO{
  79. ID: ch.Id,
  80. Name: ch.Name,
  81. BaseURL: strings.TrimRight(base, "/"),
  82. Endpoint: "",
  83. })
  84. }
  85. }
  86. }
  87. if len(upstreams) == 0 {
  88. c.JSON(http.StatusOK, gin.H{"success": false, "message": "无有效上游渠道"})
  89. return
  90. }
  91. var wg sync.WaitGroup
  92. ch := make(chan upstreamResult, len(upstreams))
  93. sem := make(chan struct{}, maxConcurrentFetches)
  94. dialer := &net.Dialer{Timeout: 10 * time.Second}
  95. transport := &http.Transport{MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, ResponseHeaderTimeout: 10 * time.Second}
  96. transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
  97. host, _, err := net.SplitHostPort(addr)
  98. if err != nil {
  99. host = addr
  100. }
  101. // 对 github.io 优先尝试 IPv4,失败则回退 IPv6
  102. if strings.HasSuffix(host, "github.io") {
  103. if conn, err := dialer.DialContext(ctx, "tcp4", addr); err == nil {
  104. return conn, nil
  105. }
  106. return dialer.DialContext(ctx, "tcp6", addr)
  107. }
  108. return dialer.DialContext(ctx, network, addr)
  109. }
  110. client := &http.Client{Transport: transport}
  111. for _, chn := range upstreams {
  112. wg.Add(1)
  113. go func(chItem dto.UpstreamDTO) {
  114. defer wg.Done()
  115. sem <- struct{}{}
  116. defer func() { <-sem }()
  117. endpoint := chItem.Endpoint
  118. var fullURL string
  119. if strings.HasPrefix(endpoint, "http://") || strings.HasPrefix(endpoint, "https://") {
  120. fullURL = endpoint
  121. } else {
  122. if endpoint == "" {
  123. endpoint = defaultEndpoint
  124. } else if !strings.HasPrefix(endpoint, "/") {
  125. endpoint = "/" + endpoint
  126. }
  127. fullURL = chItem.BaseURL + endpoint
  128. }
  129. uniqueName := chItem.Name
  130. if chItem.ID != 0 {
  131. uniqueName = fmt.Sprintf("%s(%d)", chItem.Name, chItem.ID)
  132. }
  133. ctx, cancel := context.WithTimeout(c.Request.Context(), time.Duration(req.Timeout)*time.Second)
  134. defer cancel()
  135. httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, fullURL, nil)
  136. if err != nil {
  137. logger.LogWarn(c.Request.Context(), "build request failed: "+err.Error())
  138. ch <- upstreamResult{Name: uniqueName, Err: err.Error()}
  139. return
  140. }
  141. // 简单重试:最多 3 次,指数退避
  142. var resp *http.Response
  143. var lastErr error
  144. for attempt := 0; attempt < 3; attempt++ {
  145. resp, lastErr = client.Do(httpReq)
  146. if lastErr == nil {
  147. break
  148. }
  149. time.Sleep(time.Duration(200*(1<<attempt)) * time.Millisecond)
  150. }
  151. if lastErr != nil {
  152. logger.LogWarn(c.Request.Context(), "http error on "+chItem.Name+": "+lastErr.Error())
  153. ch <- upstreamResult{Name: uniqueName, Err: lastErr.Error()}
  154. return
  155. }
  156. defer resp.Body.Close()
  157. if resp.StatusCode != http.StatusOK {
  158. logger.LogWarn(c.Request.Context(), "non-200 from "+chItem.Name+": "+resp.Status)
  159. ch <- upstreamResult{Name: uniqueName, Err: resp.Status}
  160. return
  161. }
  162. // Content-Type 和响应体大小校验
  163. if ct := resp.Header.Get("Content-Type"); ct != "" && !strings.Contains(strings.ToLower(ct), "application/json") {
  164. logger.LogWarn(c.Request.Context(), "unexpected content-type from "+chItem.Name+": "+ct)
  165. }
  166. limited := io.LimitReader(resp.Body, maxRatioConfigBytes)
  167. // 兼容两种上游接口格式:
  168. // type1: /api/ratio_config -> data 为 map[string]any,包含 model_ratio/completion_ratio/cache_ratio/model_price
  169. // type2: /api/pricing -> data 为 []Pricing 列表,需要转换为与 type1 相同的 map 格式
  170. var body struct {
  171. Success bool `json:"success"`
  172. Data json.RawMessage `json:"data"`
  173. Message string `json:"message"`
  174. }
  175. if err := json.NewDecoder(limited).Decode(&body); err != nil {
  176. logger.LogWarn(c.Request.Context(), "json decode failed from "+chItem.Name+": "+err.Error())
  177. ch <- upstreamResult{Name: uniqueName, Err: err.Error()}
  178. return
  179. }
  180. if !body.Success {
  181. ch <- upstreamResult{Name: uniqueName, Err: body.Message}
  182. return
  183. }
  184. // 若 Data 为空,将继续按 type1 尝试解析(与多数静态 ratio_config 兼容)
  185. // 尝试按 type1 解析
  186. var type1Data map[string]any
  187. if err := json.Unmarshal(body.Data, &type1Data); err == nil {
  188. // 如果包含至少一个 ratioTypes 字段,则认为是 type1
  189. isType1 := false
  190. for _, rt := range ratioTypes {
  191. if _, ok := type1Data[rt]; ok {
  192. isType1 = true
  193. break
  194. }
  195. }
  196. if isType1 {
  197. ch <- upstreamResult{Name: uniqueName, Data: type1Data}
  198. return
  199. }
  200. }
  201. // 如果不是 type1,则尝试按 type2 (/api/pricing) 解析
  202. var pricingItems []struct {
  203. ModelName string `json:"model_name"`
  204. QuotaType int `json:"quota_type"`
  205. ModelRatio float64 `json:"model_ratio"`
  206. ModelPrice float64 `json:"model_price"`
  207. CompletionRatio float64 `json:"completion_ratio"`
  208. }
  209. if err := json.Unmarshal(body.Data, &pricingItems); err != nil {
  210. logger.LogWarn(c.Request.Context(), "unrecognized data format from "+chItem.Name+": "+err.Error())
  211. ch <- upstreamResult{Name: uniqueName, Err: "无法解析上游返回数据"}
  212. return
  213. }
  214. modelRatioMap := make(map[string]float64)
  215. completionRatioMap := make(map[string]float64)
  216. modelPriceMap := make(map[string]float64)
  217. for _, item := range pricingItems {
  218. if item.QuotaType == 1 {
  219. modelPriceMap[item.ModelName] = item.ModelPrice
  220. } else {
  221. modelRatioMap[item.ModelName] = item.ModelRatio
  222. // completionRatio 可能为 0,此时也直接赋值,保持与上游一致
  223. completionRatioMap[item.ModelName] = item.CompletionRatio
  224. }
  225. }
  226. converted := make(map[string]any)
  227. if len(modelRatioMap) > 0 {
  228. ratioAny := make(map[string]any, len(modelRatioMap))
  229. for k, v := range modelRatioMap {
  230. ratioAny[k] = v
  231. }
  232. converted["model_ratio"] = ratioAny
  233. }
  234. if len(completionRatioMap) > 0 {
  235. compAny := make(map[string]any, len(completionRatioMap))
  236. for k, v := range completionRatioMap {
  237. compAny[k] = v
  238. }
  239. converted["completion_ratio"] = compAny
  240. }
  241. if len(modelPriceMap) > 0 {
  242. priceAny := make(map[string]any, len(modelPriceMap))
  243. for k, v := range modelPriceMap {
  244. priceAny[k] = v
  245. }
  246. converted["model_price"] = priceAny
  247. }
  248. ch <- upstreamResult{Name: uniqueName, Data: converted}
  249. }(chn)
  250. }
  251. wg.Wait()
  252. close(ch)
  253. localData := ratio_setting.GetExposedData()
  254. var testResults []dto.TestResult
  255. var successfulChannels []struct {
  256. name string
  257. data map[string]any
  258. }
  259. for r := range ch {
  260. if r.Err != "" {
  261. testResults = append(testResults, dto.TestResult{
  262. Name: r.Name,
  263. Status: "error",
  264. Error: r.Err,
  265. })
  266. } else {
  267. testResults = append(testResults, dto.TestResult{
  268. Name: r.Name,
  269. Status: "success",
  270. })
  271. successfulChannels = append(successfulChannels, struct {
  272. name string
  273. data map[string]any
  274. }{name: r.Name, data: r.Data})
  275. }
  276. }
  277. differences := buildDifferences(localData, successfulChannels)
  278. c.JSON(http.StatusOK, gin.H{
  279. "success": true,
  280. "data": gin.H{
  281. "differences": differences,
  282. "test_results": testResults,
  283. },
  284. })
  285. }
  286. func buildDifferences(localData map[string]any, successfulChannels []struct {
  287. name string
  288. data map[string]any
  289. }) map[string]map[string]dto.DifferenceItem {
  290. differences := make(map[string]map[string]dto.DifferenceItem)
  291. allModels := make(map[string]struct{})
  292. for _, ratioType := range ratioTypes {
  293. if localRatioAny, ok := localData[ratioType]; ok {
  294. if localRatio, ok := localRatioAny.(map[string]float64); ok {
  295. for modelName := range localRatio {
  296. allModels[modelName] = struct{}{}
  297. }
  298. }
  299. }
  300. }
  301. for _, channel := range successfulChannels {
  302. for _, ratioType := range ratioTypes {
  303. if upstreamRatio, ok := channel.data[ratioType].(map[string]any); ok {
  304. for modelName := range upstreamRatio {
  305. allModels[modelName] = struct{}{}
  306. }
  307. }
  308. }
  309. }
  310. confidenceMap := make(map[string]map[string]bool)
  311. // 预处理阶段:检查pricing接口的可信度
  312. for _, channel := range successfulChannels {
  313. confidenceMap[channel.name] = make(map[string]bool)
  314. modelRatios, hasModelRatio := channel.data["model_ratio"].(map[string]any)
  315. completionRatios, hasCompletionRatio := channel.data["completion_ratio"].(map[string]any)
  316. if hasModelRatio && hasCompletionRatio {
  317. // 遍历所有模型,检查是否满足不可信条件
  318. for modelName := range allModels {
  319. // 默认为可信
  320. confidenceMap[channel.name][modelName] = true
  321. // 检查是否满足不可信条件:model_ratio为37.5且completion_ratio为1
  322. if modelRatioVal, ok := modelRatios[modelName]; ok {
  323. if completionRatioVal, ok := completionRatios[modelName]; ok {
  324. // 转换为float64进行比较
  325. if modelRatioFloat, ok := modelRatioVal.(float64); ok {
  326. if completionRatioFloat, ok := completionRatioVal.(float64); ok {
  327. if modelRatioFloat == 37.5 && completionRatioFloat == 1.0 {
  328. confidenceMap[channel.name][modelName] = false
  329. }
  330. }
  331. }
  332. }
  333. }
  334. }
  335. } else {
  336. // 如果不是从pricing接口获取的数据,则全部标记为可信
  337. for modelName := range allModels {
  338. confidenceMap[channel.name][modelName] = true
  339. }
  340. }
  341. }
  342. for modelName := range allModels {
  343. for _, ratioType := range ratioTypes {
  344. var localValue interface{} = nil
  345. if localRatioAny, ok := localData[ratioType]; ok {
  346. if localRatio, ok := localRatioAny.(map[string]float64); ok {
  347. if val, exists := localRatio[modelName]; exists {
  348. localValue = val
  349. }
  350. }
  351. }
  352. upstreamValues := make(map[string]interface{})
  353. confidenceValues := make(map[string]bool)
  354. hasUpstreamValue := false
  355. hasDifference := false
  356. for _, channel := range successfulChannels {
  357. var upstreamValue interface{} = nil
  358. if upstreamRatio, ok := channel.data[ratioType].(map[string]any); ok {
  359. if val, exists := upstreamRatio[modelName]; exists {
  360. upstreamValue = val
  361. hasUpstreamValue = true
  362. if localValue != nil && !valuesEqual(localValue, val) {
  363. hasDifference = true
  364. } else if valuesEqual(localValue, val) {
  365. upstreamValue = "same"
  366. }
  367. }
  368. }
  369. if upstreamValue == nil && localValue == nil {
  370. upstreamValue = "same"
  371. }
  372. if localValue == nil && upstreamValue != nil && upstreamValue != "same" {
  373. hasDifference = true
  374. }
  375. upstreamValues[channel.name] = upstreamValue
  376. confidenceValues[channel.name] = confidenceMap[channel.name][modelName]
  377. }
  378. shouldInclude := false
  379. if localValue != nil {
  380. if hasDifference {
  381. shouldInclude = true
  382. }
  383. } else {
  384. if hasUpstreamValue {
  385. shouldInclude = true
  386. }
  387. }
  388. if shouldInclude {
  389. if differences[modelName] == nil {
  390. differences[modelName] = make(map[string]dto.DifferenceItem)
  391. }
  392. differences[modelName][ratioType] = dto.DifferenceItem{
  393. Current: localValue,
  394. Upstreams: upstreamValues,
  395. Confidence: confidenceValues,
  396. }
  397. }
  398. }
  399. }
  400. channelHasDiff := make(map[string]bool)
  401. for _, ratioMap := range differences {
  402. for _, item := range ratioMap {
  403. for chName, val := range item.Upstreams {
  404. if val != nil && val != "same" {
  405. channelHasDiff[chName] = true
  406. }
  407. }
  408. }
  409. }
  410. for modelName, ratioMap := range differences {
  411. for ratioType, item := range ratioMap {
  412. for chName := range item.Upstreams {
  413. if !channelHasDiff[chName] {
  414. delete(item.Upstreams, chName)
  415. delete(item.Confidence, chName)
  416. }
  417. }
  418. allSame := true
  419. for _, v := range item.Upstreams {
  420. if v != "same" {
  421. allSame = false
  422. break
  423. }
  424. }
  425. if len(item.Upstreams) == 0 || allSame {
  426. delete(ratioMap, ratioType)
  427. } else {
  428. differences[modelName][ratioType] = item
  429. }
  430. }
  431. if len(ratioMap) == 0 {
  432. delete(differences, modelName)
  433. }
  434. }
  435. return differences
  436. }
  437. func GetSyncableChannels(c *gin.Context) {
  438. channels, err := model.GetAllChannels(0, 0, true, false)
  439. if err != nil {
  440. c.JSON(http.StatusOK, gin.H{
  441. "success": false,
  442. "message": err.Error(),
  443. })
  444. return
  445. }
  446. var syncableChannels []dto.SyncableChannel
  447. for _, channel := range channels {
  448. if channel.GetBaseURL() != "" {
  449. syncableChannels = append(syncableChannels, dto.SyncableChannel{
  450. ID: channel.Id,
  451. Name: channel.Name,
  452. BaseURL: channel.GetBaseURL(),
  453. Status: channel.Status,
  454. })
  455. }
  456. }
  457. syncableChannels = append(syncableChannels, dto.SyncableChannel{
  458. ID: -100,
  459. Name: "官方倍率预设",
  460. BaseURL: "https://basellm.github.io",
  461. Status: 1,
  462. })
  463. c.JSON(http.StatusOK, gin.H{
  464. "success": true,
  465. "message": "",
  466. "data": syncableChannels,
  467. })
  468. }