model_sync.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. package controller
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math/rand"
  9. "net"
  10. "net/http"
  11. "strings"
  12. "sync"
  13. "time"
  14. "one-api/common"
  15. "one-api/model"
  16. "github.com/gin-gonic/gin"
  17. "gorm.io/gorm"
  18. )
  19. // 上游地址
  20. const (
  21. upstreamModelsURL = "https://basellm.github.io/llm-metadata/api/newapi/models.json"
  22. upstreamVendorsURL = "https://basellm.github.io/llm-metadata/api/newapi/vendors.json"
  23. )
  24. func normalizeLocale(locale string) (string, bool) {
  25. l := strings.ToLower(strings.TrimSpace(locale))
  26. switch l {
  27. case "en", "zh", "ja":
  28. return l, true
  29. default:
  30. return "", false
  31. }
  32. }
  33. func getUpstreamBase() string {
  34. return common.GetEnvOrDefaultString("SYNC_UPSTREAM_BASE", "https://basellm.github.io/llm-metadata")
  35. }
  36. func getUpstreamURLs(locale string) (modelsURL, vendorsURL string) {
  37. base := strings.TrimRight(getUpstreamBase(), "/")
  38. if l, ok := normalizeLocale(locale); ok && l != "" {
  39. return fmt.Sprintf("%s/api/i18n/%s/newapi/models.json", base, l),
  40. fmt.Sprintf("%s/api/i18n/%s/newapi/vendors.json", base, l)
  41. }
  42. return fmt.Sprintf("%s/api/newapi/models.json", base), fmt.Sprintf("%s/api/newapi/vendors.json", base)
  43. }
  44. type upstreamEnvelope[T any] struct {
  45. Success bool `json:"success"`
  46. Message string `json:"message"`
  47. Data []T `json:"data"`
  48. }
  49. type upstreamModel struct {
  50. Description string `json:"description"`
  51. Endpoints json.RawMessage `json:"endpoints"`
  52. Icon string `json:"icon"`
  53. ModelName string `json:"model_name"`
  54. NameRule int `json:"name_rule"`
  55. Status int `json:"status"`
  56. Tags string `json:"tags"`
  57. VendorName string `json:"vendor_name"`
  58. }
  59. type upstreamVendor struct {
  60. Description string `json:"description"`
  61. Icon string `json:"icon"`
  62. Name string `json:"name"`
  63. Status int `json:"status"`
  64. }
  65. var (
  66. etagCache = make(map[string]string)
  67. bodyCache = make(map[string][]byte)
  68. cacheMutex sync.RWMutex
  69. )
  70. type overwriteField struct {
  71. ModelName string `json:"model_name"`
  72. Fields []string `json:"fields"`
  73. }
  74. type syncRequest struct {
  75. Overwrite []overwriteField `json:"overwrite"`
  76. Locale string `json:"locale"`
  77. }
  78. func newHTTPClient() *http.Client {
  79. timeoutSec := common.GetEnvOrDefault("SYNC_HTTP_TIMEOUT_SECONDS", 10)
  80. dialer := &net.Dialer{Timeout: time.Duration(timeoutSec) * time.Second}
  81. transport := &http.Transport{
  82. MaxIdleConns: 100,
  83. IdleConnTimeout: 90 * time.Second,
  84. TLSHandshakeTimeout: time.Duration(timeoutSec) * time.Second,
  85. ExpectContinueTimeout: 1 * time.Second,
  86. ResponseHeaderTimeout: time.Duration(timeoutSec) * time.Second,
  87. }
  88. transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
  89. host, _, err := net.SplitHostPort(addr)
  90. if err != nil {
  91. host = addr
  92. }
  93. if strings.HasSuffix(host, "github.io") {
  94. if conn, err := dialer.DialContext(ctx, "tcp4", addr); err == nil {
  95. return conn, nil
  96. }
  97. return dialer.DialContext(ctx, "tcp6", addr)
  98. }
  99. return dialer.DialContext(ctx, network, addr)
  100. }
  101. return &http.Client{Transport: transport}
  102. }
  103. var httpClient = newHTTPClient()
  104. func fetchJSON[T any](ctx context.Context, url string, out *upstreamEnvelope[T]) error {
  105. var lastErr error
  106. attempts := common.GetEnvOrDefault("SYNC_HTTP_RETRY", 3)
  107. if attempts < 1 {
  108. attempts = 1
  109. }
  110. baseDelay := 200 * time.Millisecond
  111. maxMB := common.GetEnvOrDefault("SYNC_HTTP_MAX_MB", 10)
  112. maxBytes := int64(maxMB) << 20
  113. for attempt := 0; attempt < attempts; attempt++ {
  114. req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
  115. if err != nil {
  116. return err
  117. }
  118. // ETag conditional request
  119. cacheMutex.RLock()
  120. if et := etagCache[url]; et != "" {
  121. req.Header.Set("If-None-Match", et)
  122. }
  123. cacheMutex.RUnlock()
  124. resp, err := httpClient.Do(req)
  125. if err != nil {
  126. lastErr = err
  127. // backoff with jitter
  128. sleep := baseDelay * time.Duration(1<<attempt)
  129. jitter := time.Duration(rand.Intn(150)) * time.Millisecond
  130. time.Sleep(sleep + jitter)
  131. continue
  132. }
  133. func() {
  134. defer resp.Body.Close()
  135. switch resp.StatusCode {
  136. case http.StatusOK:
  137. // read body into buffer for caching and flexible decode
  138. limited := io.LimitReader(resp.Body, maxBytes)
  139. buf, err := io.ReadAll(limited)
  140. if err != nil {
  141. lastErr = err
  142. return
  143. }
  144. // cache body and ETag
  145. cacheMutex.Lock()
  146. if et := resp.Header.Get("ETag"); et != "" {
  147. etagCache[url] = et
  148. }
  149. bodyCache[url] = buf
  150. cacheMutex.Unlock()
  151. // Try decode as envelope first
  152. if err := json.Unmarshal(buf, out); err != nil {
  153. // Try decode as pure array
  154. var arr []T
  155. if err2 := json.Unmarshal(buf, &arr); err2 != nil {
  156. lastErr = err
  157. return
  158. }
  159. out.Success = true
  160. out.Data = arr
  161. out.Message = ""
  162. } else {
  163. if !out.Success && len(out.Data) == 0 && out.Message == "" {
  164. out.Success = true
  165. }
  166. }
  167. lastErr = nil
  168. case http.StatusNotModified:
  169. // use cache
  170. cacheMutex.RLock()
  171. buf := bodyCache[url]
  172. cacheMutex.RUnlock()
  173. if len(buf) == 0 {
  174. lastErr = errors.New("cache miss for 304 response")
  175. return
  176. }
  177. if err := json.Unmarshal(buf, out); err != nil {
  178. var arr []T
  179. if err2 := json.Unmarshal(buf, &arr); err2 != nil {
  180. lastErr = err
  181. return
  182. }
  183. out.Success = true
  184. out.Data = arr
  185. out.Message = ""
  186. } else {
  187. if !out.Success && len(out.Data) == 0 && out.Message == "" {
  188. out.Success = true
  189. }
  190. }
  191. lastErr = nil
  192. default:
  193. lastErr = errors.New(resp.Status)
  194. }
  195. }()
  196. if lastErr == nil {
  197. return nil
  198. }
  199. sleep := baseDelay * time.Duration(1<<attempt)
  200. jitter := time.Duration(rand.Intn(150)) * time.Millisecond
  201. time.Sleep(sleep + jitter)
  202. }
  203. return lastErr
  204. }
  205. func ensureVendorID(vendorName string, vendorByName map[string]upstreamVendor, vendorIDCache map[string]int, createdVendors *int) int {
  206. if vendorName == "" {
  207. return 0
  208. }
  209. if id, ok := vendorIDCache[vendorName]; ok {
  210. return id
  211. }
  212. var existing model.Vendor
  213. if err := model.DB.Where("name = ?", vendorName).First(&existing).Error; err == nil {
  214. vendorIDCache[vendorName] = existing.Id
  215. return existing.Id
  216. }
  217. uv := vendorByName[vendorName]
  218. v := &model.Vendor{
  219. Name: vendorName,
  220. Description: uv.Description,
  221. Icon: coalesce(uv.Icon, ""),
  222. Status: chooseStatus(uv.Status, 1),
  223. }
  224. if err := v.Insert(); err == nil {
  225. *createdVendors++
  226. vendorIDCache[vendorName] = v.Id
  227. return v.Id
  228. }
  229. vendorIDCache[vendorName] = 0
  230. return 0
  231. }
  232. // SyncUpstreamModels 同步上游模型与供应商,仅对「未配置模型」生效
  233. func SyncUpstreamModels(c *gin.Context) {
  234. var req syncRequest
  235. // 允许空体
  236. _ = c.ShouldBindJSON(&req)
  237. // 1) 获取未配置模型列表
  238. missing, err := model.GetMissingModels()
  239. if err != nil {
  240. c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
  241. return
  242. }
  243. if len(missing) == 0 {
  244. c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{
  245. "created_models": 0,
  246. "created_vendors": 0,
  247. "skipped_models": []string{},
  248. }})
  249. return
  250. }
  251. // 2) 拉取上游 vendors 与 models
  252. timeoutSec := common.GetEnvOrDefault("SYNC_HTTP_TIMEOUT_SECONDS", 15)
  253. ctx, cancel := context.WithTimeout(c.Request.Context(), time.Duration(timeoutSec)*time.Second)
  254. defer cancel()
  255. modelsURL, vendorsURL := getUpstreamURLs(req.Locale)
  256. var vendorsEnv upstreamEnvelope[upstreamVendor]
  257. var modelsEnv upstreamEnvelope[upstreamModel]
  258. var fetchErr error
  259. var wg sync.WaitGroup
  260. wg.Add(2)
  261. go func() {
  262. defer wg.Done()
  263. // vendor 失败不拦截
  264. _ = fetchJSON(ctx, vendorsURL, &vendorsEnv)
  265. }()
  266. go func() {
  267. defer wg.Done()
  268. if err := fetchJSON(ctx, modelsURL, &modelsEnv); err != nil {
  269. fetchErr = err
  270. }
  271. }()
  272. wg.Wait()
  273. if fetchErr != nil {
  274. c.JSON(http.StatusOK, gin.H{"success": false, "message": "获取上游模型失败: " + fetchErr.Error(), "locale": req.Locale, "source_urls": gin.H{"models_url": modelsURL, "vendors_url": vendorsURL}})
  275. return
  276. }
  277. // 建立映射
  278. vendorByName := make(map[string]upstreamVendor)
  279. for _, v := range vendorsEnv.Data {
  280. if v.Name != "" {
  281. vendorByName[v.Name] = v
  282. }
  283. }
  284. modelByName := make(map[string]upstreamModel)
  285. for _, m := range modelsEnv.Data {
  286. if m.ModelName != "" {
  287. modelByName[m.ModelName] = m
  288. }
  289. }
  290. // 3) 执行同步:仅创建缺失模型;若上游缺失该模型则跳过
  291. createdModels := 0
  292. createdVendors := 0
  293. updatedModels := 0
  294. var skipped []string
  295. var createdList []string
  296. var updatedList []string
  297. // 本地缓存:vendorName -> id
  298. vendorIDCache := make(map[string]int)
  299. for _, name := range missing {
  300. up, ok := modelByName[name]
  301. if !ok {
  302. skipped = append(skipped, name)
  303. continue
  304. }
  305. // 若本地已存在且设置为不同步,则跳过(极端情况:缺失列表与本地状态不同步时)
  306. var existing model.Model
  307. if err := model.DB.Where("model_name = ?", name).First(&existing).Error; err == nil {
  308. if existing.SyncOfficial == 0 {
  309. skipped = append(skipped, name)
  310. continue
  311. }
  312. }
  313. // 确保 vendor 存在
  314. vendorID := ensureVendorID(up.VendorName, vendorByName, vendorIDCache, &createdVendors)
  315. // 创建模型
  316. mi := &model.Model{
  317. ModelName: name,
  318. Description: up.Description,
  319. Icon: up.Icon,
  320. Tags: up.Tags,
  321. VendorID: vendorID,
  322. Status: chooseStatus(up.Status, 1),
  323. NameRule: up.NameRule,
  324. }
  325. if err := mi.Insert(); err == nil {
  326. createdModels++
  327. createdList = append(createdList, name)
  328. } else {
  329. skipped = append(skipped, name)
  330. }
  331. }
  332. // 4) 处理可选覆盖(更新本地已有模型的差异字段)
  333. if len(req.Overwrite) > 0 {
  334. // vendorIDCache 已用于创建阶段,可复用
  335. for _, ow := range req.Overwrite {
  336. up, ok := modelByName[ow.ModelName]
  337. if !ok {
  338. continue
  339. }
  340. var local model.Model
  341. if err := model.DB.Where("model_name = ?", ow.ModelName).First(&local).Error; err != nil {
  342. continue
  343. }
  344. // 跳过被禁用官方同步的模型
  345. if local.SyncOfficial == 0 {
  346. continue
  347. }
  348. // 映射 vendor
  349. newVendorID := ensureVendorID(up.VendorName, vendorByName, vendorIDCache, &createdVendors)
  350. // 应用字段覆盖(事务)
  351. _ = model.DB.Transaction(func(tx *gorm.DB) error {
  352. needUpdate := false
  353. if containsField(ow.Fields, "description") {
  354. local.Description = up.Description
  355. needUpdate = true
  356. }
  357. if containsField(ow.Fields, "icon") {
  358. local.Icon = up.Icon
  359. needUpdate = true
  360. }
  361. if containsField(ow.Fields, "tags") {
  362. local.Tags = up.Tags
  363. needUpdate = true
  364. }
  365. if containsField(ow.Fields, "vendor") {
  366. local.VendorID = newVendorID
  367. needUpdate = true
  368. }
  369. if containsField(ow.Fields, "name_rule") {
  370. local.NameRule = up.NameRule
  371. needUpdate = true
  372. }
  373. if containsField(ow.Fields, "status") {
  374. local.Status = chooseStatus(up.Status, local.Status)
  375. needUpdate = true
  376. }
  377. if !needUpdate {
  378. return nil
  379. }
  380. if err := tx.Save(&local).Error; err != nil {
  381. return err
  382. }
  383. updatedModels++
  384. updatedList = append(updatedList, ow.ModelName)
  385. return nil
  386. })
  387. }
  388. }
  389. c.JSON(http.StatusOK, gin.H{
  390. "success": true,
  391. "data": gin.H{
  392. "created_models": createdModels,
  393. "created_vendors": createdVendors,
  394. "updated_models": updatedModels,
  395. "skipped_models": skipped,
  396. "created_list": createdList,
  397. "updated_list": updatedList,
  398. "source": gin.H{
  399. "locale": req.Locale,
  400. "models_url": modelsURL,
  401. "vendors_url": vendorsURL,
  402. },
  403. },
  404. })
  405. }
  406. func containsField(fields []string, key string) bool {
  407. key = strings.ToLower(strings.TrimSpace(key))
  408. for _, f := range fields {
  409. if strings.ToLower(strings.TrimSpace(f)) == key {
  410. return true
  411. }
  412. }
  413. return false
  414. }
  415. func coalesce(a, b string) string {
  416. if strings.TrimSpace(a) != "" {
  417. return a
  418. }
  419. return b
  420. }
  421. func chooseStatus(primary, fallback int) int {
  422. if primary == 0 && fallback != 0 {
  423. return fallback
  424. }
  425. if primary != 0 {
  426. return primary
  427. }
  428. return 1
  429. }
  430. // SyncUpstreamPreview 预览上游与本地的差异(仅用于弹窗选择)
  431. func SyncUpstreamPreview(c *gin.Context) {
  432. // 1) 拉取上游数据
  433. timeoutSec := common.GetEnvOrDefault("SYNC_HTTP_TIMEOUT_SECONDS", 15)
  434. ctx, cancel := context.WithTimeout(c.Request.Context(), time.Duration(timeoutSec)*time.Second)
  435. defer cancel()
  436. locale := c.Query("locale")
  437. modelsURL, vendorsURL := getUpstreamURLs(locale)
  438. var vendorsEnv upstreamEnvelope[upstreamVendor]
  439. var modelsEnv upstreamEnvelope[upstreamModel]
  440. var fetchErr error
  441. var wg sync.WaitGroup
  442. wg.Add(2)
  443. go func() {
  444. defer wg.Done()
  445. _ = fetchJSON(ctx, vendorsURL, &vendorsEnv)
  446. }()
  447. go func() {
  448. defer wg.Done()
  449. if err := fetchJSON(ctx, modelsURL, &modelsEnv); err != nil {
  450. fetchErr = err
  451. }
  452. }()
  453. wg.Wait()
  454. if fetchErr != nil {
  455. c.JSON(http.StatusOK, gin.H{"success": false, "message": "获取上游模型失败: " + fetchErr.Error(), "locale": locale, "source_urls": gin.H{"models_url": modelsURL, "vendors_url": vendorsURL}})
  456. return
  457. }
  458. vendorByName := make(map[string]upstreamVendor)
  459. for _, v := range vendorsEnv.Data {
  460. if v.Name != "" {
  461. vendorByName[v.Name] = v
  462. }
  463. }
  464. modelByName := make(map[string]upstreamModel)
  465. upstreamNames := make([]string, 0, len(modelsEnv.Data))
  466. for _, m := range modelsEnv.Data {
  467. if m.ModelName != "" {
  468. modelByName[m.ModelName] = m
  469. upstreamNames = append(upstreamNames, m.ModelName)
  470. }
  471. }
  472. // 2) 本地已有模型
  473. var locals []model.Model
  474. if len(upstreamNames) > 0 {
  475. _ = model.DB.Where("model_name IN ? AND sync_official <> 0", upstreamNames).Find(&locals).Error
  476. }
  477. // 本地 vendor 名称映射
  478. vendorIdSet := make(map[int]struct{})
  479. for _, m := range locals {
  480. if m.VendorID != 0 {
  481. vendorIdSet[m.VendorID] = struct{}{}
  482. }
  483. }
  484. vendorIDs := make([]int, 0, len(vendorIdSet))
  485. for id := range vendorIdSet {
  486. vendorIDs = append(vendorIDs, id)
  487. }
  488. idToVendorName := make(map[int]string)
  489. if len(vendorIDs) > 0 {
  490. var dbVendors []model.Vendor
  491. _ = model.DB.Where("id IN ?", vendorIDs).Find(&dbVendors).Error
  492. for _, v := range dbVendors {
  493. idToVendorName[v.Id] = v.Name
  494. }
  495. }
  496. // 3) 缺失且上游存在的模型
  497. missingList, _ := model.GetMissingModels()
  498. var missing []string
  499. for _, name := range missingList {
  500. if _, ok := modelByName[name]; ok {
  501. missing = append(missing, name)
  502. }
  503. }
  504. // 4) 计算冲突字段
  505. type conflictField struct {
  506. Field string `json:"field"`
  507. Local interface{} `json:"local"`
  508. Upstream interface{} `json:"upstream"`
  509. }
  510. type conflictItem struct {
  511. ModelName string `json:"model_name"`
  512. Fields []conflictField `json:"fields"`
  513. }
  514. var conflicts []conflictItem
  515. for _, local := range locals {
  516. up, ok := modelByName[local.ModelName]
  517. if !ok {
  518. continue
  519. }
  520. fields := make([]conflictField, 0, 6)
  521. if strings.TrimSpace(local.Description) != strings.TrimSpace(up.Description) {
  522. fields = append(fields, conflictField{Field: "description", Local: local.Description, Upstream: up.Description})
  523. }
  524. if strings.TrimSpace(local.Icon) != strings.TrimSpace(up.Icon) {
  525. fields = append(fields, conflictField{Field: "icon", Local: local.Icon, Upstream: up.Icon})
  526. }
  527. if strings.TrimSpace(local.Tags) != strings.TrimSpace(up.Tags) {
  528. fields = append(fields, conflictField{Field: "tags", Local: local.Tags, Upstream: up.Tags})
  529. }
  530. // vendor 对比使用名称
  531. localVendor := idToVendorName[local.VendorID]
  532. if strings.TrimSpace(localVendor) != strings.TrimSpace(up.VendorName) {
  533. fields = append(fields, conflictField{Field: "vendor", Local: localVendor, Upstream: up.VendorName})
  534. }
  535. if local.NameRule != up.NameRule {
  536. fields = append(fields, conflictField{Field: "name_rule", Local: local.NameRule, Upstream: up.NameRule})
  537. }
  538. if local.Status != chooseStatus(up.Status, local.Status) {
  539. fields = append(fields, conflictField{Field: "status", Local: local.Status, Upstream: up.Status})
  540. }
  541. if len(fields) > 0 {
  542. conflicts = append(conflicts, conflictItem{ModelName: local.ModelName, Fields: fields})
  543. }
  544. }
  545. c.JSON(http.StatusOK, gin.H{
  546. "success": true,
  547. "data": gin.H{
  548. "missing": missing,
  549. "conflicts": conflicts,
  550. "source": gin.H{
  551. "locale": locale,
  552. "models_url": modelsURL,
  553. "vendors_url": vendorsURL,
  554. },
  555. },
  556. })
  557. }