ratio_sync.go 16 KB

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